Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*Дан невзвешенный неориентированный граф.
- В графе может быть несколько кратчайших путей
- между какими-то вершинами. Найдите количество
- различных кратчайших путей между заданными
- вершинами. Требуемая сложность O(V+E).*/
- #include <vector>
- #include <queue>
- #include <list>
- #include <iostream>
- using std::vector;
- using std::queue;
- using std::cin;
- using std::cout;
- int countPaths(vector<vector<int>> graph, int n, int from, int to)
- {
- vector<int> used(n), depth(n), parent(n), path_counter(n,0);
- int s = from;
- queue<int> q;
- q.push(s);
- used[s] = 1;
- depth[s] = 0;
- parent[s] = -1;
- while (!q.empty()){
- int current_vertex = q.front();
- q.pop();
- for(int i = 0; i < n; i++){
- int next_vertex = i;
- int road = graph[current_vertex][next_vertex];
- if(!road) continue;
- if(!used[next_vertex]){
- q.push(next_vertex);
- used[next_vertex] = 1;
- depth[next_vertex] = depth[current_vertex] + 1;
- parent[next_vertex] = current_vertex;
- path_counter[next_vertex]++;
- } else if (depth[next_vertex] == depth[current_vertex] + 1) path_counter[next_vertex]++;
- }
- }
- return path_counter[to];
- }
- int main()
- {
- unsigned int n = 0;
- cin >> n;
- vector<vector<int>> graph(n, vector<int>(n,0));
- int k;
- cin >> k;
- for(int i = 0; i < k; i++){
- int a, b;
- cin >> a >> b;
- graph[a][b] = 1;
- graph[b][a] = 1;
- }
- int from = 0;
- int to = 0;
- cin >> from >> to;
- cout << countPaths(graph, n, from, to);
- }
Add Comment
Please, Sign In to add comment