3 1 2 1 0 1 3 2 0 2 3 4 0 3 1 2 1 0 1 3 2 0 2 3 4 1 3 1 2 1 0 1 3 2 1 2 3 4 1 0
3 1 0
#include<stdio.h> #include<algorithm> using namespace std; //kruskal int N,ut; int root[101]; typedef struct _node{ int x,y,dis,sty; }Node; Node graph[5050]; int cmp(Node n,Node m){ return n.dis<m.dis; } int find(int i){ return root[i]=(root[i]==i?i:find(root[i])); } void unio (int i,int j){ if(i>=j) root[i]=j; else root[j]=i; } int kruskal(){ sort(graph,graph+ut,cmp); int shortest =0; for(int i=0;i<ut;++i){ //老范低级错误,这里误写成了 i < N* N, runtime ...了 N次~~~~~~~~ int t,k; t=find(graph[i].x); k=find(graph[i].y); if(t!=k){ shortest= shortest+graph[i].dis; unio(t,k); } } return shortest; } int main(){ while(~scanf("%d",&N),N){ ut=N%2==0?N/2*(N-1):(N-1)/2*N; int i,a,b,c,d; for(i=1;i<=N;++i){ root[i]=i; } for(i=0;i<ut;++i){ scanf("%d%d%d%d",&a,&b,&c,&d); graph[i].x=a;graph[i].y=b;graph[i].dis=c;graph[i].sty=d; if(d) graph[i].dis=0;//unio(a,b); } printf("%d\n",kruskal()); } return 0; }
原文:http://blog.csdn.net/qq_18062811/article/details/44687347