이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
#include <cmath>
#include <map>
#include <string>
#include <ios>
#include <iomanip>
#include <deque>
#include <queue>
#include <list>
#include <stack>
#define FASTIO ios_base::sync_with_stdio(0); cin.tie(NULL);
using ll = long long;
using namespace std;
vector<vector<ll>>gp;
vector<ll>v;
vector<vector<vector<ll>>>dp;
void dfs(ll u,ll p){
ll cnt=1e18,lox=1e18,ans=0,ans1=0;
for(ll& x:gp[u]){
if(x!=p){
dfs(x,u);
dp[u][0][0]+=min(dp[x][0][0],dp[x][1][0]);
dp[u][1][0]+=min(dp[x][1][1],dp[x][0][1]);
if(min(dp[x][0][0],dp[x][1][0])==dp[x][1][0]) ans++;
if(min(dp[x][0][1],dp[x][1][1])==dp[x][1][1]) ans1++;
cnt=min(cnt,abs(dp[x][0][0]-dp[x][1][0]));
lox=min(lox,abs(dp[x][1][1]-dp[x][0][1]));
}
}
if(gp[u].size()==1&&u!=0){
if(v[u]==0){
dp[u][0][0]=0;
dp[u][0][1]=1e17;
dp[u][1][0]=1e17;
dp[u][1][1]=1;
}
else{
dp[u][0][0]=1e17;
dp[u][0][1]=0;
dp[u][1][0]=1;
dp[u][1][1]=1e17;
}
}
else{
dp[u][0][1]=dp[u][0][0]+1;
dp[u][1][1]=dp[u][1][0]+1;
if((v[u]==1&&ans%2==0)||(v[u]==0&&ans%2==1)){
dp[u][0][0]+=cnt;
}
if((v[u]==1&&ans%2==1)||(v[u]==0&&ans%2==0)){
dp[u][0][1]+=cnt;
}
if((v[u]==1&&ans1%2==0)||(v[u]==0&&ans1%2==1)){
dp[u][1][1]+=lox;
}
if((v[u]==1&&ans1%2==1)||(v[u]==0&&ans1%2==0)){
dp[u][1][0]+=lox;
}
}
}
void solve(){
ll n; cin >> n;
v=vector<ll>(n);
gp=vector<vector<ll>>(n);
dp=vector<vector<vector<ll>>>(n,vector<vector<ll>>(2,vector<ll>(2)));
for(ll i=0;i<n-1;i++){
ll u,v; cin >> u >> v;
--u,--v;
gp[u].push_back(v);
gp[v].push_back(u);
}
for(ll i=0;i<n;i++){
cin >> v[i];
}
dfs(0,-1);
if(min({dp[0][0][0],dp[0][1][0]})>=n){
cout<<"impossible"<<endl;
}
else cout<<min({dp[0][0][0],dp[0][1][0]});
}
signed main() {
FASTIO
ll t=1;
// cin >> t;
while (t--) {
solve();
}
}
# | 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... |