UVA 12219 Common subexpression Elimination

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.