97 lines
2.2 KiB
C++
97 lines
2.2 KiB
C++
#include <fstream>
|
|
#include <deque>
|
|
#include <unordered_map>
|
|
using namespace std;
|
|
|
|
ifstream input_stream;
|
|
ofstream output_stream;
|
|
unordered_map<char, int> numbers_map = {{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}};
|
|
|
|
|
|
int64_t evaluateNum(string num) {
|
|
int64_t res = 0;
|
|
const int lim = num.length();
|
|
|
|
|
|
for (int i = 0; i < lim - 1; i++) {
|
|
if (numbers_map[num[i]] >= numbers_map[num[i + 1]]) {
|
|
res += numbers_map[num[i]];
|
|
} else {
|
|
res -= numbers_map[num[i]];
|
|
}
|
|
}
|
|
res += numbers_map[num[lim - 1]];
|
|
|
|
return res;
|
|
}
|
|
|
|
|
|
|
|
int main() {
|
|
input_stream.open("expresii.in");
|
|
output_stream.open("expresii.out");
|
|
|
|
string expression;
|
|
input_stream >> expression;
|
|
|
|
deque<int64_t> numbers;
|
|
deque<char> operations;
|
|
|
|
string currNumber = "";
|
|
const int lim = expression.length();
|
|
for (int i = 0; i < lim; i++) {
|
|
if (numbers_map[expression[i]] > 0) {
|
|
currNumber += expression[i];
|
|
} else {
|
|
numbers.push_back(evaluateNum(currNumber));
|
|
operations.push_back(expression[i]);
|
|
currNumber = "";
|
|
}
|
|
}
|
|
numbers.push_back(evaluateNum(currNumber));
|
|
|
|
|
|
// Evaluate multiplications
|
|
int pos = 0;
|
|
for (auto it = operations.begin(); it != operations.end(); it++) {
|
|
if (*it == '*') {
|
|
auto num1 = numbers.begin();
|
|
advance(num1, pos);
|
|
auto num2 = numbers.begin();
|
|
advance(num2, pos + 1);
|
|
|
|
*num1 = *num2 * *num1;
|
|
numbers.erase(num2);
|
|
pos--;
|
|
}
|
|
pos++;
|
|
}
|
|
|
|
|
|
// Evaluate other stuff
|
|
pos = 0;
|
|
int64_t res = numbers.front();
|
|
for (auto it = operations.begin(); it != operations.end(); it++) {
|
|
if (*it == '*') {
|
|
continue;
|
|
}
|
|
|
|
auto num = numbers.begin();
|
|
advance(num, pos + 1);
|
|
|
|
if (*it == '+') {
|
|
res += *num;
|
|
} else {
|
|
res -= *num;
|
|
}
|
|
|
|
pos++;
|
|
}
|
|
|
|
output_stream << res << endl;
|
|
|
|
input_stream.close();
|
|
output_stream.close();
|
|
return 0;
|
|
}
|