Returns a string(,),[,] String, which contains [the most legal substrings]
It is easy to drop the entire string into the stack for processing.
Each element of the stack stores two things, character, and position in the string.
If it is a () match, it will be discarded directly. If it is a [] match, then vis [I] ++ at this point,Then obtain the VIS prefix and
If the stack is empty, the entire string is valid and the string is directly output.
Otherwise, scan the positions of the remaining elements in the stack to cut the entire original string into several segments,These paragraphs must be valid., Find out which of the following sections contain [the largest segment,The prefix and result can be used to output this section.
Cursor, the left and right intervals are very easy to get wrong. Once I manually output '\ 0', it looks the same as the answer, that is, WA.
# Include <cstdio> # include <climits> # include <cstring> # include <iostream> # include <algorithm> using namespace STD; char STR [111111]; int vis [111111]; int sumvis [111111]; struct stack {char C; int Pos;} sta [111111]; int main () {# ifndef online_judgefreopen ("/home/raw.96/in.txt", "r", stdin); # endifcin> STR; int P =-1; int Len = strlen (STR); For (INT I = 0; I <Len; I ++) {If (P! =-1) {If (STR [I] = ')' & sta [p]. C = '(') {// directly discard p --; continue;} If (STR [I] = ']' & sta [p]. C = '[') {// vis [I] ++ to quickly obtain the number of [-included p --; vis [I] ++; continue ;} sta [++ p] = (stack) {STR [I], I };} else sta [++ p] = (stack) {STR [I], I };} sumvis [0] = vis [0]; for (INT I = 1; I <Len; I ++) sumvis [I] = sumvis [I-1] + vis [I]; If (P =-1) {// if there is nothing in the stack, the entire string is legal, output The cout string <sumvis [len-1] <Endl; cout <STR <Endl; return 0;} int x =-1, y =-1, ans = 0; // find the remaining elements in the stack so that the segments separated by the original string contain the most [String int ansx =-1, ansy =-1; for (INT I = 0; I <= P; I ++) {Y = sta [I]. pos; int tmpans = sumvis [Y-1]-sumvis [x] + (x = 0? Vis [x]: 0); If (tmpans> ans) {ans = tmpans; ansx = x + 1; ansy = Y-1;} X = y;} y = Len; int tmpans = sumvis [Y-1]-sumvis [x] + (x = 0? Vis [x]: 0); If (tmpans> ans) {ans = tmpans; ansx = x + 1; ansy = Y-1;} cout <ans <Endl; // cout <x <Endl; // cout <Y <Endl; If (ANS> 0) {for (INT I = ansx; I <= ansy; I ++) cout <STR [I];} cout <Endl ;}
Codeforces 223a bracket sequence [Stack]