题解:P13713 晴天

· · 题解

有一个比较麻烦的做法。

个人想法是先填 x 天晴天再填 y 天阴天,先考虑 x 天晴天怎么填。

考虑使用类似 1, 0, 0 这样的循环节构造 x + 2 个数(每 3 个数组合出 1 个数),最好让构造出来序列的末尾为 0, 0,于是考虑对这个循环节循环移位。

这个 0, 0 有什么作用呢?它很好地帮我们和前面的 1 隔开,这样我们再 -1, 0 交替填 y 次就能构造出 y 天阴天了。具体地,可以这样子构造:

a_1 \ a_2 \ldots a_x \ 0 \ 0 \underbrace{\color{red}{\ {-1} \ 0 \ {-1} \ 0 \ldots}}_{y \text{\ times}}

其中 (0, 0, -1), (0, -1, 0), (-1, 0, -1) 构成了满足条件的阴天。

剩下 n - x - y - 2 个数怎么填?可以分类讨论一下。

至于合不合法,直接暴力判断,注意特判 n = 1。

单次时间复杂度 O(n)。顺带一提,这个代码是在洛谷 IDE 上搓的,所以码风和平常不一样。

#include <bits/stdc++.h>
#define add(x) ans.emplace_back(x)
using namespace std;
int a[] = {1, -1, 0}, b[] = {1, 0, -1}, c[] = {0, -1};
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    int t; cin >> t;
    while (t--) {
        int n, x, y;
        std::cin >> n >> x >> y;
        if (n == 1) {
            std::cout << (!x && !y ? 0 : -2) << "\n";
            continue;
        }
        std::vector<int> ans {0};
        for (int i = 1; i <= x + 2; ++i) 
            add(i % 3 == x % 3);
        for (int i = 1; i <= y; ++i) add(c[i % 2]);
        int v = ans.back() == -1;
        for (int i = 0; i < n - y - x - 2; ++i)
            if (y == 0) add(0);
            else add((v ? b : a)[i % 3]);
        if ((int)ans.size() == n + 1) {
            for (int i = 1; i <= n; ++i)
                std::cout << ans[i] << " \n"[i == n];
        } else std::cout << "-2\n";
    }
}