二分图判定 代码源初级

// 1001 二分图判定.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

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

using namespace std;
/*
http://oj.daimayuan.top/course/14/problem/797

给你一张简单无向图,你需要判断这张图是否为二分图。

图用以下形式给出:

第一行输入两个整数 n,m,表示图的顶点数和边数,顶点编号从 1到 n。

接下来 m行,每行两个整数 x,y,表示 x和 y之间有一条边。

输出一个字符串 Yes 或者 No,Yes 表示是二分图。

输入格式
第一行两个整数 n,m。

接下来 m行,每行有两个整数,代表一条边。

输出格式
输出一个字符串表示答案。

样例输入
4 4
1 2
2 3
3 4
1 4
样例输出
Yes
数据规模
对于所有数据,保证 2≤n≤1000,0≤m≤10000,1≤x,y≤n,x≠y。
*/
#include <iostream>
#include <cstring>

using namespace std;


const int N = 100010,M=200010;
int h[N], e[M], ne[M], idx;
int n, m;
int color[N]; int cnt;

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


bool dfs(int p, int c) {
	if (color[p] != 0 && color[p] != c) return false;
	if (color[p] == c) return true;

	color[p] = c; cnt++;
	for (int i = h[p]; i != -1; i = ne[i]) {
		int j = e[i];
		if ( !dfs(j, 3 - c)) {
			return false;
		}
	}

	return true;
}


int main()
{
	cin >> n >> m;
	memset(h, -1, sizeof h);
	for (int i = 0; i < m; i++) {
		int a, b; cin >> a >> b;
		add(a, b); add(b, a);
	}

	for (int i = 1; i <= n; i++) {
		if (color[i] == 0) {
			if (!dfs(i, 1)) {
				cout << "No" << endl;
				return 0;
			}
		}
	}

	if (cnt == n) {
		cout << "Yes" << endl;
	}
	else {
		cout << "No" << endl;
	}
	return 0;
}

posted on 2024-08-12 14:47  itdef  阅读(2)  评论(0编辑  收藏  举报

导航