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
59
60
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
int n, m, first, last, from, to;
vector<vector<int> > g;
vector<bool> used;
vector<int> weight;
int dij(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] && g[cur.second][i] != 0)
q.push(make_pair(-g[cur.second][i] + cur.first, i));
}
}
return -1;
}
int main() {
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
cin >> n;
g.resize(n, vector<int>(n, 0));
used.resize(n, 0);
weight.resize(n, 0);
for (int i = 0; i < n; ++i)
cin >> weight[i];
cin >> m;
for (int i = 0; i < m; ++i) {
cin >> from >> to;
from--; to--;
g[from][to] = weight[from];
g[to][from] = weight[to];
}
cout << dij(0, n - 1) << endl;
return 0;
}