Radme
本文章仅代码详细分析文章后续补充
感想
- 自己把自己气的吐血
- 第一次写代码这门捉急
代码
#include <iostream>
#include <cstring>
using namespace std;
const int MAX = 100;
const int INF = 99999;
typedef struct{
int vex[MAX];
int edge[MAX][MAX];
int vexnum;
int edgenum;
}node;
int dist[MAX][MAX];
int p[MAX][MAX];
/*
4 8
1 2 1
1 4 4
2 3 9
2 4 2
3 2 5
3 1 3
3 4 8
4 3 6
*/
/*
int u,v;
cout << " 请输入 源点 到 目标节点:";
cin >> u >> v;
cout << "最短距离:" << dist[u][v]<< endl;
int star = u;
int ends = v;
int aim;// 要到达的
*/
void diplay_rold(node G,int s,int e){
cout << s << " " << e << " " << p[s][e] << endl;
if(p[s][e] == -1) return; // 到达目的地3 是个复数所以返回
diplay_rold(G,s,p[s][e]);
cout << p[s][e] << " === ";
}
int main(){
node G;
cin >> G.vexnum >> G.edgenum;
memset(p,-1,sizeof(p));
for (int i = 1; i <= G.vexnum; i++) G.vex[i] = i;
int u,v,w;
for (int i = 1; i <= G.vexnum; i++) {
for (int j = 1; j<= G.vexnum; j++) {
if(i==j){
G.edge[i][j] = dist[i][j] = 0;
} else {
G.edge[i][j] = dist[i][j] = INF;
}
}
}
for (int i = 1; i <= G.edgenum; i++) {
cin >> u >> v >> w;
dist[u][v] = w;
G.edge[u][v] = w;
}
for (int i = 1; i <= G.vexnum; i++)
for (int j = 1; j<= G.vexnum; j++) {
if(dist[i][j]!=INF && i!=j) p[i][j] = i; else p[i][j] = -1;
}
/* == 输出 == */
for (int i = 1; i <= G.vexnum; i++) {
for (int j = 1; j<= G.vexnum; j++) {
cout << p[i][j] << " " ;
}
cout << endl;
}
/* ==结束输出== */
/*
-1 1 -1 1
-1 -1 2 2
3 3 -1 3
-1 -1 4 -1
*/
/* Floyd算法开始 */
int node_vx = G.vexnum;
for (int k = 1; k <= node_vx; k++){
for (int i = 1; i <= node_vx; i++){
for (int j = 1; j <= node_vx; j++){
if(dist[i][j] > dist[i][k] + dist[k][j]){
dist[i][j] = dist[i][k]+ dist[k][j];
p[i][j] = p[k][j];
}
}
}
}
/* Floyd算法结束 */
/* == 输出 == */
cout << endl << endl;
for (int i = 1; i <= G.vexnum; i++) {
for (int j = 1; j<= G.vexnum; j++) {
cout << p[i][j] << " " ;
}
cout << endl;
}
/* ==结束输出== */
/* 测试样例 */
{
int u,v;
cout << " 请输入 源点 到 目标节点:";
cin >> u >> v;
cout << "最短距离:" << dist[u][v]<< endl;
diplay_rold(G,u,v);
}
}