Johnsonのアルゴリズムを実装するC++プログラム
ここでは、2つの頂点間の最短経路を見つけるためのジョンソンのアルゴリズムを見ていきます。
グラフはここにあります。エッジ間の最短経路は以下のようになります。このプログラムは、頂点の数、エッジの数、およびエッジとそのコストを取得します。
入力 −頂点:3
エッジ:5
コストのかかるエッジ-
1 2 8
2 1 12
1 3 22
3 1 6
2 3 4
出力 −グラフの距離行列。
| 0 | 8 | 12 |
| 10 | 0 | 4 |
| 6 | 14 | 0 |
アルゴリズム
johnsonAlgorithm(コスト)
入力 −与えられたグラフのコストマトリックス。
出力 −任意の頂点から任意の頂点への最短経路の行列。
Begin Create another matrix ‘A’ same as cost matrix, if there is no edge between ith row and jth column, put infinity at A[i,j]. for k := 1 to n, do for i := 1 to n, do for j := 1 to n, do A[i, j] = minimum of A[i, j] and (A[i, k] + A[k, j]) done done done display the current A matrix End
例
#include<iostream>
#define INF 9999
using namespace std;
int min(int a, int b);
int cost[10][10], adj[10][10];
inline int min(int a, int b){
return (a<b)?a:b;
}
main() {
int vert, edge, i, j, k, c;
cout << "Enter no of vertices: ";
cin >> vert;
cout << "Enter no of edges: ";
cin >> edge;
cout << "Enter the EDGE Costs:\n";
for (k = 1; k <= edge; k++) { //take the input and store it into adj and cost matrix
cin >> i >> j >> c;
adj[i][j] = cost[i][j] = c;
}
for (i = 1; i <= vert; i++)
for (j = 1; j <= vert; j++) {
if (adj[i][j] == 0 && i != j)
adj[i][j] = INF; //if there is no edge, put infinity
}
for (k = 1; k <= vert; k++)
for (i = 1; i <= vert; i++)
for (j = 1; j <= vert; j++)
adj[i][j] = min(adj[i][j], adj[i][k] + adj[k][j]); //find minimum path from i to j through k
cout << "Resultant adj matrix\n";
for (i = 1; i <= vert; i++) {
for (j = 1; j <= vert; j++) {
if (adj[i][j] != INF)
cout << adj[i][j] << " ";
}
cout << "\n";
}
} 出力
Enter no of vertices: 3 Enter no of edges: 5 Enter the EDGE Costs: 1 2 8 2 1 12 1 3 22 3 1 6 2 3 4 Resultant adj matrix 0 8 12 10 0 4 6 14 0
-
補間検索アルゴリズムを実装するC++プログラム
二分探索手法の場合、リストは等しい部分に分割されます。補間検索手法の場合、プロシージャは補間式を使用して正確な位置を見つけようとします。推定位置を見つけた後、その位置を使用してリストを分離できます。毎回正確な位置を見つけようとするため、検索時間が短縮されます。この手法では、アイテムが均一に分散されている場合、アイテムを簡単に見つけることができます。 補間検索手法の複雑さ 時間計算量:O(log 2 (log 2 n))平均的な場合、O(n)は最悪の場合(アイテムが指数関数的に分散される場合) スペースの複雑さ:O(1) Input − A sorted li
-
配列シャッフリング用のFisher-Yatesアルゴリズムを実装するC++プログラム
Fisher-Yatesアルゴリズムは、配列要素のランダムな順列を生成します。つまり、配列のすべての要素をランダムにシャッフルします。フィッシャー-イェーツアルゴリズムは偏りがないため、配列のすべての順列は同じように発生する可能性があります。 C++で配列シャッフルするためのFisher-Yatesアルゴリズムを実装するプログラムは次のとおりです- 例 #include <iostream> #include <t;stdlib.h> using namespace std; int main() { int n;