题目:
A sequence of positive integers is Palindromic if it reads the same forward and backward. For example:
23 11 15 1 37 37 1 15 11 23
1 1 2 3 4 7 7 10 7 7 4 3 2 1 1
A Palindromic sequence is Unimodal Palindromic if the values do not decrease up to the middle value and then (since the sequence is palindromic) do not increase from the middle to the end For example, the first example sequence above is NOT Unimodal Palindromic while the second example is.
A Unimodal Palindromic sequence is a Unimodal Palindromic Decomposition of an integer N, if the sum of the integers in the sequence is N. For example, all of the Unimodal Palindromic Decompositions of the first few integers are given below:
1: (1)
2: (2), (1 1)
3: (3), (1 1 1)
4: (4), (1 2 1), (2 2), (1 1 1 1)
5: (5), (1 3 1), (1 1 1 1 1)
6: (6), (1 4 1), (2 2 2), (1 1 2 1 1), (3 3),
(1 2 2 1), ( 1 1 1 1 1 1)
7: (7), (1 5 1), (2 3 2), (1 1 3 1 1), (1 1 1 1 1 1 1)
8: (8), (1 6 1), (2 4 2), (1 1 4 1 1), (1 2 2 2 1),
(1 1 1 2 1 1 1), ( 4 4), (1 3 3 1), (2 2 2 2),
(1 1 2 2 1 1), (1 1 1 1 1 1 1 1)
Write a program, which computes the number of Unimodal Palindromic Decompositions of an integer.
Input
Input consists of a sequence of positive integers, one per line ending with a 0 (zero) indicating the end.
Output
For each input value except the last, the output is a line containing the input value followed by a space, then the number of Unimodal Palindromic Decompositions of the input value. See the example on the next page.
Sample Input
2
3
4
5
6
7
8
10
23
24
131
213
92
0
Sample Output
2 2
3 2
4 4
5 3
6 7
7 5
8 11
10 17
23 104
24 199
131 5010688
213 1055852590
92 331143
翻译:给定一个数n,输出它的单调回文串的个数
解题思路:
分析:4: (4), (1 2 1), (2 2), (1 1 1 1)
我们可以发现(1 2 1)的分解,可以看成是先有一个2 后在两边加上1,左边第一个数始终是小的,所以我们可以设f[n][i]为将数n分解,左边第一个数为i的个数,而f[n][i]=f[n-2*i][i]+....f[n-2*i][i+1](i+1<n-2*i)
上面的式子可以理解为,将两边的数先拿开,分解剩下的数,最后只需将拿走的数加上,即可
解决方法为:先打表,后计算,我们需要计算的就是f[n][i](i>=1&&i<=n)
下面给出代码:
#include <stdio.h>
#include <string.h>
#define MAX 512
//sequence[n][i]:表示将n分解成单调回文中最左边的数为i的个数
unsigned sequence[MAX][MAX];
int main()
{
memset(sequence,0,sizeof(sequence));
int i, j;
for(i=1;i<MAX;i++)
{
sequence[i][i] = 1;
if(i%2==0) //如果i是偶数,则可分解成i/2i/2这种形式
sequence[i][i/2] = 1;
}
sequence[2][1] = 1;
sequence[3][1] = 1;
sequence[4][1] = 2;
sequence[4][2] = 1;
for(i=5;i<MAX;i++)
{
for(j=1;j<MAX;j++)
{
if((i-2*j)>=j)
{
for(int m=j;m<=i-2*j;m++)
sequence[i][j]+=sequence[i-2*j][m];
}
else break;
}
}
int n;
while(scanf("%d",&n)&&n!=0)
{
unsigned sum=0;
for(i=1;i<=n;i++)
sum+=sequence[n][i];
printf("%d %u\n",n,sum);
}
return 0;
}