이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll MXN = 1e5 + 20 , Inf = 1e12 + 20;
ll n , color[MXN] , c[MXN];
ll dp[MXN][2][2];
vector<int> adj[MXN];
void DFS(int v , int dad) {
if(adj[v].size() == 1) {
for(int i = 0 ; i < 2 ; i++) for(int j = 0 ; j < 2 ; j++) {
dp[v][i][j] = (i^j ? j : Inf);
}
return;
}
for(auto u : adj[v]) {
if(u == dad) continue;
DFS(u , v);
}
for(int i = 0 ; i < 2 ; i++) for(int j = 0 ; j < 2 ; j++) { // i: color / j: bezanim ya na
for(auto u : adj[v]) {
if(u == dad) continue;
c[u] = color[u] ^ j;
}
ll cst = 0;
vector<ll> a;
for(auto u : adj[v]) if(u != dad) {
a.push_back(dp[u][c[u]][1] - dp[u][c[u]][0]);
cst += dp[u][c[u]][0];
}
sort(a.begin() , a.end());
ll mn = Inf;
if(i^j) {
ll p = 0; mn = 0;
for(int i = 1 ; i < a.size() ; i+=2) {
p += a[i]+a[i-1];
mn = min(mn , p);
}
} else {
ll p = a[0]; mn = min(mn , p);
for(int i = 2 ; i < a.size() ; i+=2) {
p += a[i]+a[i-1];
mn = min(mn , p);
}
}
dp[v][i][j] = cst + mn + j;
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(NULL);
cin >> n;
for(int i = 1 ; i < n ; i++) {
int v,u; cin >> v >> u;
adj[v].push_back(u); adj[u].push_back(v);
}
for(int i = 1 ; i <= n ; i++) {
cin >> color[i]; color[i] ^= 1;
}
int root;
for(int i = 1 ; i <= n ; i++) if(adj[i].size() > 1) root = i;
DFS(root , -1);
ll ans = min(dp[root][color[root]][0] , dp[root][color[root]][1]);
if(ans > n+1000) {
cout << "impossible\n";
} else {
cout << ans << "\n";
}
// for(int i = 1 ; i <= n ; i++) {
// for(int a = 0 ; a < 2 ; a++) for(int b = 0 ; b < 2 ; b++) {
// cout << dp[i][a][b] << " ";
// }
// cout << "\n";
// }
}
컴파일 시 표준 에러 (stderr) 메시지
xanadu.cpp: In function 'void DFS(int, int)':
xanadu.cpp:37:31: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<long long int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
37 | for(int i = 1 ; i < a.size() ; i+=2) {
| ~~^~~~~~~~~~
xanadu.cpp:43:31: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<long long int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
43 | for(int i = 2 ; i < a.size() ; i+=2) {
| ~~^~~~~~~~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |