注:dijkstra算法是基于贪心的思想求最短路,因此若有负权值边,则不能使用dijkstra算法。
朴素版:
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
using namespace std;
#define endl '\n'
#define ll long long
const int maxn = 1005, inf = 0x3f3f3f3f;
int dis[maxn];//记录每个点到原点的最短距离(权值)
int arcs[maxn][maxn];//邻接矩阵,记录边,若i到j连通则赋值为权值,反之则赋值无穷
//ps:为什么我的电脑会打不出来邻字,找了好久还是选择粘贴....真lj
bool vis[maxn];//记录当前点是否被更新过
int n, m;
//快读
template<class T>inline void read(T& res)
{
char c; T flag = 1;
while ((c = getchar()) < '0' || c > '9')if (c == '-')flag = -1; res = c - '0';
while ((c = getchar()) >= '0' && c <= '9')res = res * 10 + c - '0'; res *= flag;
}
void dijkstra()
{
memset(dis, 0x3f, sizeof(dis));//全部赋值为无穷
dis[1] = 0;//1为原点
//接下来求出最短路
for (int i = 1; i < n; i++)
{
int t = -1;
for (int j = 1; j <= n; j++)
{
if (!vis[j] && (t == -1 || dis[j] < dis[t]))
t = j;
}
vis[t] = true;//记录已经查询过该点
for (int j = 1; j <= n; j++)
dis[j] = min(dis[j], dis[t] + arcs[t][j]);//更新路径i->t->j的权值以保证最小
}
if (dis[n] == inf) dis[n] = -1;//若都不连通,则输出-1
}
int main()
{
read(n); read(m);
memset(arcs, 0x3f, sizeof(arcs));//邻接矩阵初始化,若连通则更新权值
//存边
while (m--)
{
int a, b, c;//a,b为点,c为权值
read(a); read(b); read(c);
arcs[a][b] = min(arcs[a][b], c);//若有重边,则只存最短边
//若是无向图,则应写为 arcs[a][b] = arcs[b][a] = min(arcs[a][b], c)
}
dijkstra();
cout << dis[n] << endl;
return 0;
}
堆优化版(优先队列):
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
#pragma GCC optimize(3)
#define ll long long
#define endl '\n'
typedef pair<int, int> Pii;
const int maxn = 1e5, inf = 0x3f3f3f3f;
int n, m, from, to;
bool vis[maxn];
ll dis[maxn];
vector<Pii>s[maxn];
struct node {
int id; ll d;
node() {}
node(int id,ll d):id(id),d(d){}
bool operator<(const node& N) const {
return d > N.d;
}
};
void dijkstra(int from)
{
memset(dis, 0x3f, sizeof(dis));
dis[from] = 0;
priority_queue<node>que;
que.push(node(from, 0));
while (!que.empty())
{
node now = que.top();
que.pop();
if (vis[now.id]) continue;
vis[now.id] = 1;
for (int i = 0; i < s[now.id].size(); i++)
{
int idd = s[now.id][i].first;
int dist = s[now.id][i].second;
if (now.d + dist < dis[idd]) {
dis[idd] = now.d + dist;
que.push(node(idd, dis[idd]));
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin >> n >> m;
while (m--)
{
int x, y, z;
cin >> x >> y >> z;
s[x].push_back(make_pair(y, z));//有向图,无向图另一边同时存入即可
}
cin >> from >> to;
dijkstra(from);
cout << dis[to] << endl;
return 0;
}