Coloring Array Elements for Equal Parity Sums - C++ Solution
Here is a possible C++ implementation for the problem:
#include <iostream>
#include <vector>
using namespace std;
bool canColorArray(vector<int>& arr) {
int sum = 0;
int oddCount = 0;
int evenCount = 0;
for (int i = 0; i < arr.size(); i++) {
sum += arr[i];
if (arr[i] % 2 == 0) {
evenCount++;
} else {
oddCount++;
}
}
if (sum % 2 != 0) {
return false;
}
if (oddCount == 0 || evenCount == 0) {
return false;
}
return true;
}
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> arr(n);
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
if (canColorArray(arr)) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
}
return 0;
}
This solution works by iterating through the array and counting the number of odd and even elements. If there is at least one odd and one even element, and the sum of all elements is even, then it is possible to color the array in two colors with the same parity. Otherwise, it is not possible.
原文地址: https://www.cveoy.top/t/topic/qef0 著作权归作者所有。请勿转载和采集!