码迷,mamicode.com
首页 > 编程语言 > 详细

dijkstra算法演示

时间:2014-10-25 17:10:09      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   for   sp   div   on   

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 9
1 2 1
1 3 12
2 3 9
2 4 3
3 5 5
4 3 4
4 5 13
4 6 15
5 6 4

 

dijkstra算法演示

标签:style   blog   color   io   os   for   sp   div   on   

原文地址:http://www.cnblogs.com/dpblue/p/4050295.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!