-
Notifications
You must be signed in to change notification settings - Fork 814
/
Copy path1030. Travel Plan (30) .cpp
72 lines (72 loc) · 1.92 KB
/
1030. Travel Plan (30) .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
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
int n, m, s, d;
int e[510][510], dis[510], cost[510][510];
vector<int> pre[510];
bool visit[510];
const int inf = 99999999;
vector<int> path, temppath;
int mincost = inf;
void dfs(int v) {
temppath.push_back(v);
if(v == s) {
int tempcost = 0;
for(int i = temppath.size() - 1; i > 0; i--) {
int id = temppath[i], nextid = temppath[i-1];
tempcost += cost[id][nextid];
}
if(tempcost < mincost) {
mincost = tempcost;
path = temppath;
}
temppath.pop_back();
return ;
}
for(int i = 0; i < pre[v].size(); i++)
dfs(pre[v][i]);
temppath.pop_back();
}
int main() {
fill(e[0], e[0] + 510 * 510, inf);
fill(dis, dis + 510, inf);
scanf("%d%d%d%d", &n, &m, &s, &d);
for(int i = 0; i < m; i++) {
int a, b;
scanf("%d%d", &a, &b);
scanf("%d", &e[a][b]);
e[b][a] = e[a][b];
scanf("%d", &cost[a][b]);
cost[b][a] = cost[a][b];
}
pre[s].push_back(s);
dis[s] = 0;
for(int i = 0; i < n; i++) {
int u = -1, minn = inf;
for(int j = 0; j < n; j++) {
if(visit[j] == false && dis[j] < minn) {
u = j;
minn = dis[j];
}
}
if(u == -1) break;
visit[u] = true;
for(int v = 0; v < n; v++) {
if(visit[v] == false && e[u][v] != inf) {
if(dis[v] > dis[u] + e[u][v]) {
dis[v] = dis[u] + e[u][v];
pre[v].clear();
pre[v].push_back(u);
} else if(dis[v] == dis[u] + e[u][v]) {
pre[v].push_back(u);
}
}
}
}
dfs(d);
for(int i = path.size() - 1; i >= 0; i--)
printf("%d ", path[i]);
printf("%d %d", dis[d], mincost);
return 0;
}