- 論壇徽章:
- 0
|
母牛數(shù)量算法
性能最好,最容易理解的解決方法上場(chǎng)了。
#define AGE_1 0 //一歲的牛
#define AGE_2 1 //二歲的牛
#define AGE_3 2 //三歲的牛
#define AGE_4 3 //大于或者等于四歲的牛,可以生牛的牛;
int main(void)
{
int cow[4];
int years = 0;
//初始化,只有一頭一歲的母牛;
cow[AGE_1] = 1;
cow[AGE_2] = 1;
cow[AGE_3] = 1;
cow[AGE_4] = 1;
printf("input Years? " ;
scanf("%d", years);
for (int i=1; i<=years; i++)
{
//三歲的豬都長(zhǎng)了一歲,所以放到四歲的數(shù)組中來;
cow[AGE_4] += cow[AGE_3];
//2歲的豬也長(zhǎng)了一歲,放到三歲的數(shù)組中來;
cow[AGE_3] = cow[AGE_2];
//1歲的豬也長(zhǎng)了一歲,放到二歲的數(shù)組中來;
cow[AGE_2] = cow[AGE_3];
//1歲的豬是由今年四歲的和大于四歲的豬生的;
cow[AGE_1] = cow[AGE_4];
}
printf("all cow is : %d", cow[0] + cow[1] + cow[2] + cow[3]);
}
不好意思,一直以為是豬,應(yīng)該是牛,呵呵。。。
其他的幾種不大讓我滿意的解決方法:
solution1:
#include <stdio.h>;
#include <stdlib.h>;
int total_n(int year)
{
if (year <= 3) return 1;
if (year == 4) return 2;
return total_n(year-1)+total_n(year-3);
}
int main(void)
{
printf("50 years go by, total pigs: %d\n", total_n(50));
return 1;
}
solution2:
#include <iostream.h>;
struct pig
{
int age;
// int mother;
int children;
};
int count_pigs(int year)
{
int i, j, k, m;
int count, count_tmp;
pig pigs[102400000];
//init;
i=j=k=m=0;
count=count_tmp=1;
for (i=0; i<10240; i++)
{
pigs.age=0;
// pigs.mother=0;
pigs.children=0;
}
//years go by...;
for(i=1; i<=year; i++)
{
cout << "現(xiàn)在是第" << i << "年:" << endl;
for (j=0; j<count_tmp; j++)
{
pigs[j].age++;
// cout << " 第" << j << "頭豬的年齡是:" << pigs[j].age << endl;
// cout << " 她共生了" << pigs[j].children << "頭小豬" << endl;
if (pigs[j].age >;= 4)
{
pigs[j].children++;
pigs[count++].age=1;
// pigs[count-1].mother=j;
pigs[count-1].children=0;
// cout <<" 她今年生了一頭小豬" << count -1 << endl;
}
}
count_tmp=count;
cout << "\t" << "第" << i << "年豬的總數(shù): " << count << endl;
}
cout << "total pigs: " << count << endl;
return count;
}
int main(void)
{
int years=0;
//get year;
cout << "input years: ";
cin >;>; years;
count_pigs(years);
}
solution3:
#include <stdio.h>;
#define n 70
struct year{
int yearnum;
long pignum;
};
struct year yearslot[n];
int main(){
yearslot[0].yearnum=1;
yearslot[0].pignum=1;
for(int i=1;i<n;i++)
{
long num=0;
for(int j=0;j<=i-3;j++)
{
num+=yearslot[j].pignum;
}
printf("year %d's pig num = %ul\n",i+1,num);
yearslot.pignum=num;
yearslot.yearnum=1;
for(int j=0;j<i;j++)
yearslot[j].yearnum++;
}
long num=0;
for(int i=0;i<n;i++)
num+=yearslot.pignum;
printf("all pig is:%ul\n",num);
} |
|