#include <stdio.h>
char infix[10001];
char postfix[10001];
int stack[10001];
int top;
void push(int num)
{
stack[++top] = num;
}
int pop()
{
return stack[top--];
}
int main()
{
freopen("input.txt", "r", stdin);
int T;
int length;
int idx;
int res;
int tmp1, tmp2;
int i;
for (T = 1; T <= 10; ++T) {
top = -1;
idx = 0;
res = 0;
scanf("%d", &length);
scanf("%s", infix);
for (i = 0; i < length; ++i) {
if ((infix[i] >= '0') && infix[i] <= '9') // 숫자이면,
postfix[idx++] = infix[i]; // 후위 표기법 배열에 넣고
else if (infix[i] == '+') // 연산자이면,
{
while ((top > -1) && (stack[top] == '+')) // 스택에 무엇인가 있고, +가 있다면,
postfix[idx++] = pop(); // 후위연산자에 +를 넣음
push(infix[i]); // 그리고 새로운 연산자를 스택에 쌓음
}
}
while (top > -1) // 스택에 남아있는 것들을 넘김
postfix[idx++] = pop();
for (i = 0; i < idx; ++i)
{
if ((postfix[i] >= '0') && (postfix[i] <= '9'))
push(postfix[i] - '0');
else if (postfix[i] == '+')
{
tmp2 = pop();
tmp1 = pop();
push(tmp1 + tmp2);
}
}
printf("#%d %d\n", T, pop());
}
return 0;
}
댓글