二分图模板

二分图就是把一个图分成两块

一、模板

P3386 【模板】二分图最大匹配 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

#include<bits/stdc++.h>
using namespace std;

const int N = 5e2 + 10;
int G[N][N];
int match[N], reserve[N]; //匹配结果存在match[]中
int n, m;

//找一条增广路径,即给u中的x找一个匹配的v
bool dfs(int x){
	for(int i = 1; i <= m; i++){
		if(!reserve[i] && G[x][i]){
			//预定v中的i分配给x
			reserve[i] = 1;
			//(1)如果i还没有配对,就分配给x
			//(2)如果i已经配对,尝试用dfs更换i的原配,腾出位置给x
			if(!match[i] || dfs(match[i])){
				//配对成功则变换,i现在属于x
				match[i] = x;
				return true;
			}
		}
	}
	return false;
}

int main() {
	int e; cin >> n >> m >> e;
	//矩阵存图
	while(e--){
		int a, b; cin >> a >> b;
		G[a][b] = 1;
	}
	int sum = 0;
	for(int i = 1; i <= n; i++){
		memset(reserve, 0, sizeof reserve);
		if(dfs(i)) sum++;
	}
	cout << sum << '\n';
}

二、应用

1.染色问题

Problem - 1093D - Codeforces

图中的点分为两部分,一部分染奇数的点,即1,3,数量为cnt,另一部分染偶数的点,即2,数量为cnt2。所以答案为ans = ans * ((qpow(2, cnt) + qpow(2, cnt2)) % mod) % mod;

#include<bits/stdc++.h>
using namespace std;
#define qio ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
typedef long long ll;
typedef double db;
#define int ll
const int N = 3e5 + 10;
const int mod = 998244353;
vector<int> g[N];
int col[N], vis[N];
ll ans;

ll qpow(int x, int y){
	ll res = 1;
	while(y){
		if(y & 1) res = (res * x) % mod;
		y >>= 1;
		x = x * x % mod;
	}
	return res;
}

void bfs(int st){
	if(vis[st]) return;
	col[st] = 1;
	int cnt = 0, cnt2 = 0;
	queue<int> q;
	q.push(st);
	while(q.size()){
		int x = q.front(); q.pop();
		if(vis[x]) continue;
		vis[x] = 1;
		if(col[x] == 1)cnt++;
		if(col[x] == 0)cnt2++;
		for(auto &y : g[x]){
			if(vis[y] && (col[x] ^ col[y]) == 0){
				ans = 0;
				return;
			}else if(vis[y]){
				continue;
			}else{
				col[y] = col[x] ^ 1;
				q.push(y);
				
			}
		}
	}
//	for(int i = 1; i <= 10; i++) cout << col[i] << ' ';
//	cout << '\n';
//	cout << cnt << ' ' << cnt2 << '\n';
	ans = ans * ((qpow(2, cnt) + qpow(2, cnt2)) % mod) % mod;	
}

void solve() {
	int n, m; cin >> n >> m;
	for(int i = 1; i <= n; i++){
		g[i].clear();
		col[i] = 0;
		vis[i] = 0;
	} 
	ans = 1;
	for(int i = 1; i <= m; i++){
		int u, v; cin >> u >> v;
		g[u].push_back(v);
		g[v].push_back(u);
	}
	for(int i = 1; i <= n; i++){
		bfs(i);
	}
	cout << ans << '\n';
}

signed main() {
	qio
	int T = 1;
	cin >> T;
	while (T--)solve();
}

2.数论

想不起来了,还是挂个题解吧

Problem - 1220D - Codeforces

CF1220D Alex and Julian - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值