Advertisement
bogdb

AoC 2019 Day 6

Dec 6th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.23 KB | None | 0 0
  1. #include "../util.hpp"
  2.  
  3. // Advent of Code 2019 Day 6
  4. int main(int argc, char** argv)
  5. {
  6.     // Part 1
  7.     std::ifstream infile("./day6_example2.txt");
  8.     std::string line;
  9.  
  10.     std::unordered_map<std::string, std::vector<std::string>> objects;
  11.     std::unordered_set<std::string> names;
  12.  
  13.     // read input
  14.     while (std::getline(infile, line)) {
  15.         auto tokens = split(line, ')');
  16.         auto key = tokens[0];
  17.         auto val = tokens[1];
  18.         names.insert(key);
  19.         names.insert(val);
  20.         if (auto [it, ok] = objects.insert({ key, { val } }); !ok) {
  21.             objects[key].push_back(val);
  22.         }
  23.     }
  24.  
  25.     std::vector<std::string> keys(names.begin(), names.end());
  26.     std::sort(keys.begin(), keys.end());
  27.  
  28.     auto get_index = [&](const auto& v) {
  29.         auto res = std::lower_bound(keys.begin(), keys.end(), v);
  30.         assert(res != keys.end());
  31.         return std::distance(keys.begin(), res);
  32.     };
  33.  
  34.     Eigen::Matrix<int, -1, -1> graph(names.size(), names.size());
  35.     graph.fill(0);
  36.     for (size_t i = 0; i < keys.size(); ++i) {
  37.         for (const auto& v : objects[keys[i]]) {
  38.             auto j = get_index(v);
  39.             graph(i, j) = 1;
  40.         }
  41.     }
  42.  
  43.     std::function<void(int)> add = [&](int i) {
  44.         for (Eigen::Index j = 0; j < graph.cols(); ++j) {
  45.             if (i == j) continue;
  46.             if (graph(i, j) > 0) {
  47.                 graph(i, j) += graph.col(i).sum();
  48.                 add(j);
  49.             }
  50.         }
  51.     };
  52.  
  53.     auto c = get_index("COM");
  54.     add(c);
  55.     fmt::print("{}\n", graph.sum());
  56.  
  57.     // Part 2
  58.     std::vector<int> you;
  59.     std::vector<int> san;
  60.  
  61.     std::function<void(std::vector<int>&, int)> get_path = [&](std::vector<int>& path, int col) {
  62.         int row;
  63.         if (auto c = graph.col(col).maxCoeff(&row); c > 0) {
  64.             path.push_back(col);
  65.             get_path(path, row);
  66.         }
  67.     };
  68.  
  69.     get_path(you, get_index("YOU"));
  70.     get_path(san, get_index("SAN"));
  71.  
  72.     auto s = 0;
  73.  
  74.     auto yy = you.rbegin();
  75.     auto ss = san.rbegin();
  76.     for (; yy != you.rend() && ss != san.rend() && *ss == *yy; ++yy, ++ss) {
  77.         ++s;
  78.     }
  79.     fmt::print("{}\n", you.size() + san.size() - 2 * s - 2);
  80.  
  81.     return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement