Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
最大生成树,并查集,1次AC纪念,呵呵简单的水题,,, #include <cstdio> #include <algorithm> #include <cstring> using namespace std; const int maxn=1000000; struct edge { int fr,to,cost; }; edge Ed[maxn]; int V[maxn]; bool cmp(edge e1,edge e2) { return e1.cost>e2.cost; } int find(int x) { if(x!=V[x]) V[x]=find(V[x]); return V[x]; } void unite(int x,int y) { int f1=find(x); int f2=find(y); V[f1]=f2; } int main() { int v,e; scanf("%d%d",&v,&e); for(int i=0;i<e;i++) { edge ed; scanf("%d%d%d",&ed.fr,&ed.to,&ed.cost); Ed[i]=ed; } sort(Ed,Ed+e,cmp); for(int i=1;i<=v;i++) V[i]=i; int ans=0; int num=1; for(int i=0;i<e;i++) { edge ed=Ed[i]; if(find(ed.fr)!=find(ed.to)) { unite(ed.fr,ed.to); ans+=ed.cost; num++; } } num==v?printf("%d\n",ans):printf("-1\n"); return 0; } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator