题目传送门(POJ-1251)
题目传送门(HDU-1301)
题意:
给出N个节点,以及每个节点相连的节点及权值,求最小生成树。
例如 A 2 B 12 I 25
表示 与A节点相连的有两个节点
B 权值 12
I 权值 25
思路:
节点字符映射为1-26,用邻接矩阵建图,prim求最小生成树
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <queue>
#include <map>
#include <set>
using namespace std;
int mp[30][30], N;
const int inf = 0x3f3f3f3f;
void init()
{
for (int i = 0; i < 30; i++)
for (int j = 0; j < 30; j++)
mp[i][j] = inf;
return ;
}
void prim(int x)
{
int book[30], dis[30], ans;
memset(book, 0, sizeof(book));
for (int i = 1; i <= N; i++)
dis[i] = mp[x][i];
book[x] = 1;
ans = 0;
for (int i = 1; i < N; i++)
{
int mi = inf, f = -1;
for (int j = 1; j <= N; j++)
{
if (!book[j] && dis[j]<mi)
{
mi = dis[j];
f = j;
}
}
if (f==-1)
{
printf("-1\n");
return;
}
ans += mi;
book[f] = 1;
for (int j = 1; j <= N; j++)
{
if (!book[j] && mp[f][j]<dis[j])
{
dis[j] = mp[f][j];
}
}
}
printf("%d\n", ans);
return ;
}
int main(void)
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
while (~scanf("%d", &N))
{
init();
if (N == 0)
break;
for (int i = 1; i < N; i++)
{
char ch[3];
int x, dis, m;
scanf(" %s %d", ch, &m);
x = ch[0]-'A'+1;
while (m--)
{
scanf(" %s %d", ch, &dis);
if (mp[x][ch[0]-'A'+1] > dis)
{
mp[x][ch[0]-'A'+1] = dis;
mp[ch[0]-'A'+1][x] = dis;
}
}
}
prim(1);
}
return 0;
}