Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 36625 Accepted Submission(s): 16281
行对应村庄间道路的成本,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间道路的成本(也是正整数)。为简单起见,村庄从1到M编号。当N为0时,全部输入结束,相应的结果不要输出。
模版题:
#include<bits/stdc++.h> using namespace std; #define MAX_N 111 struct edge{ int from,to; long long cost; }E[MAX_N*MAX_N]; bool cmp(edge x,edge y){ return x.cost<y.cost; } int N,M; int father[MAX_N]; void init(){ for(int i=1;i<=N;i++){ father[i]=i; } } int find(int x){ if(x==father[x]) return x; return father[x]=find(father[x]); } bool Same(int x,int y){ return find(x)==find(y); } void unionSet(int x,int y){ int u=find(x),v=find(y); if(u==v) return; father[u]=v; } long long Kruskal(){ long long res=0; sort(E+1,E+1+M,cmp); for(int i=1;i<=M;i++){ if(Same(E[i].from,E[i].to)) continue; unionSet(E[i].from,E[i].to); res+=E[i].cost; } return res; } int main(){ while(scanf("%d%d",&M,&N) ==2){ if(M==0) break; init(); for(int i=1;i<=M;i++){ scanf("%d%d%lld",&E[i].from,&E[i].to,&E[i].cost); } long long res=Kruskal(); for(int i=1;i<=N;i++){ if(!Same(i,1)) res=-1; } if(res==-1){ printf("?\n"); }else{ printf("%lld\n",res); } } return 0; }