用STL的vector容器写,直接内部排序了。
#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 9999999999 using namespace std; #define maxm 100000+500 #define maxn 100000+500 struct 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; }