View difference between Paste ID: crcqnHUL and 87M39qbN
SHOW: | | - or go back to the newest paste.
1
#include <fstream>
2
#include <algorithm>
3
#define INF 9223372036854775807
4
std::ifstream fin("input.txt");
5
std::ofstream fout("output.txt");
6
int** matrix;
7
long long** dp;
8
int n;
9
10
int main(int argc, char* argv[]) {
11
	fin >> n;
12
	//adjacency matrix
13
	matrix = new int*[n];
14
	for (int i = 0; i < n; i++) {
15
		matrix[i] = new int[n];
16
		for (int j = 0; j < n; j++)
17
			fin >> matrix[i][j];
18
	}
19
	//dp
20
	dp = new long long*[1 << n];
21
	for (int i = 0; i < (1 << n) + 1; i++) {
22
		dp[i] = new long long[n];
23
		for (int j = 0; j < n; j++)
24
			dp[i][j] = INF;
25
	}
26
	//start pos
27
	for (int i = 0; i < n; i++)
28
		dp[1 << i][i] = 0;
29
	//main
30
	for (int mask = 1; mask < 1 << n; mask++) {
31
		for (int cur_planet = 0; cur_planet < n; cur_planet++) {
32
			if (dp[mask][cur_planet] == INF) continue;
33
			for (int tg_planet = 0; tg_planet < n; tg_planet++) {
34
				if (!(mask & (1 << tg_planet)) && matrix[cur_planet][tg_planet] != -1) {
35
					dp[mask ^ (1 << tg_planet)][tg_planet] = std::min(dp[mask ^ (1 << tg_planet)][tg_planet], dp[mask][cur_planet] + matrix[cur_planet][tg_planet]);
36
				}
37
			}
38
		}
39
	}
40
	//out
41
	long long min = INF;
42
	for (int planet = 0; planet < n; planet++) {
43
		if (dp[(1 << n) - 1][planet] < min) min = dp[(1 << n) - 1][planet];
44
	}
45
	fout << min;
46
	return 0;
47
}