(dp专题003)hdu 4055 Number String(dp)
题意:给出n(n<=1E3)个字符,字符可能为'D','I','?',第i位对应的字符分别表示,第i位大于第i+1位,第i位小于第i+1位,或者不确定。
现在问满足该字符串的 1..n的排列的方案数。结果9+7
思路:没有太多思路,参考了题解
主要是状态表示没有想到,后面的状态转移方程倒是不难。
思路是,dp[i][j]表示长度为i,最后一位的相对大小为j的方案数。
考虑转移:如果第i-1个位置的字符为‘I’,那么所有比j小的都可以转移到j,也就是dp[i][j] = dp[i-1][1] + dp[i-1][2] + ... + dp[i-1][j-2] + dp[i-1][j-1];
如果第i-1个位置的字符是'D',此时是这道题的重点。
有这个一个有趣的性质,比如对于一个排列{1,3,2},现在我们在递推得到dp[4][2],也就是要把2添加到这个排列的最后面,现在把当前排列即{1,3,2}中大于等于2的全部加上一得到{1,4,3},这样是仍然不会改变题目给出的关系的,然后我们再把2添加到最后,{1,4,3,2},就可以得到dp[4][2]了
此时的复杂度是n3,可以用前缀和优化掉一个n,复杂度n方。
最后答案就是sum[len+1][len+1]
1/***************************************************
2Author :111qqz
3************************************************ */
4#include <cstdio>
5#include <cstring>
6#include <iostream>
7#include <algorithm>
8#include <vector>
9#include <queue>
10#include <stack>
11#include <set>
12#include <map>
13#include <string>
14#include <cmath>
15#include <cstdlib>
16#include <deque>
17#include <ctime>
18#define fst first
19#define sec second
20#define lson l,m,rt<<1
21#define rson m+1,r,rt<<1|1
22#define ms(a,x) memset(a,x,sizeof(a))
23typedef long long LL;
24#define pi pair < int ,int >
25#define MP make_pair
26using namespace std;
27const double eps = 1E-8;
28const int dx4[4]={1,0,0,-1};
29const int dy4[4]={0,-1,1,0};
30const int inf = 0x3f3f3f3f;
31const int N=1E3+7;
32const int mod = 1000000007;
33char st[N];
34int dp[N][N],sum[N][N];//dp[i][j]表示长度为i,最后结尾的字符的相对大小为j的方案数。
35int main()
36{
37 #ifndef ONLINE_JUDGE
38 // freopen("D:\code\in.txt","r",stdin);
39 #endif
while (~scanf("%s",st+2))
{
1 int len = strlen(st+2);
2 // cout<<"len:"<<len<<endl;
3 ms(sum,0);
4 ms(dp,0);
5 dp[1][1] = 1;
6 sum[1][1] = 1;
7 for ( int i = 2 ; i <= len+1 ; i++)
8 {
9 for ( int j = 1 ; j <= i ; j++)
10 {
11 if ( st[i]=='?'||st[i]=='I') dp[i][j] = (dp[i][j] + sum[i-1][j-1])%mod;
12 if (st[i]=='?'||st[i]=='D')
13 {
14 int tmp = ((sum[i-1][i-1]-sum[i-1][j-1])%mod+mod)%mod;
15 dp[i][j] = (dp[i][j] + tmp)%mod;
16 }
17 sum[i][j] = (sum[i][j-1] + dp[i][j])%mod;
18 }
19 }
20 printf("%d\n",sum[len+1][len+1]);
21 }
1#ifndef ONLINE_JUDGE
2 fclose(stdin);
3 #endif
4 return 0;
5}