Codeforces660 D. Captain Flint and Treasure(dfs贪心)

3 篇文章 0 订阅
2 篇文章 0 订阅

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]<<' ';
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值