2022/city/11/expresii solution
This commit is contained in:
109
2022/city/11/expresii/expresii.cpp
Normal file
109
2022/city/11/expresii/expresii.cpp
Normal file
@@ -0,0 +1,109 @@
|
||||
#include <bits/stdc++.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
// ifstream in("test.in");
|
||||
// ofstream out("test.out");
|
||||
|
||||
struct Consumer {
|
||||
int consumed;
|
||||
string name;
|
||||
|
||||
bool operator<(const Consumer& other) {
|
||||
// First compare x, then y
|
||||
return consumed < other.consumed;
|
||||
}
|
||||
};
|
||||
|
||||
int convert(string roman) {
|
||||
unordered_map<char, int> numMapping;
|
||||
numMapping['I'] = 1;
|
||||
numMapping['V'] = 5;
|
||||
numMapping['X'] = 10;
|
||||
numMapping['L'] = 50;
|
||||
numMapping['C'] = 100;
|
||||
numMapping['D'] = 500;
|
||||
numMapping['M'] = 1000;
|
||||
|
||||
|
||||
if (!roman.size()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
int total = 0;
|
||||
int checkpoint = numMapping[roman[0]];
|
||||
int stretchTotal = 0;
|
||||
|
||||
for (int j = 0; j < roman.size(); j++) {
|
||||
int charDex = numMapping[roman[j]];
|
||||
if (charDex == checkpoint) {
|
||||
stretchTotal += charDex;
|
||||
} else if (charDex > checkpoint) {
|
||||
total += charDex - stretchTotal;
|
||||
checkpoint = charDex;
|
||||
stretchTotal = 0;
|
||||
} else {
|
||||
total += stretchTotal;
|
||||
checkpoint = charDex;
|
||||
stretchTotal = charDex;
|
||||
}
|
||||
}
|
||||
total += stretchTotal;
|
||||
return total;
|
||||
}
|
||||
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
string inName = "test.in";
|
||||
string outName = "test.out";
|
||||
|
||||
if (argc > 1) {
|
||||
inName = argv[1];
|
||||
cout << "Using \"" << inName << "\" for test name" << endl;
|
||||
} else {
|
||||
cout << "Warning: no in name provided, defaulting to test.in" << endl;
|
||||
}
|
||||
|
||||
if (argc > 2) {
|
||||
outName = argv[2];
|
||||
cout << "Using \"" << outName << "\" for out name" << endl;
|
||||
} else {
|
||||
cout << "Warning: no out name proviced, defaulting to test.out" << endl;
|
||||
}
|
||||
|
||||
ifstream in(inName);
|
||||
ofstream out(outName);
|
||||
|
||||
string expression = "";
|
||||
string roman = "";
|
||||
int total = 0;
|
||||
char nextOperation = '0'; // also serves as first number flag
|
||||
#define isFirstNumber nextOperation == '0'
|
||||
#define isSubtract nextOperation == '-'
|
||||
#define isSum nextOperation == '+'
|
||||
|
||||
char ch;
|
||||
while (in.get(ch)) {
|
||||
if (ch == '+' || ch == '-') {
|
||||
if (isFirstNumber || isSum) {
|
||||
total += convert(roman);
|
||||
} else {
|
||||
total -= convert(roman);
|
||||
}
|
||||
nextOperation = ch;
|
||||
roman = "";
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
roman += ch;
|
||||
}
|
||||
if (isFirstNumber || isSum) {
|
||||
total += convert(roman);
|
||||
} else {
|
||||
total -= convert(roman);
|
||||
}
|
||||
out << total << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user