您的位置:首页 > 其它

hdu 2122 Ice_cream’s world III

2015-08-12 15:28 357 查看
题目链接:

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

;
int vis
;
int dis
;

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: