1106. Two Teams
Time limit: 1.0 second
Memory limit: 64 MB
Memory limit: 64 MB
The group of people consists of
N members. Every member has one or more friends in the group. You are to write program that divides this group into two teams. Every member of each team must have friends in another team.
Input
The first line of input contains the only number
N (
N ≤ 100). Members are numbered from 1 to
N. The second, the third,…and the (
N+1)th line contain list of friends of the first, the second, …and the
Nth member respectively. This list is finished by zero. Remember that friendship is always mutual in this group.
Output
The first line of output should contain the number of people in the first team or zero if it is impossible to divide people into two teams. If the solution exists you should write the list of the first group into the second line of output. Numbers should be divided by single space. If there are more than one solution you may find any of them.
Sample
input | output |
---|---|
7 2 3 0 3 1 0 1 2 4 5 0 3 0 3 0 7 0 6 0 | 4 2 4 5 6 |
Problem Author: Dmitry Filimonenkov
Problem Source: Tetrahedron Team Contest May 2001
Problem Source: Tetrahedron Team Contest May 2001
题目大意
n个人,给出这n个人的朋友关系,将他们分成两组,使得,任意一组的任意一个人都能在另一组找到自己的一个或多个朋友
解题思路
从第一个点开始,他自己是一个队伍,他的朋友就放另一个队伍里,然后枚举他的朋友的朋友…………
这里用第0组和第1组,这样可以直接用!来代替另一个组
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <functional>
#include <algorithm>
#include <queue>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = 110;
int vist[maxn];
int a[maxn];
vector <int> g[maxn];
queue <int> q;
int main()
{
int n;
int ans = 0;
int t;
scanf("%d",&n);
for(int i = 1;i<=n;++i){
for(int j = 0;;++j){
scanf("%d",&t);
if(t==0){
if(j==0) ans = -1;///如果有个人没朋友,那就不可解
break;
}
g[i].push_back(t);
}
}
if(ans == -1) printf("0");
else{
memset(vist,-1,sizeof(vist));
for(int i = 1;i<=n;++i){
if(vist[i]!=-1) continue;
q.push(i);
vist[i] = 1;///没被分过组,就分给1组
while(!q.empty()){
int u = q.front();
q.pop();
for(int j = 0;j<g[u].size();++j){
if(vist[g[u][j]]!=-1) continue;
///他的朋友没被分过组,就分给另一个组
vist[g[u][j]] = !vist[u];
q.push(g[u][j]);
}
}
}
///统计在0组的人的个数
for(int i = 1;i<=n;++i){
if(!vist[i]){
a[ans++] = i;
}
}
printf("%d\n",ans);
for(int i = 0 ;i<ans;++i){
printf("%d",a[i]);
if(i<ans-1) printf(" ");
}
}
return 0;
}