結果

問題 No.2205 Lights Out on Christmas Tree
コンテスト
ユーザー roaris
提出日時 2023-02-03 23:04:42
言語 C++17
(gcc 15.2.0 + boost 1.90.0)
コンパイル:
g++-15 -O2 -lm -std=c++17 -Wuninitialized -DONLINE_JUDGE -o a.out _filename_
実行:
./a.out
結果
AC  
実行時間 52 ms / 2,000 ms
コード長 978 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 1,342 ms
コンパイル使用メモリ 212,856 KB
実行使用メモリ 38,784 KB
最終ジャッジ日時 2026-06-29 11:16:58
合計ジャッジ時間 4,301 ms
ジャッジサーバーID
(参考情報)
judge1_0 / judge3_1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 37
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i=0; i<n; i++)
#define pb push_back
typedef long long ll;

int N;
vector<int> G[200010];
int c[200010];
int memo[2][200010];

int dfs(int f, int v, int pv=-1) {
    if (memo[f][v]!=-1) return memo[f][v];
    int dp0 = 0;
    int dp1 = 1e9;
    for (int nv : G[v]) {
        if (nv==pv) continue;
        int c0 = dfs(0, nv, v);
        int c1 = dfs(1, nv, v);
        int ndp0 = min(dp0+c1, dp1+c0+1);
        int ndp1 = min(dp0+c0+1, dp1+c1);
        dp0 = ndp0;
        dp1 = ndp1;
    }
    int res = c[v]^f ? dp1 : dp0;
    return memo[f][v] = res;
}

int main() {
    cin.tie(0); ios::sync_with_stdio(false);
    
    cin >> N;
    rep(i, N-1) {
        int u, v; cin >> u >> v;
        G[u-1].pb(v-1);
        G[v-1].pb(u-1);
    }
    rep(i, N) cin >> c[i];
    
    rep(f, 2) rep(v, N) memo[f][v] = -1;
    int ans = dfs(1, 0);
    if (ans>=1e9) cout << -1 << endl;
    else cout << ans << endl;
}
0