CF2201B Recollect Numbers 题解

· · 题解

Luogu

CF div2-D

CF div1-B

solution

首先划定 k 的大致范围,发现 k 不能小于 n,因为每张牌至少要被翻一次;k 也不能大于 2n,因为每张牌至多被翻 2 次。

我们给每个字符用 0 表示它是第一次出现,1表示之前出现过一次。

考虑最小操作次数,显然最优情况为每一次都翻到一对相同的牌,即 0 1 0 1 \ldots 0 1 0 1,对应序列 1 1 2 2 3 3 \ldots n n。

接下来考虑最大操作次数,显然我们要最大化“浪费”的次数,尝试构造 0 0 0 1 0 1 \dots 0 1 0 1 1 1 的样子,这样每次一个 1 需要单独处理,可以使操作数最大,即 2n - 1 次操作。

然后考虑用这两个特殊情况推广到所有 k 的解法。设一个数 x,显然我们知道 n_1 = x、k_1 = 2x - 1 和 n_2 = n - x、k_2 = n - x 的解法。

因为 k_1 + k_2 = k,所以 (2x - 1) + (n - x) = k,解得 x = k - n + 1。

于是就解决了,时间复杂度 O(n)。

Code

#include<bits/stdc++.h>
#define ll long long
#define ull unsigned ll
#define lll __int128
#define db double
#define ldb long db
#define pii pair<int, int>
#define pil pair<int, ll>
#define pli pair<ll, int>
#define pll pair<ll, ll>
#define endl '\n'
#define ft first
#define sd second
using namespace std;
int T, n, k;
int main() {
    //freopen(".in", "r", stdin);
    //freopen(".out", "w", stdout);
    ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
    cin >> T;
    while(T--) {
        cin >> n >> k;
        if(k < n || k >= 2 * n) {
            cout << "No" << endl;
        } else {
            cout << "Yes" << endl;
            int x = k - n + 1;
            if(x == 1) {
                cout << 1 << " " << 1 << " ";
            } else {
                cout << 1 << " " << 2 << " ";
                for(int i = 1; i <= x - 2; i++) {
                    cout << i + 2 << " " << i << " ";
                }
                cout << x - 1 << " " << x << " ";
            }
            for(int i = 1; i <= n - x; i++) {
                cout << x + i << " " << x + i << " ";
            }
            cout << endl;
        }
    }
    return 0;
}

/*
Progress is impossible without change, and those who cannot change their minds cannot change anything.
NEVER GIVE UP.
*/