This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include "friend.h"
#include<bits/stdc++.h>
using namespace std;
#define N 100010
typedef long long int ll;
ll cost[N];
vector<ll> adj[N];
int dp[N];
int solve(int i, int p){
// Either take or do not take thsi value.
// If we do not take this value, all subtrees are available for taking, so sum up dp across that.
// If we do take this value, we sum up all secondary subtrees.
if (dp[i]==-1){
int ans1 = 0;
int ans2 = cost[i];
for (int x: adj[i]){
if (x==p||x==i) continue;
ans1+=solve(x,i);
}
for (int x: adj[i]){
if (x==p||x==i) continue;
for (int y: adj[x]){
if(y==i || y ==p||y==x) continue;
ans2+=solve(y,x);
}
}
dp[i]=max(ans1,ans2);
}
return dp[i];
}
int findSample(int n, int c[], int h[], int p[]){
int sum = 0;
ll mx = 0;
bool allOne = true;
int prot[3];
for (int i= 0 ; i < 3; i++) prot[i] = 0;
for (int i = 0 ; i< n; i++) {
cost[i] = c[i];
sum += c[i];
if (c[i]!=1)allOne=false;
mx = max(mx,cost[i]);
}
for (int i =1; i < n; i++){
prot[p[i]]++;
}
int ans = 0;
if (n <= 10){
for (int i =1;i<n;i++){
if(p[i]==1 or p[i]==2){
for (int x: adj[h[i]]){
adj[x].push_back(i);
adj[i].push_back(x);
}
}
if(p[i]==0 or p[i]==2){
adj[i].push_back(h[i]);
adj[h[i]].push_back(i);
}
}
for (int bm =0 ; bm < (1<<n); bm++){
int sum = 0;
bool works = true;
bool vis[N];
for (int i =0 ; i < n; i++) vis[i] = false;
for (int j =0 ; j < n; j++){
if ((bm&(1<<j))>0) {
vis[j]=true;
sum+=c[j];
}
}
for (int i = 0 ; i < n; i++){
if (vis[i]){
for (int x:adj[i]) if(vis[x])works=false;
}
}
if (!works)continue;
ans = max(ans,sum);
}
}
else if (prot[1]==n-1){
ans = sum;
}
else if (prot[2]==n-1){
ans = mx;
}
else if (prot[0] == n-1){
for (int i = 1; i < n; i++){
adj[i].push_back(h[i]);
adj[h[i]].push_back(i);
}
for (int i = 0 ; i < n; i++) dp[i] = -1;
ans = solve(0,0);
}
else if(allOne && prot[2]==0){
for (int i = 1; i < n; i++){
if (p[i]==0){
adj[i].push_back(h[i]);
adj[h[i]].push_back(i);
}
else{
if(adj[h[i]].size()>1)continue;
if(adj[h[i]].size()==1){
for (int x:adj[h[i]]){
adj[h[i]].push_back(x);
adj[x].push_back(h[i]);
}
}
else ans+=c[i];
}
}
ans +=solve(0,0);
}
return ans;
}
void readInput(){
int n; cin>>n;
int c[n], h[n], p[n];
for (int i = 0; i < n; i++) cin>>c[i];
for (int i =1 ; i < n; i++) cin>>h[i]>>p[i];
cout<<findSample(n,c,h,p)<<'\n';
}
# | 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... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |