Coloring Array Elements with Equal Parity Sums - C++ Implementation
You are given an array consisting of n integers. Your task is to determine whether it is possible to color all its elements in two colors in such a way that the sums of the elements of both colors have the same parity and each color has at least one element colored.
\nFor example, if the array is [1,2,4,3,2,3,5,4], we can color it as follows: [1,2,4,3,2,3,5,4], where the sum of the blue elements is 6 and the sum of the red elements is 18.
\nInput
The first line contains an integer t (1≤t≤1000) — the number of test cases.
\nEach test case begins with a line containing an integer n (2≤n≤50) — the length of the array a.
\nThe next line contains n integers a1,a2,…,an (1≤ai≤50) — the elements of the array a.
\nOutput
For each test case, output "YES" (without quotes) if it is possible to color the array in two colors in such a way that the sums of the elements of both colors have the same parity and each color has at least one element colored, and "NO" otherwise.
\nYou can output "Yes" and "No" in any case (for example, the strings "yES", "yes", and "Yes" will be recognized as correct answers).c++代码内容:Here is a possible C++ implementation for the given problem:
\n```cpp
#include
#include
using namespace std;
bool canColorArray(vector
int n = arr.size();
// Calculate the sum of all elements in the array
int totalSum = 0;
for (int i = 0; i < n; i++) {
totalSum += arr[i];
}
// If the total sum is odd, it is not possible to color the array in two colors with equal parities
if (totalSum % 2 != 0) {
return false;
}
// Calculate the prefix sum of the array
vector
prefixSum[0] = arr[0];
for (int i = 1; i < n; i++) {
prefixSum[i] = prefixSum[i-1] + arr[i];
}
// Check if there exists a prefix sum that is half the total sum
for (int i = 0; i < n; i++) {
if (prefixSum[i] == totalSum / 2) {
return true;
}
}
return false;
}
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
if (canColorArray(arr)) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
}
return 0;
}\
\
This code first checks if the total sum of the array is odd. If it is, then it is not possible to color the array in two colors with equal parities. Otherwise, it calculates the prefix sum of the array and checks if there exists a prefix sum that is half the total sum. If such a prefix sum exists, then it is possible to color the array in two colors with equal parities.
原文地址: https://www.cveoy.top/t/topic/qeha 著作权归作者所有。请勿转载和采集!