求调,只有18分,总是步数多了,不知道是什么问题
查看原帖
求调,只有18分,总是步数多了,不知道是什么问题
310773
PCCP楼主2023/1/3 21:15

调了两个小时了,仍然不知道是什么问题,求各位大佬帮忙调试,可以提供一关注的感谢。

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
const int N=2e6+10;
int n,h[N],fa[N],size[N];
int he[N<<1],ne[N<<1],to[N<<1],tot=0;
long long sum,ave,siva[N];
struct act{
	int be,en;
	long long num;
};
vector <act> q;
void addedge(int x,int y){
	to[++tot]=y;
	ne[tot]=he[x];
	he[x]=tot;
}
void dfs(int now,int f){
	fa[now]=f;
	++size[now];
	siva[now]=h[now];
	for(int i=he[now];i;i=ne[i]){
		int v=to[i];
		if(v==fa[now]){
			continue;
		}
		dfs(v,now);
		size[now]+=size[v];
		siva[now]+=siva[v];
	}
}
void work(int now){
	for(int i=he[now];i;i=ne[i]){
		int v=to[i];
		if(v==fa[now]||siva[v]<(long long)size[v]*ave){
			continue;
		}
		work(v);
		if(h[v]>ave){
			long long change;
			act a;
			change=h[v]-ave;
			a={v,now,change};
			q.push_back(a);
			siva[v]-=change;
			h[v]-=change;
			h[now]+=change;
			//cout<<"from: "<<v<<" to: "<<now<<" change: "<<change<<endl;
			//cout<<v<<" : "<<siva[v]<<" & "<<now<<" : "<<siva[now]<<endl;
		}
	}
	for(int i=he[now];i;i=ne[i]){
		int v=to[i];
		if(v==fa[now]||siva[v]==(long long)size[v]*ave){
			continue;
		}
		if(siva[v]<(long long)size[v]*ave){
			long long change;
			act a;
			change=(long long)size[v]*ave-siva[v];
			a={now,v,change};
			q.push_back(a);
			siva[v]+=change;
			h[v]+=change;
			h[now]-=change;
			//cout<<"from: "<<now<<" to: "<<v<<" change: "<<change<<endl;
			//cout<<now<<" : "<<siva[now]<<" & "<<v<<" : "<<siva[v]<<endl;
			work(v);
		}
		
	}
}
int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++){
		scanf("%d",&h[i]);
		sum+=h[i];
	}
	ave=sum/n;
	int x,y;
	for(int i=1;i<n;i++){
		scanf("%d%d",&x,&y);
		addedge(x,y);
		addedge(y,x);
	}
	dfs(1,0);
	/*for(int i=1;i<=n;i++){
		cout<<i<<" "<<size[i]<<" "<<siva[i]<<endl;
	}*/
	work(1);
	printf("%d\n",q.size());
	vector <act>::iterator item;
	for(item=q.begin();item!=q.end();item++){
		act a;
		a=*item;
		printf("%d %d %lld\n",a.be,a.en,a.num);
	}
	return 0;
}
2023/1/3 21:15
加载中...