poj 1258

大意:有一個小鎮,鎮上有一些農場。用以光纖把所有農場聯通,最少需要多少光纖。

最小生成樹,prim或者kruskal。

prim

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn = 100 + 5;
const int inf = 1e9 + 10;
int cost[maxn][maxn], mincost[maxn], n;
bool used[maxn];
void prim()
{
    memset(used, 0, sizeof(used));
    for(int i = 1; i <= n; i++)
        mincost[i] = inf;
    mincost[1] = 0;
    int ret = 0;
    while(true)
    {
        int v = -1;
        for(int i = 1; i <= n; i++)
        {
            if(!used[i] && (v == -1 || mincost[i] < mincost[v]))
            {
                v = i;
            }
        }
        if(v == -1) break;
        ret += mincost[v];
        //printf("%d\n", mincost[v]);
        used[v] = 1;
        for(int i = 1; i <= n; i++)
        {
            mincost[i] = min(mincost[i], cost[i][v]);
        }
    }
    printf("%d\n", ret);
}
int main()
{
    while(scanf("%d", &n) == 1)
    {
        for(int i = 0; i < n; i++)
            for(int j = 0; j < n; j++)
            {
                int t1;
                scanf("%d", &t1);
                cost[i + 1][j + 1] = t1;
            }
        //printf("yes\n");
        prim();
    }
    return 0;
}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章