概念
就是顶点集V可分割为两个互不相交的子集,并且图中每条边依附的两个顶点都分属于这两个互不相交的子集,两个子集内的顶点不相邻。
从其中一个点开始判断,将跟它相连的点染成和它不同的颜色,如果最后相连的点有相同的颜色,则不是二分图。
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <sstream>
#include <cstdio>
#include <vector>
#include <string>
#include <cmath>
#include <stack>
#include <queue>
#include <map>
#include <set>
#define MAX 0x3f3f3f3f
#define fori(a,b) for(int i=a;i<=b;i++)
#define forj(a,b) for(int j=a;j<=b;j++)
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
typedef long long LL;
const double PI = acos(-1);
int ch[2222][2222];
int judge[2222];
int flag;
queue<int>q;
int _fs(int now,int n){
judge[now]=1;
q.push(now);
while(!q.empty()){
int f=q.front();
q.pop();
fori(1,n){
if(ch[f][i]&&judge[i]==-1){
judge[i]=!judge[f];
q.push(i);
}
if(ch[f][i]&&judge[f]==judge[i]){
flag=0; //两点相连且颜色相同时,不时二分图
return 0;
}
}
}
return 1;
}
int main()
{
int t,n,m,a,b;
cin >> t;
fori(1,t){
while(!q.empty())
q.pop();
scanf("%d%d",&n,&m);
flag=1;
mem(ch,0);
forj(1,n)
judge[j]=-1;
while(m--){
scanf("%d%d",&a,&b);
ch[a][b]=ch[b][a]=1;
}
forj(1,n){
if(judge[j]==-1&&!_fs(j,n)){
flag=0;
break;
}
}
}
if(flag)
cout << "No" <<endl;
else
cout << "Yes" << endl;
}
return 0;
}