70pts玄关,思路大体是第一篇文章
查看原帖
70pts玄关,思路大体是第一篇文章
800499
suzhikz楼主2024/9/14 18:45
#include<bits/stdc++.h>
#define ll long long
#define reg register
#define db double
#define il inline
using namespace std;
const int N=1e6+5;
int n;
vector<int>g[N],w[N];
vector<int>huan,huan_w;
int fa[N],to_fa[N];
bool vis[N],in[N];
bool flag;
void dfs(int x,int f){
//	cout<<'a'<<x<<endl;
	fa[x]=f;
	vis[x]=1;
	bool tof=1;
	for(int i=0;i<g[x].size();i++){
		int y=g[x][i];
		if(y==f&&w[x][i]==to_fa[x]){
			if(tof){
				tof=0;
				continue;
			}
		}
//		if(y==7){
//			cout<<"abcd";
//		}
		if(fa[y]==0){
			to_fa[y]=w[x][i];
			dfs(y,x);
		}else if(flag==0){
			fa[y]=x;
			to_fa[y]=w[x][i];
			int j=x;
			do{
//				cout<<j<<' '<<to_fa[j]<<"huan"<<endl;
				huan.push_back(j);
				huan_w.push_back(to_fa[j]);
				in[j]=1;
				j=fa[j];
			}while(j!=x);
			flag=1;
		}
	}
}
ll d[N];
ll dp(int x,int f){
//	cout<<"dp"<<x<<endl;
	ll re=0;
	for(int i=0;i<g[x].size();i++){
		int y=g[x][i],c=w[x][i];
		if(y==f)continue;
		if(in[y])continue;
		re=max(re,dp(y,x));
		re=max(re,d[x]+d[y]+c);
		d[x]=max(d[x],d[y]+c); 
	}
	return re;
}
signed main(){
	scanf("%d",&n);
	for(int u,ww,i=1;i<=n;i++){
		scanf("%d%d",&u,&ww);
		g[u].push_back(i);g[i].push_back(u);
		w[u].push_back(ww);w[i].push_back(ww);
	}
	ll ans=0,maxx=0;
	for(int i=1;i<=n;i++){
		if(vis[i])continue;
		maxx=0;
		huan.clear();
		huan_w.clear();
		flag=0;
		dfs(i,-1);
		for(auto j:huan){
			maxx=max(maxx,dp(j,0));
		}
//		cout<<maxx<<"max";
		int tmp[2*N]={0};
		ll summ[2*N]={0};
		int m=huan.size();
		for(int j=0;j<huan.size();j++){
			tmp[j+1]=huan[j];
			tmp[j+1+m]=huan[j];
			summ[j+2]=huan_w[j];
			summ[j+2+m]=huan_w[j];
		}
		for(int j=m+1;j<=m*2;j++){
			tmp[j]=tmp[j-m];
		}
//		cout<<endl;
		for(int j=1;j<=m*2;j++)summ[j]+=summ[j-1];
//		cout<<endl;/
		deque<int>q;
		for(int j=1;j<=m*2;j++){
			while(!q.empty()&&j-q.front()+1>m)q.pop_front();
			if(j!=1){
				int x=q.front();
				maxx=max(maxx,summ[j]-summ[x]+d[tmp[x]]+d[tmp[j]]);
			}
			while(!q.empty()&&d[tmp[q.front()]]-summ[q.front()]<=d[tmp[j]]-summ[j])q.pop_back();
			q.push_back(j);
		}
//		cout<<"max"<<maxx<<endl;
		ans+=maxx;
	}
//	cout<<endl; 
//	for(int i=1;i<=n;i++)cout<<d[i]<<' ';
//	cout<<to_fa[2]<<' '<<to_fa[7];
	cout<<ans;
	return 0;
}

2024/9/14 18:45
加载中...