有四个点WA,原因都是读到了“Impossible”.
枚举每个点,看是否被访问过,如果没有就以这个点为起点进行BFS,统计使用的黑白子的数目,将较小的一方加到ans中。如在BFS中发现存在 (1=Black,2=White,0=Empty.不存在0==0,因为出边的父亲点一定被染过色了)相同的点,直接判Imp并结束程序。
#include <bits/stdc++.h>
using namespace std;
const int N=2e5+10;
int n,m,u[N],v[N],fi[N],ne[N],book[N],a[N],que[N],bla,whi,ans;
void add(int x,int y,int i)
{
u[i]=x,v[i]=y;
ne[i]=fi[x];
fi[x]=i;
}
int main()
{
int flag=0,tx;
cin>>n>>m;
for(int i=1; i<=n; i++) fi[i]=-1;
for(int i=1; i<=m; i++)
{
int x,y;
scanf("%d %d",&x,&y);
add(x,y,i);
i++,m++;
add(y,x,i);
}
for(int p=1; p<=n; p++)
{
if(book[p]==1 || fi[p]==-1) continue;
//BFS
int head=1,tail=2;
que[head]=p;
a[p]=1; //Black=1,White=2;
bla=1,whi=0;
while(head<tail)
{
int k=fi[que[head]];
while(k!=-1)
{
if(a[v[k]]==a[u[k]])
{
cout<<"Impossible";
return 0;
}
if(a[v[k]]!=0) break;
if(a[u[k]]==1)
{
a[v[k]]=2;
whi++;
}
else
{
a[v[k]]=1;
bla++;
}
que[tail++]=v[k];
k=ne[k];
}
book[que[head]]=1;
head++;
}
ans+=min(whi,bla);
}
cout<<ans;
return 0;
}
感激不尽!