点分治95pts悬关求调
查看原帖
点分治95pts悬关求调
752711
hateful_bug楼主2024/12/11 13:18

WA 7

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=2e5+10,inf=0x3f3f3f3f;
int n,K,h[N],b[N<<1],nx[N<<1],v[N<<1],tt,d[N],root,ans=inf,zsh[N],sum,maxp[N],now[N],dep[N],his[N*5],q[N];
bool pd[N];
void zj(int x,int y,int z)
{
	b[++tt]=y;
	v[tt]=z;
	nx[tt]=h[x];
	h[x]=tt;
}
void dfs(int x,int fa)
{
	for(int i=h[x];i;i=nx[i])
	{
		int y=b[i];
		if(pd[y]||y==fa)
		continue;
		dep[y]=dep[x]+1;
		dfs(y,x);
	}
}
void getroot(int x,int fa)
{
	zsh[x]=1;maxp[x]=0;
	for(int i=h[x];i;i=nx[i])
	{
		int y=b[i],z=v[i];
		if(pd[y]||y==fa)
		continue;
		getroot(y,x);
		zsh[x]+=zsh[y];
		maxp[x]=max(maxp[x],zsh[y]);
	}
	maxp[x]=max(maxp[x],sum-zsh[x]);
	if(maxp[x]<maxp[root])
	root=x;
}
void getdis(int x,int fa)
{
	now[++now[0]]=x;
	for(int i=h[x];i;i=nx[i])
	{
		int y=b[i],z=v[i];
		if(pd[y]||y==fa)
		continue;
		d[y]=d[x]+z;
		getdis(y,x);
	}
}
void calc(int x)
{
	int p=0;
	q[0]=0;
	his[0]=x;
	dfs(x,0);
	for(int i=h[x];i;i=nx[i])
	{
		int y=b[i],z=v[i];
		if(pd[y])
		continue;
		d[x]=0;
		d[y]=z;
		now[0]=0;
		getdis(y,0);
		for(int j=1;j<=now[0];j++)
		{
			if(K-d[now[j]]>=0&&his[K-d[now[j]]])
			ans=min(ans,dep[now[j]]+dep[his[K-d[now[j]]]]-2*dep[x]);	
		}
		for(int j=1;j<=now[0];j++)
		if(d[now[j]]<=K)
		his[d[now[j]]]=now[j],q[++p]=d[now[j]];
	}
	for(int i=0;i<=p;i++)
	his[q[i]]=0;
}
void solve(int x)
{
	pd[x]=true;
	calc(x);
	for(int i=h[x];i;i=nx[i])
	{
		int y=b[i];
		if(pd[y])
		continue;
		maxp[0]=inf;
		root=0;
		sum=zsh[y];
		getroot(y,0);
		dep[root]=0;
		dfs(root,0);
		solve(root);
	}
}
signed main()
{
	scanf("%lld%lld",&n,&K);
	for(int i=1;i<n;i++)
	{
		int x,y,z;
		scanf("%lld%lld%lld",&x,&y,&z);
		zj(x+1,y+1,z);zj(y+1,x+1,z);
	}
	maxp[0]=inf;
	root=0;
	sum=n;
	getroot(1,0);
	dep[root]=0;
	dfs(root,0);
	solve(root);
	if(ans==inf)
	ans=-1;
	printf("%lld",ans);
	return 0;
}
2024/12/11 13:18
加载中...