HDU

来源:互联网 发布:淘宝退换货退款流程 编辑:程序博客网 时间:2024/05/16 23:54


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"

....

IIIDDIDD?D??
Sample Output
122136          
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呦

好好干


原创粉丝点击