:
|朴素dijkstra算法 O(n^2);
|所有边权为正数|堆优化版dijkstra算法 O(mlogn)
|单源最短路|
最短路| |存在负权边|Bellman-ford算法 O(nm)
| |spfa 一般o(m) 最坏O(nm)
|多汇源最短路 Floyd算法O(n^3)
spfa求最短路:
//与dijkstra堆优化代码可结合起来背
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
typedef pair<int,int> PII;
const int N=1e6+10;
int dist[N];
bool st[N];//当前已经确定最短距离的点
int n,m;
int h[N],e[N],ne[N],w[N],idx;
void add(int a,int b,int c)
{
e[idx]=b,w[idx]=c,ne[idx]=h[a],h[a]=idx++;
}
int spfa()
{
memset(dist,0x3f,sizeof dist);
dist[1]=0;
queue<int> q;
q.push(1);
st[1]=true;
while (q.size())
{
auto t = q.front();
q.pop();
st[t]=false;
for (int i=h[t];i!=-1;i=ne[i])
{
int j=e[i];
if (dist[j]>dist[t]+w[i])
{
dist[j]=dist[t]+w[i];
if(!st[j])
{
q.push(j);
st[j]=true;
}
}
}
}
return dist[n];
}
int main()
{
cin>>n>>m;
memset(h,-1,sizeof h);
while(m--)
{
int a,b,c;
cin>>a>>b>>c;
add(a,b,c);
}
int t=spfa();
if(t==0x3f3f3f3f) cout<<"impossible"<<endl;
else cout<<t<<endl;
return 0;
}
spfa判断负环:
给定一个 n 个点 m 条边的有向图,图中可能存在重边和自环, 边权可能为负数。
请你判断图中是否存在负权回路。
//判断最短路的边数,如果>n说明存在负环
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
typedef pair<int,int> PII;
const int N=1e6+10;
int dist[N],cnt[N];
bool st[N];//当前已经确定最短距离的点
int n,m;
int h[N],e[N],ne[N],w[N],idx;
void add(int a,int b,int c)
{
e[idx]=b,w[idx]=c,ne[idx]=h[a],h[a]=idx++;
}
int spfa()
{
queue<int> q;
for(int i=1;i<=n;i++)
{
q.push(i);
st[i]=true;
}
while (q.size())
{
auto t = q.front();
q.pop();
st[t]=false;
for (int i=h[t];i!=-1;i=ne[i])
{
int j=e[i];
if (dist[j]>dist[t]+w[i])
{
dist[j]=dist[t]+w[i];
cnt[j]=cnt[t]+1;
if(cnt[t]>n) return true;
if(!st[j])
{
q.push(j);
st[j]=true;
}
}
}
}
return false;
}
int main()
{
cin>>n>>m;
memset(h,-1,sizeof h);
while(m--)
{
int a,b,c;
cin>>a>>b>>c;
add(a,b,c);
}
if(spfa()) puts("Yes");
else puts("No");
return 0;
}