2018/Day8/Day8B.cpp

48 lines
946 B
C++

#include <iostream>
#include <vector>
std::vector<int> read_input()
{
std::vector<int> input;
input.reserve(20000);
int i = 0;
while (std::cin >> i)
input.push_back(i);
return input;
}
int read_node(std::vector<int>::iterator &it)
{
int child_count = *it++;
int meta_count = *it++;
int value = 0;
if (child_count == 0) {
for (int i = 0; i < meta_count; i++)
value += *it++;
return value;
}
std::vector<int> children;
for (int i = 0; i < child_count; i++)
children.push_back(read_node(it));
for (int i = 0; i < meta_count; i++) {
int index = *it++;
if (index > 0 && index <= children.size())
value += children[index - 1];
}
return value;
}
int main(int argc, char **argv)
{
std::vector<int> input = read_input();
auto iterator = input.begin();
std::cout << read_node(iterator) << std::endl;
}