以下是用 C++ 解决这个问题的代码:
#include <iostream>
#include <unordered_set>
int main() {
int n;
std::cin >> n;
std::unordered_set<int> distinct_heights;
for (int i = 0; i < n; ++i) {
int height;
std::cin >> height;
distinct_heights.insert(height);
}
int num_rooms = distinct_heights.size();
std::cout << num_rooms << std::endl;
return 0;
}
在这个程序中,我们首先读取输入的奶牛数量 n
。
然后,我们用 unordered_set
来存储出现过的不同的奶牛身高。unordered_set
是一个无序容器,其中的元素不会有重复。
接下来,我们循环 n
次,读取每头奶牛的身高,并将身高插入到 unordered_set
中。
最后,我们输出 unordered_set
的大小,即为需要的房间数量。
运行示例:
输入:
5
10 30 10 20 30
输出:
3
根据题目的要求,在 80% 的数据范围内运行时,哈希表的冲突数量会比较少,因此可以使用 unordered_set
来高效地解决这个问题。在最坏的情况下,即 n 较大且所有奶牛的身高都不相同时,时间复杂度为 O(n)。