1、uva 11988 Broken Keyboard
题意:给出键盘打字的顺序,遇到[到句首,遇到]倒句末。求最后输出的句子。
思路:
①单向链表数组模拟
1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 using namespace std; 5 const int maxn = 100100; 6 char s[maxn]; 7 int Next[maxn]; 8 int main() 9 { 10 while (~scanf("%s", s + 1)) 11 { 12 int len = strlen(s + 1); 13 Next[0] = 0; 14 int cur = 0, last = 0; 15 for (int i = 1; i <= len; i++) 16 { 17 if (s[i] == '[')cur=0 ; 18 else if (s[i] == ']') cur = last; 19 else 20 { 21 Next[i] = Next[cur]; 22 Next[cur] = i; 23 if (last == cur) last = i; 24 cur = i; 25 } 26 } 27 for (int i = Next[0]; i != 0; i = Next[i]) printf("%c", s[i]); 28 printf(" "); 29 } 30 return 0; 31 }
②双向链表数组模拟
1 #include<iostream> 2 #include<cstring> 3 const int maxn = 100100; 4 char s[maxn]; 5 int L[maxn], R[maxn]; 6 int main() 7 { 8 while (~scanf("%s", s+1)) 9 { 10 int len = strlen(s+1); 11 L[0] = R[0] = 0; 12 for (int i = 1; i <= len; i++) 13 { 14 if (s[i] == '[') L[i] = 0, R[i] = R[0]; 15 else if (s[i] == ']') L[i] = L[0], R[i] = 0; 16 else 17 { 18 L[i] = i - 1, R[i] = R[i - 1]; 19 } 20 L[R[i]] = i, R[L[i]] = i; 21 } 22 for (int i = R[0]; i != 0; i = R[i]) 23 { 24 if (s[i] == '[' || s[i] == ']')continue; 25 printf("%c", s[i]); 26 } 27 printf(" "); 28 } 29 return 0; 30 }
③STL list使用
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<list> 5 using namespace std; 6 const int maxn = 100100; 7 char s[maxn]; 8 9 int main() 10 { 11 while (~scanf("%s", s)) 12 { 13 int len = strlen(s); 14 list<char>lt; 15 list<char>::iterator pos=lt.end(); 16 for (int i = 0; i < len; i++) 17 { 18 if (s[i] == '[') pos=lt.begin(); 19 else if (s[i] == ']') pos=lt.end(); 20 else 21 { 22 lt.insert(pos, s[i]); 23 } 24 } 25 for (pos = lt.begin(); pos != lt.end(); pos++) 26 { 27 printf("%c", *pos); 28 } 29 printf(" "); 30 } 31 return 0; 32 }