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 |
大水题,kruskal秒杀/* * Problem: POJ 2387 * Author: geek 7 * Time: 2012.8.3 9:52 PM * State: * Memo: kruskal & 并查集 */ #include<cstdio> #include<cstring> #include<cstdlib> const int maxn=5100; int fa[maxn]; struct node { int x,y; int va; }a[maxn]; int cmp(const void *a,const void *b) { return ((node *)a)->va-((node *)b)->va; } int find(int x) { if(x!=fa[x]) { fa[x]=find(fa[x]); } return fa[x]; } void init(int n) { int i; for(i=0;i<n;i++) scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].va); qsort(a,n,sizeof(node),cmp); for(i=0;i<maxn;i++) fa[i]=i; } void kruskal(int n,int m) { int i,ct=0,ans=0,x,y; for(i=0;i<n;i++) { x=find(a[i].x); y=find(a[i].y); if(x!=y) { ct++; ans+=a[i].va; if(ct==m-1) break; fa[y]=x; } } printf("%d\n",ans); } int main() { int m,n; while(1) { scanf("%d",&m); if(m==0) break; scanf("%d",&n); init(n); kruskal(n,m); } return 0; } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator