Test instructions
The smallest expression tree, which is to replace the same expression tree with the same number as the previous one.
Analysis:
Use map<string,int>smp,store the substring corresponding to the subtree, and then use the same number if the same subtree appears later. Use the build function to make the first contribution based on the input statement.
Code:
#include<iostream>#include<cstring>#include<cstdio>#include<algorithm>#include<vector>#include<map>UsingNamespace Std;Constint MaxLen=5e5;Constint MAXN=5e4+1;Char Str[MaxLen];map<string,Int>smp; map<string,Int::IteratorSit; vector<string>st;struct Node{int LR;int ID;Int V;booloperator<(Const node& X)Const{Return ID<x. ID||(ID==x. ID&&(l< X. l||(l= = X. l&& R< X. R)));}}tree[MAXN];map<node,Int>mp; map<node,Int::IteratorIt;int cnt;int DFS1;IntSid(String &s){If(Sit=smp.Find(s))!=SMP.End())return sit->second; St.Push_back(s); Smp.Insert(Make_pair(sSt.Size()));Return St.Size();}IntId(Node &nd){If(It=mp.Find(ND))!=MP.End())return it->second; Mp.Insert(Make_pair(NDCnt)); Tree[CNT]=nd;Return CNT++;}IntBuild(int x,Int&len){NodeU; U. V=0;StringS;int I;For(I=x; str[I];i++){If(str[I]==‘,‘|| Str[I]==‘)‘){s.Assign(str+xStr+i); U. ID=Sid(s); Len=s.Size(); U. l=u. R=-1;ReturnId(U);}ElseIf(str[I]==‘(‘){s.Assign(str+xStr+i); U. ID=Sid(s);int LSZ, Rsz; U. l=Build(++i, LSZ); I+=lsz; U. R=Build(++i, Rsz); Je=s.Size() +lsz+rsz+3;ReturnId(U);}} s.Assign(str+xStr+i); U. ID=Sid(s); U. l=u. R=-1;ReturnId(U);}voidDfs(int U){If(!tree[u].v){Tree[u].v=++dfs1;Printf('%s 'St[Tree[u].id-1].C_str());}Else{Printf("%d", tree[u].v);Return;}If(~tree[u].l){Putchar(‘(‘);Dfs(Tree[u].l);Putchar(‘,‘);Dfs(Tree[u].r);Putchar(‘)‘);}}IntMain(){int T;scanf("%d", &t);GetChar();While(T--){Gets(str); Smp.Clear(); Mp.Clear(); Stclear (); Cnt= 0int len; int root=build ( 0,len=< Span class= "Sh-number" >0; dfs (Rootprintf ( " \n "); }} /span>
UVA 12219 Common subexpression Elimination