您的位置:首页 > 其它

每日一题 No.53 最小生成树问题(Prim算法)

2017-05-27 10:59 337 查看

本题要求:

给出一个有向图,让你求出这个图的最小生成树

输入格式:

第一行输入V,E分别代表顶点数和边数

接下来E行,每行输入from to cost 代表从from到to的距离为cost

输出格式:

输出最小消耗

输入样例:

3 3

0 1 2

1 2 3

0 2 4

输出样例:

5

解题思路 :

跟Dijkstra算法很像,不过就是找走遍所有点的最小消耗。

代码 :

#include <iostream>

using namespace std;

int main() {
int cost[101][101];
int minCost[101];
bool used[101];
int V;
cin >> V;
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
cost[i][j] = 0x7f7f;
}
}
for (int i = 0; i < V; i++) {
minCost[i] = 0x7f7f;
used[i] = false;
}
int E;
cin >> E;
for (int i = 0; i < E; i++) {
int f, t, c;
cin >> f >> t >> c;
cost[f][t] = c;
}
minCost[0] = 0;
int res = 0;
while (true) {
int v = -1;
for (int u = 0; u < V;
4000
u++) {
if (!used[u] && (v == -1 || minCost[u] < minCost[v])) {
v = u;
}
}
if (v == -1) {
break;
}
used[v] = true;
res += minCost[v];
for (int u = 0; u < V; u++) {
minCost[u] = min(minCost[u], cost[v][u]);
}
}
cout << res << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: