Problem J
Stand in a Line
Input: Standard Input
Output: Standard Output
All the people in the byteland want to stand in a line in such a way that no
person stands closer to the front of the line than his father. You are given
the information about the people of the byteland. You have to determine the number of ways the bytelandian people can stand in a line.
Input
First line of the input contains
T (T<14) the number of test case. Then following lines contains T Test
cases.
Each test case starts with 2
integers n (1≤n≤40000) and m (0≤m<n). n is the number of
people in the byteland and m is the number of people
whose father is alive. These n people are numbered 1...n.Next m line contains two integers a
and b denoting that b is the father of a. Each person can have at most
one father. And no person will be an ancestor of himself.
Output
For each test case the output
contains a single line denoting the number of different ways the soldier can
stand in a single line. The result may be too big. So always output the remainder
on dividing ther the result by 1000000007.
Sample Input Output for
Sample Input
3 3 2 2 1 3 1 3 0 3 1 2 1 |
2 6 3
|
Problem setter: Abdullah-al-Mahmud
Special Thanks: Derek Kisman
这道题结论很有意思。
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int mod=;
const int maxn=;
int cnt,fir[maxn],to[maxn],nxt[maxn];
int fa[maxn],sz[maxn];
long long inv[maxn]; void addedge(int a,int b){
nxt[++cnt]=fir[a];to[cnt]=b;fir[a]=cnt;
} void DFS(int x){
sz[x]=;
for(int i=fir[x];i;i=nxt[i]){
DFS(to[i]);
sz[x]+=sz[to[i]];
}
} void Solve(int n){
DFS();
long long ans=;
for(int i=;i<sz[];i++)
(ans*=i)%=mod; for(int i=;i<=n;i++)
(ans*=inv[sz[i]])%=mod; printf("%lld\n",ans);
} int main(){
#ifndef ONLINE_JUDGE
//freopen("","r",stdin);
//freopen("","w",stdout);
#endif
inv[]=;
for(int i=;i<=;i++){
inv[i]=(1ll*inv[mod%i]*(mod-mod/i))%mod;
//printf("%lld\n",inv[i]);
} int T,n,m;
scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&m);
memset(fir,,sizeof(fir));
memset(fa,,sizeof(fa));cnt=;
for(int i=,a,b;i<=m;i++){
scanf("%d%d",&a,&b);
fa[a]=;addedge(b,a);
}
for(int i=;i<=n;i++)
if(fa[i]==)
addedge(,i); Solve(n);
}
return ;
}