OpenJ_Bailian - 1751
OpenJ_Bailian - 1751
题解:最小生成树问题,Kruskal算法
已经帮你建好的边就不用再建了,直接合并,当然我们这一题需要将给的坐标转化成边的,然后我们如何输出建哪几条路呢?我们知道我们合并的时候其实就是建路的过程,所有我们可以修改一下merge函数,增加一维参数op,代表是否输出从哪到哪建路
#include <bits/stdc++.h>
#define Zeoy std::ios::sync_with_stdio(false), std::cin.tie(0), std::cout.tie(0)
#define all(x) (x).begin(), (x).end()
#define endl '\n'
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1e9 + 7;
const double eps = 1e-9;
const int N = 1000;
int n, m, tot; //tot表示边数
int fa[N];
void init()
{
for (int i = 1; i <= n; ++i)
fa[i] = i;
}
int find(int x)
{
return x == fa[x] ? x : fa[x] = find(fa[x]);
}
void merge(int x, int y, int op) //op代表输出从哪到哪建路
{
int fx = find(x);
int fy = find(y);
if (fx != fy)
{
fa[fx] = fy;
if (op)
cout << x << " " << y << endl;
}
}
struct node
{
int u, v;
double w;
bool operator<(const node &t) const
{
return w < t.w;
}
} edge[N * N];
pii a[N];
int main(void)
{
Zeoy;
int t = 1;
// cin >> t;
while (t--)
{
cin >> n;
init();
for (int i = 1; i <= n; ++i)
{
cin >> a[i].first >> a[i].second;
}
cin >> m;
for (int i = 1, u, v; i <= m; ++i)
{
cin >> u >> v;
merge(u, v, 0); //已经建好的路直接合并就好了
}
tot = 1;
for (int i = 1; i <= n; ++i)
{
for (int j = 1; j <= n; ++j)
{
if (j != i)
{
double w = sqrt((a[i].first - a[j].first) * (a[i].first - a[j].first) + (a[i].second - a[j].second) * (a[i].second - a[j].second));
edge[tot].u = i;
edge[tot].v = j;
edge[tot].w = w;
tot++;
}
}
}
tot--;
sort(edge + 1, edge + tot + 1); //kruskal生成最小生成树
for (int i = 1; i <= tot; ++i)
{
int u = edge[i].u;
int v = edge[i].v;
int fx = find(u);
int fy = find(v);
if (fx != fy)
{
merge(u, v, 1);
}
}
}
return 0;
}