2017阿里C++研发工程师-校招-笔试模拟

题目描述:

  1. 猎人把一对兔子婴儿(一公一母称为一对)放到一个荒岛上,两年之后,它们生00下一对小兔,之后开始每年都会生下一对小兔。生下的小兔又会以同样的方式继续繁殖。
  2. 兔子的寿命都是x(x>=3)年,并且生命的最后一年不繁殖。
  3. 如果岛上的兔子多于10对,那么猎人会每年在兔子们完成繁殖或者仙逝之后,从岛上带走两对最老的兔子。
    请问y年(y>=3)后荒岛上所有的兔子加起来多少岁?(注意, 在条件3执行完之后)

输入: 从命令行输入两行整数,第一行是x,第二行是y
输出: y年后荒岛上所有的兔子岁数的总和

样例:

输入:
3
3
输出:
2

解题思路:

开一个数组, tu[j] 表示在第 某年 年末, j 岁大的兔子对数。 然后每过一年 tu[j] = tu[j-1] (j >= 1), tu[0] 为新生的兔子对数。
手动模拟几组数据

年份(年末)/兔子年龄, 为了简单,先不考虑兔子年龄限制,不考虑超过十对时取走两对年龄大的兔子。

           0        1        2        3        4        5        6      

1          0        1

2          1        0       1

3          1        1       0        1

4          2        1       1        0         1    

5          3        2        1       1        0         1 

6          5         3        2        1       1        0         1 

然后假设 兔子年龄限制为 5, 并且超过十对时取走两对年龄大的兔子。

年份(年末)/兔子年龄,假设 兔子年龄限制为 5, 并且超过十对时取走两对年龄大的兔子。

           0        1        2        3        4        5        6      

1          0        1

2          1        0       1

3          1        1       0        1

4          2        1       1        0         1    

5          3        2        1       1        0        0

6          4        3        2        0       0        0         0 

7          5        4        3        0       0        0         0

吐槽: 年末年初的问题好容易搞混啊,以及兔子生命最后一年的情况,需要静下心慢慢分析,才能“蒙对”题意 -_- || 。

#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <list>
#include <stack>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <stdexcept>
#include <cstdio>
#include <cstdlib>
using namespace std;

int result(int x, int y)
{
    vector<int> tu(x+5, 0); 
    tu[1] = 1; 
    for(int i = 2; i <= y; i++)
    {
        int newTu = 0; 
        for(int j = x+1; j >=1; j--)
        {
            tu[j] = tu[j-1]; 
            if(j >= 2 && j <= x)
                newTu += tu[j]; 
        }
        tu[0] = newTu; 

        int lastY = 0; 
        int tot = 0; 
        for(int j = x; j >= 0; j--)
        {
            tot += tu[j]; 
            if(lastY == 0 && tu[j])
                lastY = j; 
        }
        if(tot > 10)
        {
            if(tu[lastY] >= 2)
                tu[lastY] -= 2; 
            else
            {
                tu[lastY] = 0; 
                for(int k = lastY-1; k >= 0; k--)
                    if(tu[k])
                    {
                        tu[k] -= 1; 
                        break; 
                    }
            }
        }
    }

    int ans = 0; 
    for(int i = 1; i <= x; i++)
        ans += tu[i] * i; 
   
    return ans*2; 
}

int main()
{
    int x, y; 
    cin >> x; 
    cin >> y; 
    int res = result(x, y); 
    cout << res << endl; 

    return 0; 
}



原文地址:https://www.cnblogs.com/acm1314/p/7406816.html