(邻接矩阵)最短路径算法

Floyd算法:

思路 :遍历计算 i 点 经过 k 点 到 j 点 的最小路径值 (动态规划思路)

缺点:时间复杂度高,不能解决负边情况

输入样例:

4 8
1 2 2
1 3 6
1 4 4
2 3 3
3 1 7
3 4 1
4 1 5
4 3 12

输出样例:

1-->2:2
1-->3:5
1-->4:4
2-->1:9
2-->3:3
2-->4:4
3-->1:6
3-->2:8
3-->4:1
4-->1:5
4-->2:7
4-->3:10

#include <cstdio>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <math.h>
#include <queue>
using namespace std;
const int inf=0x7fffff;
const long long mod=1e9+7;
const double PI=acos(-1);

int n,m,start,end;
int ans=9999999;
bool vis[105];
int e[105][105];

void init(){                           //初始化邻接矩阵 
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            if(i==j) e[i][j]=0;
            else e[i][j]=inf;
        }
    }
} 

void Floyd(){                                       //思路:依此判断 i 通过 k 到 j 的最短路 
    for(int k=1;k<=n;k++){                          // k 经转的节点 
        for(int i=1;i<=n;i++){                      // i 每次的起点 
            for(int j=1;j<=n;j++){                  // j 每次的终点 
                if(k==i&&k==j) continue;
                if(e[i][j]>e[i][k]+e[k][j]){
                    e[i][j]=e[i][k]+e[k][j];
                }
            }
        }
    }
}

int main()
{
    int x,y,value;
    cin>>n>>m;
    init();
    for(int i=0;i<m;i++){
        cin>>x>>y>>value;
        e[x][y]=value;
    }
    Floyd();
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            if(i==j) continue;
            cout<<i<<"-->"<<j<<":"<<e[i][j]<<endl;
        }
    } 
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/xusi/p/12582820.html
今日推荐