UVa 341 - Non-Stop Travel

Contents

  1. 1. Problem
  2. 2. Solution
  3. 3. Code

Problem

題目網址
中文網址

Solution

做 Dijkstra,權重為時間。

Code

UVa 341
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
#include<cstdio>
#include<queue>
#include<stack>
#define N 11
using namespace std;

struct Node{
int u, d;
Node(int uu, int dd) :u(uu), d(dd){}
bool operator<(const Node& n)const{ return d>n.d; }
};
int adjM[N][N];

void dijkstra(int s, int g);
int main()
{
int n, i, j, Case = 1;
while (scanf("%d", &n) && n)
{
for (i = 0; i < N; i++)
for (j = 0; j < N; j++)
adjM[i][j] = -1;

int t, u, d;
for (i = 1; i <= n; i++)
{
scanf("%d", &t);
for (j = 0; j < t; j++)
{
scanf("%d%d", &u, &d);
adjM[i][u] = d;
}
}
int s, g;
scanf("%d%d", &s, &g);
printf("Case %d: Path =", Case++);
dijkstra(s, g);
}

return 0;
}
void dijkstra(int s, int g)
{
int d[N] = {}, path[N] = {};
bool isVisit[N] = {};
priority_queue<Node> PQ;
PQ.push(Node(s, 0));

for (int i = 0; i < N; i++)
d[i] = 1e9;

d[s] = 0;
while (true)
{
int next = -1;
while (!PQ.empty() && isVisit[next = PQ.top().u])
PQ.pop();

if (next == -1 || next == g)
break;

PQ.pop();
isVisit[next] = true;

for (int i = 1; i < N; i++)
if (!isVisit[i] && adjM[next][i] != -1)
if (d[next] + adjM[next][i] < d[i])
{
d[i] = d[next] + adjM[next][i];
path[i] = next;
PQ.push(Node(i, d[i]));
}
}

int last = g;
stack<int> Stack;
Stack.push(g);
while (last != s)
{
last = path[last];
Stack.push(last);
}

while (!Stack.empty())
{
printf(" %d", Stack.top());
Stack.pop();
}

printf("; %d second delay\n", d[g]);
}