题意
链接: link.
一个由01组成的字符串,要求相同字符不能相邻,把原字符串拆成多少个字符串,每一个字符属于第几个字符串
思路
用两个队列来存放最后一个可放字符的队列号,如果还有就取出来,记住对应字符的归属对列,此对号所对应的字符串的最后一个调节到另一个队列以备复用,如果所对应的尾号用完了,就新开一个队
AC代码
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define N 200010
string s;
int arr[N];
int main()
{
int t;
cin >> t;
while (t--)
{
queue<int> q[2]; //q[0]为1结尾的,q[1]为以0结尾的
int n;
cin >> n;
cin >> s;
int res = 0;
for (int i = 0; i < n; i++)
{
int op = s[i] - '0';
if (!q[op].empty())
{
int temp = q[op].front();
q[op].pop();
arr[i] = temp;
q[op ^ 1].push(temp);//复用队列
}
else
{
res++;
q[op^1].push(res);//开起新的诗篇
arr[i] = res;
}
}
cout << res << endl;
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
//system("pause");
return 0;
}