Divide Groups(二分图染色判定 入门题)
Divide Groups
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3178 Accepted Submission(s): 1101
Problem Description
This year is the 60th anniversary of NJUST, and to make the celebration more colorful, Tom200 is going to invite distinguished alumnus back to visit and take photos.
After carefully planning, Tom200 announced his activity plan, one that contains two characters:
1. Whether the effect of the event are good or bad has nothing to do with the number of people join in.
2. The more people joining in one activity know each other, the more interesting the activity will be. Therefore, the best state is that, everyone knows each other.
The event appeals to a great number of alumnus, and Tom200 finds that they may not know each other or may just unilaterally recognize others. To improve the activities effects, Tom200 has to divide all those who signed up into groups to take part in the activity at different time. As we know, one's energy is limited, and Tom200 can hold activity twice. Tom200 already knows the relationship of each two person, but he cannot divide them because the number is too large.
Now Tom200 turns to you for help. Given the information, can you tell if it is possible to complete the dividing mission to make the two activity in best state.
Input
The input contains several test cases, terminated by EOF.
Each case starts with a positive integer n (2<=n<=100), which means the number of people joining in the event.
N lines follow. The i-th line contains some integers which are the id
of students that the i-th student knows, terminated by 0. And the id starts from 1.
Output
If divided successfully, please output "YES" in a line, else output "NO".
Sample Input
3
3 0
1 0
1 2 0
Sample Output
YES
题意:给出彼此认识的关系(不传递),问是否可以分成两部分使得两部分中都互相认识
给定 N 个点和一些有向边,求是否能够将这个有向图的点分成两个集合,使得同一个集合内的任意两个点都有双向边联通。
做法:反向思考,对于没有双向边的两个点一定不能在同一个集合中。因此,构建一个图,若两点之间有双向的边,则表示这两个点不能在同一个集合中。
二分图的裸题
进行二分图染色判定即可,若是二分图,则满足条件,反之则不满足
注意题目给的有向边,需要将没有双向边的单向边建一条无向边来进行判断是否是二分图。
#include<bits/stdC++.h>
using namespace std;
const int N=120;
int vis[N][N],color[N],x;
vector<int>G[N];
int dfs(int id,int t)
{
color[id]=t;
for(int i=0;i<G[id].size();i++)
{
int v=G[id][i];
if(color[v]==t) return 0;
if(color[v]!=-1) continue;
if(!dfs(v,!t)) return 0;
}
return 1;
}
int main()
{
int n;
while(cin>>n){
memset(vis,0,sizeof(vis));
for(int i=1;i<=n;i++) G[i].clear();
for(int i=1;i<=n;i++)
{
while(scanf("%d",&x)&&x)
vis[i][x]=1;
}
memset(color,-1,sizeof(color));
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
if(i==j) continue;
if(vis[i][j]==0||vis[j][i]==0)
{
G[i].push_back(j),G[j].push_back(i);
}
}
bool f1=1;
for(int i=1;i<=n&&f1;i++)
{
if(color[i]==-1)
{
if(!dfs(i,0)) f1=0;
}
}
if(f1) printf("YES\n");
else printf("NO\n");
}
}
上一篇: 你一定不知这七种坚果有减肥功效
下一篇: MySQL创建查找数据部分练习