跳到正文

题解

题解:CF288D Polo the Penguin and Trees

wflhx2011约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年1月12日
收录
2026年2月11日
更新
2026年11月11日
篇幅
约 3 分钟
题目
CF288D

版本

  1. v2当前
  2. v1

这道题要求没有交点的路径数量,但我不知道要怎么快速判断两条路径有无交点。

所谓正难则反,考虑从总情况中减掉有交点的情况。

总情况是任选两个不相同的 aa,bb 的方案,再任选两个不相同的 cc,dd 的方案,两个相乘。即 Cn2∗Cn2=n2(n−1)24C_n^2*C_n^2=\frac{n^2(n-1)^2}{4}。

求有交点的路径数量,因为 nn 很小所以可以枚举。

设交点为 xx,这时两条路径有几种情况:

  1. 两条路径都在 xx 子树内。

为了不重复计算,让两条路径位于两个不同的 xx 的儿子节点子树内。

避免枚举造成时间复杂度过大,也考虑容斥,答案 ans1ans1 就是 (Csizx2−∑u∈sonxCsizu2)2(C_{siz_x}^2-\sum_{u\in son_x} C_{siz_u}^2)^2。

  1. 一条路径在子树内,另一条在子树外。

子树内就是 ans1ans1,子树外是 sizx×(n−sizx)siz_x \times (n-siz_x),把这两个乘起来。

  1. 两条都在子树外。但因为是一棵树,所以他们会在 xx 的祖先上也产生交点,重复了不管。

减一下就是答案。

C++
#include<bits/stdc++.h>
using namespace std;
long long n,tot;
long long sum,head[200005],siz[200005];
struct edge
{
	long long f,t;
}e[200005];
void add(long long x,long long y)
{
	e[++tot].t=y;
	e[tot].f=head[x];
	head[x]=tot;
}
void dfs(long long u,long long fa)
{
	siz[u]=1;
	long long ans1=0,ans2=0;
	for(long long i=head[u];i;i=e[i].f)
	{
		if(e[i].t==fa)
			continue;
		dfs(e[i].t,u);
		siz[u]+=siz[e[i].t];
		ans1-=1ll*siz[e[i].t]*(siz[e[i].t]-1)/2ll;
	}
	ans1+=(long long)(1ll*siz[u]*(siz[u]-1)/2ll);
	ans2+=(long long)(1ll*siz[u]*(n-siz[u]));
//	cout<<ans1<<" "<<ans2<<endl;
	sum+=(long long)(1ll*ans1*ans1+ans1*ans2*2ll);
}
int main()
{
	cin>>n;
	for(long long i=1;i<n;i++)
	{
		long long u,v;
		cin>>u>>v;
		add(u,v);
		add(v,u);
	}
	dfs(1,0);
//	cout<<sum<<endl;
	cout<<(long long)((long long)(1ll*n*1ll*(n-1)/2ll)*(long long)(1ll*n*1ll*(n-1)/2ll)-sum);
	return 0;
}
原文