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

来源:互联网 发布:php 数值转字符串 编辑:程序博客网 时间:2024/06/05 03:49

本题要求:

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

输入格式:

第一行输入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; 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; }