欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

D. Captain Flint and Treasure(拓扑排序+贪心)

程序员文章站 2022-07-07 22:52:58
...

题目链接
D. Captain Flint and Treasure(拓扑排序+贪心)
D. Captain Flint and Treasure(拓扑排序+贪心)

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=2e5+5;
int n,in[maxn],b[maxn];
ll ans,a[maxn];
vector<int>g[maxn],v;
queue<int>q;
stack<int>s;
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;++i) scanf("%lld",&a[i]);
	for(int i=1;i<=n;++i)
	{
		scanf("%d",&b[i]);
		if(b[i]!=-1)
		{
			g[i].push_back(b[i]);
			in[b[i]]++;
		}
	}
	ll ans=0;
	for(int i=1;i<=n;++i) if(in[i]==0) q.push(i);
	while(!q.empty())
	{
		int top=q.front();
		q.pop();
		if(a[top]>=0) ans+=a[top],v.push_back(top);
		else s.push(top);
		for(int to:g[top])
		{
			if(a[top]>=0) a[to]+=a[top];
			--in[to];
			if(!in[to]) q.push(to);
		}
	}
	while(!s.empty())
	{
		int top=s.top();
		s.pop();
		ans+=a[top];
		v.push_back(top);
	}
	printf("%lld\n",ans);
	for(auto i:v) printf("%d ",i);	
} 
相关标签: 拓扑排序