总结
accumulate 的返回值的类型是第三个参数的类型,大数的时候需要注意
问题
具体的思路自行查阅,题目给定的数据范围是10^18,因此需要使用 long 数据类型存储,初始代码如下:
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
class Solution {
public:
unsigned long minMax(vector<unsigned long>& nums) {
sort(nums.begin(), nums.end());
unsigned long sum = accumulate(nums.begin(), nums.end(), 0);
if (nums[0] + nums[1] > nums[2]) {
return (sum + 2) / 3;
}
if (2 * (nums[0] + nums[1]) < nums[2]) {
return (nums[2] + 1) / 2;
}
return (sum + 2) / 3;
}
};
int main(int argc, char *argv[]) {
int N;
cin >> N;
vector<unsigned long> nums(3);
for (int i = 0; i < N; ++i) {
cin >> nums[0];
cin >> nums[1];
cin >> nums[2];
cout << Solution().minMax(nums) << endl;
}
return 0;
}
但是结果使用错误。结果是在
unsigned long sum = accumulate(nums.begin(), nums.end(), 0);
的使用上,参照 C++ Reference 上的原型:
可以看出,上述代码会因为返回值是int类型而被截断(因为没有任何尾标的 0 被推导为 int 类型),解决方法:
unsigned long sum = accumulate(nums.begin(), nums.end(), 0ul);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)