Uva11988 broken keyboard (tragic text)
Link: uva11988
Description:
The input contains multiple groups of data, each of which occupies one row and contains no more than 100000 letters, underscores, and characters "[" or "]". The character "[" indicates the Home key, and "]" indicates the end key. The input end mark is the file end character (EOF). The input file cannot exceed 5 MB. For each group of data, a line is output, that is, the tragic text on the screen.
Sample input:
This_is_a_[Beiju]_text[[]][]Happy_Birthday_to_Tsinghua_University
Sample output:
BeijuThis_is_a__textHappy_Birthday_to_Tsinghua_University
Question Analysis:
The simplest idea is to use an array to save the text, and then use a variable POs to save the "cursor position". Inputting a character is equivalent to inserting a character into the array, in this way, you need to first shift all the subsequent characters to the right and fill out the position for the new characters.
From the analysis above, we can know that this is very complicated and will take a long time.
Therefore, we consider using a linked list)
For convenience, a virtual node is usually placed before the first element of the linked list.
Store each input character. Set the input string to s [1 ~ N], you can use next [I] to represent the character number on the Right of S [I] on the current display.
If there is a virtual s [0] at the beginning of string S, next [0] can represent the leftmost character on the display screen, and then use the variable cur to represent the cursor position, that is, the current cursor is located on the right of S [cur]. If cur = 0, the cursor is located on the right of the virtual character s [0], that is, the leftmost part of the display. To move the cursor, you also need to use a variable last to represent the last character s [last] of the display.
<<
Reference code:
// Damaged keyboard. CPP # include <iostream >#include <string> using namespace STD; const int maxn = 100000 + 5; int last, cur, next [maxn]; char s [maxn]; int main () {While (CIN> S + 1) {int n = strlen (S + 1); last = cur = 0; next [0] = 0; for (INT I = 1; I <= N; I ++) {char CH = s [I]; If (CH = '[') cur = 0; else if (CH = ']') cur = last; else {next [I] = next [cur]; next [cur] = I; If (cur = last) last = I; // update the "last character" number cur = I ; // Move the cursor} For (INT I = next [0]; I! = 0; I = next [I]) cout <s [I]; // here, place the [cursor cur in the 0 position cout <Endl;} return 0 ;}
Debugging analysis:
Test data:
This_is_a_[Beiju]_text
We can analyze that in the display program, next [0] = 12, then I = next [12] = 13, so s is displayed from S [13.