POJ1258-Agri-Net

来源:互联网 发布:淘宝店铺宣传语大全 编辑:程序博客网 时间:2024/04/27 15:29

考察最小生成树,只要一个Prim算法即可

#include <cstdio>#include <algorithm>using namespace std;const int maxn = 105;const int INF = 10e5+10;int cost[maxn][maxn];int mincost[maxn];bool used[maxn];int prim(int v) {    for (int i = 0; i < v; i++) {        mincost[i] = INF;        used[i] = false;    }    mincost[0] = 0;    int res = 0;    while (true) {        int u = -1;        for (int i = 0; i < v; i++) {            if (!used[i] && (u == -1 || mincost[i] < mincost[u]))                u = i;        }        if (u == -1) {            break;        }        used[u] = true;        res += mincost[u];        for (int i = 0; i < v; i++) {            mincost[i] = min(mincost[i], cost[u][i]);        }    }    return res;}int main(int argc, char const *argv[]) {    int n;    while (scanf("%d", &n) == 1) {        for (int i = 0; i < n; i++) {            for (int j = 0; j < n; j++) {                scanf("%d", &cost[i][j]);            }        }        int ans = prim(n);        printf("%d\n", ans);    }    return 0;}


0 0
原创粉丝点击