A. Odd Selection
题意
判断是否能从 n 个数中选 m 个数,使其加起来为奇数。
思路
至少要有一个奇数,否则不可能。
选了一个奇数之后,后面的 m-1 个数加起来应该为偶数。
此时相当于从n-1个数中选m-1个数,使其加起来为偶数。
向后面的 m-1 个数中加入成对的奇数或者单个偶数即可。
加入奇数对时要注意m的奇偶性。
代码
#include<bits/stdc++.h>
using namespace std;
int t;
int main(){
cin >> t;
while(t--){
int n,m;
cin >> n >> m;
int odd = 0;
int even = 0;
for(int i = 1; i <= n; ++i){
int x;
cin >> x;
((x&1) ? odd : even)++;
}
if(odd==0){
cout << "No\n";
}
else{
--odd;
--m;
int flag = 0;
if(m&1)
flag = 1,--m;
//让m减去所有的奇数对
m -= 2 * (odd / 2);
if(flag){
if(m<=0)
m = 1;
else
++m;
}
cout << (even >= m ? "Yes\n" : "No\n");
}
}
return 0;
}
附上比赛时写的代码,太惨了
#include <bits/stdc++.h>
using namespace std;
int t;
int n,m;
int main()
{
cin >> t;
while(t--){
cin >> n >> m;
int odd = 0;
int even = 0;
for(int i = 1; i <= n; ++i){
int x;
cin >> x;
if(x&1){
odd++;
}
else{
even++;
}
}
if(odd==0){
printf("No\n");
}
else{
int x = odd-1;
--m;
if(m&1){
if(even==0){
printf("No\n");
}
else{
--m;
--even;
if(x&1)
--x;
m -= x;
if(m-even<=0){
printf("Yes\n");
}
else{
printf("No\n");
}
}
}
else{
if(x&1)
--x;
m -=x;
if(m-even<=0){
printf("Yes\n");
}
else{
printf("No\n");
}
}
}
}
return 0;
}