Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <queue>
- #include <utility>
- #include <vector>
- using namespace std;
- using vvi = vector<vector<int>>;
- const int inf = 1e9;
- void dfs(vvi& graph, vector<int>& visited, vector<int>& vertexes, int v)
- {
- visited[v] = 1;
- vertexes.push_back(v);
- for (int i = 0; i < graph.size(); ++i)
- if (graph[v][i] && !visited[i])
- dfs(graph, visited, vertexes, i);
- }
- vector<int> bfs(vvi& graph, int start)
- {
- vector<int> visited(graph.size(), 0);
- vector<int> degree(graph.size(), 0);
- queue<int> q;
- visited[start] = 1;
- q.push(start);
- while (!q.empty())
- {
- int v = q.front();
- q.pop();
- for (int i = 0; i < graph.size(); ++i)
- {
- if (graph[v][i] && !visited[i])
- {
- degree[v]++;
- visited[i] = 1;
- q.push(i);
- }
- }
- }
- return degree;
- }
- vector<int> djikstra(vector<vector<int>>& graph, int start)
- {
- vector<int> dist(graph.size(), inf);
- priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
- dist[start] = 0;
- q.emplace(dist[start], start);
- while (!q.empty())
- {
- pair<int, int> u = q.top();
- q.pop();
- if (u.first > dist[u.second]) continue;
- for (int i = 0; i < graph[u.second].size(); ++i)
- {
- if (graph[u.second][i] != 0 && dist[i] > dist[u.second] + graph[u.second][i])
- {
- dist[i] = dist[u.second] + graph[u.second][i];
- q.emplace(dist[i], i);
- }
- }
- }
- return dist;
- }
- int main()
- {
- vvi graph = { { 0, 5, 6, 6, 6, 4, 5, 0, 0, 8, 8, 4, 4 },
- { 5, 0, 8, 0, 3, 8, 4, 8, 6, 6, 6, 3, 4 },
- { 6, 8, 0, 2, 0, 0, 0, 9, 3, 5, 3, 8, 1 },
- { 6, 0, 2, 0, 2, 4, 7, 7, 7, 9, 5, 5, 5 },
- { 6, 3, 0, 2, 0, 1, 5, 5, 4, 4, 1, 4, 2 },
- { 4, 8, 0, 4, 1, 0, 8, 1, 5, 4, 5, 8, 6 },
- { 5, 4, 0, 7, 5, 8, 0, 6, 9, 0, 1, 2, 0 },
- { 0, 8, 9, 7, 5, 1, 6, 0, 4, 6, 7, 3, 3 },
- { 0, 6, 3, 7, 4, 5, 9, 4, 0, 4, 4, 1, 1 },
- { 8, 6, 5, 9, 4, 4, 0, 6, 4, 0, 9, 2, 7 },
- { 8, 6, 3, 5, 1, 5, 1, 7, 4, 9, 0, 6, 9 },
- { 4, 3, 8, 5, 4, 8, 2, 3, 1, 2, 6, 0, 3 },
- { 4, 4, 1, 5, 2, 6, 0, 3, 1, 7, 9, 3, 0 } };
- vector<int> degree = bfs(graph, 1);
- cout << degree[1];
- vector<int> visited(graph.size(), 0);
- vector<int> ver;
- dfs(graph, visited, ver, 0);
- cout << '\n';
- for (auto it : ver)
- cout << it << " ";
- cout << '\n';
- vvi dist(graph.size());;
- for (int i = 0; i < graph.size(); ++i)
- {
- dist[i] = djikstra(graph, i);
- }
- cout << '\n';
- for (int i = 0; i < graph.size(); ++i)
- {
- for (auto it : dist[i])
- cout << it << " ";
- cout << '\n';
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement