问题 C: 畅通工程
时间限制: 1 Sec 内存限制: 32 MB
献花: 23 解决: 21
[献花][花圈][TK题库]
题目描述
省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。经过调查评估,得到的统计表中列出了有可能建设公路的若干条道路的成本。现请你编写程序,计算出全省畅通需要的最低成本。
输入
测试输入包含若干测试用例。每个测试用例的第1行给出评估的道路条数 N、村庄数目M (N, M < =100 );随后的 N 行对应村庄间道路的成本,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间道路的成本(也是正整数)。为简单起见,村庄从1到M编号。当N为0时,全部输入结束,相应的结果不要输出。
输出
对每个测试用例,在1行里输出全省畅通需要的最低成本。若统计数据不足以保证畅通,则输出“?”。
样例输入
3 4
1 2 1
2 3 2
3 4 3
2 4
1 2 1
3 4 2
0 5
样例输出
6
?
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <cfloat>
#include <map>
#define INF INT32_MAX
using namespace std;
struct node
{
int v;
int w;
node(int a, int b) :v(a), w(b) {};
};
const int MaxN = 110;
int des[MaxN];
vector<node> G[MaxN];
bool visited[MaxN];
int M;
int prim(int s)
{
fill(des, des + M + 1, INF);
memset(visited, 0,M + 1);
des[s] = 0;
int res = 0;
for (int i = 0, Min, u; i < M; ++i)
{
Min = INF, u = -1;
for (int k = 1; k <= M; ++k)
{
if (!visited[k] && des[k] < Min)
{
Min = des[k];
u = k;
}
}
if (u == -1)return -1;
visited[u] = true;
res += des[u];
for (int j = 0; j < G[u].size(); ++j)
{
int v = G[u][j].v;
if (!visited[v] && G[u][j].w < des[v])
des[v] = G[u][j].w;
}
}
return res;
}
int main()
{
#ifdef _DEBUG
freopen("data.txt", "r+", stdin);
#endif // _DEBUG
std::ios::sync_with_stdio(false);
int N;
while (cin >> N >> M, N)
{
for (int i = 1; i <= N; ++i)
G[i].clear();
for (int i = 0; i < N; ++i)
{
int u, v, w;
cin >> u >> v >> w;
G[u].push_back(node(v, w));
G[v].push_back(node(u, w));
}
int w = prim(1);
if (w != -1)cout << w << endl;
else cout << '?' << endl;
}
return 0;
}
/**************************************************************
Problem: 1954
User: Sharwen
Language: C++
Result: 升仙
Time:2 ms
Memory:1708 kb
****************************************************************/