Nowadays, at least one wrestling match is held every year in our country. There are a lot of people in the game is “good player”, the rest is “bad player”. Now, Xiao Ming is referee of the wrestling match and he has a list of the matches in his hand. At the same time, he knows some people are good players,some are bad players. He believes that every game is a battle between the good and the bad player. Now he wants to know whether all the people can be divided into “good player” and “bad player”.
Input
Input contains multiple sets of data.For each set of data,there are four numbers in the first line:N (1 ≤ N≤ 1000)、M(1 ≤M ≤ 10000)、X,Y(X+Y≤N ),in order to show the number of players(numbered 1toN ),the number of matches,the number of known “good players” and the number of known “bad players”.In the next M lines,Each line has two numbersa, b(a≠b) ,said there is a game between a and b .The next line has X different numbers.Each number is known as a “good player” number.The last line contains Y different numbers.Each number represents a known “bad player” number.Data guarantees there will not be a player number is a good player and also a bad player.
Output
If all the people can be divided into “good players” and “bad players”, output “YES”, otherwise output “NO”.
Sample Input
5 4 0 0
1 3
1 4
3 5
4 5
5 4 1 0
1 3
1 4
3 5
4 5
2
Sample Output
NO
YES
题意:在n个人中进行比赛,然后给出m种两两对阵的情况,在一场对阵中,如果确定了一方是好人的话,另一方就是坏人,然后会给你一些已经确定了的好人的名单,和一些已经确定了的坏人的名单,问你能否把所有的人都分成好人或者坏人,当然一个人是不能同时是坏人,同时又是好人的
解题思路:color[i]记录的是第i个人的好坏情况,color[i]=0代表这个人没有被染色,如果color[i]=1代表这个人被染为好人,color[i]=-1代表这个人被染为坏人;
一开始的时候应该把所有color[i]初始化为-999,然后在把在对阵中的人的color[i]更新为0,在把已经确定了是好人的color[i]更新为1,把坏人更新为-1; 然后再根据已经被染色了的人进行后继的染色,一边染色一边判断是否和之前染色过的存在矛盾,若是矛盾的话,就说明不能符合题目; 要注意的是后继染色中,染的只是和题目给的已经确定了好坏的人的点有着直接或者间接对立关系的点,剩下的就是和已经被染色了的点无任何关系的点;
前面成立的话,还要判断剩下的点,可以随意染成-1或者1,看矛盾与否,若是不矛盾,还应该遍历所有人,看是否已经被染色了(被划分了),如果还存在有人没有被染色,也不符合题目要求,输出NO
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
int n,m,x,y;
int color[1100];
vector<int>G[1100];
bool dfs(int u,int w)
{
color[u]=w;
for(int i=0; i<G[u].size(); i++)
{
if(color[G[u][i]]==w)
return false;
if(color[G[u][i]]==0&&!dfs(G[u][i],-w))
return false;
}
return true;
}
bool slove()
{
for(int i=0; i<=n; i++)
{
if(color[i]==1&&!dfs(i,1))
return false;
if(color[i]==-1&&!dfs(i,-1))
return false;
}
for(int i=0; i<n; i++)
{
if(color[i]==0&&!dfs(i,1))
return false;
}
for(int i=0; i<n; i++)
{
if(color[i]==-999)
return false;
}
return true;
}
int main()
{
int a,b,good,bad;
while(~scanf("%d%d%d%d",&n,&m,&x,&y))
{
for(int i=0; i<n; i++)
{
G[i].clear();
color[i]=-999;
}
for(int i=0; i<m; i++)
{
scanf("%d%d",&a,&b);
a--;
b--;
G[a].push_back(b);
G[b].push_back(a);
color[a]=0;
color[b]=0;
}
for(int i=1; i<=x; i++)
{
scanf("%d",&good);
good--;
color[good]=1;
}
for(int i=1; i<=y; i++)
{
scanf("%d",&bad);
bad--;
color[bad]=-1;
}
if(slove()) printf("YES\n");
else printf("NO\n");
}
}