编译原理 Assign1

  1 #include<iostream>
  2 #include<cstdio>
  3 #include<cstring>
  4 #include<cstdlib>
  5 #include<algorithm>
  6 #include<vector>
  7 #include<stack>
  8 using namespace std;
  9 const int maxn=1007;
 10 const int inf=0x3f3f3f3;
 11 struct node
 12 {
 13     int to;
 14 };
 15 vector<node> G[maxn];
 16 int root,ans[maxn],n;
 17 bool flag[maxn];
 18 char value[maxn];
 19 void init()
 20 {
 21     for(int i=0;i<maxn;i++) G[i].clear();
 22     memset(value,0,sizeof(value));
 23     memset(flag,0,sizeof(flag));
 24     memset(ans,0,sizeof(ans));
 25     root=-1;
 26 }
 27 void input()
 28 {
 29     int a,b;node n1;
 30     for(int i=1;i<n;i++)
 31         {
 32             scanf("%d%d",&a,&b);
 33             n1.to=b;
 34             G[a].push_back(n1);
 35             n1.to=a;
 36             G[b].push_back(n1);
 37         }
 38         scanf("%d",&root);
 39         scanf("%s",value+1);
 40 }
 41 char dfs(int point,int father)
 42 {
 43     int l=G[point].size();
 44     if(l==1&&point!=root) {return value[point];}
 45     stack<char> str;
 46     while(!str.empty()) str.pop();
 47     for(int i=0;i<l;i++)
 48     {
 49         if(G[point][i].to==father) continue;
 50         if(!flag[G[point][i].to])
 51             str.push(dfs(G[point][i].to,point));
 52     }
 53     if(str.size()==1) value[point]=str.top();
 54     else if(str.size()==3){
 55         char a=str.top();str.pop();
 56         char b=str.top();str.pop();
 57         char c=str.top();str.pop();
 58         if(b=='+') value[point]=(a-'0')+(c-'0')+'0';
 59         else if(b=='-') value[point]=(a-'0')-(c-'0')+'0';
 60         else if(b=='*') value[point]=(a-'0')*(c-'0')+'0';
 61     }
 62     return value[point];
 63 }
 64 int main()
 65 {
 66     int a,b;
 67     while(~scanf("%d",&n)){
 68         init();
 69         input();
 70         flag[root]=1;
 71         dfs(root,-1);
 72         int res=value[root]-'0';
 73         printf("%d
",res);
 74     }
 75     return 0;
 76 }
 77 /*
 78 10
 79 1 2
 80 1 3
 81 1 4
 82 2 5
 83 4 6
 84 4 7
 85 4 8
 86 6 9
 87 8 10
 88 1
 89 EE+E3E*E45
 90 10
 91 1 2
 92 1 3
 93 1 4
 94 2 5
 95 2 6
 96 2 7
 97 5 8
 98 7 9
 99 4 10
100 1
101 EE*EE+E345
102 */
原文地址:https://www.cnblogs.com/codeyuan/p/4367719.html