N - Broken Keyboard (a.k.a. Beiju Text)(DFS,链表)
N - Broken Keyboard (a.k.a. Beiju Text)
Time Limit:1000MS Memory Limit:0KB 64bit IO Format:%lld & %llu
Description
You’re typing a long text with a broken keyboard. Well it’s not so badly broken. The only problem with the keyboard is that sometimes the “home” key or the “end” key gets automatically pressed (internally).
You’re not aware of this issue, since you’re focusing on the text and did not even turn on the monitor! After you finished typing, you can see a text on the screen (if you turn on the monitor).
In Chinese, we can call it Beiju. Your task is to find the Beiju text.
Input
There are several test cases. Each test case is a single line containing at least one and at most 100,000 letters, underscores and two special characters ‘[’ and ‘]’. ‘[’ means the “Home” key is pressed internally, and ‘]’ means the “End” key is pressed internally. The input is terminated by end-of-file (EOF).
Output
For each case, print the Beiju text on the screen.
Sample Input
This_is_a_[Beiju]_text
[[]][][]Happy_Birthday_to_Tsinghua_University
Sample Output
BeijuThis_is_a__text
Happy_Birthday_to_Tsinghua_University
//超时代码
用两条链表。head存储排好序的,l_head另一条存储前面的,碰到']'和'\n'就连接起来,然后输出,可惜这超时了。可能用链表在创建时和删除时会很慢吧。但是为了纪念一下我的劳动。还是保存一下
1 #include <iostream>
2 #include <cstring>
3 #include <deque>
4 using namespace std;
5
6 struct num
7 {
8 char x;
9 struct num*next;
10 };
11
12 struct num *head;
13 struct num *endy;
14 struct num *cur,*ne;
15
16 void sv_head()
17 {
18 if (cur!=NULL)
19 {
20 ne->next=head;
21 head=cur;
22 cur=NULL;
23 }
24 }
25
26
27 int main()
28 {
29 int flag=1;
30 char k;
31 head=NULL;
32 cur=ne=head;
33 while(k=getchar())
34 {
35 if (k!='\n')
36 {
37 if(k=='['){flag=0;cur=NULL;continue;}
38 if(k==']'){flag=1;sv_head();continue;}
39 if(flag)
40 {
41 if (head==NULL)
42 {
43 head=new num;
44 head->x=k;
45 head->next=NULL;
46 endy=head;
47 }
48 else
49 {
50 ne=new num;
51 ne->x=k;
52 ne->next=NULL;
53 endy->next=ne;
54 endy=ne;
55 }
56 }
57 else
58 {
59 if (cur==NULL)
60 {
61 cur=new num;
62 cur->x=k;
63 cur->next=NULL;
64 ne=cur;
65 }
66 else
67 {
68 ne->next=new num;
69 ne->next->x=k;
70 ne->next->next=NULL;
71 ne=ne->next;
72 }
73 }
74 }
75 else
76 {
77 sv_head();
78 cur=ne=head;
79 while (ne!=NULL)
80 {
81 printf("%c",ne->x);
82 ne=ne->next;
83 delete cur;
84 cur=ne;
85 }
86 printf("\n");
87
88 flag=1;
89 head=NULL;
90 cur=ne=endy=NULL;
91 }
92
93 }
94 return 0;
95 }
//AC的 DFS 先输出后面括号里的
1 #include <iostream>
2 #include <cstring>
3 #include <cstdio>
4 using namespace std;
5
6 char buf[100001];
7 void dfs(int l, int r)
8 {
9 int s = r;
10 while (s >= l && buf[s] != '[' && buf[s] != ']') s --;
11 if (buf[s] == ']') dfs(l, s-1);
12 for (int i = s+1 ; i <= r ; ++ i)
13 printf("%c",buf[i]);
14 if (buf[s] == '[') dfs(l, s-1);
15 }
16
17 int main()
18 {
19 while (gets(buf))
20 {
21 dfs(0, strlen(buf)-1);
22 printf("\n");
23 }
24 return 0;
25 }