首页 > 代码库 > 图算法-Prime

图算法-Prime

主要思想:利用了贪心属性,它有最优子结构,即它的导出子图也是最小生成树。

技术分享

#include <iostream>
using namespace std;

const int nmax= 100;
int e[nmax][nmax];
const int inf = 1 << 20;

int MST_Prime(int e[][nmax], int n) {
    int book[nmax], dis[nmax],sum=0;

    memset(book, 0, sizeof(book));
    for (int i = 1; i <= n; i++)
        dis[i] = inf;
    
    int flag = 1;
    dis[flag] = 0;
    book[flag] = 1;
    int t = n-1;
    while (t--) {
        for (int i = 1; i <= n; i++)
            if (book[i] == 0 && e[flag][i] < dis[i])
                dis[i] = e[flag][i];
                
        int tmp = inf;
        for(int i=1;i<=n;i++)
            if (book[i]==0&&dis[i] < tmp) {
                tmp = dis[i];
                flag = i;
            }

        sum += tmp;
        book[flag] = 1;
    }
    return sum;
}


int main() {
    int V, E;
    while (cin >> V >> E) {
        for(int i=0;i<=V;i++)
            for (int j = 0; j <= V; j++) {
                if (i == j)e[i][j] = 0;
                else e[i][j] = inf;
            }
        
        for (int i = 0; i < E; i++) {
            int x, y, z;
            cin >> x >> y >> z;
            e[x][y] = z;
            e[y][x] = z;
        }
        cout << MST_Prime(e, V) << endl;
    }
}

 

图算法-Prime