Try to use more idiomatic C++

This commit is contained in:
Kiril Kovachev 2024-12-01 06:10:04 +00:00
parent d9bdd40d0a
commit e2c1c14b3d

31
q1.cpp
View File

@ -1,6 +1,7 @@
#include <algorithm> #include <algorithm>
#include <fstream> #include <fstream>
#include <iostream> #include <iostream>
#include <numeric>
#include <sstream> #include <sstream>
#include <unordered_map> #include <unordered_map>
#include <vector> #include <vector>
@ -9,17 +10,10 @@ int q1(std::ifstream &in) {
std::vector<int> l1; std::vector<int> l1;
std::vector<int> l2; std::vector<int> l2;
// for (std::string line; std::getline(in, line);) {
// std::string left = line.substr(0, line.find(" "));
// std::string right = line.substr(line.rfind(" "));
// l1.push_back(std::stoi(left));
// l2.push_back(std::stoi(right));
// }
for (std::string line; std::getline(in, line);) { for (std::string line; std::getline(in, line);) {
int left, right; int left, right;
std::stringstream s(line); std::stringstream(line) >> left >> right;
s >> left >> right;
l1.push_back(left); l1.push_back(left);
l2.push_back(right); l2.push_back(right);
} }
@ -39,19 +33,16 @@ int q2(std::ifstream &in) {
std::unordered_map<int, int> l2; std::unordered_map<int, int> l2;
for (std::string line; std::getline(in, line);) { for (std::string line; std::getline(in, line);) {
std::string left = line.substr(0, line.find(" ")); int left, right;
std::string right = line.substr(line.rfind(" ")); std::stringstream(line) >> left >> right;
l1.push_back(std::stoi(left));
l2[std::stoi(right)]++; l1.push_back(left);
l2[right]++;
} }
std::sort(l1.begin(), l1.end()); return std::accumulate(l1.begin(), l1.end(), 0, [&l2](int acc, int curr) {
return acc + curr * l2[curr];
int sum = 0; });
for (int i = 0; i < l1.size(); i++) {
sum += l1[i] * l2[l1[i]];
}
return sum;
} }
int main() { int main() {