Test instructions: There are n cities, there are n-1 between cities to connect each city, that is, there is a tree, the enemy in some cities to put missiles, a total of M missiles, the enemy wants to bring the missiles together and war, now give you a task is to destroy some road, so that any two missiles can not be brought together, Destroying each road has a corresponding cost, for the lowest price.
Analysis:
Missiles can't be transported together. That is, any two missiles cannot be in a connected graph, so our task is to destroy some roads with the least cost to make M-missiles separate in M-connected graphs.
This problem is on the opposite side, the least cost, then is the cost of the remaining road, the greater the better, this is the largest spanning tree, so the problem-solving method is: Using the Kruskal algorithm to find the largest spanning tree, with and check set to maintain two of missiles can not be in a connected diagram.
Code:
#include <iostream> #include <algorithm>using namespace Std;int fa[100005],n,m,t;struct node{int X,y;long Long V;} Edge[100005];int K[100005];long Long Sum;bool cmp (node A,node b) {return A.V>B.V;} int find (int x) {if (fa[x]==x) return x;else return Fa[x]=find (Fa[x]);} void merge (int x,int y) {fa[find (x)]=find (y);} void Kruskal () {for (int i=0;i<n-1;i++) {int fax=find (edge[i].x); int fay=find (EDGE[I].Y); if (K[fax]&&k[fay] ) {sum+=edge[i].v;continue;} Else{if (k[fax]| | K[fay]) K[fax]=k[fay]=1;merge (Fax,fay);}} int main () {cin>>t;while (t--) {memset (k,0,sizeof (k)); cin>>n>>m;for (int i=0;i<n;i++) fa[i]=i; for (int i=0;i<n-1;i++) cin>>edge[i].x>>edge[i].y>>edge[i].v;int tmp;for (int i=0;i<m;i++) { Cin>>tmp;k[tmp]=1;} Sort (edge,edge+n-1,cmp); Sum=0;kruskal (); Cout<<sum<<endl;}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
! HDU 4313 destruction of missile siege plan-connectivity graph-(minimum spanning tree deformation)