HDU - 4055 (dp)


jThe signature of a permutation is a string that is computed as follows: for each pair of consecutive elements of the permutation, write down the letter 'I' (increasing) if the second element is greater than the first one, otherwise write down the letter 'D' (decreasing). For example, the signature of the permutation {3,1,2,7,4,6,5} is "DIIDID"

....

II
ID
DI
DD
?D
??
Sample Output
1
2
2
1
3
6

        
  
Hint
Permutation {1,2,3} has signature "II".
Permutations {1,3,2} and {2,3,1} have signature "ID".
Permutations {3,1,2} and {2,1,3} have signature "DI".
Permutation {3,2,1} has signature "DD".
"?D" can be either "ID" or "DD".
"??" gives all possible permutations of length 3.

        
 



这个题目我以为是找规律,比完之后看了看题解发现是dp

就是对于题解



对于字符串S

s[i-1]  ='I'   dp[i] [j]=dp[i-1][j]+dp[i-1][j-2]+....+dp[i-1][1];

s[i-1]='D'   dp[i][j]=dp[i-1][j]+dp[i][j+1]+dp[i-1][j+2]+...}dp[i][i];

因为要令当前位为j,如果前面出现过j,就令前面的所有大于等于j的数+1,就能构造出新的排列了。比如

{1, 3, 5, 2, 4},要在第六位插入3,令 >= 3的数都+1,于是就构造出新的 排列{1, 4, 6, 2, 5, 3}。然后代码的话处理出前缀和sum[i][j],就不用dp[i][j]了。感觉还是很巧妙的,


代码中对于D的部分由于是1到i+1 部分是顺序相加,所以用sum和去相减的方法来求效果是一样的。


#include <iostream>
#include<cstring>
#include<string>
#include<algorithm>

using namespace std;

const int maxn=1000+5;
long long  sum[maxn][maxn];


int main()
{
    string s;
    int mod=1000000007;
    while(cin>>s)
    {
         memset(sum,0,sizeof(sum));
         sum[0][1]=1;
         int len=s.size();
         for(int i=1;i<=len;i++)
         {
             for(int j=1;j<=i+1;j++)
             {
                 sum[i][j]=sum[i][j-1];
                 if(s[i-1]!='I')
                    sum[i][j]+=sum[i-1][i]-sum[i-1][j-1]+mod;
                 if(s[i-1]!='D')
                    sum[i][j]+=sum[i-1][j-1];
                 sum[i][j]=sum[i][j]%mod;
             }
         }
         cout<<sum[len][len+1]<<endl;
    }

  //  cout << "Hello world!" << endl;
    return 0;
}


dp呦

好好干


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值