codeforces 1367B - Even Array

B. Even Array
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given an array a[0…n−1] of length n 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 i (0≤i≤n−1) the equality imod2=a[i]mod2 holds, where xmod2 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: imod2=1mod2=1, but a[i]mod2=4mod2=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 a good, or say that this is not possible.

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

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

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

Output
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.

Example
inputCopy
4
4
3 2 7 6
3
3 2 6
1
7
7
4 9 2 1 18 3 0
outputCopy
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.

链接:https://codeforces.ml/problemset/problem/1367/B
题意:一个数组中所有i%2要和a[i]%2相等则为good 如果能,输出交换的次数,如果不相等,看看能否通过交换使得数组为good 不能则输出-1
思路:只需要统计能不能的次数,就只需要去统计就好了,通过发现可以知道数组需要 偶数 奇数 偶数 奇数… 所以判断a[i]是否为对应的偶数或者奇数,如果不是则统计,判断最后统计出来的奇偶是否相等
ac代码如下:

#include<iostream>
#include<cstring>
using namespace std;
int main()
{
	int t,a[1002];
	cin>>t;
	while(t--)
	{
		int n,cou1=0,cou2=0;
		cin>>n;
		
		for(int i=0;i<n;i++)
		{
			cin>>a[i];
		}
		
		for(int i=0;i<n;i+=2)
		{
			if(a[i]%2!=0) cou1++;
		}
		
		for(int i=1;i<n;i+=2)
		{
			if(a[i]%2!=1) cou2++;
		}
		
		if(cou1==cou2) cout<<cou1<<endl;
		else cout<<-1<<endl;
		
		memset(a,0,sizeof(a));
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值