题意:给定n个顶点和m条边的无向图,求能否构成二分图,若能,输出两个顶点集,否则输出 -1
对某个顶点,对于有边与它相连的其他点,染成与它不同的颜色,然后再研究这些点,继续染与它们有关系的点,直到所有有边相连的点都被染色完毕。
不能构成:若要染的顶点之前已经被染成同样的颜色,则不能构成二分图。
孤立顶点不作研究。
#include<cstdio>
#include<cstring>
#include<cctype>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<sstream>
#include<iterator>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<deque>
#include<queue>
#include<stack>
#include<list>
typedef long long ll;
typedef unsigned long long llu;
const int MAXN = 100 + 10;
const int MAXT = 100000 + 10;
const int INF = 0x7f7f7f7f;
const double pi = acos(-1.0);
const double EPS = 1e-6;
using namespace std;
int n, m, vis[MAXT];
vector<int> e[MAXT];
bool dfs(int lur, int t){
int len = e[lur].size();
if(!len) return true;
vis[lur] = t;
for(int i = 0; i < len; ++i){
int &tmp = e[lur][i];
if(vis[tmp] == -t) continue;
else if(vis[tmp] == t) return false;
if(!dfs(tmp, -t)) return false;
}
return true;
}
int main(){
memset(vis, 0, sizeof vis);
scanf("%d%d", &n, &m);
int a, b;
for(int i = 0; i < m; ++i){
scanf("%d%d", &a, &b);
e[a].push_back(b); e[b].push_back(a);
}
bool flag = true;
for(int i = 1; i <= n; ++i){
if(vis[i]) continue;
if(!e[i].size()){
vis[i] = 2;
continue;
}
if(!dfs(i, 1)){
flag = false;
break;
}
}
if(!flag) printf("-1\n");
else{
e[0].clear(); e[1].clear();
for(int i = 1; i <= n; ++i)
if(vis[i] == 1) e[0].push_back(i);
else if(vis[i] == -1) e[1].push_back(i);
a = e[0].size();
printf("%d\n", a);
for(int i = 0; i < a; ++i){
if(i) printf(" ");
printf("%d", e[0][i]);
}
a = e[1].size();
printf("\n%d\n", a);
for(int i = 0; i < a; ++i){
if(i) printf(" ");
printf("%d", e[1][i]);
}
printf("\n");
}
return 0;
}