The original image may have multiple connected components, DFS finds the smallest node in each connected component, which is necessarily the city to be captured.
Set N is the number of nodes, M is the number of edges, CNT is the initial number of connected components, the remaining number of edges is not less than M-(n-cnt), the graph of connectivity is constant, that is, before this can be appropriate strategy to delete the edge to keep the result unchanged.
When the number of sides is less than or equal to M-(n-cnt), every deletion of an edge, there is bound to be more than one connected component, we can always do so that the minimum node of the connected component is all nodes in the removal of those nodes that have been selected outside the smallest nodes, so at this point in the weight of the node from small to large to
#include <stdio.h>#include<string.h>#include<stdlib.h>#include<algorithm>typedefLong LongLL;Const intMAXN =1111111;Const intMAXM =2111111;intN, M, K;intFST[MAXN];intWT[MAXN];intVIS[MAXN];intNEX[MAXM], W[MAXM], NTP;voidAddedge (intAintb) {NEX[NTP]=Fst[a]; W[NTP]=b; Fst[a]= NTP + +;} InlineintMinintAintb) {returnA < b?a:b;}voidDFS (intndint&okcity) { if(Vis[nd])return; VIS[ND]=true; if(Okcity = =-1|| WT[ND] <wt[okcity]) okcity=nd; for(inti = fst[nd]; I! =-1; i =Nex[i]) DFS (W[i], okcity);}intMain () {intT, CA; for(SCANF ("%d", &t), CA =1; CA <= T; CA + +) { intA, B; scanf ("%d%d%d", &n, &m, &k); memset (FST,-1,sizeof(FST)); memset (Vis,0,sizeof(VIS)); for(inti =1; I <= N; i + +) scanf ("%d", &Wt[i]); NTP=0; for(inti =0; I < m; i + +) {scanf ("%d%d", &a, &b); Addedge (A, b); Addedge (b, a); } intCNT =0; LL ans=0; for(inti =1; I <= N; i + +) { intOkcity =-1; DFS (i, okcity); if(Okcity! =-1) CNT+ +, ans + = wt[okcity], vis[okcity] =2; } if(K-= M-(n-cnt)) >0) { intI, J; for(i =1, j =1; I <= N; i + +) if(Vis[i]! =2) Wt[j + +] =Wt[i]; Std::sort (WT+1, WT +j); for(inti =1; K >0&& I <= J; i + +) ans+ = Wt[i], K--; } printf ("Case #%d:%lld\n", CA, ans); } return 0;}
Hihocoder 1160 Gongchenglvede