TLE on 9 求调
查看原帖
TLE on 9 求调
1395112
IdtwteiNeptune楼主2024/8/14 10:53
#include<bits/stdc++.h>
#include<ext/pb_ds/priority_queue.hpp>
using namespace std; 
using namespace __gnu_pbds;

#define i128 __int128
const int N=3e5+100;
#define gc getchar()
#define rd read()
inline i128 read(){
	i128 x=0,f=0; char c=gc;
	for(;c<'0'||c>'9';c=gc) f|=(c=='-');
	for(;c>='0'&&c<='9';c=gc) x=(x<<1)+(x<<3)+(c^48);
	return f?-x:x;
}
#define pc(x) putchar(x)
#define wt(x) write(x)
void write(i128 x){
	if(x<0) return pc('-'),wt(-x);
	if(x>9) wt(x/10);
	pc(x%10^48);
}

int n; i128 m,a[N];
int head[N],ne[N],v[N],tot=0;
void add(int x,int y){ ne[++tot]=head[x]; head[x]=tot; v[tot]=y; }

i128 f[N],g[N];

struct cmp{ bool operator()(const int &x,const int &y){ return f[x]>f[y]; } };
__gnu_pbds::priority_queue<int,cmp> hp[N],q;

void sol(int x){
	i128 cur=0; hp[x].push(x);
	while(!hp[x].empty()){
		int u=hp[x].top(); hp[x].pop();
		if(cur<f[u]) f[x]+=f[u]-cur,cur=f[u];
		if(u==x){ cur+=a[u]; for(int i=head[u];i;i=ne[i]) hp[x].push(v[i]); }
		else{ cur+=g[u]; if(hp[x].size()<hp[u].size()) swap(hp[x],hp[u]); hp[x].join(hp[u]); }
		if(cur>f[x]) return g[x]=cur-f[x],void();
	}
	f[x]=LLONG_MAX;
}
void dfs(int u,int fu){ for(int i=head[u];i;i=ne[i]) if(v[i]!=fu) dfs(v[i],u); sol(u); }

signed main(){
	
	n=rd+1,m=rd;
	for(int i=1,x;i<n;++i) a[i]=rd,x=rd,x=x==0?n:x,add(x,i);
	
	dfs(n,0);
	
	i128 cur=m; q.push(n);
	while(!q.empty()){
		int u=q.top(); q.pop();
		if(cur<f[u]) break; cur+=a[u];
		for(int i=head[u];i;i=ne[i]) q.push(v[i]);
	}
	wt(cur-m);
	
	return 0;
}

思路同题解。

2024/8/14 10:53
加载中...