想必看这道题的时候直接看数据还有那个图就能明白什么意思吧,说的已经很清楚了,每个点都有一些相连的点和权值,求出来如果连接所有点,最小的权值是多少,赤裸裸的最小生成树。。。
************************************************************************************
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<vector>
using namespace std;
#define maxn 30
struct node
{
int v, len;
node(int v, int len):v(v),len(len){}
friend bool operator < (node a, node b){
return a.len > b.len;
}
};
vector<node> G[maxn];
int prim(int s)
{
int i, ans=0, use[maxn]={0}, M;
priority_queue<node> Q;
use[s] = 1;
for(i=0, M=G[s].size(); i<M; i++)
Q.push(G[s][i]);
while(Q.size())
{
node q = Q.top();Q.pop();
if(use[q.v] == 0)
{
for(i=0, M=G[q.v].size(); i<M; i++)
Q.push(G[q.v][i]);
use[q.v] = 1, ans += q.len;
}
}
for(i=0; i<maxn; i++)
G[i].clear();
return ans;
}
int main()
{
int N;
while(scanf("%d", &N) != EOF && N)
{
int i, u, v, len, M;
char s[10];
for(i=1; i<N; i++)
{
scanf("%s%d", s, &M);
u = s[0] - 'A';
while(M--)
{
scanf("%s%d", s, &len);
v = s[0] - 'A';
G[u].push_back(node(v, len));
G[v].push_back(node(u, len));
}
}
int ans = prim(u);
printf("%d ", ans);
}
return 0;
}
#include<cstring>
#include<cstdio>
#include<queue>
#include<vector>
using namespace std;
#define maxn 30
struct node
{
int v, len;
node(int v, int len):v(v),len(len){}
friend bool operator < (node a, node b){
return a.len > b.len;
}
};
vector<node> G[maxn];
int prim(int s)
{
int i, ans=0, use[maxn]={0}, M;
priority_queue<node> Q;
use[s] = 1;
for(i=0, M=G[s].size(); i<M; i++)
Q.push(G[s][i]);
while(Q.size())
{
node q = Q.top();Q.pop();
if(use[q.v] == 0)
{
for(i=0, M=G[q.v].size(); i<M; i++)
Q.push(G[q.v][i]);
use[q.v] = 1, ans += q.len;
}
}
for(i=0; i<maxn; i++)
G[i].clear();
return ans;
}
int main()
{
int N;
while(scanf("%d", &N) != EOF && N)
{
int i, u, v, len, M;
char s[10];
for(i=1; i<N; i++)
{
scanf("%s%d", s, &M);
u = s[0] - 'A';
while(M--)
{
scanf("%s%d", s, &len);
v = s[0] - 'A';
G[u].push_back(node(v, len));
G[v].push_back(node(u, len));
}
}
int ans = prim(u);
printf("%d ", ans);
}
return 0;
}