Dima came to the horse land. There are n horses living in the land. Each horse in the horse land has several enemies (enmity is a symmetric relationship). The horse land isn't very hostile, so the number of enemies of each horse is at most 3.
Right now the horse land is going through an election campaign. So the horses trusted Dima to split them into two parts. At that the horses want the following condition to hold: a horse shouldn't have more than one enemy in its party.
Help Dima split the horses into parties. Note that one of the parties can turn out to be empty.
The first line contains two integers n, m — the number of horses in the horse land and the number of enemy pairs.
Next m lines define the enemy pairs. The i-th line contains integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi), which mean that horse ai is the enemy of horse bi.
Consider the horses indexed in some way from 1 to n. It is guaranteed that each horse has at most three enemies. No pair of enemies occurs more than once in the input.
Print a line, consisting of n characters: the i-th character of the line must equal "0", if the horse number i needs to go to the first party, otherwise this character should equal "1".
If there isn't a way to divide the horses as required, print -1.
3 3 1 2 3 2 3 1
100
2 1 2 1
00
10 6 1 2 1 3 1 4 2 3 2 4 3 4
0110000000
题目大意:
思路:
不难想到,因为他保证了每个点的度数 <=3,那么我们能够肯定给出一个图它一定有解。
看了其他同学的Ac代码,似乎都是暴力去过的。
具体时间复杂度并不会证明,但是可以估计一下,大概500+次肯定能够找到一个合法解。方法如下:
①首先置flag=0;
②然后从1到n遍历,如果其相连边的颜色和当前点颜色相同的个数大于了1,那么将当前点颜色置反,然后flag=1
③如果flag==1回到步骤①,否则结束,找到一个可行解。
Ac代码:
#include<stdio.h>
#include<string.h>
#include<vector>
using namespace std;
vector<int>mp[450000];
int color[450000];
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m))
{
for(int i=1;i<=n;i++)mp[i].clear();
memset(color,0,sizeof(color));
for(int i=1;i<=m;i++)
{
int x,y;
scanf("%d%d",&x,&y);
mp[x].push_back(y);
mp[y].push_back(x);
}
int flag=1;
while(flag)
{
flag=0;
for(int i=1;i<=n;i++)
{
int cnt=0;
for(int j=0;j<mp[i].size();j++)
{
int v=mp[i][j];
if(color[v]==color[i])cnt++;
}
if(cnt>=2)flag=1,color[i]=1-color[i];
}
}
for(int i=1;i<=n;i++)printf("%d",color[i]);
printf("\n");
}
}