-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
83 lines (67 loc) · 1.72 KB
/
main.cpp
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
#include <iostream>
#include <vector>
void testcase() {
int n, m;
std::cin >> n >> m;
std::vector<std::vector<std::pair<int, int>>> forwardAdjList(
n, std::vector<std::pair<int, int>>());
std::vector<std::vector<std::pair<int, int>>> backwardAdjList(
n, std::vector<std::pair<int, int>>());
for (int i = 0; i < m; i++) {
int u, v, f;
std::cin >> u >> v >> f;
if (u < v) {
forwardAdjList[u].push_back({v, f});
} else {
backwardAdjList[v].push_back({u, f});
}
}
std::vector<std::vector<int>> dp =
std::vector<std::vector<int>>(n, std::vector<int>(n, -1));
for (int j = n - 1; j >= 0; j--) {
for (int i = n - 1; i >= 0; i--) {
// Base Case
if (i == n - 1 && j == n - 1) {
dp[i][j] = 0;
continue;
}
// Cannot visit same node twice
if (i == j && i != 0) {
dp[i][j] = -1;
continue;
}
if (i < j) {
int currMax = -1;
for (auto street : forwardAdjList[i]) {
int dest = street.first;
int rats = street.second;
if (dp[dest][j] != -1) {
currMax = std::max(currMax, rats + dp[dest][j]);
}
}
dp[i][j] = currMax;
continue;
}
if (i >= j) {
int currMax = -1;
for (auto street : backwardAdjList[j]) {
int dest = street.first;
int rats = street.second;
if (dp[i][dest] != -1) {
currMax = std::max(currMax, rats + dp[i][dest]);
}
}
dp[i][j] = currMax;
}
}
}
std::cout << dp[0][0] << "\n";
}
int main() {
std::ios_base::sync_with_stdio(false);
int t;
std::cin >> t;
for (int i = 0; i < t; i++) {
testcase();
}
}