hdu 1863 畅通工程 (并查集 、 kruskal)

畅通工程
Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 37969    Accepted Submission(s): 16915
Problem Description
省*“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。经过调查评估,得到的统计表中列出了有可能建设公路的若干条道路的成本。现请你编写程序,计算出全省畅通需要的最低成本。
 
Input
测试输入包含若干测试用例。每个测试用例的第1行给出评估的道路条数 N、村庄数目M ( < 100 );随后的 N
行对应村庄间道路的成本,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间道路的成本(也是正整数)。为简单起见,村庄从1到M编号。当N为0时,全部输入结束,相应的结果不要输出。
 
Output
对每个测试用例,在1行里输出全省畅通需要的最低成本。若统计数据不足以保证畅通,则输出“?”。
 
Sample Input
3 3
1 2 1
1 3 2
2 3 4
1 3
2 3 2
0 100
 
Sample Output
3
?

C/C++:

 #include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <stack>
#include <set>
#include <map>
#include <queue>
#include <climits>
#include <bitset>
#define eps 1e-6
using namespace std; int n, m, my_pre[]; struct node
{
int a, b, a_b_distance;
}my_round[]; bool cmp(node a, node b)
{
return a.a_b_distance < b.a_b_distance;
} int my_find(int x)
{
int r = x;
while (r != my_pre[r])
r = my_pre[r];
int i = x, j;
while (r != my_pre[i])
{
j = my_pre[i];
my_pre[i] = r;
i = j;
}
return r;
} void my_join(int a, int b)
{
int n1 = my_find(a), n2 = my_find(b);
if (n1 != n2)
my_pre[n1] = n2;
} int kruskal()
{
int my_ans = ;
sort(my_round, my_round + n, cmp);
for (int i = ; i < n; ++ i)
{
if (my_find(my_round[i].a) == my_find(my_round[i].b)) continue;
my_join(my_round[i].a, my_round[i].b);
my_ans += my_round[i].a_b_distance;
}
int temp_pre = my_find();
for (int i = ; i <= m; ++ i)
{
if (temp_pre == my_find(i)) continue;
return ;
}
return my_ans;
} int main()
{
ios::sync_with_stdio(false); while(scanf("%d%d", &n, &m), n)
{
/**
Initialize
*/
for (int i = ; i <= m; ++ i)
my_pre[i] = i;
memset (my_round, , sizeof(my_round)); /**
Date Input
*/
for (int i = ; i < n; ++ i)
{
scanf("%d%d%d", &my_round[i].a, &my_round[i].b, &my_round[i].a_b_distance);
} /**
Process
*/
int my_temp = kruskal();
if (my_temp)
printf("%d\n", my_temp);
else
printf("?\n");
}
return ;
}
上一篇:SVN服务器搭建和使用(三)


下一篇:R语言多项式回归