感动,我终于写染色的图论题了

感谢洛谷的随机跳题
[封锁阳光大学][1]
[1]: https://www.luogu.org/problemnew/show/1330
(因为河蟹不好听,下文叫它乌龟)
两只乌龟不能相邻,就相当于

相邻的两点颜色不同

进行染色即可

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
inline void in(int &p,char c=getchar())
{
	while(c<'0' or c>'9')
		c=getchar();
	p=0;
	while(c>='0' and c<='9')
		p=(p<<3)+(p<<1)+c-'0',c=getchar();
}
int head[1000001],k,n,m,color[1000001],ans1,ans2,ans;//ans1是颜色为1的点的数量,ans2是颜色为2的点的数量
struct edge
{
	int next;
	int to;
}e[1000001];
void add(int x,int y)
{
	k++;
	e[k].to=y;
	e[k].next=head[x];
	head[x]=k;
}
void dfs(int x,int se)
{
	if(color[x] and color[x]!=se)//染过色,并且染了的颜色和即将要染的不同,则impossible
	{
		cout<<"Impossible";
		exit(0);
	}
	if(color[x])//染过了,溜了溜了
		return ;
	if(se==1)
		ans1++;
	else
		ans2++;
	color[x]=se;
	for(int i=head[x];i;i=e[i].next)
		dfs(e[i].to,3-se);//3-1=2,3-2=1
}
int main()
{
	in(n);in(m);
	for(int i=0;i<m;i++)
	{
		int a,b;
		in(a);
		in(b);
		add(a,b);
		add(b,a);//无向图
	}
	for(int i=1;i<=n;i++)
		if(!color[i])
		{
			ans1=ans2=0;
			dfs(i,1);
			ans+=min(ans1,ans2);//题意要求的尽量少。
			//+=是因为图可能不联通,需要染多个图
		}
	if(!ans)//易得,符合题意就一定要有乌龟
		cout<<"Impossible";
	else
		cout<<ans;
	return 0;
}
原文地址:https://www.cnblogs.com/syhien/p/7722299.html