D - Even Relation
Time Limit: 2 sec / Memory Limit: 1024 MB
Score : 400400 points
Problem Statement
We have a tree with NN vertices numbered 11 to NN. The ii-th edge in the tree connects Vertex uiui and Vertex vivi, and its length is wiwi. Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:
- For any two vertices painted in the same color, the distance between them is an even number.
Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.
Constraints
- All values in input are integers.
- 1≤N≤1051≤N≤105
- 1≤ui<vi≤N1≤ui<vi≤N
- 1≤wi≤1091≤wi≤109
Input
Input is given from Standard Input in the following format:
NN u1 v1 w1 u2 v2 w2 .. .. .. uN−1 vN−1 wN−1
Output
Print a coloring of the vertices that satisfies the condition, in NN lines. The ii-th line should contain 0
if Vertex ii is painted white and 1
if it is painted black.
If there are multiple colorings that satisfy the condition, any of them will be accepted.
Sample Input 1
3 1 2 2 2 3 1
Sample Output 1
0 0 1
Sample Input 2
5 2 5 2 2 3 10 1 3 8 3 4 2
Sample Output 2
1 0 1 0 1
题意:给你N个顶点,N-1条边,每条边有wi距离.你可以给每个顶点染成白色或黑色,但是有一个限制条件:两个顶点颜色相同的边所对应的距离为偶数.
题解:由于这是一个无向图,因此可以以1为起点,开始遍历整个图.那么1的颜色是不确定的,从1开始走过的距离为奇数的话,则对应颜色为1(黑色).当然,如果存在环的话,顶点1的颜色可能会变为黑色,否则默认为白色.
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i,n) for(int i=0;i<n;i++)
#define loop(i,L,R) for(int i=L;i<=R;i++)
using namespace std;
const int N=2e5+5;
struct node
{
int v;
ll w;
node(ll sw,int sv)
{
w=sw;
v=sv;
}
};
vector<node>v[2*N+1];
int vis[N]= {0},vis1[N]= {0};
void dfs(int u,ll d)
{
for(int i=0; i<v[u].size(); i++)
{
int vv=v[u][i].v;
if(vis1[vv])
continue;
vis1[vv]=1;
if((d+v[u][i].w)%2)
vis[vv]=1;
dfs(vv,d+v[u][i].w);
}
}
int main()
{
int n;
scanf("%d",&n);
memset(vis,0,sizeof(vis));
loop(i,1,n-1)
{
int x,y;
scanf("%d%d",&x,&y);
ll w;
cin>>w;
v[x].push_back(node(w,y));
v[y].push_back(node(w,x));
}
vis1[1]=1;
dfs(1,0);
for(int i=1; i<=n; i++)
printf("%d\n",vis[i]);
}