题解:P12639 [UOI 2020] Topological Sorting of a Tree
思路
考虑 DP,设
将
此时考虑
注意到可以前缀和优化这个过程,且
代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 3005,mod = 1e9+7;
int n,c[N][N],f[N][N],sz[N];
char ch[N];
vector<int> g[N];
void dfs(int u,int fa)
{
f[u][1] = 1,sz[u] = 1;
for(auto v:g[u])
{
if(v==fa) continue;
dfs(v,u);
for(int i = sz[u];i;i--)
{
int tmp = f[u][i];
f[u][i] = 0;
for(int j = 0;j<=sz[v];j++)
{
int now = tmp*c[i+j-1][i-1]%mod*c[sz[u]+sz[v]-(i+j)][sz[u]-i]%mod;
if(ch[v]=='<') now = now*(f[v][sz[v]]-f[v][j]+mod);
else now = now*f[v][j];
(f[u][i+j]+=now)%=mod;
}
}
sz[u]+=sz[v];
}
for(int i = 1;i<=sz[u];i++)
f[u][i] = (f[u][i-1]+f[u][i])%mod;
}
signed main()
{
// freopen(".in","r",stdin);
// freopen(".out","w",stdout);
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
c[0][0] = 1;
for(int i = 1;i<N;i++)
{
c[i][0] = 1;
for(int j = 1;j<N;j++)
c[i][j] = (c[i-1][j-1]+c[i-1][j])%mod;
}
cin>>n;
for(int i = 2,x;i<=n;i++)
cin>>x>>ch[i],g[x].push_back(i);
dfs(1,0);
cout<<f[1][n];
return 0;
}