Even-odd Boxes hackerrank 分类讨论

https://www.hackerrank.com/contests/101hack50/challenges/even-and-odd-boxes/editorial

昨晚做的时候卡了挺久的。

首先能想到的是-1的情况,奇偶性要相同,因为序列操作只是移动,所以总量是固定的。所以,如果能把它变成合法的序列。

则是偶数 + 奇数 + 偶数 + .......这样,这个序列的奇偶性就是n / 2了,要相同。

然后找出不合法的位置,假设一共有ans个,那么ans / 2就是答案。

一开始是这样想的,后来看清楚题目了,每个箱子至少要1个。

那么就要看到,奇数位置上,放了1的话,它肯定只能够是增加一个,变得合法。

所以这类又要分类出来判断。设为add个,那么有可能ans >= add,或者ans < add

ans >= add的话好办,直接是add + (ans - add) / 2

不是的话,就是需要某些合法的位置给一些去add了。很多细节,我自己的小数据

7
6
6 8 3 1 1 4
5
3 1 1 1 1
3
14 3 10
3
1 2 4
4
1 1 1 1
5
1 1 1 1 6
7
1 4 1 2 1 1 1

ans:

2
-1
0
1
-1
2
4

#include <bits/stdc++.h>
#define IOS ios::sync_with_stdio(false)
using namespace std;
#define inf (0x3f3f3f3f)
typedef long long int LL;
const int maxn = 1e5 + 20;
int a[maxn];
vector<int>vc, ff;
void work() {
    vc.clear();
    ff.clear();
    int n;
    scanf("%d", &n);
    for (int i = 1; i <= n; ++i) scanf("%d", a + i);
    int ans = 0;
    LL sum = 0;
    int add = 0;
    for (int i = 1; i <= n; ++i) {
        sum += a[i];
        if (a[i] == 1 && (i & 1)) {
            add++;
            continue;
        }
        if (i & 1) {
            if (a[i] & 1) {
                ans++;
                ff.push_back(a[i] - 1); //存的是不合法的位置
            } else if (a[i] != 1) vc.push_back(a[i]);
        } else {
            if (!(a[i] & 1)) {
                ans++;
                ff.push_back(a[i] - 1); //不合法的序列,要变成合法,先 - 1,全部去了add
            } else if (a[i] != 1) {
                vc.push_back(a[i]);
            }
        }
    }
    int res = n / 2;
    if ((sum + res) & 1) {
        printf("-1
");
        return;
    }
    if (ans >= add) {
        printf("%d
", add + (ans - add) / 2);
    } else {
        int want = ans;
        add -= ans;
        for (int i = 0; i < vc.size(); ++i) {
            while (add > 0 && vc[i] > 2) {
                vc[i] -= 2;
                add -= 2;
                want += 2;
            }
        }
        for (int i = 0; i < ff.size(); ++i) {
            while (add > 0 && ff[i] > 2) {
                ff[i] -= 2;
                add -= 2;
                want += 2;
            }
        }
        if (add) {
            printf("-1
");
            return;
        }
        printf("%d
", want);
    }
}

int main() {
#ifdef local
    freopen("data.txt", "r", stdin);
//    freopen("data.txt", "w", stdout);
#endif
    int t;
    cin >> t;
    while (t--) work();
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/liuweimingcprogram/p/7059521.html