dijkstra 最短路算法

时间:2023-03-08 15:59:15
dijkstra 最短路算法

最朴素的做法o(V*V/2+2E)~O(V^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

*/

最短路的优先队列做法,时间复杂度O(2E+VlogV)~o(vlgv)

#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
#include<string>
#include<string.h>
#include<queue>
#include<algorithm>
struct node
{
int x, d;
node(int _x, int _d) :x(_x), d(_d){}
bool operator< (const node &b) const{
return d > b.d;
}
};
const int MAX = 2002;
int n;
int graph[MAX][MAX];
vector<vector<int>> edges(MAX);
int dis[MAX];
bool vis[MAX];
const int INF = 0X7FFFFFFF;

int dijkstra()
{
memset(vis, false, sizeof(vis));
priority_queue<node> que;

for (int i = 1; i <= n; i++)
dis[i] =INF;
dis[1] = 0;

que.push(node(1, 0));

while (!que.empty())
{
node tmp = que.top();
que.pop();
if (vis[tmp.x]) continue;
vis[tmp.x] = true;
for (int i = 0; i < edges[tmp.x].size(); i++)
{
if (!vis[edges[tmp.x][i]] && graph[edges[tmp.x][i]][tmp.x]!=0 && dis[edges[tmp.x][i]]>(dis[tmp.x] + graph[edges[tmp.x][i]][tmp.x]))
{
dis[edges[tmp.x][i]] = graph[edges[tmp.x][i]][tmp.x] + dis[tmp.x];
que.push(node(edges[tmp.x][i], dis[edges[tmp.x][i]]));
}
}

}

return dis[n];
}

int main()
{

int t;
cin >> t>> n;
memset(graph, 0, sizeof(graph));
edges.resize(MAX);

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;
edges[x1].push_back(y1);
edges[y1].push_back(x1);
}

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

/*

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

*/