每日一题之 hiho200 Shortening Sequence

描述
There is an integer array A1, A2 …AN. Each round you may choose two adjacent integers. If their sum is an odd number, the two adjacent integers can be deleted.

Can you work out the minimum length of the final array after elaborate deletions?

输入
The first line contains one integer N, indicating the length of the initial array.

The second line contains N integers, indicating A1, A2 …AN.

For 30% of the data:1 ≤ N ≤ 10

For 60% of the data:1 ≤ N ≤ 1000

For 100% of the data:1 ≤ N ≤ 1000000, 0 ≤ Ai ≤ 1000000000

输出
One line with an integer indicating the minimum length of the final array.

样例提示
(1,2) (3,4) (4,5) are deleted.

样例输入
7
1 1 2 3 4 4 5
样例输出
1

题意:

给一组序列 A 1 A n ,如果两个相邻的数的和为奇数的话那么这两个数可以删除。求这样删除之后这组序列的最小的长度是多少?

思路:

首先两个数的和为奇数的情况只能是一个奇数一个偶数的和,如果最后剩下全是奇数或者全是偶数的情况那么一定不能继续删除了,所以说只要这个序列中同时存在奇数和偶数那么一定可以删除,所以只要统计这个序列中奇数和偶数的个数,求其差值就是答案了。

启示:

有时候要跳出问题的框架去看本质,这里主要考察的就是和为奇数的情况只能是一个奇数和一个偶数相加,想通这一点题目就变得很简单。

#include <cstdio>
#include <iostream>
#include <vector>
#include <cstring>
#include <map>
using namespace std;

const int maxn = 1e6+5;


int A[maxn];

int main()
{

    int n,x;

    cin >> n;

    int even = 0;
    int odd = 0;

    for (int i = 0; i < n; ++i) {
        cin >> x;
        if (x%2) ++odd;
        else 
            ++even;
    }

    int res = abs(even-odd);

    cout << res << endl;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/u014046022/article/details/80560939
今日推荐