## Re-moved

Moved by everything again.

# 畅通工程

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 26432    Accepted Submission(s): 11550

Problem Description

Input

Output

Sample Input
3 3 1 2 1 1 3 2 2 3 4 1 3 2 3 2 0 100

Sample Output
3 ?

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int N=110;
const int M=5000;
struct edge{
int u,v,w;
}edges[M];
int pre[N];

int find(int i){
return pre[i]==i?i:pre[i]=find(pre[i]);
}
int cmp(edge a,edge b){
return a.w<b.w;
}
int kruskal(int n,int m){
int ans=0,cnt=0;

for(int i=1;i<=n;i++) pre[i]=i;
sort(edges+1,edges+m+1,cmp);
for(int i=1;i<=m;i++){
int x=find(edges[i].u);
int y=find(edges[i].v);
if(x!=y){
ans+=edges[i].w;
pre[x]=y;
cnt++;

}
}
if(cnt==n-1) return ans;
else return -1;
}

int main(){
int n,m;
while(~scanf("%d %d",&m,&n)&&m){
for(int i=1;i<=m;i++){
scanf("%d %d %d",&edges[i].u,&edges[i].v,&edges[i].w);
}

int ans=kruskal(n,m);

if(ans>=0) printf("%d\n",ans);
else printf("?\n");

}
}
/*
3 3
1 2 1
1 3 2
2 3 4
1 3
2 3 2
*/ 

Kruskal模版题。

Kruskal算法的本质其实就是贪心+并查集；

Kruskal算法用于求最小生成树；

05-25 3491

11-01 739

08-03 203

08-19 327

04-14 476

10-31 857

08-03 120

09-04 672

08-11 447

08-11 875