dp--dhu1502

http://blog.csdn.net/jiang199235jiangjj/article/details/7452389

Consider words of length 3n over alphabet {A, B, C} . Denote the number of occurences of A in a word a as A(a) , analogously let the number of occurences of B be denoted as B(a), and the number of occurenced of C as C(a) . 

Let us call the word w regular if the following conditions are satisfied: 

A(w)=B(w)=C(w) ; 
if c is a prefix of w , then A(c)>= B(c) >= C(c) . 
For example, if n = 2 there are 5 regular words: AABBCC , AABCBC , ABABCC , ABACBC and ABCABC . 

Regular words in some sense generalize regular brackets sequences (if we consider two-letter alphabet and put similar conditions on regular words, they represent regular brackets sequences). 

Given n , find the number of regular words.


我之前是用递归做的,就是和做括号组合的种类一样的思路,想不到还是有递归的方法。

解题:设函数dp[i][j][k]表示该序列中有i个A,j个B,k个C组成,则dp[i][j][k]是有dp[i-1][j][k],dp[i][j-1][k],dp[i][j][k-1]这三个添加过来的,所以动态转移方程式

dp[i][j][k]=dp[i-1][j][k]+dp[i][j-1][k]+dp[i][j][k-1];同时注意,dp的结果很大,要用到大数。

设sum[i]表示当n为i时的结果,即当i==j==k时的结果。(注意:把dp和sum都定义成char型数组,否则会超存)。



#include <iostream>
#include <stdio.h>
#include <string.h>
#include <cmath>
#define N 80
using namespace std;

char num[62][N],dp[62][62][62][N];

void sum(char a[N],char b[N])
{
	int n=a[0],m=b[0],i,j,k;
	a[0]=k=max(n,m);	
	for(i=1;i<=k;i++)
	{
		a[i]+=b[i];
		if(a[i]>9)
		{
			a[i+1]++;			a[i]%=10;
			if(i+1>k)
			{
				k++;a[0]++;
			}
		}
	}
}
void cpy(char a[N],char b[N])
{
	int i;
	for(i=0;i<=b[0];i++)
	{
		a[i]=b[i];
	}
}
void add(int x,int y,int z)
{
	if(x-1>=0&&x-1>=y&&y>=z)
		sum(dp[x][y][z],dp[x-1][y][z]);
	if(y-1>=0&&x>=y-1&&y-1>=z)
		sum(dp[x][y][z],dp[x][y-1][z]);
	if(z-1>=0&&x>=y&&y>=z-1)
		sum(dp[x][y][z],dp[x][y][z-1]);
}
void fun()
{
	int i,j,k;
	memset(dp,0,sizeof(dp));
	dp[0][0][0][0]=dp[0][0][0][1]=1;
	for(i=1;i<=60;i++)
		for(j=0;j<=i;j++)
			for(k=0;k<=j;k++)
			{
				add(i,j,k);
				if(i==j&&j==k)
				{
					cpy(num[i],dp[i][j][k]);
				}
			}
}
int main()
{
	fun();
	int n;
	while(~scanf("%d",&n))
	{
		for(int i=num[n][0];i>0;i--)
			printf("%d",num[n][i]);
		printf("\n\n");
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值