题解:P15776 [JAG 2025 Summer Camp #2] All Copy Paste

· · 题解

首先可以注意到,经过一次操作序列的长度会翻倍,那么经过 \log 次操作后,序列的长度肯定 \ge m。

暴力模拟这 \log 次操作,剩下的操作中 x_{q}>m 的操作显然没有用,直接扔掉,并且模拟的时候可以只保留前 m 位。

一次操作等价于把一个序列的一个前缀取出来拼到前面去,直接这么做不好做,考虑倒着做,一个当前的序列肯定可以看作上一步的两个前缀在 x_{q} 处拼起来,递归去求上一步的前缀即可。

容易用双端队列模拟。


#include <bits/stdc++.h>
#define int long long 
using namespace std;
const int N = 4e6 + 5;
int n, m, q, a[N], b[N], c[N], cnt, res, bot;
deque<int> tmp;
vector<int> vec;
void solve (int x, int t) {
    if (x == res) {
        for (int i = 1; i <= t; ++ i) {
            tmp.push_back(c[i]);
        }
        return ;
    }
    if (a[x] >= t) {
        solve(x - 1, t);
    } else {
        vector<int> vec;
        if (a[x] >= t - a[x]) {
            solve(x - 1, a[x]);
            bot = 0;
            while (bot < t - a[x]) {
                vec.push_back(tmp.front());
                tmp.pop_front();
                ++ bot;
            }
            for (int i = vec.size() - 1; i >= 0; -- i) {
                tmp.push_front(vec[i]);
            }
            for (int i = 0; i < vec.size(); ++ i) {
                tmp.push_back(vec[i]);
            }
        } else {
            solve(x - 1, t - a[x]);
            bot = 0;
            while (bot < a[x]) {
                vec.push_back(tmp.front());
                tmp.pop_front();
                ++ bot;
            }
            for (int i = vec.size() - 1; i >= 0; -- i) {
                tmp.push_front(vec[i]);
            }
            for (int i = vec.size() - 1; i >= 0; -- i) {
                tmp.push_front(vec[i]);
            }
        }
    }
} 
signed main () {
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    cin >> n >> m >> q;
    for (int i = 1; i <= q; ++ i) {
        cin >> a[i];
    }
    for (int i = 1; i <= n; ++ i) {
        c[i] = i;
    }
    if (n >= m) res = 0;
    else {
        for (int i = 1; i <= q; ++ i) {
            if (n < m) {
                cnt = 0;
                for (int j = 1; j <= n; ++ j) b[j] = c[j];
                for (int j = 1; j <= a[i]; ++ j) ++ cnt, c[cnt] = b[j];
                for (int j = 1; j <= n; ++ j) ++ cnt, c[cnt] = b[j];
                for (int j = a[i] + 1; j <= n; ++ j) ++ cnt, c[cnt] = b[j];
                n = cnt;
            }
            if (n >= m) {
                res = i;
                break;
            }
        }
    }
    solve(q, m);
    while (! tmp.empty()){
        cout << tmp.front() << ' ';
        tmp.pop_front(); 
    }
    return 0;
}