hdu 1879 裸最小生成树

来源:互联网 发布:js设置元素display为'' 编辑:程序博客网 时间:2024/05/23 18:42

这是一道裸的最小生成树问题,很适合用来入门,练模板。赫赫~~

#include <iostream>#include <algorithm>#include <cstdio>#include <cmath>#include <cstdlib>#include <string>#include <ctime>#include <cstring>using namespace std;struct ss {int to,s,next,w;};ss e[10086];int head[120];int size;int n;bool c(const ss &a,const ss &b){//if(a.w!=b.w) return a.w<b.w;//else return a.s<b.s;}int father[120];int gefather(int v){if(father[v]==0) return v;  else return gefather(father[v]);}void comb(int a,int b){a=gefather(a);b=gefather(b);    if(a!=b) father[a]=b;}void tjb(int x,int y,int z){size++;e[size].s=x;e[size].next=head[x];head[x]=size;e[size].to=y;e[size].w=z;}int main(){while(cin>>n&&n!=0){size=0;memset(head,0,sizeof(head));memset(e,0,sizeof(e));memset(father,0,sizeof(father));for(int i=1;i<=n*(n-1)/2;i++){int x,y,a,b;cin>>x>>y>>a>>b;if(b==0) tjb(x,y,a);else tjb(x,y,0);}sort(e+1,e+1+size,c);int rep=0,ans=0;for(int i=1;i<=size;i++){if(rep==n-1) break;if(gefather(e[i].s)!=gefather(e[i].to)) {   comb(e[i].s,e[i].to);   rep++;   ans+=e[i].w;    }}cout<<ans<<endl;}   return 0;}


原创粉丝点击