1、匹配方案(卡特兰数)
问:长度为n的括号字符串,有多少种匹配方案?
令h(0)=1,h(1)=1,catalan数满足递推式:
h(n)= h(0)*h(n-1)+h(1)*h(n-2) + … + h(n-1)*h(0) (n>=2)
例如:h(2)=h(0)*h(1)+h(1)*h(0)=1*1+1*1=2
h(3)=h(0)*h(2)+h(1)*h(1)+h(2)*h(0)=1*2+1*1+2*1=5
另类递推式:
h(n)=h(n-1)(4*n-2)/(n+1)
递推关系的解为:
h(n)=C(2n,n)/(n+1) (n=0,1,2,…)
递推关系的另类解为:
h(n)=c(2n,n)-c(2n,n-1)(n=0,1,2,…)
code:
#include <iostream>
using namespace std;
int main() {
long long num[16];
num[0]=1;
num[1]=1;
for(int i = 2;i<=15;i++)
num[i] = num[i-1]*(4*i-2)/(i+1);
printf("%lld",num[15]);
}
2、字符串哈希转换(相比map节约了时间和空间)
http://poj.org/problem?id=1200
题意:给定字符串,n,nc 。 nc表示该字符串不同字母个数, n表示切分成长度n的子串,问可切成不同子串数
思路:字符转换成数字的思想,例如 123 这个数字 是又1*100+2*10+3 组成,他拥有独一无二的地位,不会重复,那么如何给字符串分配类似的哈希值呢 , 假设现在有4种字符 ,a b c d 那么分别令为0123 ,那么abcd可以表示成 0*4*4*4 + 1*4*4 + 2*4 + 3
code:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <map>
using namespace std;
const int maxn = 16000005;
char st[maxn];
int hash[150];
bool mp[maxn];
int main()
{
int n,m;
memset(hash,0,sizeof(hash));
memset(mp,0,sizeof(mp));
while(~scanf("%d%d",&n,&m))
{
scanf("%s",st);
int len = strlen(st);
int cnt = 1;
for(int i=0; i<len; i++)
if(!hash[st[i]])
{
hash[st[i]] = cnt++;
}
int ans = 0;
for(int i=0; i<=len-n; i++)
{
int tmp = 0;
for(int j=i; j<n+i; j++)
{
tmp = tmp*m + hash[st[j]];
}
if(!mp[tmp])
{
mp[tmp] = 1;
ans++;
}
else
mp[tmp] = 1;
}
printf("%d\n",ans);
}
return 0;
}