D. Captain Flint and Treasure
Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure’s location or may not. That’s why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this…
There are two arrays a and b of length n. Initially, an ans is equal to 0 and the following operation is defined:
Choose position i (1≤i≤n);
Add ai to ans;
If bi≠−1 then add ai to abi.
What is the maximum ans you can get by performing the operation on each i (1≤i≤n) exactly once?
Uncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them.
Input
The first line contains the integer n (1≤n≤2⋅105) — the length of arrays a and b.
The second line contains n integers a1,a2,…,an (−106≤ai≤106).
The third line contains n integers b1,b2,…,bn (1≤bi≤n or bi=−1).
Additional constraint: it’s guaranteed that for any i (1≤i≤n) the sequence bi,bbi,bbbi,… is not cyclic, in other words it will always end with −1.
Output
In the first line, print the maximum ans you can get.
In the second line, print the order of operations: n different integers p1,p2,…,pn (1≤pi≤n). The pi is the position which should be chosen at the i-th step. If there are multiple orders, print any of them.
思路
dfs过程中贪心从子节点向上累加,遇到子节点累加还为负数的就直接跳过。同时将累加为正数的结果正序输出(dfs序先输出子节点),负数的结果倒序输出。
代码
#include<bits/stdc++.h>
#define ll long long
#define LL long long
#define PB push_back
#define MP make_pair
using namespace std;
const int maxn=2e5+100;
const ll inf=1e18+10;
ll a[maxn],b[maxn],an[maxn],ans=0;
vector<int>g[maxn],st,ed;
void dfs1(int pre,int now){
ll sum=an[now];
for(int i=0;i<g[now].size();i++){
int x=g[now][i];
if(x==pre)continue;
dfs1(now,x);
if(an[x]>0){
sum+=an[x];
}
}
an[now]=sum;
if(sum>0)st.PB(now);
else ed.PB(now);
}
int main(){
ios::sync_with_stdio(false);
int n;
cin>>n;
for(int i=1;i<=n;i++)g[i].clear();
for(int i=1;i<=n;i++){
cin>>a[i];
an[i]=a[i];
}
for(int i=1;i<=n;i++){
cin>>b[i];
if(b[i]!=-1)g[b[i]].PB(i);
}
for(int i=1;i<=n;i++){
if(b[i]==-1)dfs1(0,i);
}
for(int i=1;i<=n;i++)ans+=an[i];
cout<<ans<<'\n';
for(int i=0;i<st.size();i++)cout<<st[i]<<' ';
for(int i=ed.size()-1;i>=0;i--)cout<<ed[i]<<' ';
}