DescriptionYou is given a graph with N nodes and M edges.Then every time is required to add a additional edge with weight Wi connecting the node Ai and Bi in the graph, and then calculate the sum of the edges ' weight of the Minimum Spanning Tree of the current graph. you'll be asked to complete the mission for Q Times.
The Minimum Spanning Tree of a graph is defined to being a set of N-1 edges which connects all the N nodes of the graph and the sum of the edges is as small as possible.It's guaranteed that's the graph is connected.Inputfirst Line of all case contains three numbers N, M and Q. (1?≤?? n,q≤?1000, 1?≤?? m?≤?100000,)
The following M lines contains three numbers Ai, Bi and Wi. (1?≤?? Ai, bi?≤?1000, 1?≤?? wi≤?100000).
The last Q lines of the contains three numbers Ai, Bi and Wi. (1 <= Ai, Bi <= 1000, 1?≤?? wi≤?100000). Outputoutput the answer in a, single, and each case.
Sample INPUT3 3 3
2 1 8
3 1 4
1 2 6
1 2 4
2 3 1
1 1 4
3 3 3
2 1 7
3 2 8
3 3 6
1 3 3
2 2 3
2 2 3Sample Output8
5
5
10
10
10
It is written in the vector container of STL, and it is sorted directly inside.
#include <stdio.h> #include <string.h> #include <iostream> #include <math.h> #include < algorithm> #include <vector> #include <queue> #include <map> #define PI acos ( -1.0) #define M 1000005/ /10^6#define EPS 1e-8#define LL long long#define Moo 1000000007#define INF 9999999999using namespace std; #define MAXM 1000 00+500#define maxn 100000+500struct edge{int u,v,w; BOOL operator < (const Edge &RHS) Const {return w<rhs.w; } void Read () {scanf ("%d%d%d", &u,&v,&w); }}edge[maxm];vector<edge> res;int fa[maxm];int FINDFA (int x) {if (x==fa[x]) return x; Return Fa[x]=findfa (Fa[x]);} BOOL Same (int a,int b) {return Findfa (a) ==findfa (b);} void merge (int a,int b) {int Xx=findfa (a); int Yy=findfa (b); if (xx>yy) fa[xx]=yy; else fa[yy]=xx;} int kruscal (vector<edge> &e,int N) {for (int i=1;i<=n;i++) fa[i]=i; vector<edge>res; Sort (E.begin (), E.end()); int ans=0; for (int i=0;i<e.size (); i++) {if (Same (E[I].U,E[I].V)) continue; Merge (E[I].U,E[I].V); ANS+=E[I].W; Res.push_back (E[i]); } e=res; return ans;} int main () {int m,n,q; while (~SCANF ("%d%d%d", &n,&m,&q)} {for (int i=0;i<m;i++) edge[i].read (); Edge[m++].read (); Sort (edge,edge+m); Res.clear (); for (int i=1;i<=n;i++) fa[i]=i; int ans=0; for (int i=0;i<m;i++) {if (Same (EDGE[I].U,EDGE[I].V)) continue; Merge (EDGE[I].U,EDGE[I].V); ANS+=EDGE[I].W; Res.push_back (Edge[i]); } q--; printf ("%d\n", ans); while (q--) {int u,v,w; scanf ("%d%d%d", &u,&v,&w); Res.push_back (Edge) {u,v,w}); printf ("%d\n", Kruscal (Res,n)); }} return 0;}
Fourth session of Central China Programming Invitational and Wuhan University 13th session Network qualifier Problem 1566-c-Spanning Tree