题意:
python 里面,给出 n 个 for 循环或陈述语句,’f’ 里面必须要有语句。按 python 缩进的方式组合成合法的程序,最后一行一定为陈述。问有多少种可能方案。
思路:
dp[i][j]代表第i行缩进j的方案数。答案即为∑dp[n][k] (0<=k<=n-1)
当第 i 个是 f 时:第 i+1 个字符一定缩进,即dp[i+1][j+1]=dp[i][j]
当第 i 个是 s 时:第 i+1 个字符的缩进量 <= 第 i 个字符的缩进量,dp[i+1][j]=∑dp[i][k] (j<=k<=n-1)
(可能不是很好理解,我看了好长时间的解题报告才想通orz)
代码:
#include<bits/stdc++.h>
using namespace std;
int dp[5005][5005];
typedef long long LL;
const LL mod = 1e9+7;
int main()
{
int n, i, j;
LL sum;
char c;
cin>>n;
getchar();
dp[1][0]=1;
for(i=1; i<=n; i++)
{
cin>>c;
if(c=='f')
{
for(j=0; j<n; j++)
{
dp[i+1][j+1]=dp[i][j];
}
}
else
{
sum=0;
for(j=n-1; j>=0; j--)
{
sum=(sum+dp[i][j])%mod;
dp[i+1][j]=sum;
}
}
}
sum=0;
for(j=0; j<n; j++)
sum=(sum+dp[n][j])%mod;
cout<<sum<<endl;
return 0;
}