#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int n, q, a , b, temp, pos, cnt, ans;
struct node
{
int op;
int ed;
int len;
bool operator < (const node Next) const
{
return len < Next.len;
}
} edge[10005];
int root[105];
int Find(int x)
{
return root[x] == x ? x : root[x] = Find(root[x]);
}
void Kruskal()
{
ans = 0;
for(int i = 0; i < pos; i ++)
{
int x = Find(edge[i].op);
int y = Find(edge[i].ed);
if(x != y)
{
root[y] = x;
ans += edge[i].len;
cnt ++;
}
if(cnt == n - 1)
break;
}
}
int main()
{
while(~scanf("%d", & n))
{
pos = 0;
for(int i = 1; i <= n; i ++)
{
for(int j = 1; j <= n; j ++)
{
scanf("%d", & temp);
if(!temp)
continue;
edge[pos].len = temp;
edge[pos].op = i;
edge[pos].ed = j;
pos ++;
}
}
for(int i = 1; i <= n; i ++)
root[i] = i;
sort(edge, edge + pos);
scanf("%d", & q);
cnt = 0;
while(q --)
{
scanf("%d %d", & a, & b);
int x = Find(a);
int y = Find(b);
if(x != y)
{
root[y] = x;
cnt ++;
}
}
Kruskal();
printf("%d\n", ans);
}
return 0;
}
题意:
输入n。之后n行分别输入n个数。第i行第j列代表i城镇到j城镇的距离。之后输入q。之后q行分别输入a b。表示a城镇与b城镇已连通,不需要建设道路。
题解:
Kruskal继续。把a b先处理连接就好。