Recently, Pari and Arya did some research about NP-Hard problems and they found the minimum vertex cover problem very interesting.
Suppose the graph G is given. Subset A of its vertices is called a vertex cover of this graph, if for each edge uv there is at least one endpoint of it in this set, i.e. or (or both).
Pari and Arya have won a great undirected graph as an award in a team contest. Now they have to split it in two parts, but both of them want their parts of the graph to be a vertex cover.
They have agreed to give you their graph and you need to find two disjoint subsets of its vertices A and B, such that both A and B are vertex cover or claim it's impossible. Each vertex should be given to no more than one of the friends (or you can even keep it for yourself).
Input
The first line of the input contains two integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 100 000) — the number of vertices and the number of edges in the prize graph, respectively.
Each of the next m lines contains a pair of integers ui and vi (1 ≤ ui, vi ≤ n), denoting an undirected edge between ui and vi. It's guaranteed the graph won't contain any self-loops or multiple edges.
Output
If it's impossible to split the graph between Pari and Arya as they expect, print "-1" (without quotes).
If there are two disjoint sets of vertices, such that both sets are vertex cover, print their descriptions. Each description must contain two lines. The first line contains a single integer k denoting the number of vertices in that vertex cover, and the second line contains k integers — the indices of vertices. Note that because of m ≥ 1, vertex cover cannot be empty.
Examples
4 2
1 2
2 3
1
2
2
1 3
3 3
1 2
2 3
1 3
-1
题意:N点M边,能不能分为两个没有公共点的点集,二者都覆盖所有的边。
思路:因为每条边只有两个端点,所以两端点必须分到不同的集合,所以就说二分图判定,先判定完,然后dfs染色即可。
这里用到了带权的并查集优化了一下。
#include<bits/stdc++.h>
#define rep(i,a,b) for(int i=a;i<=b;i++)
using namespace std;
const int maxn=;
int fa[maxn],vis[maxn],u[maxn],v[maxn],dis[maxn];
vector<int>G[maxn],a,b;
int find(int x){
if(x!=fa[x]){
int fx=find(fa[x]);
dis[x]^=dis[fa[x]];
//因为这里有压缩路径,所以是x到根距离与fax到根的距离差
fa[x]=fx;
}
return fa[x];
}
int Union(int x,int y){
int fx=find(x),fy=find(y);
if(fx==fy){
if(dis[x]==dis[y]) return false;
return true;
}
fa[fx]=fy; dis[fx]=dis[x]^dis[y]^;
return true;
}
void dfs(int x,int op){
vis[x]=;
if(op==) a.push_back(x); else b.push_back(x);
rep(i,,G[x].size()-) if(!vis[G[x][i]]) dfs(G[x][i],-op);
}
int main()
{
int N,M;
scanf("%d%d",&N,&M);
rep(i,,N) fa[i]=i;
rep(i,,M) {
scanf("%d%d",&u[i],&v[i]);
G[u[i]].push_back(v[i]);
G[v[i]].push_back(u[i]);
if(!Union(u[i],v[i])) return puts("-1"),;
}
rep(i,,N){ if(!vis[i]&&G[i].size()) dfs(i,);}
printf("%d\n",a.size());
rep(i,,a.size()-) printf("%d ",a[i]); puts("");
printf("%d\n",b.size());
rep(i,,b.size()-) printf("%d ",b[i]); puts("");
return ;
}