Gym 100726B Common Subexpression Elimination

递归下降建树,然后对每个节点编号....一个节点该节点的hash值和左儿子的编号和右儿子的编号是唯一的....用map查询

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;

const int maxn = 800000;

struct node
{
	int val, id, is;
	string s;
	node *ch[2];
}pool[maxn], *tail, *root;

struct point
{
	int val, lson, rson;
	bool operator < (const point &b) const {
		if(val != b.val) return val < b.val;
		if(lson != b.lson) return lson < b.lson;
		return rson < b.rson;
	}
};

map<point, int> mpp;
vector<int> ans;
char P[maxn];
int top, n, id;

node* newnode(int val, string s)
{
	tail->val = val;
	tail->ch[0] = tail->ch[1] = NULL;
	tail->s.clear();
	tail->s = s;
	return tail++;
}

void init()
{
	tail = pool;
}

node* eat()
{
	string ss;
	ss.clear();
	int t = 0;
	while(top <= n && P[top] >= 'a' && P[top] <= 'z') {
		ss += P[top];
		t = t * 30 + P[top] - 'a' + 1;
		top++;
	}
	return newnode(t, ss);
}

void ate(char ch)
{
	if(P[top] == ch) top++;
}

node* build()
{
	if(top > n) return NULL;
	node *p = eat();
	if(P[top] == '(') {
		ate('(');
		p->ch[0] = build();
		ate(',');
		p->ch[1] = build();
		ate(')');
	}
	return p;
}

void dfs(node *p)
{
	point t;
	t.val = p->val;
	int now = ++id;
	if(p->ch[0]) {
		dfs(p->ch[0]);
		dfs(p->ch[1]);
		t.lson = p->ch[0]->id;
		t.rson = p->ch[1]->id;
	}
	else t.lson = t.rson = -1;
	
	if(mpp.count(t)) {
		p->is = 1, p->id = mpp[t];
		id--;
	}
	else {
		p->id = mpp[t] = now;
		p->is = 0;
		
	}
}

void DFS(node *p)
{
	if(p->is == 0) {
		for(int i = 0; i < p->s.length(); i++) ans.push_back(-p->s[i]);
	}
	else ans.push_back(p->id);
	if(p->ch[0] && p->is == 0) {
		ans.push_back(-'(');
		DFS(p->ch[0]);
		ans.push_back(-',');
		DFS(p->ch[1]);
		ans.push_back(-')');
	}
}

void work()
{
	mpp.clear();
	scanf("%s", P+1);
	n = strlen(P+1);
	top = 1;
	root = build();
	
	id = 0;
	dfs(root);
	
	ans.clear();
	DFS(root);
	for(int i = 0; i < ans.size(); i++) {
		if(ans[i] < 0) printf("%c", -ans[i]);
		else printf("%d", ans[i]);
	}
	printf("\n");
}

int main()
{
//freopen("data", "r", stdin);
	int _;
	scanf("%d", &_);
	while(_--) {
		init();
		work();
	}
	
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值