题意
分析
\[
f(i)=f(c_1)f(c_2)\dots\times(s(i)-1)!/(s(c_1)!s(c_2)! \dots s(c_k)! )\\
f(root)=(s(root)-1)!/(s(1)s(2)s(3)\dots s(n))
\]
预处理阶乘以及逆元。
时间复杂度\(O(Tn)\)
代码
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<set>
#include<map>
#include<queue>
#include<stack>
#include<algorithm>
#include<bitset>
#include<cassert>
#include<ctime>
#include<cstring>
#define rg register
#define il inline
#define co const
template<class T>il T read()
{
rg T data=0;
rg int w=1;
rg char ch=getchar();
while(!isdigit(ch))
{
if(ch=='-')
w=-1;
ch=getchar();
}
while(isdigit(ch))
{
data=data*10+ch-'0';
ch=getchar();
}
return data*w;
}
template<class T>T read(T&x)
{
return x=read<T>();
}
using namespace std;
typedef long long ll;
co int N=4e4+1,mod=1e9+7;
int fac[N],inv[N];
int mul(int x,int y)
{
return (ll)x*y%mod;
}
int qpow(int x,int k)
{
int res=1;
while(k)
{
if(k&1)
res=mul(res,x);
x=mul(x,x),k>>=1;
}
return res;
}
int n,fa[N];
int nx[N],to[N];
int siz[N];
void dfs(int x)
{
siz[x]=1;
for(int i=to[x];i;i=nx[i])
{
dfs(i);
siz[x]+=siz[i];
}
}
int main()
{
// freopen(".in","r",stdin);
// freopen(".out","w",stdout);
fac[0]=fac[1]=1;
inv[0]=inv[1]=1;
for(int i=2;i<N;++i)
{
fac[i]=mul(i,fac[i-1]);
inv[i]=mul(mod-mod/i,inv[mod%i]);
}
int T=read<int>();
while(T--)
{
read(n);
fill(fa,fa+n+1,0);
fill(nx,nx+n+1,0);
fill(to,to+n+1,0);
int m=read<int>();
for(int i=1;i<=m;++i)
{
int a=read<int>(),b=read<int>();
fa[a]=b;
nx[a]=to[b],to[b]=a;
}
for(int i=1;i<=n;++i)
if(!fa[i])
nx[i]=to[0],to[0]=i;
dfs(0);
int ans=fac[n];
for(int i=1;i<=n;++i)
ans=mul(ans,inv[siz[i]]);
printf("%d\n",ans);
}
return 0;
}