HDU-Expression 枚举

将所有括号都找出来,枚举所有的可能,再用strcmp排下序就可以了。标程用到的方法更好,直接标记每个括号属于哪一个括号组,然后直接解压状态即可。

代码如下:

#include <cstdlib>

#include <cstring>

#include <cstdio>

#include <algorithm>

using namespace std;



char s[210], rec[1050][210];



int stack[15], top, length, cnt;



struct Parentheses

{

    int l, r;

}P[15];



void init()

{

    top = cnt = 0;

}



int cmp(const void *s1, const void *s2)

{

    return strcmp((char *)s1, (char *)s2);

}



void print()

{

    int LIM = 1 << cnt;

    bool hash[210];

    for (int i = 1; i < LIM; ++i) {

        memset(hash, false, sizeof (hash));

        for (int j = 0; j < cnt; ++j) {

            if ((1 << j) & i) {

                hash[P[j+1].l] = hash[P[j+1].r] = 1;

            }

        }

        int k = 0;

        for (int j = 0; j < length; ++j) {

            if (!hash[j]) {

                rec[i][k++] = s[j];

            }

        }

        rec[i][k] = '\0';

    }

    qsort(rec[1], LIM-1, sizeof (rec[0]), cmp);

    for (int i = 1; i < LIM; ++i) {

        if (strcmp(rec[i], rec[i-1]) != 0) {

            puts(rec[i]);

        }

    }

}



int main()

{

    int T;

    scanf("%d", &T);

    while (T--) {

        init();

        scanf("%s", s);

        length = strlen(s);

        for (int i = 0; i < length; ++i) {

            if (s[i] == '(') {

                stack[++top] = i;

            }      

            else if (s[i] == ')') {

                P[++cnt].l = stack[top--];

                P[cnt].r = i;

            }

        }

        print();

    }

    return 0;

}

你可能感兴趣的:(express)