papamelon 242. 二分图判定(挑战程序设计竞赛)

地址 https://www.papamelon.com/problem/242

解答
如果图中没有出现奇数环,就不会出现涂色冲突.

我们使用DFS依次遍历图中的点将其更迭的染成1或者2类颜色,最后看所有点是否会有冲突,即可判断是不是二分图。

#include <iostream>
#include <vector>
#include <memory.h>


using  namespace std;

const int N = 1010;

vector<int> gra[N];
int color[N];
int n;


bool  dfs(int curr, int fill) {
	//已经涂色 有冲突
	if (color[curr] != 0 && color[curr] != fill) return false;
	//已经涂色 且无冲突
	if (color[curr] == fill) return true;

	//涂色
	color[curr] = fill;

	for (int i = 0; i < gra[curr].size(); i++) {
		int next = gra[curr][i];
		//换个颜色 涂色下一个点
		if (false == dfs(next, 3 - fill)) return false;
	}


	return true;
}

int main()
{
	scanf("%d", &n);
		memset(color, 0, sizeof color);
		for (int i = 0; i < N; i++) { gra[i].clear(); }
		
		for (int i = 0; i < n; i++) {
			int a, b; scanf("%d%d",&a,&b);
			gra[a].push_back(b);
			gra[b].push_back(a);
		}
		int flag = 1;
		
		//逐个的更换颜色  dfs 涂色每个点
		//考虑到可能不是连通,每个点都要作为dfs起点检测
		for (int i = 0; i < n; i++) {
			if ( false == dfs(i, 1)) {
				flag = 0; break;
			}
		}

		if (flag == 1) {
			printf("Yes\n");
		}
		else {
			printf("No\n");
		}
	


	return 0;
}

我的视频题解空间

posted on 2022-06-05 21:59  itdef  阅读(47)  评论(0编辑  收藏  举报

导航