Pagini recente » Cod sursa (job #285283) | Cod sursa (job #3032286) | Cod sursa (job #1238095) | Cod sursa (job #678326) | Cod sursa (job #2811687)
// 2. Dijkstra. Forma poloneza postfix.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <fstream>
#include <algorithm>
#include <string.h>
#include <stack>
#include <cctype>
#include <cstring>
#define DIM 100006
std::ifstream fin("evaluare.in");
std::ofstream fout("evaluare.out");
using namespace std;
char s[DIM];
int p = 0;
stack<int> op;
stack<int> nr;
int eval(int x, int y, char semn)
{
switch (semn)
{
case '+': return x + y;
case '-': return x - y;
case '*': return x * y;
case '/': return x / y;
}
}
int nextnum()
{
int numar = 0;
while ('0' <= s[p] && s[p] <= '9')
numar = numar * 10 + (s[p++] - '0');
return numar;
}
bool prioritate(char s1, char s2)
{
if (s1 == '(')
return true;
if ((s1 == '-' || s1 == '+') && (s2 == '*' || s2 == '/'))
return true;
return false;
}
void solve()
{
while (s[p] != '\0')
{
switch (s[p])
{
case '(':
op.push(s[p++]);
break;
case ')':
while (op.top() != '(')
{
int v2 = nr.top();
nr.pop();
int v1 = nr.top();
nr.pop();
char semn = op.top();
op.pop();
nr.push(eval(v1, v2, semn));
}
op.pop();
p++;
break;
case '+':
case '-':
case '*':
case '/':
if (op.empty() || prioritate(op.top(), s[p]))
op.push(s[p++]);
else
{
do
{
int v2 = nr.top();
nr.pop();
int v1 = nr.top();
nr.pop();
char semn = op.top();
op.pop();
nr.push(eval(v1, v2, semn));
} while (!op.empty() && !prioritate(op.top(), s[p]));
}
break;
default:
nr.push(nextnum());
}
}
while (!op.empty())
{
int v2 = nr.top();
nr.pop();
int v1 = nr.top();
nr.pop();
char semn = op.top();
op.pop();
nr.push(eval(v1, v2, semn));
}
fout << nr.top();
}
int main()
{
fin.getline(s, DIM);
solve();
return 0;
}