aboutsummaryrefslogtreecommitdiff
path: root/2015/src
diff options
context:
space:
mode:
authorThomas Schmucker <ts@its1.de>2024-11-14 21:25:25 +0100
committerThomas Schmucker <ts@its1.de>2024-11-14 21:25:25 +0100
commit90e31528ce685cb1d6e02baa40fc47ca88c713e0 (patch)
tree0e684430c392eb3349255a902f132712051e392d /2015/src
parented65c5937950373f96026f476c03bf8984360900 (diff)
downloadadvent-of-code-90e31528ce685cb1d6e02baa40fc47ca88c713e0.tar.gz
advent-of-code-90e31528ce685cb1d6e02baa40fc47ca88c713e0.tar.bz2
advent-of-code-90e31528ce685cb1d6e02baa40fc47ca88c713e0.zip
aoc 2015, day 9
Diffstat (limited to '2015/src')
-rw-r--r--2015/src/day09.cpp102
1 files changed, 102 insertions, 0 deletions
diff --git a/2015/src/day09.cpp b/2015/src/day09.cpp
new file mode 100644
index 0000000..45cd5c4
--- /dev/null
+++ b/2015/src/day09.cpp
@@ -0,0 +1,102 @@
1#include <algorithm>
2#include <fstream>
3#include <iostream>
4#include <limits>
5#include <map>
6#include <sstream>
7#include <string>
8#include <tuple>
9#include <vector>
10
11using namespace std;
12
13auto
14split(const string& line, char sep)
15{
16 vector<string> parts;
17 stringstream input{ line };
18
19 for ( string part; getline(input, part, sep); ) {
20 parts.emplace_back(part);
21 }
22
23 return parts;
24}
25
26auto
27read_file(string_view filename)
28{
29 fstream input{ filename };
30 map<string, map<string, long>> distances;
31
32 for ( string line; getline(input, line); ) {
33 const auto parts = split(line, ' ');
34
35 distances[parts[0]][parts[2]] = stol(parts[4]);
36 distances[parts[2]][parts[0]] = stol(parts[4]);
37 }
38
39 return distances;
40}
41
42void
43part1(map<string, map<string, long>>& distances)
44{
45 vector<string> vertex;
46
47 vertex.reserve(distances.size());
48 for ( const auto& iter: distances ) {
49 vertex.emplace_back(iter.first);
50 }
51
52 long min_path = numeric_limits<long>::max();
53
54 do {
55 long current_min_path = 0;
56
57 auto start = vertex[0];
58 for ( const auto& ver: vertex ) {
59 current_min_path += distances[start][ver];
60 start = ver;
61 }
62
63 min_path = min(min_path, current_min_path);
64 } while ( next_permutation(begin(vertex), end(vertex)) );
65
66 cout << min_path << endl;
67}
68
69void
70part2(map<string, map<string, long>>& distances)
71{
72 vector<string> vertex;
73
74 vertex.reserve(distances.size());
75 for ( const auto& iter: distances ) {
76 vertex.emplace_back(iter.first);
77 }
78
79 long max_path = numeric_limits<long>::min();
80
81 do {
82 long current_max_path = 0;
83
84 auto start = vertex[0];
85 for ( const auto& ver: vertex ) {
86 current_max_path += distances[start][ver];
87 start = ver;
88 }
89
90 max_path = max(max_path, current_max_path);
91 } while ( next_permutation(begin(vertex), end(vertex)) );
92
93 cout << max_path << endl;
94}
95
96int
97main()
98{
99 auto distances = read_file("data/day09.txt");
100 part1(distances);
101 part2(distances);
102}