Common Subexpression Elimination UVA - 12219

#include <iostream>
#include <bits/stdc++.h>
#define maxn 50005
using namespace std;
string s;
int k,u;//u是单词的id

struct tree
{
    string tmp;
    int lch,rch;
    bool operator < (const tree & a) const
    {
        if(tmp!=a.tmp) return tmp<a.tmp;
        else if(lch!=a.lch) return lch<a.lch;
        else return rch<a.rch;
    }
};

map<int,tree>node;
map<tree,int>num;
int flag[maxn];

int build()
{
    string cur;
    while(isalpha(s[k]))
        cur.push_back(s[k++]);
    int id = ++u;
    node[id].tmp = cur;node[id].lch = 0;node[id].rch = 0;
    if(s[k]=='(')
    {
        k++;
        node[id].lch = build();
        k++;
        node[id].rch = build();
        k++;
    }
    tree t = node[id];
    if(num[t])
    {
        u--;
        return num[t];
    }
    else
    {
        return num[t] = id;
    }
}

void dfs(int k)
{
    if(flag[k])
    {
        cout<<k;
        return;
    }
    flag[k] = 1;
    cout<<node[k].tmp;
    if(node[k].lch)
    {
        cout<<"(";
        dfs(node[k].lch);
        cout<<",";
        dfs(node[k].rch);
        cout<<")";
    }
}

int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        cin>>s;
        k = 0;u = 0;
        num.clear();node.clear();
        memset(flag,0,sizeof(flag));
        build();
        dfs(1);
        cout<<endl;
    }
    return 0;
}

/**
3
this(is(a,tiny),tree)
a(b(f(a,a),b(f(a,a),f)),f(b(f(a,a),b(f(a,a),f)),f))
z(zz(zzzz(zz,z),zzzz(zz,z)),zzzz(zz(zzzz(zz,z),zzzz(zz,z)),z))
**/

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值