题解
题目大意
给定整数 和长度为 的 字符串 。将 排成一个排列,规定:相邻两数差值为偶数对应字符 0,差值为奇数对应字符 1。要求构造出字典序最小的合法排列;若无法构造,输出 -1。
题目思路
- 先根据给定的 01 串,推算出整个排列需要用到的奇数、偶数数量。
- 再统计 中实际的奇数和偶数个数。
- 若两者数量不匹配,则无法构造合法排列,直接输出 -1。
- 若数量匹配,将所有奇数、偶数分别按从小到大的顺序存储。
- 从最小的奇数开始,按照 01 串规则选数:字符 0 保持奇偶性不变,字符 1 切换奇偶性。
- 依次拼接选出的数字,即可得到字典序最小的合法排列。
代码
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,shao=0,yu=0,NBA=0;
string s;
cin >> n >> s;
int t = 1;
for(char c : s)
if(c == '1') t ^= 1;
int co = 0, ce = 0;
for(int i = 1; i <= n; ++i)
if(i & 1) co++;
else ce++;
int st = 1, ro = 1, re = 0;
for(char c : s){
if(c == '1') st ^= 1;
if(st) ro++;
else re++;
}
if(ro != co or re != ce){
cout << -1;
return 0;
}
vector<int> O,E;
for(int i = 1; i <= n; ++i)
if(i & 1) O.push_back(i);
else E.push_back(i);
vector<int> A;
int p = 0, q = 0;
A.push_back(O[p++]);
st = 1;
for(char c : s){
if(c == '1') st ^= 1;
if(st) A.push_back(O[p++]);
else A.push_back(E[q++]);
}
for(int x : A) cout << x << " ";
return 0;
}