UVa 673 - Parentheses Balance(链表)

来源:互联网 发布:合肥万户网络招聘 编辑:程序博客网 时间:2024/05/22 15:18

用链表把配对的全部隔过去, 最后如果还有剩下的括号那就不合法。

#include<iostream>#include<cstdio>#include<string>#include<cstring>#define MAXN (128 + 10)using namespace std;int next[MAXN], last[MAXN];char line[MAXN];void link(int l) {    for(int i = 0; i < l; i++) {        next[i] = i + 1;        last[i + 1] = i;    }}int main() {    #ifndef ONLINE_JUDGE    freopen("in.txt", "r", stdin);    #endif // ONLINE_JUDGE    int n;    cin >> n;    getchar();    while(n--) {        memset(line, 0, sizeof(line));        memset(next, 0, sizeof(next));        memset(last, 0, sizeof(last));        gets(line);        int len = strlen(line);        if(len& 1) cout << "No" << endl;        else {            link(len);            int beg = 0, k = len / 2;            while(k--) {                for(int i = beg; i != len; i = next[i]) {                    if((line[i] == '('&& line[next[i]] == ')')||                       (line[i] == '['&& line[next[i]] == ']')) {                            if(i) {                                line[i] = 0;                                line[next[i]] = 0;                                next[last[i]] = next[next[i]];                                last[next[next[i]]] = last[i];                            } else {                                line[i] = 0;                                line[next[i]] = 0;                                beg = next[next[i]];                                i = next[i];                            }                       }                }            }            bool corrent = true;            for(int i = 0; i < len; i++)                if(line[i]) corrent = false;            corrent ? cout << "Yes" : cout << "No";            cout << endl;        }    }    return 0;}


0 0
原创粉丝点击