D. Captain Flint and Treasure
Posted thusloop
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了D. Captain Flint and Treasure相关的知识,希望对你有一定的参考价值。
Captain Flint and Treasure
思路:子树中为正的留着(入队列),负的舍去(最后输出,入栈)
#pragma GCC optimize(2)
#pragma GCC optimize(3,"Ofast","inline")
#include<bits/stdc++.h>
#define ll long long
#define fi first
#define se second
#define pb push_back
#define pii pair<int,int>
#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
const int maxn=2e5+100;
ll a[maxn],b[maxn],mx[maxn];
int ans[maxn];
vector<int>g[maxn];
stack<int>s;
queue<int>q;
void dfs(int x,int f)
{
for(auto it:g[x])
{
if(it==f)continue;
dfs(it,x);
if(mx[it]>=0)
{
q.push(it);
mx[x]+=mx[it];
}
}
if(mx[x]<0)
{
s.push(x);
}
else if(f==-1)
{
s.push(x);
}
}
signed main()
{
IOS
int n;
cin>>n;
for(int i=1; i<=n; i++)
{
cin>>a[i];
mx[i]=a[i];
}
for(int i=1; i<=n; i++)
{
cin>>b[i];
if(b[i]==-1)continue;
g[b[i]].pb(i);
//g[i].pb(b[i]);
}
for(int i=1; i<=n; i++)
{
if(b[i]==-1)
{
dfs(i,-1);
}
}
int cnt=0;
while(!q.empty())
{
int tp=q.front();
q.pop();
ans[++cnt]=tp;
}
while(!s.empty())
{
int tp=s.top();
s.pop();
ans[++cnt]=tp;
}
ll res=0;
for(int i=1; i<=cnt; i++)
{
int it=ans[i];
res+=a[it];
if(b[it]==-1)continue;
a[b[it]]+=a[it];
}
cout<<res<<"\\n";
for(int i=1; i<=cnt; i++)
{
cout<<ans[i]<<" ";
}
}
以上是关于D. Captain Flint and Treasure的主要内容,如果未能解决你的问题,请参考以下文章
CF#660 B - Captain Flint and a Long Voyage
B. Captain Flint and a Long Voyage1000 / 构造