Pagini recente » Cod sursa (job #319177) | Cod sursa (job #1941322) | Cod sursa (job #1459734) | Cod sursa (job #367193) | Cod sursa (job #1541460)
// infoarenaDFSnonRec.cpp : Defines the entry point for the console application.
//
//#include "stdafx.h"
#include <fstream>
#include <string>
#include <stack>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
string s;
string pol;
stack<char> signStack;
int main()
{
fin >> s;
for (size_t i = 0; i < s.length(); ++i) {
if (s[i] == '(') {
signStack.push(s[i]);
}
else if (s[i] == ')') {
while (!signStack.empty() && signStack.top() != '(') {
pol.push_back(signStack.top());
pol.push_back(' ');
signStack.pop();
}
assert(!signStack.empty());
signStack.pop();
}
else if (s[i] == '+' || s[i] == '-') {
while (!signStack.empty() && signStack.top() != '(') {
pol.push_back(signStack.top());
pol.push_back(' ');
signStack.pop();
}
signStack.push(s[i]);
}
else if (s[i] == '*' || s[i] == '/') {
while (!signStack.empty() && (signStack.top() == '*' || signStack.top() == '/')) {
pol.push_back(signStack.top());
pol.push_back(' ');
signStack.pop();
}
signStack.push(s[i]);
}
else if ('0' <= s[i] && s[i] <= '9') {
int num = s[i] - '0';
int j = i + 1;
while (j < s.length() && '0' <= s[j] && s[j] <= '9') {
num = num * 10 + (s[j] - '0');
++j;
}
pol.append(to_string(num));
pol.push_back(' ');
i = j - 1;
}
}
while (!signStack.empty()) {
pol.push_back(signStack.top());
pol.push_back(' ');
signStack.pop();
}
stack<int> result;
char * p = (char *)pol.c_str();
p = strtok(p, " ");
while (p != NULL) {
if (*p == '+' || *p == '-' || *p == '*' || *p == '/') {
int a = result.top();
result.pop();
int b = result.top();
result.pop();
if (*p == '+')
result.push(a + b);
if (*p == '-')
result.push(b - a);
if (*p == '*')
result.push(a * b);
if (*p == '/')
result.push(b / a);
}
else {
result.push(atoi(p));
}
p = strtok(NULL, " ");
}
assert(result.size() == 1);
fout << result.top();
return 0;
}