Valera has got n domino pieces in a row. Each piece consists of two halves — the upper one and the lower one. Each of the halves contains a number from 1 to 6. Valera loves even integers very much, so he wants the sum of the numbers on the upper halves and the sum of the numbers on the lower halves to be even.
To do that, Valera can rotate the dominoes by 180 degrees. After the rotation the upper and the lower halves swap places. This action takes one second. Help Valera find out the minimum time he must spend rotating dominoes to make his wish come true.
The first line contains integer n (1 ≤ n ≤ 100), denoting the number of dominoes Valera has. Next n lines contain two space-separated integers xi, yi (1 ≤ xi, yi ≤ 6). Number xi is initially written on the upper half of the i-th domino, yi is initially written on the lower half.
Print a single number — the minimum required number of seconds. If Valera can't do the task in any time, print - 1.
2 4 2 6 4
0
1 2 3
-1
3 1 4 2 3 4 4
1
In the first test case the sum of the numbers on the upper halves equals 10 and the sum of the numbers on the lower halves equals 6. Both numbers are even, so Valera doesn't required to do anything.
In the second sample Valera has only one piece of domino. It is written 3 on the one of its halves, therefore one of the sums will always be odd.
In the third case Valera can rotate the first piece, and after that the sum on the upper halves will be equal to 10, and the sum on the lower halves will be equal to 8.
题意:给n组数,每组数有两个数,要求所有的前一个数之和sum1为偶数,所有的后一个数之和sum2为奇数。可以通过交换某几组数的两个数位置来满足这个要求,求需要交换几组,如果无法满足该要求,则输出-1。
分类讨论,若sum1和sum2均为偶数,则输出0;若sum1和sum2是一奇一偶,则无论怎么交换都无法使二者均为偶数,输出-1;若sum1和sum2均为奇数,则找n组数据中是否存在一组数是一奇一偶,如果存在则输出1,反之输出-1。时间复杂度O(N)。
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int n, a, b, sum1, sum2, flag;
while(scanf("%d", &n) != EOF)
{
sum1 = 0;
sum2 = 0;
flag = 0;
for(int i = 0; i < n; i++)
{
scanf("%d%d", &a, &b);
sum1 += a;
sum2 += b;
if((a + b) % 2)
flag = 1;
}
if(sum1 % 2 == 0 && sum2 % 2 == 0)
{
printf("0\n");
continue;
}
if((sum1 + sum2) % 2)
{
printf("-1\n");
continue;
}
if(flag)
{
printf("1\n");
continue;
}
printf("-1\n");
}
}