死循了求助助助助助助助
  • 板块学术版
  • 楼主easy_Cooker
  • 当前回复6
  • 已保存回复6
  • 发布时间2022/7/17 15:26
  • 上次更新2023/10/27 19:53:10
查看原帖
死循了求助助助助助助助
542182
easy_Cooker楼主2022/7/17 15:26

RT

题目传送器!

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn=2e6+100;
int n,cnt;
ll ans;
int root;
ll f[maxn][2];
int head[maxn],val[maxn],vis[maxn];
int dad[maxn];
inline int read()
{
	int ret=0,f=1;
	char ch=getchar();
	while(!isdigit(ch))
	{
		if(ch=='-')
		{
			f=-1;
		}
		ch=getchar();
	}
	while(isdigit(ch))
	{
		ret=(ret<<1)+(ret<<3)+(ch^'0');
		ch=getchar();
	}
	return ret*f;
}
struct edge
{
	int po;
	int to;
};
edge e[maxn];
inline void add(int from,int to)
{
	e[++cnt]={to,head[from]=cnt}; 
}
inline void dp(int now)
{
	vis[now]=1;
	f[now][0]=0;
	f[now][1]=val[now];
	for(int i=head[now];i;i=e[i].po)
	{
		int go=e[i].to;
		if(go!=root)
		{
			dp(go);
			f[now][0]+=max(f[go][1],f[go][0]);
			f[now][1]+=f[go][0];
		}
		else
		{
			f[go][1]=-maxn;
		}
	} 
}
inline void find(int x)
{
	vis[x]=1;
	root=x;
	while(!vis[dad[root]])
	{
		root=dad[root];
		vis[root]=1;
	}
	dp(root);
	ll t=max(f[root][0],f[root][1]);
	vis[root]=1;
	root=dad[root];
	dp(root); 
	ans+=max(t,max(f[root][0],f[root][1]));
	return ;
}
int main()
{
	n=read();
	for(int i=1;i<=n;i++)
	{
		val[i]=read();
		int x=read();
		add(x,i);
		dad[i]=x;
	}
	for(int i=1;i<=n;i++)
	{
		if(!vis[i])
		{
			find(i);
		}
	}
	cout<<ans<<endl;
	return 0;
}
2022/7/17 15:26
加载中...