Coloring Array Elements with Equal Parity Sums: C++ Code Solution
"You are given an array consisting of n\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.\n\nFor example, if the array is [1,2,4,3,2,3,5,4\n], we can color it as follows: [1,2,4,3,2,3,5,4\n], where the sum of the blue elements is 6\n and the sum of the red elements is 18\n.\n\nInput\nThe first line contains an integer t\n (1≤t≤1000\n) — the number of test cases.\n\nEach test case begins with a line containing an integer n\n (2≤n≤50\n) — the length of the array a\n.\n\nThe next line contains n\n integers a1,a2,…,an\n (1≤ai≤50\n) — the elements of the array a\n.\n\nOutput\nFor 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.\n\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 C++ code implementation to solve the given problem:\n\ncpp\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nstring canColorArray(vector<int> arr) {\n int n = arr.size();\n int sum = 0;\n for(int i=0; i<n; i++) {\n sum += arr[i];\n }\n if(sum % 2 != 0) {\n return \"NO\";\n }\n int oddCount = 0, evenCount = 0;\n for(int i=0; i<n; i++) {\n if(arr[i] % 2 == 0) {\n evenCount++;\n } else {\n oddCount++;\n }\n }\n if(oddCount > 0 && evenCount > 0) {\n return \"YES\";\n } else {\n return \"NO\";\n }\n}\n\nint main() {\n int t;\n cin >> t;\n while(t--) {\n int n;\n cin >> n;\n vector<int> arr(n);\n for(int i=0; i<n; i++) {\n cin >> arr[i];\n }\n cout << canColorArray(arr) << endl;\n }\n return 0;\n}\n\n\nIn this code, we first calculate the sum of all elements in the array. If the sum is odd, then it is not possible to color the array in two colors with the same parity sum. Otherwise, we count the number of odd and even elements in the array. If both counts are greater than zero, then it is possible to color the array in two colors.
原文地址: https://www.cveoy.top/t/topic/qeg7 著作权归作者所有。请勿转载和采集!