[2017纪中10-31]Tree 构造

5 篇文章 0 订阅

加入x的子树都已变白,x为黑的画,把x和x的所有儿子反色一下就好了。dfs一遍即可。
代码:

#include<iostream>
#include<cstdio>
using namespace std;
const int maxn=500010;
int n;
bool c[maxn],f[maxn];
struct edge
{
    int t;
    edge *next;
}*con[maxn];
int read()
{
    int x=0;
    char ch=getchar();
    while(ch<'0'||ch>'9') ch=getchar();
    while(ch>='0'&&ch<='9') {x=x*10+ch-'0';ch=getchar();}
    return x;
}
void ins(int x,int y)
{
    edge *p=new edge;
    p->t=y;
    p->next=con[x];
    con[x]=p; 
}
void dfs(int v)
{
    f[v]=c[v];
    for(edge *p=con[v];p;p=p->next)
        dfs(p->t),f[p->t]^=f[v];    
}
int main()
{
    n=read();
    for(int i=1;i<=n;i++)
        c[i]=read();
    for(int i=1;i<n;i++)
    {
        int x=read(),y=read();
        ins(x,y);
    }
    dfs(1);
    for(int i=1;i<=n;i++)
        if(f[i]) printf("%d ",i);
    return 0;
}

更巧妙的办法,因为读入的是有父子关系的,我们只要保证父子颜色相同(不同就儿子反一下色),最后保证1为白色即可。
代码:

#include<iostream>
#include<cstdio>
using namespace std;
const int maxn=500010;
int n;
bool c[maxn],f[maxn];
int read()
{
    int x=0;
    char ch=getchar();
    while(ch<'0'||ch>'9') ch=getchar();
    while(ch>='0'&&ch<='9') {x=x*10+ch-'0';ch=getchar();}
    return x;
}
int main()
{
    n=read();
    for(int i=1;i<=n;i++)
        c[i]=read();
    for(int i=1;i<n;i++)
    {
        int x=read(),y=read();
        if(c[x]!=c[y]) f[y]=1;
    }
    f[1]=c[1];
    for(int i=1;i<=n;i++)
        if(f[i]) printf("%d ",i);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值