1. 程式人生 > 實用技巧 >Broken Keyboard (a.k.a. Beiju Text) UVA - 11988

Broken Keyboard (a.k.a. Beiju Text) UVA - 11988

原題連結

當涉及到頻繁地改變元素位置的時候,我們考慮用連結串列解決問題,這裡有兩種解決方法

一、STL的List(deque貌似也可)

二、陣列模擬連結串列

兩種方法本質都是先找插入位置再插入

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int N = 100010;
 4 char word[N];
 5 int main()
 6 {
 7     freopen("in.txt","r",stdin);
 8 //    freopen("out.txt","w",stdout);
 9     while(scanf("
%s",word)!=EOF){//scanf("%s",word)!=EOF 10 //printf("%s\n",word); 11 list<char> lst; 12 auto it = lst.begin(); 13 for(int i=0;i<strlen(word);i++){//這裡使用auto i:word是錯的 14 if(word[i]=='[') it=lst.begin(); 15 else if(word[i]==']') it = lst.end();
16 else lst.insert(it,word[i]);//使用迭代器模擬滑鼠,不必想得太複雜,當游標移動到前面時,仍然是尾插 17 } 18 for(auto its:lst) printf("%c",its); 19 printf("\n"); 20 } 21 return 0; 22 }
STL
 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int N = 100010;
 4 char word[N];
 5 int
main() 6 { 7 // freopen("in.txt","r",stdin) ; 8 while(scanf("%s",word+1)!=EOF){ 9 int idx = 0,head = 0,ne[N],e[N],last = 0; 10 ne[0] = -1; 11 int len = strlen(word+1); 12 for(int i=1;i<=len;i++){ 13 if(word[i]==']') idx = last; 14 else if(word[i]=='[') idx = head;//選好插入位置 15 else{ 16 e[i] = word[i];//本質就是在k的後面插入一個結點 17 ne[i] = ne[idx]; 18 ne[idx] = i; 19 if(idx==last) last= i;//更新 20 idx = i; 21 } 22 } 23 for(int i=ne[head];i!=-1;i=ne[i]) printf("%c",e[i]); 24 printf("\n"); 25 } 26 }
陣列模擬

注意: 當涉及陣列範圍開得很大而又沒有全部利用的時候,我們不用auto 遍歷

補充:STL的程式碼,it儲存的是初始的begin迭代器,當在it插入時,個人理解it隨著所指向元素位置改變而改變(但是看除錯又沒有改變),這個問題讓我有點費解

可能it = insert();it++更好理解點