Description
给定M个二元组(A_i, B_i),求X_1, …, X_N满足:对于任意(A_i, B_i),有|X_{A_i} - X_{B_i}| = 1成立。
Input
第1行,2个整数N、M。
第2行到第M + 1行,2个整数A_i和B_i。
Output
第1行,1个字符串,”YES”表示有解,”NO”表示无解。
第2行,N个整数,X_1, X_2, …, X_N,无解则不输出。
要求|X_i| <= 1,000,000,000,任意一解均可。
Sample Input
输入1:
3 3
1 2
2 3
3 1
输入2:
6 5
1 2
2 3
3 4
4 1
5 6
Sample Output
输出1:
NO
输出2:
YES
0 1 0 1 -99 -100
Data Constraint
对于40%的数据,1 <= N <= 10。
对于100%的数据,1 <= N <= 10,000,0 <= M <= 100,000,1 <= A_i, B_i <= N。
Solution
数据非常大,显然不能暴力(废话)
仔细思考后发现,答案只能是两种,即相邻的两个数,我就用0和1算了
可以把它的约束想象成图的边
于是相邻的两个点的答案不能一样,那就一个为0,相邻的全部搞成1,再递归下去,相邻的又搞回0,如果有冲突,就NO,否则输出即可
Code
#include<cstdio>
#include<algorithm>
#include<cmath>
#define fo(i,a,b) for(int i=a;i<=b;i++)
#define N 100100
using namespace std;
int n,m,last[N*10],next[N*10],to[N*10],tot=1,bz[N],k=0,ans[N],bl=1;
void putin(int x,int y)
{
next[++tot]=last[x];last[x]=tot;to[tot]=y;
next[++tot]=last[y];last[y]=tot;to[tot]=x;
}
void dg(int x)
{
bz[x]=1;
for(int i=last[x];i;i=next[i])
{
int y=to[i];
if(bz[y]==0) ans[y]=1-ans[x],dg(y);
else if(ans[y]==ans[x]) bl=0;
if(!bl) return;
}
}
int main()
{
freopen("perfect.in","r",stdin);freopen("perfect.out","w",stdout);
scanf("%d%d",&n,&m);
fo(i,1,m)
{
int x,y;scanf("%d%d",&x,&y);putin(x,y);
}
fo(i,1,n) if(!bz[i]&&bl) ans[i]=1,dg(i);
if(bl==0) printf("NO\n");
else
{
printf("YES\n");
fo(i,1,n) printf("%d ",ans[i]);
}
fclose(stdin);fclose(stdout);
}