复习模板
poj 1251
【题目大意】 给出一张 n 个点(1 < n < 27)的无向连通图,边有边权,请求出此图的最小生成树。 【输入格式】 包含多组测试数据。
每组测试数据第一行包含一个整数 n,代表点的数量,点的编号为大写字母 A ~ Z。 接下来 n - 1
行,按顺序给出和每个点相连的边的信息。每行首先给出一个大写字母,代表当前点的编号(按顺序);随后给出一个整数 k
表示和该点相连的边的个数;写下来 k 组边的信息,每组信息包含一个大写字母,代表该边连接的另一个点,和一个正整数,代表该边的边权(边权不超过
100)。 当 n = 0时,停止输入。 【输出格式】 对于每组测试数据,输出一行表示该图最小生成树的边权和。
对于模板的掌握还是不够熟练,需要勤加练习
#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<vector>
#include<string>
#define INF 0x3f3f3f3f
typedef long long ll;
using namespace std;
const int maxn = 30;
int n;
int cnt;
int pre[maxn];
struct node{
int x,y,val;
}edge[105];
bool cmp(node a,node b){
return a.val < b.val;
}
void init(){
for(int i=0; i<27; i++)
pre[i] = i;
}
int find(int x){
int r = x;
while(r!=pre[r])
r = pre[r];
while(x!=r){
int t = pre[x];
pre[x] = r;
x = t;
}
return r;
}
void join(int a,int b){
pre[find(a)] = find(b);
}
void input(){
cnt = 0;
char a,b;
int val,t;
for(int i=0; i<n-1; i++){
cin >> a >> t;
while(t--){
cin >> b >> val;
edge[cnt].x = a - 'A';
edge[cnt].y = b - 'A';
edge[cnt++].val = val;
}
}
}
int Kruskal(){
sort(edge,edge+cnt,cmp);
int ans = 0;
int t = 0;
for(int i=0; i<cnt; i++){
if(t==n-1)
break; //已经连了n-1条线
if(find(edge[i].x) != find(edge[i].y)){
ans += edge[i].val;
join(edge[i].x,edge[i].y);
}
}
return ans;
}
int main(){
while(cin >> n && n){
init();
input();
cout << Kruskal() << endl;
}
return 0;
}