-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraph.cpp
75 lines (68 loc) · 1.48 KB
/
Graph.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
73
74
75
/*
* Code by Ivan Petukhov
*/
#include <iostream>
#include <vector>
#include <set>
#define MAX 10000
#define INF 100000
using namespace std;
vector<int> Graph[MAX];
set<pair <long long, int>> q;
long long len[MAX];
int prnt[MAX];
vector <long long> res;
void findShortPath(vector<int> *Graph, int a, int b, int n, int m){
for (int i = 0; i < n; i++)
len[i] = INF;
len[a] = 0;
q.insert (make_pair (len[a], a));
while (!q.empty()) {
int v = q.begin()->second;
q.erase (q.begin());
for (int i = 0; i < Graph[v].size(); i++){
int end = Graph[v][i];
if (len[v] < len[end]) {
q.erase (make_pair (len[end], end));
len[end] = len[v] + 1;
prnt[end] = v;
q.insert (make_pair (len[end], end));
}
}
}
if (len[b] == INF) {
long long r = -1;
res.push_back(r);
return;
}
res.push_back(len[b]);
return;
}
int main(){
int N, M;
cin >> N;
cin >> M;
for (int i = 0; i < M; i++){
int start, end;
cin >> start;
start -= 1;
cin >> end;
end -= 1;
Graph[end].push_back(start);
Graph[start].push_back(end);
}
int Q;
cin >> Q;
int start, end;
for (int i = 0; i < Q; i++){
cin >> start;
start -= 1;
cin >> end;
end -= 1;
findShortPath(Graph, start, end, N, M);
}
for (vector<long long>::iterator iter = res.begin(); iter < res.end(); iter++){
cout << *(iter) << endl;
}
return 0;
}