1.问题描述
森林中,每个兔子都有颜色。其中一些兔子(可能是全部)告诉你还有多少其他的兔子和自己有相同的颜色。我们将这些回答放在 answers 数组里。
返回森林中兔子的最少数量。
示例:
输入: answers = [1, 1, 2]
输出: 5
解释:
两只回答了 “1” 的兔子可能有相同的颜色,设为红色。
之后回答了 “2” 的兔子不会是红色,否则他们的回答会相互矛盾。
设回答了 “2” 的兔子为蓝色。
此外,森林中还应有另外 2 只蓝色兔子的回答没有包含在数组中。
因此森林中兔子的最少数量是 5: 3 只回答的和 2 只没有回答的。
输入: answers = [10, 10, 10]
输出: 11
输入: answers = []
输出: 0
2.输入说明
首先输入answers数组的长度n,n<=1000
然后输入n个整数,以空格分隔,每个整数在 [0, 999] 范围内
3.输出说明
输出一个整数
4.范例
输入
3
1 1 2
输出
5
5.代码
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
int NumOfRabbits(vector<int> answers)
{
// x/y 向上取整的写法 :(x+(y-1))/y 或者直接用ceil(x/y);
// x/(y+1) 向上取整 :(x+y)/(y+1)
//参考贪心算法题解: https://leetcode.cn/problems/rabbits-in-forest/solution/sen-lin-zhong-de-tu-zi-by-leetcode-solut-kvla/
if (answers.size() == 0)
return 0;
int n = answers.size();
unordered_map<int, int>map;
for (auto t : answers)
{
map[t]++;//统计每个t出现的次数
}
int ans = 0;
for (auto s : map)
{
//同一颜色的兔子回答的数值必然是一样的
//但回答同样数值的,不一定就是同颜色兔子
int val = s.first;//回答相同颜色的兔子只数 ,若回答val,则至少有(val+1)只兔子是同种颜色的
int cnt = s.second;
if (cnt % (val + 1) == 0)
ans += (cnt / (val + 1))*(val + 1);//cnt/(val+1)计算出最少有几种颜色 每种颜色至少有val+1只兔子
else
ans+= (cnt / (val + 1)+1)*(val + 1);
}
return ans;
}
int main()
{
int n,tmp;
cin >> n;
vector<int>answers;
for (int i = 0; i < n; i++)
{
cin >> tmp;
answers.push_back(tmp);
}
int res = NumOfRabbits(answers);
cout << res << endl;
return 0;
}