0
点赞
收藏
分享

微信扫一扫

智能优化算法应用:基于象群算法3D无线传感器网络(WSN)覆盖优化 - 附代码

江南北 2023-12-16 阅读 39

图论——二分图

二分图通俗解释

在这里插入图片描述

性质

  • 二分图不含有奇数环
  • 图中没有奇数环,一定可以转换为二分图

判断二分图——染色法(dfs)

代码
#include <cstring>
#include <iostream>

using namespace std;

const int N = 1e5 + 10, M = 2e5 + 10;

// 链式前向星 
int h[N], e[M], ne[M], idx;

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

// 各个点的颜色,0 未染色,1 是红色,2 是黑色 
int color[N];

bool dfs(int u, int c) {
	color[u] = c;
	for (int i = h[u]; i != -1; i = ne[i]) {
		int j = e[i];
		if (!color[j]) {
			if (!dfs(j, 3 - c)) 
				return false;
		}
		else if (color[j] == c)	return false;
	}
	return true;
}

int main() {
	memset(h, -1, sizeof h);
	
	int n, m;
	cin >> n >> m;
	while (m --) {
		int a, b;
		cin >> a >> b;
		add(a, b);
		add(b, a);
	}
	
	bool flag = true;
	for (int i = 1; i <= n; i ++) {
		if (!color[i]) {
			if (!dfs(i, 1)) {
				flag = false;
				break;
			}
		}
	}
	if (flag)	puts("Yes");
	else	puts("No");
	return 0;
}

二分图的最大匹配——匈牙利算法(详细证明请见《算法导论》)

代码
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 510, M = 100010;

int h[N], e[M], ne[M], idx;

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

int match[N];
bool st[N];

bool find(int x) {
	for (int i = h[x]; i != -1; i = ne[i]) {
		int j = e[i];
		if (!st[j]) {
			st[j] = true;
			if (!match[j] || find(match[j])) {
				match[j] = x;
				return true;
			}
		}
	}
	return false;
}

int main() {
	memset(h, -1, sizeof h);
	int n1, n2, m;
	cin >> n1 >> n2 >> m;
	while (m --) {
		int a, b;
		cin >> a >> b;
		add(a, b);
	}
	int res = 0;
	for (int i = 1; i <= n1; i ++) {
		memset(st, 0, sizeof st);
		if (find(i))	res ++;
	}
	cout << res << endl;
	
	return 0;
}
举报

相关推荐

0 条评论