zoukankan      html  css  js  c++  java
  • [HDOJ3429]Resistors

    表达式求值~

    View Code
    1 #include <cstdio>
    2 #include <cstring>
    3 #include <stack>
    4 usingnamespace std;
    5
    6 struct num
    7 {
    8 int u,d;
    9 };
    10
    11 stack<struct num> NUM;
    12 stack<char> OPP;
    13
    14 constint LEN =1024;
    15
    16 char input[LEN];
    17
    18 void MyClear()
    19 {
    20 while (!NUM.empty()) NUM.pop();
    21 while (!OPP.empty()) OPP.pop();
    22 }
    23
    24 int gcd(int a,int b)
    25 {
    26 if (a ==0) return b;
    27 elsereturn gcd(b % a,a);
    28 }
    29
    30 struct num work(struct num & a,struct num & b,char opp)
    31 {
    32 struct num ans;
    33 if (opp =='&')
    34 {
    35 ans.u = a.u * b.d + a.d * b.u;
    36 ans.d = a.d * b.d;
    37 int tmp = gcd(ans.u,ans.d);
    38 ans.u /= tmp;
    39 ans.d /= tmp;
    40 }
    41 else
    42 {
    43 struct num ians;
    44 ians.u = a.u * b.d + a.d * b.u;
    45 ians.d = a.u * b.u;
    46 int tmp = gcd(ians.u,ians.d);
    47 ans.u = ians.d / tmp;
    48 ans.d = ians.u / tmp;
    49 }
    50 return ans;
    51 }
    52 int main()
    53 {
    54 struct num in;
    55 while (gets(input))
    56 {
    57 MyClear();
    58 int length = strlen(input);
    59 for (int i = length -1;i >=0;i--)
    60 {
    61 if (input[i] =='') continue;
    62 if (input[i] ==')'|| input[i] =='&'|| input[i] =='|')
    63 OPP.push(input[i]);
    64 elseif (input[i] >='0'&& input[i] <='9')
    65 {
    66 while (input[i] !='/') i--;
    67 i--;
    68 while (input[i] >='0'&& input[i] <='9'&& i >=0) i--;
    69 i++;
    70 sscanf(input + i,"%d/%d",&in.u,&in.d);
    71 NUM.push(in);
    72 }
    73 elseif (input[i] =='(')
    74 {
    75 while (OPP.top() !=')')
    76 {
    77 char opp = OPP.top();
    78 OPP.pop();
    79 struct num num1 = NUM.top();
    80 NUM.pop();
    81 struct num num2 = NUM.top();
    82 NUM.pop();
    83 struct num ans = work(num1,num2,opp);
    84 NUM.push(ans);
    85 }
    86 OPP.pop();
    87 }
    88 }
    89 while (!OPP.empty())
    90 {
    91 char opp = OPP.top();
    92 OPP.pop();
    93 struct num num1 = NUM.top();
    94 NUM.pop();
    95 struct num num2 = NUM.top();
    96 NUM.pop();
    97 struct num ans = work(num1,num2,opp);
    98 NUM.push(ans);
    99 }
    100 in= NUM.top();
    101 int tmp = gcd(in.u,in.d);
    102 printf("%d/%d\n",in.u / tmp,in.d / tmp);
    103 }
    104 return0;
    105 }
  • 相关阅读:
    泛型理解及应用(二):使用泛型编写通用型Dao层
    泛型的理解及应用(一):泛型擦除
    Servlet、Filter 生命周期
    Java多线程(六) 线程系列总结
    Java多线程(五) Lock接口,ReentranctLock,ReentrantReadWriteLock
    Java多线程(四) 线程池
    Java多线程(三) 多线程间的基本通信
    Java多线程(二) 多线程的锁机制
    Java多线程(一) 多线程的基本使用
    Spring Boot实战:模板引擎
  • 原文地址:https://www.cnblogs.com/debugcool/p/HDOJ3429.html
Copyright © 2011-2022 走看看