CodeForces #650 B. Even Array(思维)

B. Even Array

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

给出一个长度为n的数组,如果每个位置的a[i] % 2 == i % 2;则是良好数组,如果不满足,输出需要交换几次能够使其成为良好数组,如果不能,输出“-1”;

思路:(与Codeforces #644 C.Simple Pairs解决有些相似)

如果是良好数组,则a[i]的奇偶性情况与i要相同,但是对于n,n固定,0~n-1的偶数情况就固定了:

1. 如果n是奇数,则从0到n-1,偶数个数-奇数个数 = 1;

2. 如果n是偶数,则从0到n-1,奇数个数等于偶数个数。

所以首先要满足这两个情况才可能通过交换得到良好数组。

如果满足其中一个之后,因为不满足的一定是对应的(一个奇数下标i不满足对应一定有一个偶数下标j不满足),所以只需判断有几个奇数不满足情况,得出来的就是交换次数;

代码:

#include 
using namespace std;

int main() {
	int t;
	cin >> t;
	while(t--) {
		int n, odd = 0, even = 0, d = 0, ans = 0;
		cin >> n;
		int a[50];
		
		for(int i = 0; i < n; i++) {
			cin >> a[i];
			if(a[i] % 2) odd++;		//奇数个数 
			else even++;			//偶数个数 
		}
		
		if(n % 2) {		//判断情况 
			if(even - odd == 1) {	
				for(int i = 0; i < n; i++) {	//循环判断有几个奇数下标不满足 
					if(i % 2 && i % 2 != a[i] % 2) {
						ans++;
					}
				}
				
				cout << ans << endl;
			}else {		//如果不满足一定不能得到 
				cout << "-1" << endl;
			}
			
			
		}else {
			if(even != odd) {
				cout << "-1" << endl;
			}else {			//循环判断你有几个奇数不满足 
				for(int i = 0; i < n; i++) {
					if(i % 2 && i % 2 != a[i] % 2) {
						ans++;
					}
				}
				
				cout << ans << endl;
			}
		}
	}
	
	return 0;
}

原题:

题目:

You are given an array a[0…n−1]of length nn which consists of non-negative integers. Note that array indices start from zero.

An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all ii (0≤i≤n−1) the equality i mod 2=a[i] mod2 holds, where x mod 2 is the remainder of dividing x by 2.

For example, the arrays [0,5,2,1] and [0,17,0,3] are good, and the array [2,4,6,7] is bad, because for i=1, the parities of i and a[i] are different: i mod 2 = 1 mod 2 = 1, but a[i] mod 2 = 4 mod 2 = 0.

In one move, you can take any two elements of the array and swap them (these elements are not necessarily adjacent).

Find the minimum number of moves in which you can make the array aa good, or say that this is not possible.

输入:

The first line contains a single integer t (1≤t≤1000) — the number of test cases in the test. Then tt test cases follow.

Each test case starts with a line containing an integer n (1≤n≤40) — the length of the array aa.

The next line contains nn integers a0,a1,…,an−1 (0≤ai≤1000) — the initial array.

输出:

For each test case, output a single integer — the minimum number of moves to make the given array a good, or -1 if this is not possible.

样例:

Input:

4
4
3 2 7 6
3
3 2 6
1
7
7
4 9 2 1 18 3 0

Output:

2
1
-1
0

Note:

In the first test case, in the first move, you can swap the elements with indices 0 and 1, and in the second move, you can swap the elements with indices 2 and 3.

In the second test case, in the first move, you need to swap the elements with indices 0 and 1.

In the third test case, you cannot make the array good.

你可能感兴趣的:(思维)