现在的位置: 首页 > 综合 > 正文

[HDOJ3429]Resistors

2012年10月09日 ⁄ 综合 ⁄ 共 1590字 ⁄ 字号 评论关闭

表达式求值~

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 }

抱歉!评论已关闭.