CF 717E[dfs]

題意:給定一棵樹,每個節點初始有顏色,共兩種顏色.你一開始在點1,走到哪個點就把它的顏色改變.輸出一種合法的方案使最終的樹顏色都變爲1 .

dfs構造
對每個節點如果當前爲-1就從它到父親節點走一遍
如果當前是root爲-1沒有父親就隨便找個兒子走一遍再走到那個兒子上(因爲是dfs處理它的兒子都已經是1了)

#include<cstdio>
#define N 200005
using 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]]=x

void 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":" ");
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章