CF 717E[dfs]

来源:互联网 发布:如何注册自己的域名 编辑:程序博客网 时间:2024/05/29 07:34

题意:给定一棵树,每个节点初始有颜色,共两种颜色.你一开始在点1,走到哪个点就把它的颜色改变.输出一种合法的方案使最终的树颜色都变为1.

dfs构造
对每个节点如果当前为-1就从它到父亲节点走一遍
如果当前是root为-1没有父亲就随便找个儿子走一遍再走到那个儿子上(因为是dfs处理它的儿子都已经是1了)

#include<cstdio>#define N 200005using namespace std;inline char nc() {    static char buf[100000],*p1=buf,*p2=buf;    return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++;}inline void read(int &x) {    char c=nc(),b=1;    for(;!(c>='0'&&c<='9');c=nc()) if(c=='-') b=-1;    for(x=0;c>='0'&&c<='9';x=x*10+c-'0',c=nc()); x*=b;}struct edge{int to,next;}e[N<<1];int n,cnt,head[N],clo[N],ans[N<<1];inline void add(int x,int y) {    e[++cnt].next=head[x],e[cnt].to=y,head[x]=cnt;    e[++cnt].next=head[y],e[cnt].to=x,head[y]=cnt;}#define ans_push(x) ans[++ans[0]]=xvoid dfs(int x,int fa) {    clo[x]^=1;    ans_push(x);    for(int i=head[x];i;i=e[i].next)        if(e[i].to!=fa) {            dfs(e[i].to,x);            ans_push(x);            clo[x]^=1;        }    if(clo[x]==0)        if(x==1) {            ans_push(e[head[x]].to);            ans_push(x);            ans_push(e[head[x]].to);        }        else {            ans_push(fa);            ans_push(x);            clo[fa]^=1;            clo[x]^=1;        }}int main() {    read(n);    int flag=0;    for(int i=1;i<=n;++i) {        read(clo[i]);        if(clo[i]==-1) flag=1,clo[i]=0;    }    for(int i=1,x,y;i<n;++i) {        read(x),read(y);        add(x,y);    }    if(!flag) puts("1");    else {        clo[1]^=1;        dfs(1,0);        for(int i=1;i<=ans[0];++i)            printf("%d%s",ans[i],i==ans[0]?"\n":" ");    }}
原创粉丝点击