Witam.
Chciałem rozwiązać zadanie: https://szkopul.edu.pl/problemset/problem/zFA7joqxZZ9lbwA0FoqjmZwP/site/?key=submissions
I to jest mój kod:
#include <iostream>
#include <vector>
#include <string>
std::pair<uint32_t, uint32_t> read_fraction(const std::string& fraction) {
uint32_t i = 0;
uint32_t nominator = 0;
while (fraction[i] != '/') {
nominator = nominator * 10 + (fraction[i] - '0');
i++;
}
// Omit the '/'
i++;
uint32_t denominator = 0;
while (i < fraction.size()) {
denominator = denominator * 10 + (fraction[i] - '0');
i++;
}
return std::make_pair(nominator, denominator);
}
int main()
{
uint32_t n;
std::cin >> n;
std::vector<std::string> level{"0/1", "1/0"};
std::vector<std::string> next_level(3);
for (uint32_t i = 0; i < n; i++) {
uint32_t added = 0;
for (uint32_t j = 0; j < level.size() - 1; j++) {
next_level[j + added] = level[j];
std::pair<uint32_t, uint32_t> left = read_fraction(level[j]);
std::pair<uint32_t, uint32_t> right = read_fraction(level[j + 1]);
std::string result = std::to_string(left.first + right.first) + "/" + std::to_string(left.second + right.second);
next_level[j + added + 1] = result;
added++;
}
next_level[level.size() - 1 + added] = level[level.size() - 1];
level = next_level;
next_level.erase(next_level.begin(), next_level.end());
next_level.resize(level.size() * 2 - 1);
}
for (const std::string& fraction : level)
std::cout << fraction << " ";
return 0;
}
Ale niestety nie mogę zaliczyć ostatniego testu, bo zużywam zbyt dużo pamięci. Właściwie zauważyłem że wystarczy około 5s i już zużywam 400mb. Przechowuję tylko ostatni level i kolejny, żeby właśnie tej pamięci oszczędzić. Co tu mogę jeszcze poprawić, żeby zaliczyć na 100?
W tagach zadania wskazane jest użycie rekurencji - ale czy to tylko nie pogorszy problemu z pamięcią? Poza tym takie rozwiązanie wydaje mi się trudniejsze