题目背景
HDU1502
题目描述
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.
题目大意
ABC每个字母有n个,求满足要求的排列的个数:在该排列的任意前缀中满足 A的个数不少于B的个数 不少于C的个数。
输入格式
输入文件中有多组数据。每组数据包含n(0≤n≤60)。每组数据下都空一行。
输出格式
输出长度为3n的满足题意的排列数。在每个答案间空一行。
样例数据
输入
2
3
输出
5
42
分析:作为一道DP题还是比较简单的: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]。(因为
i<j
和
j<k
的情况为0,所以加了也没关系)
但是到最后答案太大啦!81位,long long都没办法,而高精度加法又会MLE(就算有足够内存也会TLE),所以只有利用高精度加法的思想存储(也就是压位),具体见代码。
感谢pter给我提供了思路以及打表的数据:http://www.cnblogs.com/pter/p/5749072.html。
代码
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
#include<ctime>
#include<cmath>
#include<algorithm>
#include<cctype>
#include<iomanip>
#include<queue>
#include<set>
using namespace std;
int n,dp[65][65][65][30];//前三位分别代表A、B、C的个数,最后一位代表这是10000的几次方
void add(int A[],int B[])
{
for (int i=0;i<30;i++)
{
A[i]+=B[i];
A[i+1]+=A[i]/10000;
A[i]%=10000;
}
}
int main()
{
freopen("rw.in","r",stdin);
freopen("rw.out","w",stdout);
dp[0][0][0][0]=1;
for(int i=1;i<=60;++i)
for(int j=0;j<=i;++j)
for(int k=0;k<=j;++k)
{
add(dp[i][j][k],dp[i-1][j][k]);//不要问我,我也觉得四维用其中三维又在函数中完成对第四维的修改很神奇
add(dp[i][j][k],dp[i][j-1][k]);//而且j、k小于零了也没有炸orz
add(dp[i][j][k],dp[i][j][k-1]);
}
while(scanf("%d",&n)!=EOF)
{
int k=29;
while(!dp[n][n][n][k])//找到最高位的位置
k--;
for(int i=k;i>=0;--i)
{
if(i!=k)//不是第一个时
{
int p=1000;
while(dp[n][n][n][i]<p)//如果没有4位用0凑
{
printf("0");
p/=10;
}
}
if(dp[n][n][n][i])
printf("%d",dp[n][n][n][i]);
}
printf("\n\n");
}
return 0;
}
本题结。