include iostream include vector include algorithm include queue using

 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
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
int N, M, first, last, from, to;
vector <vector <int> > graph;
vector <bool> used;
vector <int> gas;
int dijkstra(int first, int last) {
priority_queue <pair <int, int> > q;
q.push(make_pair(0, first));
while (!q.empty()) {
pair <int, int> cur = q.top();
q.pop();
used[cur.second] = 1;
if (cur.second == last)
return -cur.first;
for (int i = 0; i < N; ++i) {
if (!used[i] && graph[cur.second][i] != 0)
q.push(make_pair(-graph[cur.second][i] + cur.first, i));
}
}
return -1;
}
int main() {
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
cin >> N;
graph.resize(N, vector <int>(N, 0));
used.resize(N, 0);
gas.resize(N, 0);
for (int i = 0; i < N; ++i)
cin >> gas[i];
cin >> M;
for (int i = 0; i < M; ++i) {
cin >> from >> to;
from--; to--;
graph[from][to] = gas[from];
graph[to][from] = gas[to];
}
cout << dijkstra(0, N - 1) << endl;
return 0;
}