带权值的并查集及二分图的应用

例题1: 关押罪犯

做法1:二分 + 染色法判断二分图

思路:二分最大的影响力值,根据该值对图进行染色,判断是否可以构成二分图,如果可以构成二分图说明这种划分是可行的,否则说明不可行。

#include <iostream>
#include <algorithm>
#include <cstring>

using namespace std;

const int N = 20010, M = 200010;

int h[N], e[M], ne[M], w[M], idx; 
int color[N], n, m, l, r;

void add(int a, int b, int c)
{
	w[idx] = c;
	e[idx] = b;
	ne[idx] = h[a];
	h[a] = idx ++ ;	
} 

bool bfs(int u, int c, int v)
{
	color[u] = c;
	for(int i = h[u]; i != -1; i = ne[i])
	{
		if(w[i] > v)
		{
			int j = e[i];
			if(!color[j])	//这里一定要加括号!!! 
			{
				if(!bfs(j, 3 - c, v))	return false;
			}
			else if(color[j] == c)	return false;
		}
	}
	return true;
}

bool check(int v)
{
	memset(color, 0, sizeof color);
	for(int i = 1; i <= n; i ++ )
	{
		if(!color[i])
			if(!bfs(i, 1, v))
				return false;
	}
	return true;
}

int main()
{
	memset(h, -1, sizeof h);
	cin >> n >> m;
	while(m -- )
	{
		int a, b, c;
		cin >> a >> b >> c;
		add(a, b, c);
		add(b, a, c);
		r = max(r, c);
	}
	while(l < r)
	{
		int mid = l + r >> 1;
		if(check(mid))	r = mid;
		else	l = mid + 1;
	}
	
	cout << l << endl;
	
	return 0;
}

 做法2:并查集

思路:域并查集。将两个监狱划分成并查集的两个区间,每次贪心你的把怒气值最大的囚犯分到这两个域当中,如果发生冲突(这两个囚犯的根属于同一个监狱),说明此时发生冲突,该怒气值就是最大影响力。

#include <iostream>
#include <algorithm>
#include <cstring>

using namespace std;

const int N = 20010, M = 100010;

int n, m, res, pre[N << 1];

struct node
{
	int l, r, w;
}g[M];

bool cmp(const node &x, const node &y)
{
	return x.w > y.w;
}

int get(int x)
{
	if(pre[x] ==
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值