《编程题》穷举法求N年后有多少头牛

若一头小母牛,从出生起第四个年头开始每年生一头母牛,按这个规律,第N年时有多少头母牛?

 

 1 #include <iostream>
 2 
 3 int main(int argc, const char * argv[]) {
 4 
 5     int N = 0;
 6 
 7     std::cout<<"请输入年份\n";
 8     std::cin>>N;
 9     int *iA;
10     
11     if((iA = (int *)malloc(N*sizeof(int)))==NULL)
12     {
13         return 0;
14     }
15 
16     int theResult = 0;
17     
18     
19     for(int i=0;i<N;++i)
20     {
21         iA[i] = 0;
22     }
23     
24     for(int i=0;i<N;++i)
25     {
26         theResult+=1;
27         for(int j=0;j<=i;++j)
28         {
29             iA[j] += 1;
30             if(iA[j]>=4)
31                 theResult += 1;
32         }
33     }
34     
35     std::cout << theResult << "\n";
36     free(iA);
37     return 0;
38 }

 

posted @ 2016-07-16 23:11  看代码`lookdaima.com  阅读(352)  评论(0编辑  收藏  举报