简述:有一个n个元素的序列,选奇数下一个就选偶数,偶数则下一个就是奇数,问能否取完,能取完输出0,否则输出能剩下的最小的之和
思路:统计奇偶数个数,若相等或相差一则取完,否则排列后取出最小的前x个(x为相差个数,x > 1)
代码:
#include<iostream> #include<algorithm> #include<cstdio> #include<vector> using namespace std; const int maxm = 2019; int buff[maxm]; int main() { int n; scanf("%d",&n); for(int i = 0;i < n;++i) { scanf("%d",&buff[i]); } vector<int> even,odd; for(int i = 0;i < n;++i) { int tmp = buff[i]; if(tmp % 2 == 0) even.push_back(tmp); else odd.push_back(tmp); } int evenlength = even.size(),oddlength = odd.size(); if(evenlength == oddlength) printf("0"); else if(evenlength == oddlength - 1 || evenlength == oddlength + 1) { printf("0"); } else { int length = abs(evenlength - oddlength); sort(even.begin(),even.end()), sort(odd.begin(), odd.end()); if(evenlength > oddlength) { int val1 = 0,val2 = 0; for(int i = 0;i < length ;++i) val1 += even[i]; for(int i = 0;i < length-1 ;++i) val2 += even[i]; val1 = min(val1,val2); printf("%d",val1); } else { int val1 = 0,val2 = 0; for(int i = 0;i < length ;++i) val1 += odd[i]; for(int i = 0;i < length-1 ;++i) val2 += odd[i]; val1 = min(val1,val2); printf("%d",val1); } } return 0; }