【POI 2014】Hotel

传送门


Problem

有一颗有 n n n 个点的树,边权为 1 1 1

求满足 d i s x , y = d i s y , z = d i s x , z dis_{x,y}=dis_{y,z}=dis_{x,z} disx,y=disy,z=disx,z 的无序三元组 ( x , y , z ) (x,y,z) (x,y,z) 的数量( x , y , z x,y,z x,y,z 两两不同)。

数据范围: n ≤ 1 0 5 n≤10^5 n105


Solution

先贴一篇题解吧,明天再写。

https://blog.csdn.net/qq_42555009/article/details/88917806


Code

#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 100005
#define ll long long
using namespace std;
int n,t;
int first[N],v[N<<1],nxt[N<<1];
int son[N],len[N];
ll ans,temp[N<<2],*f[N],*g[N],*pos=temp;
void add(int x,int y){
	nxt[++t]=first[x],first[x]=t,v[t]=y;
}
void dfs(int x,int fa){
	for(int i=first[x];i;i=nxt[i]){
		int to=v[i];
		if(to==fa)  continue;
		dfs(to,x);
		if(len[to]>len[son[x]])  son[x]=to;
	}
	len[x]=len[son[x]]+1;
}
void dp(int x,int fa){
	if(son[x])  f[son[x]]=f[x]+1,g[son[x]]=g[x]-1,dp(son[x],x);
	f[x][0]=1,ans+=g[x][0];
	for(int i=first[x];i;i=nxt[i]){
		int to=v[i];
		if(to==fa||to==son[x])  continue;
		f[to]=pos,pos+=len[to],g[to]=pos+len[to],pos+=2*len[to];
		dp(to,x);
		for(int j=len[to]-1;~j;--j){
			ans+=g[x][j+1]*f[to][j];
			if(j)  ans+=f[x][j-1]*g[to][j];
			g[x][j+1]+=f[x][j+1]*f[to][j];
			f[x][j+1]+=f[to][j];
		}
		for(int j=len[to]-1;j;--j)  g[x][j-1]+=g[to][j];
	}
}
int main(){
	int x,y,i;
	scanf("%d",&n);
	for(i=1;i<n;++i){
		scanf("%d%d",&x,&y);
		add(x,y),add(y,x);
	}
	dfs(1,0);
	f[1]=pos,pos+=len[1],g[1]=pos+len[1],pos+=2*len[1];
	dp(1,0);
	printf("%lld",ans);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值