rray Coloringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array consisting of n integers Your task is to determine whether it i
Here is a possible C++ implementation for this problem:
#include <iostream>
#include <vector>
using namespace std;
bool canColorArray(vector<int>& array) {
int n = array.size();
int sum = 0;
for (int i = 0; i < n; i++) {
sum += array[i];
}
if (sum % 2 != 0) {
return false;
}
int oddCount = 0, evenCount = 0;
for (int i = 0; i < n; i++) {
if (array[i] % 2 == 0) {
evenCount++;
} else {
oddCount++;
}
}
if (oddCount != 0 && evenCount != 0) {
return true;
}
return false;
}
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> array(n);
for (int i = 0; i < n; i++) {
cin >> array[i];
}
if (canColorArray(array)) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
}
return 0;
}
Explanation:
- First, we define a function
canColorArraythat takes an array as input and returns a boolean value indicating whether it is possible to color the array as required. - In this function, we calculate the sum of all elements in the array. If this sum is odd, it is not possible to color the array as required, so we return false.
- Next, we count the number of odd and even elements in the array. If both counts are non-zero, it is possible to color the array as required, so we return true. Otherwise, we return false.
- In the main function, we read the number of test cases
t. - For each test case, we read the length of the array
n, and then read the elements of the array. - We call the
canColorArrayfunction with the array as input, and print "YES" if it returns true, and "NO" otherwise
原文地址: https://www.cveoy.top/t/topic/iwS1 著作权归作者所有。请勿转载和采集!