CF1399D. Binary String To Subsequences

思路

用两个队列来存储遇到的0和1的位置,然后边遍历边判断是否要开新的子序列来存下当前的字符

ac代码

#include <bits/stdc++.h>

using namespace std;
using i64 = long long;
const i64 inf = 1e18;
typedef pair<int, int> pii;
const int mod = 1e9 + 7;
const int N = 3e5 + 10;

void solve() {
    int n; cin >> n;
    string t; cin >> t;
    int idx = 0;
    vector<int> res(n);
    queue<int> la_0, la_1;
    for (int i = 0; i < t.size(); i++) {
        if (t[i] == '1') {
            if (la_0.size() == 0) {
                la_1.push(i);
                res[i] = ++ idx;
            } else {
                res[i] = res[la_0.front()];
                la_0.pop();
                la_1.push(i);
            }
        } else {
            if (la_1.size() == 0) {
                la_0.push(i);
                res[i] = ++ idx;
            } else {
                res[i] = res[la_1.front()];
                la_1.pop();
                la_0.push(i);
            }
        }
    }
    
    cout << idx << endl;
    for (auto i : res) cout << i <<  ' ';
    cout << endl;
}   

int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    cout.tie(0);

    int t = 1;
    cin >> t;
    while (t --) solve();

    return 0;
}
posted @ 2024-01-22 00:07  jvdyvan  阅读(11)  评论(0)    收藏  举报