您的位置:首页 > 其它

pku 1850 Code(组合数学,DP)

2009-08-11 17:21 453 查看
题意:字符串,长度可以是1-26,串中不能有重复的字符,串中的字符必须按增序排列。字母表后的字符大于字母表前的字符,长的字符大于短的字符。给定一个字符串,问这是第几个满足要求的串。

 

我自己想的是用DP,0ms。

做完后看discuss,其实可以直接用组合数学做,因为字母必须递增排列,所以数选好了位置就定了,这样就不是很难。

后来回过头来看自己DP的代码,突然觉得和算好组合数C(n,k)的数学做法好像好像。

// pku 1496.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
int DP[11][30],DP2[11][30];
void init()
{
memset(DP,0,sizeof(DP));//DP[i][j]表示第i位是j的时候,有多少种排列
memset(DP2,0,sizeof(DP2));//DP2[i][j]表示第i位是j的时候,有多少种排列在前面
for(int i=1;i<=26;i++)
{
DP[1][i]=1;
}
for(int i=2;i<=5;i++)
{
for(int j=25;j>0;j--)
{
DP[i][j]=DP[i][j+1]+DP[i-1][j+1];
}
}
for(int i=1;i<=5;i++)
{
DP2[i][1]=DP2[i-1][26]+DP[i-1][26];
for(int j=2;j<=26;j++)
{
DP2[i][j]=DP[i][j-1]+DP2[i][j-1];
}
}
}
int main()
{
init();
char str[15];
while(scanf("%s",str+1)!=EOF)
{
_strrev(str+1);
int len=strlen(str+1),ans;
ans=DP2[len][str[len]-'a'+1];
str[len+1]='a'-1;
for(int i=len-1;i>0;i--)
{
if(str[i]<=str[i+1])
{
ans=-1;
break;
}
for(int j=str[i+1]-'a'+1+1;j<str[i]-'a'+1;j++)
{
ans+=DP[i][j];
}
}
printf("%d/n",ans+1);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c