点分写挂,求dalao查错qaq
查看原帖
点分写挂,求dalao查错qaq
37881
yzhang楼主2018/11/17 21:35
#include <bits/stdc++.h>
#define N 50005
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
inline int read()
{
	register int x=0,f=1;register char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
	while(ch>='0'&&ch<='9')x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
	return x*f;
}
inline void write(register ll x)
{
	if(!x)putchar('0');if(x<0)x=-x,putchar('-');
	static int sta[36];int tot=0;
	while(x)sta[tot++]=x%10,x/=10;
	while(tot)putchar(sta[--tot]+48);
}
inline int Max(register int a,register int b)
{
	return a>b?a:b;
}
struct node{
	int to,next,v;
}e[N<<1];
int head[N],tot=0;
inline void add(register int u,register int v,register int k)
{
	e[++tot]=(node){v,head[u],k};
	head[u]=tot;
}
int n,k;
int size[N];
int rt,sizee,mx;
bool vis[N];
ll ans=0;
ll d[N],q[N],l,r;
inline void getroot(register int u,register int fa)
{
	size[u]=1;
	int num=0;
	for(register int i=head[u];i;i=e[i].next)
	{
		int v=e[i].to;
		if(v==fa||vis[v])
			continue;
		getroot(v,u);
		size[u]+=size[v];
		num=Max(num,size[v]);
	}
	num=Max(num,sizee-size[u]);
	if(mx>num)
		mx=num,rt=u;
}
inline void getdis(register int u,register int fa)
{
	q[++r]=d[u];
	for(register int i=head[u];i;i=e[i].next)
	{
		int v=e[i].to;
		if(v==fa||vis[v])
			continue;
		d[v]=d[u]+e[i].v;
		getdis(v,u);
	}
}
inline ll solve(register int u,register int val)
{
	r=0;
	d[u]=val;
	getdis(u,0);
	ll sum=0;
	l=1;
	sort(q+1,q+r+1);
	while(l<r)
	{
		if(q[l]+q[r]<=k)
			sum+=r-l,++l;
		else
			--r;
	}
	return sum;
 } 
inline void devide(register int u)
{
	ans+=solve(u,0);
	vis[u]=true; 
	int totsize=sizee;
	for(register int i=head[u];i;i=e[i].next)
	{
		int v=e[i].to;
		if(vis[v])
			continue;
		ans-=solve(v,e[i].v);
		rt=0,sizee=size[v]>size[u]?totsize-size[u]:size[v],mx=inf;
		getroot(v,0);
		devide(rt);
	}
}
int main()
{
	n=read(),k=read();
	for(register int i=1;i<n;++i)
	{
		int u=read(),v=read();
		add(u,v,1),add(v,u,1);
	}
	sizee=n,mx=inf;
	getroot(1,rt=0);
	devide(rt);
	write(ans);
	return 0;
}
2018/11/17 21:35
加载中...