首页 > 代码库 > dijkstra算法演示
dijkstra算法演示
dijkstra算法演示精髓
#include <iostream>#include <fstream>#include <cstring>#include <vector>#include <queue>#include <stack>#include <algorithm>#include <cmath>using namespace std;#define loop(i,n) for(int i=0;i<(n);i++)#define loop2(i,n) for(int i=1;i<=(n);i++)const int maxn=10;int inf=99999999;int e[maxn][maxn],dis[maxn],book[maxn];int n,m;void dijkstra(void){ //找到离1号顶点最近的点 int u,v; int xmin; loop2(i,n-1) { xmin=inf; loop2(j,n) { if(book[j]==0 && dis[j]<xmin) { xmin=dis[j]; u=j; } } book[u]=1; loop2(v,n) //松驰 { if(e[u][v]<inf) if(dis[v]>dis[u]+e[u][v]) dis[v]=dis[u]+e[u][v]; } }}void test(){ freopen("dijkstra.in","r",stdin); //freopen("dijkstra.out","w",stdout); cin>>n>>m; cout<<n<<" "<<m<<endl; loop2(i,n) loop2(j,m) if(i==j)e[i][j]=0; else e[i][j]=inf; int t1,t2,t3; loop2(i,m) { cin>>t1>>t2>>t3; e[t1][t2]=t3; } loop2(i,n) dis[i]=e[1][i]; book[1]=1; dijkstra(); loop2(i,n) cout<<dis[i]<<" "; cout<<endl;}int main () { test(); return 0;}
test data:
6 91 2 11 3 122 3 92 4 33 5 54 3 44 5 134 6 155 6 4
dijkstra算法演示
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。