二分图——相关习题

//待补的一篇博客

(1)二分图染色问题:https://codeforces.com/problemset/problem/688/C

#include 
using namespace std;

const int max_n = 1e5 + 5;

int color[max_n];
vector G[max_n];
vector ans[2];

bool dfs(int now, int Color)
{
	color[now] = Color;
	ans[Color].push_back(now);

	for (int i = 0; i < G[now].size(); i++)
	{
		if (color[now] == color[G[now][i]])
			return false;
		else if (color[G[now][i]] == -1 && !dfs(G[now][i], !Color))
			return false;
	}
	return true;
}

int main()
{
	int T = 1;
	//scanf("%d", &T);
	while (T--)
	{
		int n, m, st;
		scanf("%d%d", &n, &m);
		for (int i = 1; i <= n; i++)
			color[i] = -1;
		for (int i = 0; i < m; i++)
		{
			int u, v;
			scanf("%d%d", &u, &v);
			G[u].push_back(v);
			G[v].push_back(u);
		}
		bool flag = 1;
		for (int i = 1; i <= n; i++)
			if (color[i] == -1)
				if (dfs(i, 0) == 0)
					flag = 0;

		if (flag == 0)
			printf("-1");
		else
		{
			printf("%d\n", ans[0].size());
			for (int i = 0; i < ans[0].size(); i++)
				printf("%d ", ans[0][i]);

			printf("\n%d\n", ans[1].size());
			for (int i = 0; i < ans[1].size(); i++)
				printf("%d ", ans[1][i]);
		}
	}
	return 0;
}

 

你可能感兴趣的:(二分图——相关习题)