网址如下:
Broken Keyboard (a.k.a. Beiju Text) - UVA 11988 - Virtual Judge (vjudge.net)
(第三方网站)
刚刚开始我是用C++的list来做的,不过里面的元素是char,直接TLE
说实话我有点震惊,这不是双端链表吗,插入的效率不是比较高,结果还是超时了
改进思路也很简单,把元素换成string就行了
元素是char的代码如下:
#include<list>
#include<cstdio>
#include<cstring>
using namespace std;
char s[100000];int main(void)
{while(scanf("%s", s) == 1){list<char> ans;auto pos = ans.begin();for(int i = 0; i < strlen(s); i++)if(s[i] == '[') pos = ans.begin();else if(s[i] == ']') pos = ans.end();else pos = ans.insert(pos, s[i]), pos++;for(auto it = ans.begin(); it != ans.end(); it++)putchar(*it);putchar('\n');}return 0;
}
元素是string的代码如下:
#include<list>
#include<string>
#include<iostream>
using namespace std;int main(void)
{string s;while(cin >> s){list<string> ans; string str;auto pos = ans.begin();for(int i = 0; i < s.size(); i++)if(s[i] == '['){ans.insert(pos, str); str.clear(); pos = ans.begin();}else if(s[i] == ']'){ans.insert(pos, str); str.clear(); pos = ans.end();}else str.push_back(s[i]);if(!str.empty()) ans.insert(pos, str);for(auto it = ans.begin(); it != ans.end(); it++)cout << *it;cout << endl;}return 0;
}
这里放一下算法书的代码,思路和我之前记录的骚操作差不多,都是一个数组记录原来的字符串的样子,然后一个数组记录这个字符的下一个字符的位置
效率比我的高,我那个120ms,这个80ms
代码如下:
#include<cstdio>
#include<cstring>
const int maxn = 100000 + 5;
int last, cur, next[maxn];
char s[maxn];int main()
{while(scanf("%s", s + 1) == 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;cur = i;}}for(int i = next[0]; i; i = next[i])putchar(s[i]);putchar('\n');}return 0;
}