每日一题 No.53 最小生成树问题(Prim算法)
2017-05-27 10:59
337 查看
本题要求:
给出一个有向图,让你求出这个图的最小生成树输入格式:
第一行输入V,E分别代表顶点数和边数接下来E行,每行输入from to cost 代表从from到to的距离为cost
输出格式:
输出最小消耗输入样例:
3 30 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; }
相关文章推荐
- ZOJ 1586 : QS Network - prim算法解决最小生成树问题
- 每日一题 No.54 最小生成树问题(Kruskal算法)
- 最小生成树问题用Prim算法或Kruskal算法
- prim算法解决最小生成树问题
- prim算法来解最小生成树问题
- NY--38 -- 布线问题 [prim算法求最小生成树]
- 最小生成树问题·POJ-1258 Agri-Net·prim算法
- 最小生成树问题——Prim算法(C实现)
- Agri-Net(prim算法,最小生成树问题)
- 最小生成树问题中Kruskal算法和Prim算法的C语言实现
- 算法java实现--贪心算法--最小生成树问题--Prim算法
- HDU 1875 畅通工程再续(最小生成树问题)Prim算法
- 最小生成树----Prim算法
- 旅行员售货的什么近似算法;随便写了写,用了图的最小生成树Prim算法与深搜;
- C# 最小生成树 prim算法
- HDU 1879(最小生成树问题,Prim)
- 最小生成树PRIM算法及KRUSKAL算法第四集
- 最小生成树(prim算法)
- POJ 1258-Agri Net 最小生成树Prim算法
- 最小生成树——prim算法实现