kuangbin带你飞——专题六 最小生成树(5)
题目来源:ZOJ 1586 QS Network
VJ 不能提交,下面给出 ZOJ 该题网站
题解
经典最小生成树题型。Kruskal 算法:
题目意思是,如果有两个节点要连接,则需要购买两个适配器和一条网线。适配器只能绑定一条网线,如果该节点仍然需要再连接一条网线,需要再购买适配器。
题目的边权值是两个节点的之和加上边权。
先讲各边从矩阵中提取出,再存边,在按照边权值排序,在排序后依次选择边,如果这条边连接的点没有加入最小生成树,则加入,否则不加入。
AC代码
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <vector>
using namespace std;
const int maxn = 105;
// 存图
struct edge
{
int u, v;
int w;
edge(int x, int y, int z) : u(x), v(y), w(z) {}
bool operator<(const edge &B) const
{
return w < B.w;
}
};
// 并查集维护连通性
int fa[maxn];
void init()
{
for (int i = 1; i < maxn; ++i)
fa[i] = i;
}
int find(int x)
{
if (fa[x] == x)
return x;
fa[x] = find(fa[x]);
return fa[x];
}
void unin(int x, int y)
{
fa[find(x)] = find(y);
}
int main()
{
int n;
scanf("%d", &n);
vector<edge> G;
for (int i = 1; i <= n; ++i)
{
for (int j = 1; j <= n; ++j)
{
int w;
scanf("%d", &w);
// 可以按照顺序存图
if (j > i)
G.push_back(edge(i, j, w));
}
}
init();
int m, ans = 0;
scanf("%d", &m);
for (int i = 1; i <= m; ++i)
{
int u, v;
scanf("%d%d", &u, &v);
unin(u, v);
}
// 排序
sort(G.begin(), G.end());
// 遍历
vector<edge>::iterator it;
for (it = G.begin(); it != G.end(); ++it)
{
int u = it->u, v = it->v;
if (find(u) != find(v))
{
ans += it->w;
unin(u, v);
}
}
printf("%d", ans);
return 0;
}