自己写的时候不知道怎么处理编号,看了别人的代码才发现可以预留编号,学习一个
今天才知道map需要处理好顺序才能正确查找
#include<iostream> #include<algorithm> #include<cstdio> #include<algorithm> #include<map> #include<cstring> using namespace std; #define LL long long #define maxn 50010 #define CLR(a,b) memset(a,b,sizeof(a)) struct tree { string s; int lch; int rch; bool operator < (const tree &x ) const{ if(s!=x.s) return s<x.s; else if(lch!=x.lch) return lch < x.lch; else return rch < x.rch; } }; map<tree,int> MAP; map<int,tree> NODE; int vis[maxn]; string s; int cnt = 0; int k = 0; int solve() { string cur; while(s[k] >= ‘a‘ && s[k] <= ‘z‘) cur.push_back(s[k++]); int id = ++cnt; tree &t = NODE[id]; t.lch = 0; t.rch = 0; t.s = cur; if(s[k] == ‘(‘){ k++; t.lch = solve(); k++; t.rch = solve(); k++; } if(MAP[t]){ cnt--; return MAP[t]; } else return MAP[t] = id; } void print(int u) { if(vis[u]){ cout<<u; } else{ vis[u] = 1; cout<<NODE[u].s; if(NODE[u].lch){ cout<<‘(‘; print(NODE[u].lch); cout<<‘,‘; print(NODE[u].rch); cout<<‘)‘; } } } int main() { int n; cin>>n; while(n--){ MAP.clear(); NODE.clear(); CLR(vis,0); k = 0, cnt = 0; cin>>s; solve(); print(1); cout<<endl; } return 0; }
原文地址:https://www.cnblogs.com/Tokisaki-Kurumi-/p/8763214.html
时间: 2024-11-08 19:23:53