题解 | #数组分组#
数组分组
https://www.nowcoder.com/practice/9af744a3517440508dbeb297020aca86
#include <stdio.h> #include <math.h> #include <string.h> int SumArr(int * arr, int len) { int out=0; for (int i=0; i<len; i++) { out += arr[i]; } return out; } int main() { int n, arr[100]={0}; scanf("%d\n",&n); for (int i=0; i<n; i++) { scanf("%d",&arr[i]); } int arr5[50]={0}, arr3[50]={0}, arr_non[50]={0}, i=0, j=0, k=0, index; for (index=0; index<n; index++) { if (arr[index]%5==0) arr5[i++]=arr[index]; else if (arr[index]%3==0) arr3[j++]=arr[index]; else arr_non[k++]=arr[index]; } int l_base=SumArr(arr5, i), r_base=SumArr(arr3, j), possibility_all=1; //possibility从1开始,因为后面加pow时相当于(举例3bit)只能到111即7这么大,没考虑000的情况 // printf("left_base=%d,right_base=%d\n",l_base,r_base); for (i=0; i<k; i++) possibility_all+=pow(2,i); // 每一位赋值二进制01,遍历所有情况 // printf("possibility_cnt=%d\n", possibility_all); int flag=1, a_non_map[k]; for (i=0; i<possibility_all; i++) { // printf("i=%d\n",i); memset(a_non_map, 0, sizeof(a_non_map)); int ind=0, i0=i; // 重新赋值给i0,不要动到原本循环里的i while(i0>0) { a_non_map[ind++] = i0%2; // printf("a_non_map[%d]=%d\n",ind-1,a_non_map[ind-1]); i0 = i0/2; // printf("i/=2 = %d\n", i0); } int left=l_base, right=r_base; for (j=0; j<k; j++) { if(a_non_map[j]==0) { left += arr_non[j]; } else { right += arr_non[j]; } } if (left==right) { flag=1; break; } else { if (i==possibility_all-1) { // 即搜索到最后一种情况依然不出现left==right flag=0; break; } } // printf("checkpoint\n"); } if (flag) printf("true\n"); else printf("false\n"); return 0; }