#include <iostream>
#include <algorithm>
using std::cout;
using std::cin;
using std::sort;
#define MAX_CITY 100
//#define __DEBUG__
int rank[MAX_CITY];
int parent[MAX_CITY];
int isum = 0;
bool bConnectFlag = false;
void make_set(int x)
{//初始化集合,使得每个节点为一个集合
rank[x] = 0;
parent[x] = x;
}
void link(int x, int y);
int find_set_parent(int ipar);
void union_set(int x, int y)
{//合并节点,根据X,Y所在结合的秩,秩小的指向秩大的根节点
#ifdef __DEBUG__
x = find_set_parent(x); y = find_set_parent(y);
link(x, y);
#else
link(find_set_parent(x), find_set_parent(y));
#endif
}
int find_set_parent(int ipar)
{//路径压缩,使得ipar直接指向ipar的根节点
if (ipar != parent[ipar])
parent[ipar] = find_set_parent(parent[ipar]);//动态更新当前ipar的父亲节点指向根节点
return parent[ipar]; //递归到结束返回的是本和集合的根节点
}
void link(int x, int y)
{//连接根节点,使得秩大的指向秩小的
if (x != y){
bConnectFlag = true;
if (rank[x] > rank[y]){
parent[y] = x;
} else{
if (rank[x] == rank[y])
rank[y]++;
parent[x] = y;
}
}
}
struct Init{
int s, d;
int weight;
};
Init node[(MAX_CITY + 1) * MAX_CITY / 2 + 1];
bool cmp(Init & e1, Init & e2)
{
return e1.weight < e2.weight;
}
void init(int n)
{
int node_iter = 0;
for (int i = 0; i < n; ++i){
make_set(i);
}
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j){
if (j > i){
node[node_iter].s = i;
node[node_iter].d = j;
cin >> node[node_iter++].weight;
}
else cin >> isum;
}
int iConnect = 0;
cin >> iConnect;
for (int i = 0; i < iConnect; ++i) {
int s, d;
cin >> s >> d;
s--; d--;
union_set(s, d);
}
sort(node, node + node_iter, cmp);
isum = 0;
for (int i = 0; i < node_iter; ++i)
{
bConnectFlag = false;
union_set(node[i].s, node[i].d);
if (bConnectFlag) isum += node[i].weight;
}
}
int main()
{
int n;
while (cin >> n){
init(n);
cout << isum << '\n';
}
return 0;
}HDU 1102
最新推荐文章于 2020-03-06 23:39:49 发布
本文探讨了并查集算法在解决图论问题中的应用,包括连通性判断、最小生成树构建和最大匹配等场景。通过实例演示算法实现过程,深入理解其在实际问题中的高效解决方案。
开发板推荐:天空星STM32F407VET6开发板
超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印
开发板推荐:天空星STM32F407VET6开发板
超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

359

被折叠的 条评论
为什么被折叠?



