-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDijkstra.cpp
More file actions
72 lines (72 loc) · 1.49 KB
/
Dijkstra.cpp
File metadata and controls
72 lines (72 loc) · 1.49 KB
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 <bits/stdc++.h>
using namespace std;
const int maxn = 1000005;
const int INF = 1e9;
using ll = long long;
int n, m, s;
vector<pair<int, int>> adj[maxn];
vector<vector<ll>> v;
void nhap()
{
cin >> n >> m;
for(int i = 1; i <= m; i++)
{
int x, y, w; cin >> x >> y >> w;
adj[x].push_back({y, w});
adj[y].push_back({x, w});
}
}
void dijkstra(int s)
{
vector<ll> d(n+1, INF);
d[s] = 0;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
// khoang cach va dinh -> lay ra dinh co khoang cach nho nhat
q.push({0, s});
while (!q.empty())
{
pair<int, int> top = q.top(); q.pop();
int u = top.second;
int kc = top.first;
if(kc > d[u]) continue;
for(auto it : adj[u])
{
int v = it.first;
int w = it.second;
if(d[v] > d[u] + w)
{
d[v] = d[u] + w;
q.push({d[v], v});
}
}
}
vector<ll> tmp;
for(int i = 1; i <= n; i++)
{
tmp.push_back(d[i]);
}
v.push_back(tmp);
}
int main()
{
nhap();
for(int i = 1; i <= n; i++)
{
dijkstra(i);
}
int q; cin >> q;
while(q--)
{
int x, y;
cin >> x >> y;
cout << v[x-1][y-1] << endl;
}
// for(auto it : v)
// {
// for(int i = 0; i < n; i++)
// {
// cout << it[i] << " ";
// }
// cout << endl;
// }
}