本题只是输入看起来比较复杂,细心一点处理好就可以了。
用三个一维数组代替二维数组存储边,降低时间复杂度。
#include<iostream>
#include<cstring>
using namespace std;
const int N = 30, NN = 80, INF = 99999999;
int c1[NN], c2[NN], c3[NN], f[N];//三个一维数组代替二位数组存储数据,降低时间复杂度
int find(int x)
{//寻找根节点
if (x == f[x]) return x;
f[x] = find(f[x]);
return f[x];
}
int mer(int x, int y)
{//将x和y所在的两个集合合并
x = find(x);
y = find(y);
if (x != y)
f[x] = y;
return 1;
}
int main()
{
int n, x, y, k, num, sum;
char xx, yy;
while (cin >> n && n)
{
num = 0;
sum = 0;
memset(c1, 0, sizeof(c1));
memset(c2, 0, sizeof(c2));
memset(c3, 0, sizeof(c3));
for (int i = 0; i <= N; i++)
f[i] = i;//顶点初始化
for (int i = 0; i < n - 1; i++)
{
cin >> xx >> k;
x = xx - 'A';
while (k--)
{
cin >> yy;
y = yy - 'A';
c1[num] = x;
c2[num] = y;
cin >> c3[num];
num++;
}
}//for
while (1)
{
int min0 = INF, flag = 1;
for(int i = 0; i < num; i++)
if (c3[i] < min0 && find(c1[i]) != find(c2[i]))
{
min0 = c3[i];
x = i;
flag = 0;
}
if (flag) break;
sum += min0;
mer(c1[x], c2[x]);
}
cout << sum << endl;
}
return 0;
}
来源:CSDN
作者:qq_44724908
链接:https://blog.csdn.net/qq_44724908/article/details/104188644