HDU 2122(最小生成树模板)

题目地址:点击打开链接

思路:模板题,注意重边和不能构成的情况即可

AC代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <cstring>
#include <climits>
#include <cmath>
#include <cctype>

typedef long long ll;
using namespace std;
const int zui = 1000000000;

int n,m;
int map1[1010][1010];
int lowdist[1010];
int visit[1010];
int sum;
bool flag;

void Prim()
{
    int i,j,k;
    sum = 0;
    memset(visit,0,sizeof(visit));
    for(i=0; i<=n-1; i++)
    {
        lowdist[i] = map1[0][i];
    }
    visit[0] = 1;
    for(i=1; i<n; i++)
    {
        int min1 = zui;
        k = -1;
        for(j=0; j<=n-1; j++)
        {
            if(!visit[j] && lowdist[j] < min1)
            {
                min1 = lowdist[j];
                k = j;
            }
        }
        if(k == -1)
        {
            flag = false;
            return;
        }
        visit[k] = 1;
        sum += lowdist[k];
        for(j=0; j<=n-1; j++)
        {
            if(!visit[j] && map1[k][j] < lowdist[j])
            {
                lowdist[j] = map1[k][j];
            }
        }
    }
}

int main()
{
    int i,j;
    while(scanf("%d%d",&n,&m) != EOF)
    {
        int a,b,c;
        for(i=0; i<=n-1; i++)
        {
            for(j=0; j<=n-1; j++)
            {
                map1[i][j] = zui;
            }
        }
        for(i=0; i<m; i++)
        {
            scanf("%d%d%d",&a,&b,&c);
            if(c < map1[a][b])//注意重边
            {
                map1[a][b] = map1[b][a] = c;
            }
        }
        flag = true;//注意这里刚开始是true
        Prim();
        if(flag)
        {
            printf("%d\n\n",sum);
        }
        else
        {
            printf("impossible\n\n");
        }
    }
    return 0;
}


你可能感兴趣的:(HDU 2122(最小生成树模板))