二分图判定+贪心
对每个联通块内的黑白点数进行统计,将个数较多的累加到ans1中
需特判两个情况:
1、点数 < 2,此时一定无法分成点数均 >= 1的两组
2、没有边,此刻若按上述方法贪心,会出现第二组个数为零的情况
也就是说m == 0和ans2 == 0只需要判一个就好了
#include<iostream>
#include<cstdio>
#include<queue>
#include<algorithm>
using namespace std;
const int MAXN = 200000 + 50;
struct edge{
int f,t;
}l[MAXN << 1];
int n,m,head[MAXN],nxt[MAXN << 1],tot,cnt1,cnt2,ans1,ans2;
queue <int> q;
bool flag;
int col[MAXN];
void init(int n){
tot = 0;
flag = false;
cnt1 = cnt2 = 0;
ans1 = ans2 = 0;
while(!q.empty())q.pop();
for(int i = 1;i <= n;i ++)
head[i] = col[i] = -1;
}
int a,b;
void build(int f,int t){
l[++ tot].f = f;
l[tot].t = t;
nxt[tot] = head[f];
head[f] = tot;
}
void bfs(int x){
col[x] = true;
cnt1 ++;
q.push(x);
while(!q.empty()){
int u = q.front();
q.pop();
for(int i = head[u];i != -1;i = nxt[i]){
int t = l[i].t;
if(col[t] == -1){
col[t] = !col[u];
q.push(t);
if(col[t])cnt1 ++;
else cnt2 ++;
}
else if(col[t] == col[u]){
flag = true;
return;
}
}
}
if(cnt1 < cnt2)swap(cnt1,cnt2);
ans1 += cnt1;
ans2 += cnt2;
}
int T;
int main(){
scanf("%d",&T);
while(T --){
scanf("%d%d",&n,&m);
init(n);
if(n < 2){
printf("Poor wyh\n");
continue;
}
for(int i = 1;i <= m;i ++){
scanf("%d%d",&a,&b);
build(a,b);
build(b,a);
}
/*if(!m){
printf("%d %d\n",n - 1,1);
continue;
}*/
for(int i = 1;i <= n;i ++){
cnt1 = cnt2 = 0;
if(col[i] == -1)bfs(i);
if(flag == true)break;
}
if(flag){
printf("Poor wyh\n");
continue;
}
if(!ans2)ans2 ++,ans1 --;
printf("%d %d\n",ans1,ans2);
}
return 0;
}