aboutsummaryrefslogtreecommitdiff
path: root/2015/src/day09.cpp
blob: 45cd5c4f6ff23593c173094ad13c6db6eceedecc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <algorithm>
#include <fstream>
#include <iostream>
#include <limits>
#include <map>
#include <sstream>
#include <string>
#include <tuple>
#include <vector>

using namespace std;

auto
split(const string& line, char sep)
{
	vector<string> parts;
	stringstream   input{ line };

	for ( string part; getline(input, part, sep); ) {
		parts.emplace_back(part);
	}

	return parts;
}

auto
read_file(string_view filename)
{
	fstream                        input{ filename };
	map<string, map<string, long>> distances;

	for ( string line; getline(input, line); ) {
		const auto parts = split(line, ' ');

		distances[parts[0]][parts[2]] = stol(parts[4]);
		distances[parts[2]][parts[0]] = stol(parts[4]);
	}

	return distances;
}

void
part1(map<string, map<string, long>>& distances)
{
	vector<string> vertex;

	vertex.reserve(distances.size());
	for ( const auto& iter: distances ) {
		vertex.emplace_back(iter.first);
	}

	long min_path = numeric_limits<long>::max();

	do {
		long current_min_path = 0;

		auto start = vertex[0];
		for ( const auto& ver: vertex ) {
			current_min_path += distances[start][ver];
			start = ver;
		}

		min_path = min(min_path, current_min_path);
	} while ( next_permutation(begin(vertex), end(vertex)) );

	cout << min_path << endl;
}

void
part2(map<string, map<string, long>>& distances)
{
	vector<string> vertex;

	vertex.reserve(distances.size());
	for ( const auto& iter: distances ) {
		vertex.emplace_back(iter.first);
	}

	long max_path = numeric_limits<long>::min();

	do {
		long current_max_path = 0;

		auto start = vertex[0];
		for ( const auto& ver: vertex ) {
			current_max_path += distances[start][ver];
			start = ver;
		}

		max_path = max(max_path, current_max_path);
	} while ( next_permutation(begin(vertex), end(vertex)) );

	cout << max_path << endl;
}

int
main()
{
	auto distances = read_file("data/day09.txt");
	part1(distances);
	part2(distances);
}