Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #include <algorithm>
- using namespace std;
- int main() {
- cout << "Enter vertex count: ";
- int n;
- cin >> n;
- const int INF = 1e9;
- // ввод графа
- cout << "Enter sprase matrix (n*n):\n";
- int **spm = new int*[n];
- for (int i = 0; i < n; ++i) {
- spm[i] = new int[n];
- for (int j = 0; j < n; ++j) {
- cin >> spm[i][j];
- if (spm[i][j] <= 0) {
- spm[i][j] = INF;
- }
- if (i == j) {
- spm[i][j] = 0;
- }
- }
- }
- // выбор алгоритма
- int algo = -1;
- while (algo != 0 && algo != 1) {
- cout << "Choose algorithm.\n"
- "0 -> dijkstra\n"
- "1 -> floyd\n"
- "Your choice: ";
- cin >> algo;
- }
- if (algo == 0) {
- // дейкстра
- cout << "Enter start vertex number: ";
- int s;
- cin >> s;
- int *path = new int[n], *visited = new int[n];
- for (int i = 0; i < n; ++i) {
- path[i] = INF;
- visited[i] = false;
- }
- path[s] = 0;
- for (int i = 0; i < n; ++i) {
- int cur = -1;
- for (int j = 0; j < n; ++j) {
- if (!visited[j] && (cur == -1 || path[cur] > path[j])) {
- cur = j;
- }
- }
- if (path[cur] == INF) {
- break;
- }
- visited[cur] = true;
- for (int i = 0; i < n; ++i) {
- if (spm[cur][i] != INF) {
- path[i] = min(path[i], path[cur] + spm[cur][i]);
- }
- }
- }
- for (int i = 0; i < n; ++i) {
- if (path[i] == INF) {
- cout << "INF ";
- } else {
- cout << path[i] << " ";
- }
- }
- } else {
- // флойд
- for (int i = 0; i < n; ++i) {
- for (int j = 0; j < n; ++j) {
- for (int l = 0; l < n; ++l) {
- spm[i][j] = min(spm[i][j], spm[i][l] + spm[l][j]);
- }
- }
- }
- for (int i = 0; i < n; ++i) {
- for (int j = 0; j < n; ++j) {
- if (spm[i][j] >= INF) {
- cout << "INF ";
- } else {
- cout << spm[i][j] << " ";
- }
- }
- cout << "\n";
- }
- }
- cout << "\n";
- }
Add Comment
Please, Sign In to add comment