結果

問題 No.2205 Lights Out on Christmas Tree
ユーザー Manuel1024
提出日時 2023-08-24 01:15:01
言語 C++14
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 190 ms / 2,000 ms
コード長 1,160 bytes
コンパイル時間 816 ms
コンパイル使用メモリ 80,856 KB
実行使用メモリ 17,664 KB
最終ジャッジ日時 2024-12-22 13:28:04
合計ジャッジ時間 8,497 ms
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 37
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;

int main(){
    int n; cin >> n;
    vector<vector<int>> G(n);
    for(int i = 0; i < n-1; i++){
        int a, b; cin >> a >> b;
        a--; b--;
        G[a].emplace_back(b);
        G[b].emplace_back(a);
    }
    vector<int> c(n);
    for(auto &it: c) cin >> it;

    int blackcnt = 0;
    for(auto &it: c) blackcnt += it;
    if(blackcnt%2 != n%2){
        cout << -1 << endl;
        return 0;
    }

    vector<int> in(n);
    queue<int> Q;
    for(int i = 0; i < n; i++){
        in[i] = G[i].size();
        if(in[i] == 1) Q.emplace(i);
    }

    int ans = 0;
    while(!Q.empty()){
        int cur = Q.front(); Q.pop();
        in[cur]--;
        int nex = -1;
        for(const auto &it: G[cur]){
            if(in[it] > 0){
                nex = it;
                break;
            }
        }
        if(nex == -1) break;
        if(c[cur] == 0){
            c[cur] = c[cur]^1;
            c[nex] = c[nex]^1;
            ans++;
        }
        in[nex]--;
        if(in[nex] == 1) Q.emplace(nex);
    }
    cout << ans << endl;
    return 0;
}
0