Description
Your rich uncle died recently, and the heritage needs to be divided among your relatives and the church (your uncle insisted in his will that the church must get something). There are N relatives (N <= 18) that were mentioned in the will. They are sorted in descending order according to their importance (the first one is the most important). Since you are the computer scientist in the family, your relatives asked you to help them. They need help, because there are some blanks in the will left to be filled. Here is how the will looks:
Relative #1 will get 1 / ... of the whole heritage,
Relative #2 will get 1 / ... of the whole heritage,
---------------------- ...
Relative #n will get 1 / ... of the whole heritage.
The logical desire of the relatives is to fill the blanks in such way that the uncle's will is preserved (i.e the fractions are non-ascending and the church gets something) and the amount of heritage left for the church is minimized.
Relative #1 will get 1 / ... of the whole heritage,
Relative #2 will get 1 / ... of the whole heritage,
---------------------- ...
Relative #n will get 1 / ... of the whole heritage.
The logical desire of the relatives is to fill the blanks in such way that the uncle's will is preserved (i.e the fractions are non-ascending and the church gets something) and the amount of heritage left for the church is minimized.
Input
The only line of input contains the single integer N (1 <= N <= 18).
Output
Output the numbers that the blanks need to be filled (on separate lines), so that the heritage left for the church is minimized.
Sample Input
2
Sample Output
2 3
解题思路
1/2,1/3,1/7,1/43……,后一个人的分母Y是前一个人分母X有以下关系:Y = X*(X-1) + 1;
AC代码
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define maxn 50000
int a[20][maxn], b[maxn], len[20];
void func(int n)
{
a[1][0] = 2;
len[1] = 1;
for(int i=2; i <= n; i++)
{
int d = 0;
for(int j = 0; j < len[i - 1]; j++)
{
if(j == 0)
b[0] = a[i - 1][0] - 1;
else
b[j] = a[i - 1][j] + d;
if(b[j] < 0)
{
d = -1;
b[j] += 10; //d用来处理借位
}
else
d = 0;
}
for(int j = 0; j < len[i - 1]; j++)
for(int k = 0; k < len[i - 1]; k++)
a[i][j + k] += a[i - 1][j] * b[k];
a[i][ len[i - 1] * 2 - 1] = 0;
a[i][0] += 1;
for(int j = 0; j < len[i - 1] * 2 - 1; j++) //处理进位
{
a[i][j + 1] += a[i][j] / 10;
a[i][j] %= 10;
}
len[i] = 2 * len[i - 1] - 1;
if( a[i][ 2 * len[i - 1] - 1 ] )
len[i] += 1;
}
}
int main()
{
int n;
scanf("%d", &n);
func(n);
for(int i = 1; i <= n; i++)
{
for(int j = len[i] - 1; j >= 0; j--)
printf("%d", a[i][j]);
printf("\n");
}
return 0;
}