Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #define endl '\n'
- using namespace std;
- string rec(string s) {
- if (s.size() == 0) return "";
- int balance = 0;
- vector<string> V;
- string word;
- for (int i = 0; i < (int)s.size(); i++) {
- if (s[i] == '|' && balance == 0) {
- V.push_back(word);
- word = "";
- continue;
- }
- if (s[i] == '(') balance++;
- else if (s[i] == ')') balance--;
- word += s[i];
- }
- if (word.size()) V.push_back(word);
- if (V.size() == 1) {
- string res;
- word = "";
- balance = 0;
- for (int i = 0; i < (int)s.size(); i++) {
- if (s[i] == '(') balance++;
- else if (s[i] == ')') {
- balance--;
- }
- if (balance == 0) {
- if (word.size()) res += rec(word);
- word = "";
- if (s[i] != '(' && s[i] != ')' && s[i] != '$') res += s[i];
- } else {
- if (s[i] != '(' || balance != 1) word += s[i];
- }
- }
- return res;
- }
- string res;
- for (int i = 0; i < 555; i++) {
- res += 'z';
- }
- for (int i = 0; i < (int)V.size(); i++) {
- string ss = rec(V[i]);
- if (ss.size() < res.size() || (ss.size() == res.size() && ss < res)) res = ss;
- }
- return res;
- }
- string clean(string s) {
- string res;
- reverse(s.begin(), s.end());
- for (int i = 0; i < (int)s.size(); i++) {
- if (s[i] != '*') {
- res += s[i];
- } else {
- res += '$';
- if (s[i+1] != ')') {
- i++;
- continue;
- } else {
- int balance = 0;
- for ( i++; i < (int)s.size(); i++) {
- if (s[i] == '(') balance++;
- else if (s[i] == ')') balance--;
- if (balance == 0) break;
- }
- }
- }
- }
- reverse(res.begin(), res.end());
- return res;
- }
- int main( void ) {
- int T;
- cin >> T;
- for (int tt = 0; tt < T; tt++) {
- string s, ans;
- string ss;
- cin >> s;
- for (int i = 0; i < s.size(); i++) {
- if (ss.size() > 0 && ss[ss.size()-1] == '*' && s[i] == '*') continue;
- ss += s[i];
- }
- s = clean(ss);
- ans = rec(s);
- if (ans.size() == 0) ans = "$";
- cout << ans << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement