#include <bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("avx,avx2,fma")
using namespace std;
typedef long long ll;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
#define MAX 101010
#define MAXS 22
#define INF 1000000000000000001
#define bb ' '
#define ln '\n'
#define Ln '\n'
vector<int> adj[MAX];
int C[MAX];
int dp[4][MAX];
int N;
void dfs(int x, int pv = 0) {
if (adj[x].size() == 1 && pv) {
dp[C[x]][x] = 0;
dp[2 | (C[x] ^ 1)][x] = 1;
return;
}
for (auto v : adj[x]) if (v != pv) dfs(v, x);
for (auto p : { 0, 1 }) {
int mn = N * 10;
int par = 0; //parity
int sum = 0;
for (auto v : adj[x]) if (v != pv) {
if (dp[p][v] > dp[p | 2][v]) par ^= 1;
mn = min(mn, abs(dp[p][v] - dp[p | 2][v]));
sum += min(dp[p][v], dp[p | 2][v]);
}
dp[p << 1][x] = dp[(p << 1) | 1][x] = sum + p;
dp[(p << 1) | C[x] ^ p ^ par ^ 1][x] += mn;
}
}
signed main() {
ios::sync_with_stdio(false), cin.tie(0);
cin >> N;
int i, a, b;
for (i = 1; i < N; i++) {
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
for (i = 1; i <= N; i++) cin >> C[i];
for (i = 1; i <= N; i++) for (int j = 0; j < 4; j++) dp[j][i] = N * 10;
dfs(1);
int ans = min(dp[0][1], dp[2][1]);
if (ans > N) cout << "impossible" << ln;
else cout << ans << ln;
}
Compilation message
swaps.cpp: In function 'void dfs(int, int)':
swaps.cpp:37:32: warning: suggest parentheses around arithmetic in operand of '|' [-Wparentheses]
37 | dp[(p << 1) | C[x] ^ p ^ par ^ 1][x] += mn;
| ~~~~~~~~~~~~~~~^~~
/usr/bin/ld: /tmp/ccZYYgfS.o: in function `main':
grader.cpp:(.text.startup+0x0): multiple definition of `main'; /tmp/ccaucuTR.o:swaps.cpp:(.text.startup+0x0): first defined here
/usr/bin/ld: /tmp/ccZYYgfS.o: in function `main':
grader.cpp:(.text.startup+0x67): undefined reference to `solve(int, int)'
collect2: error: ld returned 1 exit status