#include <iostream> #include <vector> #include <algorithm> #include <sstream>使用命名空间 std;bool isValidSet(int a, int b, int c) { return (a == b && b == c) ||(a + 1 == b && b + 1 == c);} string checkHu(vector<int>& nums) { int n = nums.size(); if (n % 3 != 2) { return “xianggong”; } sort(nums.begin(), nums.end()); for (int i = 0; i < n - 5; i += 3) { if (!isValidSet(nums[i], nums[i + 1], nums[i + 2])) { return “BUHU”; } } if (nums[n - 2] != nums[n - 1]) { return “BUHU”; } return “HU”; } int main() { vector<int> nums; string line; string result; while (true) { getline(cin, 行);if (line == “0”) { break; } stringstream ss(line);整数;while (ss >> num) { nums.push_back(num); } result = checkHu(nums);cout <<结果<< endl;nums.clear();} 返回 0;}如何加以定义个数字的数量不超过4个,集合中元素的数量不超过14个不用返回不胡
时间: 2024-03-17 08:41:30 浏览: 161
#include <iostream>
如果我们想在 checkHu 函数中判断数字的数量和集合中元素的数量是否符合要求,但是不需要返回 "BUHU" 或 "HU",只需要在 checkHu 函数中进行判断即可。修改后的代码如下:
```
#include <iostream>
#include <vector>
#include <algorithm>
#include <sstream>
#include <unordered_map>
using namespace std;
bool isValidSet(int a, int b, int c) {
return (a == b && b == c) || (a + 1 == b && b + 1 == c);
}
void checkHu(vector<int>& nums) { // 修改返回值类型为 void
int n = nums.size();
if (n % 3 != 2) {
cout << "XIANGGONG" << endl; // 直接输出结果
return;
}
unordered_map<int, int> count;
for (int num : nums) {
count[num]++;
if (count[num] > 4) {
cout << "XIANGGONG" << endl;
return;
}
}
if (count.size() > 14) {
cout << "XIANGGONG" << endl;
return;
}
sort(nums.begin(), nums.end());
for (int i = 0; i < n - 5; i += 3) {
if (!isValidSet(nums[i], nums[i + 1], nums[i + 2])) {
cout << "XIANGGONG" << endl;
return;
}
}
if (nums[n - 2] != nums[n - 1]) {
cout << "XIANGGONG" << endl;
return;
}
cout << "OK" << endl; // 输出结果为 OK
}
int main() {
vector<int> nums;
string line;
while (true) {
getline(cin, line);
if (line == "0") {
break;
}
stringstream ss(line);
int num;
while (ss >> num) {
nums.push_back(num);
}
checkHu(nums); // 调用 checkHu 函数,不需要接收返回值
nums.clear();
}
return 0;
}
```
阅读全文