Portals G【并查集】

>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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值