RE球调

P1241 括号序列

Yaoshui_lv @ 2024-08-23 10:59:43

#include <iostream>
#include <string>
#define len s.length() 
using namespace std;

int  q[100001], top;
string s, t;

int main() {
    #ifndef ONLINE_JUDGE
        freopen("in.txt", "r", stdin);
        freopen("out.txt", "w", stdout);
    #endif
    cin >> s;
    for (int i = 0; i < len; i++) {
        if (s[i] == '(') {q[++top] = i; t[i]=')';}
        if (s[i] == '[') {q[++top] = i; t[i]=']';}
        if (s[i] == ')' || s[i] == ']')
            if (!top || t[q[top]] != s[i])
                if (s[i] == ')') t[i] = '(';
                else t[i] = '[';
            else t[q[top--]] = ' ';
    }
    for (int i = 0; i < len; i++) {
        if (t[i] == '(' || t[i] == '[') cout << t[i];
        cout << s[i];
        if (t[i] == ')' || t[i] == ']') cout << t[i];
    }
    return 0;
}

by Gcc_Gdb_7_8_1 @ 2024-08-23 11:40:10

@Yaoshui_lv

cin >> s;

for (int i = 0; i < len; i++)

这两行之间插入

t.resize(len);

by Gcc_Gdb_7_8_1 @ 2024-08-23 11:41:37

完整AC Code:

#include <iostream>
#include <string>
#define len s.length()
using namespace std;

int  q[100001], top;
string s, t;

int main() {
    #ifndef ONLINE_JUDGE
        freopen("in.txt", "r", stdin);
        freopen("out.txt", "w", stdout);
    #endif
    cin >> s;
    t.resize(len); //设置t的长度
    for (int i = 0; i < len; i++) {
        if (s[i] == '(') {q[++top] = i; t[i]=')';}
        if (s[i] == '[') {q[++top] = i; t[i]=']';}
        if (s[i] == ')' || s[i] == ']')
            if (!top || t[q[top]] != s[i])
                if (s[i] == ')') t[i] = '(';
                else t[i] = '[';
            else t[q[top--]] = ' ';
    }
    for (int i = 0; i < len; i++) {
        if (t[i] == '(' || t[i] == '[') cout << t[i];
        cout << s[i];
        if (t[i] == ')' || t[i] == ']') cout << t[i];
    }
    return 0;
}

by Yaoshui_lv @ 2024-08-24 10:14:03

球原理QWQ


|