>Link
luogu P7528
>Description
>解题思路
求使每一条边相连通的最小哞尼值
认真想一想,就会发现初始情况,本来就相连通的边会形成一个个环(一个点只有两条边,如果一条进就一定是另一条出…)
所以我们现在就是要把每个环连起来
连起来的时候就是交换一下一个点两条不对应的边,这样就是原来环中一条边被删去,然后连出一条边到另一个环中,因为一个点最多这样改变一次,且集合是个环,所以删掉边的那个点依然在集合里
用并查集维护下同一集合就行了
>代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define N 400010
#define LL long long
using namespace std;
struct node
{
int p[5], c;
} a[N];
int n, fa[N];
LL ans;
bool vis[N];
bool cmp (node aa, node bb) {return aa.c < bb.c;}
int find (int x)
{
if (fa[x] == x) return x;
return fa[x] = find (fa[x]);
}
int main()
{
int x, y;
scanf ("%d", &n);
for (int i = 1; i <= 2 * n; i++) fa[i] = i;
for (int i = 1; i <= n; i++)
{
scanf ("%d", &a[i].c);
for (int j = 1; j <= 4; j++)
scanf ("%d", &a[i].p[j]);
x = find (a[i].p[1]), y = find (a[i].p[2]);
if (x < y) fa[y] = x;
else fa[x] = y;
x = find (a[i].p[3]), y = find (a[i].p[4]);
if (x < y) fa[y] = x;
else fa[x] = y;
}
sort (a + 1, a + 1 + n, cmp);
for (int t = 1; t <= n; t++)
{
x = find (a[t].p[1]), y = find (a[t].p[3]);
if (x == y) continue;
if (x < y) fa[y] = x;
else fa[x] = y;
ans += a[t].c;
}
printf ("%lld", ans);
return 0;
}