题目大意,求最小生成树
思路,kruskal算法,因为n小,暴力找到最小边即可,复杂度o(n^3)。判断是不是在一个图的时候用了并查集!刚开始没过,改成64位过了。在练并查集,kruskal的复杂度什么的就不管了………………
#include <cstdio>
#include <string>
#include <cstring>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <iomanip>
#include <iostream>
#include <sstream>
using namespace std;
#define maxn 1003
#define MOD 1000000007
#define mem(a , b) memset(a , b , sizeof(a))
#define LL __int64
int n , m;
int fa[maxn];
LL dis[27][27];
int findfa(int n)
{
if(fa[n] != n) fa[n] = findfa(fa[n]);
return fa[n];
}
int main()
{
while(scanf("%d" , &n) && n != 0)
{
for(int i = 0 ; i <= n ; i ++) fa[i] = i;
for(int i = 0 ; i < n ; i ++)
for(int j = 0 ; j < n ; j ++)
dis[i][j] = 99999999;
char tmp[1];
LL len , ans = 0 , minn;
for(int i = 0 ; i < n - 1 ; i ++)
{
scanf("%s %d" , tmp , &m);
int start = tmp[0] - 'A';
for(int i = 0 ; i < m ; i ++)
{
scanf("%s %I64d" , tmp , &len);
dis[start][tmp[0]-'A'] = min(dis[start][tmp[0]-'A'] , len);
dis[tmp[0]-'A'][start] = min(dis[tmp[0]-'A'][start] , len);
}
}
for(int i = 0 ; i < n - 1; i ++)
{
int sa = 0 , sb = 0;
minn = 99999999;
for(int j = 0 ; j < n ; j ++)
{
for(int k = 0 ; k < n ;k ++)
{
if(dis[j][k] < 99999999)
{
int a = findfa(j);
int b = findfa(k);
if(a != b)
{
if(minn > dis[j][k])
{
minn = dis[j][k];
sa = a ;
sb = b;
}
}
}
}
}
if(minn != 99999999)
{
ans += minn;
fa[sb] = sa;
}
}
printf("%I64d\n" , ans);
}
return 0;
}