C언어
백준 1918번 후위표기식 만들기 : 반례추가
mcdn
2020. 8. 18. 16:26
반응형
예제 입력 1
A*(B+C)
예제 출력 1
ABC+*
예제 입력 2 (추가)
A+B*C+D*E+G
예제 출력 2
답: ABC*+DE*+G+
오답: ABC*DE*G+++
#include <iostream>
#include <stack>
#include <cstring>
using namespace std;
int cal(char c)
{
if (c == '+' || c == '-')
return 1;
else if (c == '*' || c == '/')
return 2;
else
return 0;
}
int main(void)
{
char str[101];
cin >> str;
int len = strlen(str);
stack <char> st;
for (int i = 0; i < len; i++)
{
if (str[i] >= 'A' && str[i] <= 'Z')
cout << str[i];
else if (str[i] == '(')
st.push(str[i]);
else if (str[i] == ')')
{
while (st.top() != '(')
{
cout << st.top();
st.pop();
}
st.pop();
}
else
{
while (!st.empty() && cal(st.top()) >= cal(str[i]))
{
cout << st.top();
st.pop();
}
st.push(str[i]);
}
}
while (!st.empty())
{
cout << st.top();
st.pop();
}
return 0;
}
반응형