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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值