题解:P13020 [GESP202506 八级] 遍历计数
P13020 [GESP202506 八级] 遍历计数 题解
题目链接
转至专栏阅读
解题思路
题目让我们计算一棵树上所有不同的 DFS 序的数量。将题目转化一下:计算在 DFS 的过程中,每一步有多少种选择,然后将所有选择数相乘。
设
先考虑固定起点的情况。对于起点
以该节点为起点的情况数为:
所以总数为:
因为所有顶点的度数之和等于边数的两倍。所以在一棵有
将此结果代回到原式中,总数为:
注意:当
参考代码
#include<iostream>
using namespace std;
const int N=1e5+5,mod=1e9;
int n,ans;
int deg[N],fac[N]={1};
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cin>>n;
ans=2*(n-1);
if(n==1){
cout<<1;
return 0;
}
for(int i=1;i<=n;i++) fac[i]=1ll*fac[i-1]*i%mod;
for(int i=1,x,y;i<n;i++){
cin>>x>>y;
deg[x]++,deg[y]++;
}
for(int i=1;i<=n;i++) ans=1ll*ans*fac[deg[i]-1]%mod;
cout<<ans;
return 0;
}
AC 记录