题解:CF2259E Treasure Map Destruction (Constructive Version)

· · 题解

思路:

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

AC 代码:

#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;
}