[树的dfs] Codeforces 717 E. Paint it really, really dark gray

2 篇文章 0 订阅

Solution S o l u t i o n

又是这个idea。。。
大致就是自下向上调整每个点,把调整的媒介丢给父亲。
最后特判一下根就好了。

#include <bits/stdc++.h>
#define show(x) cerr << #x << " = " << x << endl
using namespace std;
typedef long long ll;
typedef pair<int, int> Pairs;

const int N = 202020;

inline char get(void) {
    static char buf[100000], *S = buf, *T = buf;
    if (S == T) {
        T = (S = buf) + fread(buf, 1, 100000, stdin);
        if (S == T) return EOF;
    }
    return *S++;
}
template<typename T>
inline void read(T &x) {
    static char c; x = 0; int sgn = 0;
    for (c = get(); c < '0' || c > '9'; c = get()) if (c == '-') sgn = 1;
    for (; c >= '0' && c <= '9'; c = get()) x = x * 10 + c - '0';
    if (sgn) x = -x;
}

vector<int> G[N];
int col[N];
int n, x, y, gcnt;
vector<int> ans;

inline void AddEdge(int from, int to) {
    G[from].emplace_back(to);
    G[to].emplace_back(from);
}
inline void dfs(int u, int fa) {
    if (fa) col[u] ^= 1;
    ans.emplace_back(u);
    for (int to: G[u])
        if (to != fa) dfs(to, u);
    if (!col[u] && fa) {
        ans.emplace_back(fa);
        ans.emplace_back(u);
        col[u] ^= 1; col[fa] ^= 1;
    }
    if (fa) {
        ans.emplace_back(fa);
        col[fa] ^= 1;
    }
}

int main(void) {
    freopen("1.in", "r", stdin);
    freopen("1.out", "w", stdout);
    read(n);
    for (int i = 1; i <= n; i++) {
        read(x); col[i] = (x == 1);
    }
    for (int i = 1; i < n; i++) {
        read(x); read(y);
        AddEdge(x, y);
    }
    dfs(1, 0);
    if (!col[1]) {
        ans.emplace_back(*G[1].begin());
        ans.emplace_back(1);
        ans.emplace_back(*G[1].begin());
    }
    for (int x: ans) printf("%d ", x);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值