IT民工
加油!

先将字母转换成数字,然后建图。建完图用堆优化的prim,写这道

题花了不少时间,居然写成了dij,搞混了。

/*Accepted    180K    0MS    C++    1594B    2012-07-27 15:57:47*/
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<queue>
#include<iostream>
using namespace std;

const int MAXN = 1 << 5;
const int inf = 0x3f3f3f3f;
bool vis[MAXN];
int g[MAXN][MAXN], n;

int pos( char c)
{
    return c - 'A';
}

void ReadGraph()
{
    for( int i = 0; i < n; i ++)
        for( int j = 0; j < n; j ++)
        {
            if( i != j)
                g[i][j] = inf;
            else
                g[i][j] = 0;
        }
    int m, val;
    char a[5], b[5];
    for( int i = 1; i <= n - 1; i ++)
    {
        scanf( "%s%d", a, &m);
        while( m --)
        {
            scanf( "%s%d", b, &val);
            g[pos(a[0])][pos(b[0])] = g[pos(b[0])][pos(a[0])] = val;
        }
    }
}

int prim()
{
    int ret = 0, lowc[MAXN] = {0};
    typedef pair<int, int> pii;
    memset( vis, false, sizeof vis);
    priority_queue< pii, vector<pii>, greater<pii> > q;
    for( int i = 1; i < n; i ++)
        lowc[i] = inf;
    q.push( make_pair(lowc[0], 0));
    while( !q.empty())
    {
        pii u = q.top();q.pop();
        int x = u.second;
        if(vis[x]) continue;
        ret += lowc[x];
        vis[x] = true;
        for( int i = 0; i < n; i ++)
        {
            if( !vis[i] && g[x][i] < lowc[i])
            {
                lowc[i] = g[x][i];
                q.push( make_pair(lowc[i], i));
            }
        }
    }
    return ret;
}

int main()
{
    while( scanf( "%d", &n), n)
    {
        ReadGraph();
        printf( "%d\n", prim());
    }
    return 0;
}

 

 

posted on 2012-07-27 16:02  找回失去的  阅读(111)  评论(0编辑  收藏  举报