Codeforces #646 A - Odd Selection(思维)

A - Odd Selection

题目大意:(原题在文末)

要从n个整数中取出x个数,判断是否能够使取出的x个数的和为奇数;

思路:

因为要使和为奇数,则要有一个单独的奇数,剩下的x-1个数加起来为偶数;所以要满足剩下的数,要么全部为偶数,要么奇数成对存在。(奇 + 奇 = 偶、偶 + 偶 = 偶、奇 + 偶 = 奇)

代码:

#include <iostream>
using namespace std;

int main() {
	int t;
	cin >> t;
	
	while(t--) {
		int n, x;
		cin >> n >> x;
		
		int odd = 0, even = 0;		//分别统计偶数和奇数的个数 
		
		for(int i = 0; i < n; i++){
			int a;
			cin >> a;
			
			if(a & 1) odd++;	
			else even++;
		}
		
		if(odd == 0) {
			cout << "NO" << endl;
			continue;
		}
		
		odd--;		//一定要有一个奇数,先拿出 
		x--;		//已经拿出一个数,剩下x-1个数 
		int flag = 0;
			
		if(x & 1) {			//注意要判断一下(x-1)是否为奇数,下文有解释 
			flag = 1;
		}
			
		x -= 2 * (odd / 2);		//(odd / 2) 是奇数对的个数 
			
		if(flag)
			if(x <= 1) 		//如果(x-1)是奇数,则需要留下一个位置来放一个偶数; 
				x = 1;
			
			cout << (even >= x ? "YES" : "NO") << endl;;
		}
	}
	
	return 0;
} 

 


题目:

Shubham has an array a of size n, and wants to select exactly x elements from it, such that their sum is odd. These elements do not have to be consecutive. The elements of the array are not guaranteed to be distinct.

Tell him whether he can do so.

输入:

The first line of the input contains a single integer t (1≤t≤100) — the number of test cases. The description of the test cases follows.

The first line of each test case contains two integers n and x(1≤x≤n≤1000) — the length of the array and the number of elements you need to choose.

The next line of each test case contains nn integers a1,a2,…,an(1≤ai≤1000) — elements of the array.

输出:

For each test case, print "Yes" or "No" depending on whether it is possible to choose x elements such that their sum is odd.

You may print every letter in any case you want.

样例输入输出:

input

5

1 1

999   ------------ YES 

1 1

1000 ------------- NO 

2 1

51 50 ------------ YES 

2 2

51 50 ------------ YES 

3 3

101 102 103 --- NO

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值