在队友的强烈建议(压迫)下放弃了可能会被卡死的优先队列优化SPFA去计算最短路于是现学了Dij算法。为了避免某比赛上忘记,疯狂背板子(怨念.jpg)
题目来源:洛谷P4779
模板题
基本思想:
- 将图上的初始点看作一个集合S,其它点看作另一个集合
- 根据初始点,求出其它点到初始点的距离dis[i] (若相邻,则dis[i]为边权值;若不相邻,则d[i]为无限大)
- 选取最小的dis[i](记为dis[x]),并将此dis[i]边对应的点(记为x)加入集合S(实际上,加入集合的这个点的dis[x]值就是它到初始点的最短距离)
- 再根据x,更新跟 x 相连点 y 的dis[y]值, d i s [ y ] = m i n { d i s [ y ] , d i s [ x ] + e d [ x ] [ y ] } dis[y]=min\{dis[y],dis[x]+ed[x][y]\} dis[y]=min{dis[y],dis[x]+ed[x][y]}。因为可能把距离调小,所以这个更新操作叫做松弛操作。
- 重复3,4两步,直到目标点也加入了集合,此时目标点所对应的d[i]即为最短路径长度。
用优先队列(堆)优化的情况下,可以大大减小复杂度。
代码
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <string>
#include <cstring>
#include <map>
#include <queue>
#include <stack>
using namespace std;
typedef long long LL;
const int N = 100007;
const int mod = 1000000007;
const double pi = acos(-1);
const double db = 1;
const int INF = 0x3f3f3f3f;
#define endl '\n';
LL read()
{
LL x = 0, w = 1;
char ch = 0;
while (ch < '0' || ch>'9')
{
if (ch == '-')
{
w = -1;
}
ch = getchar();
}
while (ch >= '0' && ch <= '9')
{
x = x * 10 + ch - '0';
ch = getchar();
}
return w * x;
}
struct nod
{
int u, v, w;
int next;
}ed[N*2];//边数
int cnt, head[N], dis[N];//点数
int n, m, s;
//前项星存图
void add(int x, int y, int w)
{
ed[++cnt].u = x;
ed[cnt].v = y;
ed[cnt].w = w;
ed[cnt].next = head[x];
head[x] = cnt;
}
//head[x]存的是最后一个起点为x的边的ed序号,上一个起点为x的边存在ed[head[x]].next里,存的是ed的序号(似乎用pre会更准确点?无所谓了)
struct nn
{
int u;
int d;
bool operator < (const nn &b)const//如果返回true,就把d排到b.d的后面,大于才是小到大?
{
return d > b.d;
}
};
priority_queue <nn> q;
stack <int> st;
void dij(int st)
{
for (int i = 1; i <= n; ++i)
{
dis[i] = INF;
}
nn now;
now.u = st;
now.d = 0;
dis[st] = 0;
q.push(now);
while (!q.empty())
{
now = q.top();
q.pop();
//如果当前的边权值比dis该边大,那就没必要算了,怎么算都不会小的
if (now.d > dis[now.u])
{
continue;
}
for (int i = head[now.u]; i != 0; i = ed[i].next)
{
if (dis[ed[i].v] > dis[now.u] + ed[i].w)//松弛操作
{
dis[ed[i].v] = dis[now.u] + ed[i].w;
nn tmp;
tmp.u = ed[i].v;
tmp.d = dis[ed[i].v];
q.push(tmp);
}
}
}
}
int main()
{
std::ios::sync_with_stdio(0);
std::cin.tie(0);
std::cout.tie(0);
cin >> n >> m >> s;
cnt = 0;
for (int i = 1; i <= m; ++i)
{
int vi, ui, wi;
cin >> ui >> vi >> wi;
add(ui, vi, wi);//前项星加边
}
dij(1);
for (int i = 1; i <= n; ++i)
{
cout << dis[i] << ' ';
}
return 0;
}