最短路模板

来源:互联网 发布:js防水涂料与水泥结合 编辑:程序博客网 时间:2024/06/05 11:50

Bellman-Fold算法:
不断去尝试 每一条边是否能更新点到点之间的距离

#include<iostream>#include<math.h>#include<cstring>#include<algorithm>using namespace std;const int maxn;struct edge{    int from,to,cost;};edge es[maxn];int d[maxn];int V,E;const int INF=0x7fffffff;void shortest_path(int s){    for(int i = 0;i < V;i++)        d[i] = INF;    d[s] = 0;    while(true)    {        bool update = false;        for(int i = 0;i < E;i++)        {            edge e=es[i];            if(d[e.from] != INF &&d[e.to] > d[e.from] + e.cost)            {                d[e.to] = d[e.from] + e.cost;                update = true;            }        }        if(!update)            break;    }}int main(){    return 0;}

如果不存在负圈那么最短路不不会经过同一个顶点两次最多通过V-1条边执行次数超过V-1则有负。因此可以用这个性质来检查负圈。如果一开始对所有顶点i,d[i]=0则可以检查出所有负圈
Dijkstra算法:

#include<iostream>#include<math.h>#include<cstring>#include<algorithm>using namespace std;int cost[maxv][maxv];int d[maxv];bool used[maxv];int V;const int INF=0x7fffffff;void dijkstra(int s){    fill(d,d+V,INF);    fill(used,used+V,false);    d[s]=0;    while(true)    {        int v=-1;//从未使用的顶点找出一个距离最小的点(d[i]不会在之后的更新中变小,最短距离已经确定)        for(int u=0;u<V;u++)        {            if(!used[u] && (v == -1) || d[u]<d[v])                v=u;        }        if(v==-1)            break;        used[v]=true;        for(int u=0;u<V;u++)            d[u]=min(d[u],d[v]+cost[v][u]);//一般化更新向外扩展    }}int main(){    return 0;}

堆优化:

#include<iostream>#include<math.h>#include<cstring>#include<algorithm>#include<queue>using namespace std;const int maxn=;const int INF=0x7fffffff;struct edge{    int to,cost;};typedef pair<int,int > P;int V;vector<edge> G[maxn];int d[maxn];void dijkstra(int s){    priority_queue<P,vector<P>,greater<P> > que;//greate指定从小到大    fill(d,,d+V,INF);    d[s]=0;    que.push(P(0,s));    while(!que.empty())    {        P p=que.top();        que.pop();        int v=p.second;        if(d[v]<p.first)            continue;        for(int i=0;i<G[v].size();i++)        {            edge e=G[v][i];            if(d[e.to]>d[v]+e.cost)             {                d[e.to]=d[v]+cost;             que.push(P(d[e.to],e.to));             }        }    }}//N>logNint main(){    return 0;}//复杂度为O(e*logV)

Floyd-Warshall:不断尝试通过第三方点是否能转移

#include<iostream>#include<math.h>#include<cstring>#include<algorithm>using namespace std;const int maxn=;int main(){    int V;    int d[maxn][maxn];//d[i][i]=0;不存在为INF    for(int k=0;k<V;k++)        for(int i=0;i<V;i++)            for(int j=0;j<V;j++)                d[i][j]=min(d[i][k]+d[k][j],d[i][j]);    return 0;}
原创粉丝点击