C++ Code to Determine Two-Color Array Parity
This C++ code determines if an array can be colored in two colors such that the sums of elements in each color have the same parity. It calculates the sum of all elements and counts the number of odd and even elements. If the sum is odd or there are no odd or even elements, it is not possible to color the array in the desired way, so it returns "NO". Otherwise, it returns "YES".
cpp
#include <iostream>
#include <vector>

using namespace std;

string solve(vector<int>& a) {
 int sum = 0;
 for (int num : a) {
 sum += num;
 }

 int oddCount = 0, evenCount = 0;
 for (int num : a) {
 if (num % 2 == 0) {
 evenCount++;
 } else {
 oddCount++;
 }
 }

 if (sum % 2 != 0) {
 return "NO";
 }

 if (oddCount == 0 || evenCount == 0) {
 return "NO";
 }

 return "YES";
}

int main() {
 int t;
 cin >> t;

 while (t--) {
 int n;
 cin >> n;

 vector<int> a(n);
 for (int i = 0; i < n; i++) {
 cin >> a[i];
 }

 cout << solve(a) << endl;
 }

 return 0;
}

Explanation:
- The code takes the number of test cases as input.
- For each test case, it takes the length of the array and the elements of the array.
- It then calls the solve function to check if it is possible to color the array in the desired way and prints the result.
- The solve function calculates the sum of all elements in the array and counts the number of odd and even elements.
- If the sum is odd or there are no odd or even elements, it is not possible to color the array in the desired way, so it returns "NO".
- Otherwise, it returns "YES".
This code provides a straightforward and efficient solution to the problem of determining if an array can be colored with two colors such that the sums of elements in each color have the same parity.
原文地址: https://www.cveoy.top/t/topic/qeg6 著作权归作者所有。请勿转载和采集!