您的位置:首页 > 其它

#HDU 1233 还是畅通工程 【Prim算法】

2016-03-02 11:41 309 查看

题目:


还是畅通工程

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 35937    Accepted Submission(s): 16210


Problem Description

某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。

 

Input

测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。

当N为0时,输入结束,该用例不被处理。

 

Output

对每个测试用例,在1行里输出最小的公路总长度。

 

Sample Input

3
1 2 1
1 3 2
2 3 4
4
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5
0

 

Sample Output

3
5

HintHint
Huge input, scanf is recommended.

 

Source

浙大计算机研究生复试上机考试-2006年

思路:经典的最小生成树问题,可用prim,kruskal,spfa等算法解决。

选用了prim算法,因为已经给定了可使用的路径,即,所有村庄之间是全连接,所以可以使用邻接矩阵存,不会造成空间浪费。

代码较简单

#include<iostream>
#include<algorithm>
#include<cmath>
#include<string.h>

using namespace std;
int con[1005][1005];
int confar[1005];
long long ans, node;

int main()
{
int be, ed, lenth, n, m, target;
while (cin >> n)
{
if (n == 0)
{
return 0;
}

m = n*(n - 1) / 2;
memset(con, 0, sizeof(con));
memset(confar, 0, sizeof(confar));
ans = 0;
node = 1;
target = 0;

for (size_t i = 0; i < m; i++)
{
scanf("%d%d%d", &be, &ed, &lenth);
if (con[be][ed])
{
con[be][ed] = min(con[be][ed], lenth);
}
else
{
con[be][ed] = lenth;
}
if (con[ed][be])
{
con[ed][be] = min(con[ed][be], lenth);
}
else
{
con[ed][be] = lenth;
}
}

be = 1;
confar[1] = 1e9;
while (node != n)
{
for (size_t i = 1; i <= n; i++)
{
if (con[be][i] && confar[i] != 1e9)
{
if (confar[i])
{
confar[i] = min(confar[i], con[be][i]);
}
else
{
confar[i] = con[be][i];
}
}
}
int find = 1e9;
for (size_t i = 1; i <= n; i++)
{
if (find>confar[i] && confar[i] != 0)
{
find = confar[i];
be = i;
}
}
if (find == 1e9)
{
target = 1;
}
ans += find;
confar[be] = 1e9;
node++;
}
if (target)
{
cout << "?\n";
}
else
{
cout << ans << "\n";
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息