思路:
1、相邻的三个人需要有两个人的食物是不同的,那么其实如果我们只要保证每两个人之间的食物种类是不同的即可。
那么对应我们建立无向边:
(i*2,i*2-1);
因为每对情侣我们也需要要求食物种类是不同的,那么对应我们还要建立无向边:
(输入进来的第一个编号,输入进来的第二个编号);
2、很容易发现,因为一共只有两种食物,那么整个图是一个二分图的模型,对应我们接下来只需要对每个点进行染色即可。
这里Dfs实现。
Ac代码:
#include<stdio.h>
#include<string.h>
#include<vector>
using namespace std;
int color[200500];
int p[100500][2];
int vis[200500];
vector<int >mp[200500];
void Dfs(int u,int col)
{
color[u]=col;
vis[u]=1;
for(int i=0;i<mp[u].size();i++)
{
int v=mp[u][i];
if(vis[v]==0)
{
Dfs(v,3-col);
}
}
}
int main()
{
int n;
while(~scanf("%d",&n))
{
for(int i=1;i<=n;i++)
{
int x,y;
scanf("%d%d",&x,&y);
p[i][0]=x;
p[i][1]=y;
mp[x].push_back(y);
mp[y].push_back(x);
mp[2*i].push_back(2*i-1);
mp[2*i-1].push_back(2*i);
}
memset(vis,0,sizeof(vis));
for(int i=1;i<=2*n;i++)
{
if(vis[i]==0)
{
vis[i]=1;
Dfs(i,1);
}
}
for(int i=1;i<=n;i++)
{
printf("%d %d\n",color[p[i][0]],color[p[i][1]]);
}
}
}