Adding 1s, 2s, and 3s |
Time Limit: 1000ms, Special Time Limit:2500ms, Memory Limit:32768KB |
Total submit users: 854, Accepted users: 813 |
Problem 10074 : No special judgement |
Problem description |
Integer 4 can be expressed as a sum of 1s, 2s, and 3s in seven different ways as follows: 1+1+1+1, (1) 1+1+2, (2) 1+2+1, (3) 2+1+1, (4) 2+2, (5) 1+3, (6) 3+1. (7) Write a program that determines the number of ways in which a given integer can be expressed as a sum of 1s, 2s, and 3s. You may assume that the integer is positive and less than 20. |
Input |
The input consists of T test cases. The number of test cases (T ) is given in the first line of the input file. Each test case consists of an integer written in a single line. |
Output |
Print exactly one line for each test case. The line should contain an integer representing the number of ways. |
Sample Input |
3 4 7 10 |
Sample Output |
7 44 274 |
Problem Source |
SJTU2004 |
公式:f(n)=f(n-3)+f(n-2)+f(n-1)
运用推导出来的公式直接解决:
#include
int main()
{
int i,j,n;
int f[21]={1,1,2};
for(i=3;i<21;i++)
{
f[i]=f[i-1]+f[i-2]+f[i-3];
}
scanf("%d",&j);
while(j--)
{
scanf("%d",&n);
printf("%d\n",f[n]);
};
return 0;
}
#include
int s;
void f(int n)
{
int i;
if(!n) //如果n为0,则递归结束,返回上一级,同时总数加1
{
s++;
return;
}
for(i=n<3?n:3;i!=0;i--) //重点!如果n此时大于等于3,则令i=n,否则i=n;然后令i递减至0,每次都递归调用f(n-i)
f(n-i);
}
int main()
{
int i,t,x;
scanf("%d", &t); //读取一共有T个数字
for(i=t;i>0;i--) //循环读取这T个数字,每次读取一个,读取完后立即处理并输出
{
scanf("%d", &x); //读取当前要处理的数字
s=0; //拆分方法总数置零
f(x); //计算
printf("%d\n", s); //输出这个数字的拆分方法总数
}
return 0;
}