ZCMU-1312: Domino

这几天忙着转专业的事情了,没怎么更新了,题目也没怎么写。今天闲下来一点时间,来看一道奇数偶数的数论题。

文章目录

题目


Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 187 Solved: 78
[Submit][Status][Web Board]
Description

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.

Input

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.

Output

Print a single number — the minimum required number of seconds. If Valera can’t do the task in any time, print  - 1.

Sample Input

2
4 2
6 4
1
2 3
3
1 4
2 3
4 4

Sample Output

0
-1
1

想法

这道题就是给你一个n数,接下来有2n组数据,前n个存入a数组,后n个存入b数组,问你是否可以通过交换上下两组数据达到两组数据之和都是偶数的结果,如果可以输出需要几秒(交换一次是1秒),不行则输出-1

我们先来讨论奇数偶数相加的结果
偶数 + 偶数 = 偶数
奇数 + 奇数 = 偶数
奇数 + 偶数 = 奇数/偶数

那么如果把a数组和b数组都把数据抽象话,看成是偶数奇数的随机出现,这道题就变的具体了。

根据公式第一条和第二条,我们可以忽略成对偶数奇数对答案的影响,也就是剔除那些数剩下来就是以下几种情况

1.偶数个奇数,显然可以形成偶数个偶数对(两两一对),则直接输出0(不需要交换)
2.上下都是奇数个奇数,那么如果要使得满足题意,我们需要剔除一个数和下面的交换,怎么才能满足条件呢?我们看公式三,如果a[i]+b[i]是奇数,则显然一定会是一个奇数和一个偶数,那么只需要进行交换,这样上面那组可以满足相加和为偶数了(偶数个奇数对+一个偶数),则

3.其他情况就都不能满足了,我们直接输出-1

AC代码

#include<bits/stdc++.h>
using namespace std;
int main(){
    
    
 
    int n,i;
    int a[105],b[105];
    while(cin>>n){
    
    
           int fa=0,fb=0;
           for(i=0;i<n;i++){
    
    
               cin>>a[i]>>b[i];
               if(a[i]&1) fa++;
               if(b[i]&1) fb++;
           }
           if(fa%2==0&&fb%2==0){
    
    
               cout<<0;
           }
           else if((fa&1)&&(fb%2==1)){
    
    
               bool f=false;
               for(i=0;i<n;i++){
    
    
                   if((a[i]+b[i])&1) f=1;
                   if(f) break;
               }
               if(f) cout<<1;
               else cout<<-1;
           }
           else{
    
    
               cout<<-1;
           }
           cout<<endl;
    }
      return 0;
      }

总结

最近写题目少了,需要抽时间写!

猜你喜欢

转载自blog.csdn.net/DAVID3A/article/details/114945316