题解:P16795 [蓝桥杯 2026 国 B] 奇偶校验排列

· · 题解

题解

题目大意

给定整数 n 和长度为 n-1 的 01 字符串 S。将 1 \sim n 排成一个排列,规定:相邻两数差值为偶数对应字符 0,差值为奇数对应字符 1。要求构造出字典序最小的合法排列;若无法构造,输出 -1。

题目思路

代码


#include<bits/stdc++.h>
using namespace std;
int shao=0,yu=0,NBA=0;
int n;string s;
vector<int> O,E;
vector<int> g(int st){
    int co=0,ce=0;
    int now=st;
    if (now == 1) co++;
    else ce++;
for(char c : s){
    if(c == '1')now ^= 1;
    if (now == 1)co++;
    else ce++;
    }
    if(co != O.size() || ce != E.size())
    return {};
    vector<int> a;
    int p1=0,p2=0;
    now=st;
    if (now == 1)
        a.push_back(O[p1++]);
     else
        a.push_back(E[p2++]);
for(char c : s){
    if(c == '1')now ^= 1;
    if (now == 1)
    a.push_back(O[p1++]);
    else a.push_back(E[p2++]);
    }
    return a;
}
int main(){
    cin >> n >> s;
for(int i = 1; i <= n; i++){
    if(i & 1)
    O.push_back(i);
    else E.push_back(i);
    }
    auto a = g(1);
    if(!a.empty()){
for(int x : a)
    cout << x << " ";
        return 0;
    }
    a = g(0);
    if(!a.empty()){
        for(int x : a)
            cout << x << " ";
        return 0;
    }
    cout << -1;
}