Question meaning: Given a 01 string, you are required to separate it into several subsequences (each number can only belong to a certain subsequence). If this is not possible, output -1.
analyze:
It's easy to think of the need to greedily pair 0 and 1
That is, if you can construct alternately 0 and 1, try to choose this scheme, so that you can use fewer 0s to pair as many 1s as possible.
Use the two-dimensional array vector<int> idx[] to hold the information of each subsequence
Use two sets to hold the subsequences of the now 0-terminated and 1-terminated subsequences
Then O(n) sweep from left to right, for 0 elements to check if there is currently a subsequence that ends with 1
If there are any, fill in it, otherwise create a new subsequence, starting with this 0. if there is not,
Indicates that it cannot be done, output -1
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<bits/stdc++.h> #define LL long long using namespace std; const int maxn = 2e5 + 10; int num0, num1, len, ans, arr[maxn]; vector<int> idx[maxn]; set<int> zero, one; int main(void) { while(true){ char ch; scanf("%c", &ch); if(ch == '\n') break; if(ch == '0') num0++, arr[++len] = 0; else num1++, arr[++len] = 1; } if(num0 <= num1){ puts("-1"); return 0; } for(int i=1; i<=len; i++){ if(arr[i] == 0){ num0--; if(one.size() == 0){ idx[ans].push_back(i); zero.insert(ans++); }else{ int ii = *one.begin(); one.erase(one.begin()); idx[ii].push_back(i); zero.insert(ii); } }else{ num1--; if(num0 <= 0){ puts("-1"); return 0; } if(zero.size() == 0){ puts("-1"); return 0; }else{ int ii = *zero.begin(); zero.erase(zero.begin()); idx[ii].push_back(i); one.insert(ii); } } } if(one.size() > 0){ puts("-1"); return 0; } printf("%d\n", ans); for(int i=0; i<ans; i++){ printf("%d ", idx[i].size()); for(int j=0; j<idx[i].size(); j++){ printf("%d ", idx[i][j]); }puts(""); } return 0; }