题解:P16795 [蓝桥杯 2026 国 B] 奇偶校验排列
题解
题目大意
给定整数
题目思路
- 先根据给定的 01 串,推算出整个排列需要用到的奇数、偶数数量。
- 再统计
1 \sim n 中实际的奇数和偶数个数。 - 若两者数量不匹配,则无法构造合法排列,直接输出 -1。
- 若数量匹配,将所有奇数、偶数分别按从小到大的顺序存储。
- 从最小的奇数开始,按照 01 串规则选数:字符 0 保持奇偶性不变,字符 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;
}