例题6-4 破损的键盘(又名:悲剧文本)(Broken Keyboard(a.k.a. Beiju Text), UVa 11988)

xiaoxiao2021-02-28  8

#ifdef _DEBUG #pragma warning(disable : 4996) #endif #include <iostream> #include <string> #include <vector> #include <stack> #include <queue> #include <deque> #include <set> #include <map> #include <algorithm> #include <functional> #include <sstream> #include <utility> #include <cstring> #include <cstdio> #include <cstdlib> #include <ctime> #include <cmath> #include <cctype> #define CLEAR(a, b) memset(a, b, sizeof(a)) #define CLOSE() ios::sync_with_stdio(false) #define IN() freopen("in.txt", "r", stdin) #define OUT() freopen("out.txt", "w", stdout) #define PF(a) printf("%d\n", a) #define SF(a) scanf("%d", &a) #define SFF(a, b) scanf("%d%d", &a, &b) #define FOR(i, a, b) for(int i = a; i < b; ++i) #define LL long long #define maxn 100005 #define mod 1000007 #define INF 1e15 using namespace std; //------------------------------------------------------------------------------------------// typedef struct Node *List; struct Node { char ch; Node *next; }; List Create(char ch) { List head = new(Node); head->ch = ch; head->next = nullptr; return head; } void Insert(List pos, List L) { L->next = pos->next; pos->next = L; } void Print(List head) { List p = head->next; while (p != nullptr) { printf("%c", p->ch); p = p->next; } } int main() { string msg; while (cin >> msg) { List last, cur, L = Create(0); last = cur = L; FOR(i, 0, msg.size()) { if (msg[i] == '[') { cur = L; } else if (msg[i] == ']') { cur = last; } else { List node = Create(msg[i]); Insert(cur, node); if (cur == last) last = node; cur = node; } } Print(L); puts(""); } return 0; } //看了lrjls的代码,发现自己学的还是太死板了,链表只是一种思想,用数组同样可以表示。 //主要在于模拟出光标cursor的位置,每次添加在cursor之后 int next[maxn]; char str[maxn]; int main() { int cur, last; while (scanf("%s", str+1) == 1) { int n = strlen(str + 1); cur = last = 0; next[0] = 0; FOR(i, 1, n + 1) { if (str[i] == '[') cur = 0; else if (str[i] == ']') cur = last; else { next[i] = next[cur]; next[cur] = i; if (cur == last) last = i; cur = i; } } for (int i = next[0]; i != 0; i = next[i]) printf("%c", str[i]); puts(""); } return 0; }
转载请注明原文地址: https://www.6miu.com/read-850151.html

最新回复(0)