Common Subexpression Elimination UVA - 12219

图论的一道简单的题目,在进行实现的时候既要记录每个节点的信息,包括该节点所指向的右子树的节点同时也包括左子树的节点位置,以及当前节点当中所包含的字符的信息,同时利用一个Map来进行查询以及去重,具体实现见如下代码:

#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
#include<cstdio>
#include<deque>
using namespace std;

string express;

class Node{
public:
	int hash, left, right;
	string s;
	bool operator< (const Node a) const{
		if (hash != a.hash) return hash < a.hash;
		else if (left != a.left) return left < a.left;
		return right < a.right;
	}
};

Node node[50005];
map<Node, int> dict;

class Solve{
public:
	int amount;
	int finish[50005];
	int cur;
	
	int parse(int& ind){
		int id;
		id = amount++;
		Node& temp=node[id];
		temp.left = temp.right = -1;
		temp.hash = 0;
		temp.s = "";
		while (ind < express.size() && isalpha(express[ind])){
			temp.hash = temp.hash * 27 + express[ind] - 'a' + 1;
			temp.s += express[ind];
			ind++;
		}
		if (express[ind] == '('){
			ind++;
			temp.left = parse(ind);
			ind++;
			temp.right = parse(ind);
			ind++;
		}
		if (dict.count(temp) != 0){
			id--;
			amount--;
			return dict[temp];
		}
		return dict[temp] = id;
	}

	void Print(int ind){
		if (finish[ind] == cur){
			cout << ind + 1;
		}
		else{
			finish[ind] = cur;
			cout << node[ind].s;
			if (node[ind].left != -1){
				cout << "(";
				Print(node[ind].left);
				cout << ",";
				Print(node[ind].right);
				cout << ")";
			}
		}
	}

	void Deal(){
		cur++;
		amount = 0;
		int ind = 0;
		int res=parse(ind);
		Print(res);
		cout << endl;
	}
};

int  main(){
	int c;
	cin >> c;
	Solve a;
	a.cur = 0;
	memset(a.finish,0,sizeof(a.finish));
	while (c--){
		dict.clear();
		cin >> express;	
		a.Deal();
	}
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值