跳到正文

题解

题解:CF2259E Treasure Map Destruction (Constructive Version)

Charged_Charge约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年9月29日
收录
2026年9月29日
更新
2026年11月11日
篇幅
约 4 分钟
获赞
1
题目
CF2259E

版本

  1. v1当前

思路:

首先,如果位置 ii 的 aia_i 不为 −1-1 或 00,则我们可以确认,在 [max⁡(1,i−ai+1),min⁡(i+ai−1,n)][\max(1,i-a_i+1),\min(i+a_i-1,n)] 内一定没有宝藏,并且位置 max⁡(1,i−ai+1)\max(1,i-a_i+1) 或 min⁡(i+ai−1,n)\min(i+a_i-1,n) 一定有宝藏。于是我们通过差分维护哪些位置不能有宝藏。如果遇到某个位置已经有宝藏然而我们不希望这里有宝藏,则无解。接下来,把那些 ai=−1a_i=-1 但可以有宝藏的位置全部设为有宝藏。因为这里就算有宝藏,也不会与已知信息相矛盾,反而可以最大限度地满足现有信息所有的要求。

AC 代码:

C++
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N = 2e5 + 10;
int t, n, a[N], s[N], ls[N], rs[N];
int main(){
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    cin >> t;
    while(t--){
        cin >> n;
        for(int i = 0; i <= n; i++) s[i] = 0, ls[i] = 1e9, rs[i] = 1e9;
        for(int i = 1; i <= n; i++) cin >> a[i];
        bool ok = true;
        for(int i = 1; i <= n; i++){
            if(a[i] == -1 || a[i] == 0) continue;
            if(a[max(i - a[i], 1)] != -1 && a[min(i + a[i], n)] != -1){
                if(a[max(i - a[i], 1)] != 0 && a[min(i + a[i], n)] != 0){
                    ok = false;
                    break;
                }
            }
            s[max(i - a[i] + 1, 1)]++;
            s[min(i + a[i], n + 1)]--;
        }
        if(!ok){
            cout << -1 << '\n';
            continue;
        }
        for(int i = 1; i <= n; i++) s[i] = s[i - 1] + s[i];
        for(int i = 1; i <= n; i++){
            if(a[i] == 0 && s[i] == 1){
                ok = false;
                break;
            }
        }
        if(!ok){
            cout << -1 << '\n';
            continue;
        }
        for(int i = 1; i <= n; i++) if(s[i] == 0 && a[i] == -1) a[i] = 0;
        int lt = -1e9;
        for(int i = 1; i <= n; i++){
            if(a[i] == 0) lt = i;
            ls[i] = i - lt;
        }
        int nx = 1e9;
        for(int i = n; i >= 1; i--){
            if(a[i] == 0) nx = i;
            rs[i] = nx - i;
        }
        for(int i = 1; i <= n; i++){
            if(a[i] == -1) continue;
            if(min(ls[i], rs[i]) != a[i]){
                ok = false;
                break;
            }
        }
        if(!ok) cout << -1;
        else for(int i = 1; i <= n; i++) cout << (a[i] == 0 ? 1 : 0);
        cout << '\n';
    }
    return 0;
}
原文