Problem Description
You are given a number 1 ≤ N ≤ 50. Every ticket has its 2N-digit number. We call a ticket lucky, if the sum of its first N digits is equal to the sum of its last N digits. You are also given the sum of ALL digits in the number. Your task is to count an amount of lucky numbers, having the specified sum of ALL digits.
Input
The input file contains multiple cases, please proceed until end of file!
each test case consists of two space-separated numbers: N and S. Here S is the sum of all digits. Assume that 0 ≤ S ≤ 1000.
Output
For each case, print the amount of lucky tickets in a single line.
Sample Input
2 2
3 100
Sample Output
4
0
Hint:
Category: Basic Dynamic Programming
Another Hint:
The answer may exceed 2^63 - 1, which means even long long is not enough for this problem.
Try to handle the arithmetic operations yourself, or utilize BigInteger in Java.
本身dp很简单,但是需要自己实现大整数加法,乘法
代码:
#include<iostream>
using namespace std;
#define LEN 45
int dp[505][52][LEN];
int ans[LEN*2];
void addp(int a[],int b[])
{
int c = 0;
for(int i=LEN*2-1;i>=0;i--)
{
int tmp = c+a[i]+b[i];
c = tmp/10;
a[i] = tmp%10;
}
}
void mul(int i,int j)
{
memset(ans,0,sizeof(ans));
int pos = LEN*2-1;
int outputlen = pos;
int len = dp[i][j][LEN-1];
for(int k=LEN-2;k>=LEN-1-len;k--)
{
int p = dp[i][j][k];
int c = 0,l=LEN-2;
int tmppos = pos;
int tmp[LEN*2]={0};
for(l=LEN-2;l>=LEN-1-len;l--)
{
int temp = p*dp[i][j][l]+c;
c = temp/10;
tmp[tmppos--]=temp%10;
}
if(c!=0)
tmp[tmppos]=c;
addp(ans,tmp);
pos--;
}
bool flag = false;
for(int t=0;t<=outputlen;t++)
{
if(flag==false&&ans[t]!=0)
{
printf("%d",ans[t]);
flag = true;
}
else if(flag==true)
printf("%d",ans[t]);
}
printf("\n");
}
void add(int i,int j,int x,int y)
{
int maxlen = max(dp[i][j][LEN-1],dp[x][y][LEN-1]);
int c = 0,p = LEN-2;
for(p=LEN-2;p>=LEN-1-maxlen;p--)
{
int tmp = c+dp[i][j][p]+dp[x][y][p];
c = tmp/10;
dp[i][j][p] = tmp%10;
}
dp[i][j][LEN-1] = maxlen;
if(c!=0)
{
dp[i][j][p] = c;
dp[i][j][LEN-1]++;
}
}
int main()
{
memset(dp,0,sizeof(dp));
for(int i=0;i<=500;i++)
{
if(i<=9)
{
dp[i][1][LEN-2]=1;
dp[i][1][LEN-1]=1;
}
for(int j=2;j<=50;j++)
{
int bound = min(i,9);
for(int k=0;k<=bound;k++)
add(i,j,i-k,j-1);
}
}
int n,s;
while(~scanf("%d %d",&n,&s))
{
if(s%2==1||dp[s/2][n][LEN-1]==0)
printf("0\n");
else
{
mul(s/2,n);
}
}
}