题目链接
题目大意
输入一个字串s 由0和1组成,将它的拆分成“0101010”的形式,保证不能让两个相同的字符相邻 求最少要拆成多少块
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int maxn=2e5+1;
string s;
int n;
int a[maxn]; //用来记录每个字符所在的子串数
void solve(){
cin>>n;
cin>>s;
queue<int> q1,q0; //队列是用来记录以0或者1结尾的子串的 个数 和子串序号
int idx=0; //用来记录子串数
int x;
for(int i=0;i<n;i++){
if(s[i]=='0'){
if(!q1.empty()){
x=q1.front(); //x用来记录字符0所在的最前面以1结尾的子串的序号
q1.pop(); //因为此时最前面的子串已经变成了以0结尾的子串,所以要将其弹出
a[i]=x; //记录字符0所在的子串
q0.push(x); //因为当前子串已经变成了0结尾,所以要将其入到q0的队列中
}
else{ //如果没有以1结尾的子串,就自己建立一个子串
idx++;
q0.push(idx); //表示当前第idx个以0结尾的子串
a[i]=idx; //此处容易遗忘,这里要记录当前字符新建的子串序号
}
}
else{
if(!q0.empty()){
x=q0.front();
q0.pop();
a[i]=x;
q1.push(x);
}
else{
idx++;
q1.push(idx);
a[i]=idx;
}
}
}
cout<<idx<<endl;
for(int i=0;i<n;i++){
cout<<a[i]<<" ";
}
cout<<endl;
}
int main(){
int t;
cin>>t;
while(t--){
solve();
}
}