90pts我真的要红温了,有大佬吗?
查看原帖
90pts我真的要红温了,有大佬吗?
774188
ClearluvXL楼主2024/11/21 21:35
#include<bits/stdc++.h>
#define endl '\n'

using namespace std;

const int N=1e5+10;

typedef long long ll;
typedef pair<int,int> pii;

int n;

vector<pii> e[N];

void add(int u,int v,int w){
	e[u].push_back({v,w});
}//end

ll s[N],a[N];

bool vis[N];
int rt;
int sz[N],sum,maxson[N];

void calcsiz(int x,int fa){
	sz[x]=1; maxson[x]=0; 
	for(auto nxt:e[x]){
		int y=nxt.first,w=nxt.second;
		if(y==fa||vis[y]) continue;
		calcsiz(y,x);
		sz[x]+=sz[y];
		maxson[x]=max(maxson[x],sz[y]);
 	}
 	maxson[x]=max(maxson[x],sum-sz[x]);
 	if(maxson[x]<maxson[rt]) rt=x;
}//end

int i1f,i1n,i2f,i2n;//下标 
ll t1f[N],t1n[N],t2f[N],t2n[N];

ll ch[N],dic[N];

void dfs2(int x,int fa,ll dianh,ll bianh){ 
	for(auto nxt:e[x]){
		int y=nxt.first,w=nxt.second;
		if(y==fa||vis[y]) continue;
		ch[y]=min(ch[x]+a[y]-w,a[y]-w);//维护最小前缀区间和 
		if(ch[y]>=0) t1n[++i1n]=dianh+a[y]-bianh-w;
		dfs2(y,x,dianh+a[y],bianh+w);
	}
}//end

void dfs3(int x,int fa,ll mindic){ 
	for(auto nxt:e[x]){
		int y=nxt.first,w=nxt.second;
		if(y==fa||vis[y]) continue;
		dic[y]=dic[x]+a[x]-w;
		int nowmindic=min(mindic,dic[y]);
		t2n[++i2n]=nowmindic;
		dfs3(y,x,nowmindic);
	}
}//end

ll ans=0;

void solve(int x,int fa){
	vis[x]=1;
	ch[x]=0;
	
	i1f=i2f=0;
	
	t1f[++i1f]=0;//根节点本身 
	t2f[++i2f]=0;
	
	for(auto nxt:e[x]){
		int y=nxt.first,w=nxt.second;
		if(y==fa||vis[y]) continue;
		ch[y]=ch[x]+a[y]-w;//前缀和 
		dic[y]=a[x]-w;
		i1n=i2n=0;
		
		if(ch[y]>=0) t1n[++i1n]=ch[y];
		dfs2(y,x,a[y],w); 
		
		t2n[++i2n]=dic[y];
		dfs3(y,x,dic[y]);
		
		sort(t1n+1,t1n+i1n+1);
		sort(t2n+1,t2n+i2n+1);
		
		int r=i1f+1;
		for(int i=1;i<=i2n;i++){
			while(r>1&&t1f[r-1]+t2n[i]>=0) r--;
			ans+=(i1f-r+1);
		}
		
		r=i1n+1;
		for(int i=1;i<=i2f;i++){
			while(r>1&&t1n[r-1]+t2f[i]>=0) r--;
			ans+=(i1n-r+1);
		}
		
		for(int i=1;i<=i1n;i++) t1f[++i1f]=t1n[i];
		for(int i=1;i<=i2n;i++) t2f[++i2f]=t2n[i];
		
		sort(t1f+1,t1f+i1f+1);
		sort(t2f+1,t2f+i2f+1);
	}
	
	for(auto nxt:e[x]){
		int y=nxt.first,w=nxt.second;
		if(y==fa||vis[y]) continue;
		sum=sz[y];
		rt=0;
		calcsiz(y,x);
		calcsiz(rt,x);
		solve(rt,x);
	}
}//end

int main(){
	freopen("1.in","r",stdin);
//	freopen("transport.out","w",stdout);
	
	ios::sync_with_stdio(0);
	
	cin>>n;
	
	for(int i=1;i<=n;i++) cin>>a[i];
	
	for(int i=1;i<n;i++){
		int u,v,w; cin>>u>>v>>w;
		add(u,v,w); add(v,u,w);
	}
	
	maxson[0]=(int)1e9;
	rt=0; sum=n;
	calcsiz(1,0);
	calcsiz(rt,0);
	solve(rt,0);
		
	cout<<ans<<endl;
	
	return 0;
}//end
2024/11/21 21:35
加载中...