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

dijkstra 最短路算法

时间:2016-06-28 23:21:22      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:

最朴素的做法o(n^2)
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
#include<string>
#include<string.h>
const int MAX = 2002;
int n;
int graph[MAX][MAX];
int dis[MAX];
bool vis[MAX];
const int INF = 0X7FFFFFFF;
int dijkstra()
{
memset(vis, false, sizeof(vis));
vis[1] = true;
for (int i = 1; i <= n; i++)
dis[i] =INF;
dis[1] = 0;
for (int i = 1; i <= n; i++)
{
if (graph[i][1] != 0)
dis[i] = graph[i][1];
}

for (int i = 0; i < n-1; i++)
{
int minn = INF, position = 1;
for (int i = 1; i <= n; i++)
{
if (!vis[i] && minn>dis[i])
{
minn = dis[i];
position = i;
}
}
vis[position] = true;
for (int i = 1; i <= n; i++)
{
if (!vis[i] &&graph[i][position]!=0&&dis[i] > (dis[position] + graph[i][position]))
dis[i] = dis[position] + graph[i][position];
}
}

return dis[n];
}

int main()
{

int t;
cin >> t>> n;
memset(graph, 0, sizeof(graph));
for (int i = 0; i < t; i++)
{
int x1, y1, val;
cin >> x1 >> y1 >> val;
if (graph[x1][y1])
{
if (graph[x1][y1]>val)
graph[x1][y1] = graph[y1][x1] = val;
}
else
{
graph[x1][y1] = graph[y1][x1] = val;
}

}
cout << dijkstra() << endl;
return 0;
}

/*

5 5
1 2 20
2 3 30
3 4 20
4 5 20
1 5 100

*/

dijkstra 最短路算法

标签:

原文地址:http://www.cnblogs.com/wuxiangli/p/5625225.html

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