hdu 2122 Ice_cream’s world III

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=2122

解题思路:

求最小生成树。。。注意测试数据里有重边。。。

AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>
#define INF 0xfffffff
using namespace std;

const int N = 1005;
const int M = 10005;
int n,m;
int edge[N][N];
int vis[N];
int dis[N];

void build(){
    memset(vis,0,sizeof(vis));
    for(int i = 0; i < n; i++){
        edge[i][i] = 0;
        for(int j = 0; j < i; j++)
            edge[i][j] = edge[j][i] = INF;
    }
    for(int i =0; i < m; i++){
        int x,y,z;
        scanf("%d%d%d",&x,&y,&z);
        edge[x][y] = edge[y][x] = min(edge[x][y],z);
    }
}

void prime(int cur)
{
    int i, j, tmp;
    int sum = 0;
    memset(vis, 0, sizeof(vis));
    vis[cur] = 1;
    for(i = 0; i < n; i++)
        dis[i] = edge[cur][i];
    for(i = 1; i < n; i++)
    {
        int Min = INF,tmp = -1;
        for(j = 0; j < n; j++)
        {
            if(!vis[j] && dis[j] < Min)
                Min = dis[tmp = j];
        }
        if(tmp == -1){
            printf("impossible\n");
            return ;
        }
        vis[tmp] = 1;
        sum += Min;
        for(j = 0; j < n; j++)
        {
            if(!vis[j] && dis[j] > edge[tmp][j])
                dis[j] = edge[tmp][j];
        }
    }
    printf("%d\n",sum);
}

int main(){
    while(~scanf("%d%d",&n,&m)){
        build();
        prime(0);
        printf("\n");
    }
    return 0;
}



你可能感兴趣的:(最小生成树)