最短路(两种常用算法!!!)

https://www.cnblogs.com/chuninggao/p/7301083.html 

SPFA算法(邻接表):

#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
const int maxn = 4010;
const int MAX = 0x3f3f3f3f;
int dis[maxn];
int n, m, head[maxn], d[maxn], time[maxn];
bool visit[maxn];
struct node
{
    int u, v, w, next;
}mp[maxn];
bool sfpa(int s, int n)
{
    for(int i=1; i<=n; i++)
    {
        dis[i]= MAX;
    }
    queue<int>q;
    int x;
    memset(visit, 0, sizeof(visit));
    memset(time, 0, sizeof(time));
    visit[s] = 1;
    dis[s] = 0;
    q.push(s);
    while(!q.empty())
    {
        x = q.front();q.pop();
        visit[x] = 0;
        for(int i=head[x]; i!=-1; i = mp[i].next)
        {
            if(dis[mp[i].v]>dis[x]+mp[i].w)
            {
                dis[mp[i].v]=dis[x]+mp[i].w;
                if(!visit[mp[i].v])
                {
                    visit[mp[i].v] = 1;
                    q.push(mp[i].v);
                    if(++time[mp[i].v]>=n)
                        return 1;
                }
            }
        }
    }
    printf("%d\n", dis[n]);
    return 0;
}
int main()
{
    int n, m, a, b, c, top;
    scanf("%d%d", &m,&n);
    top = 0;
    memset(head, -1, sizeof(head));
    for(int i=1; i<=m; i++)
    {
        scanf("%d%d%d", &a, &b, &c);
        mp[top].u = a;
        mp[top].v = b;
        mp[top].w = c;
        mp[top].next = head[a];
        head[a] = top++;

        mp[top].u = b;
        mp[top].v = a;
        mp[top].w = c;
        mp[top].next = head[b];
        head[b] = top++;
    }
    sfpa(1, n);
    return 0;
}
Dijkstra算法(邻接表+队列优化):

struct point  
{  
    int val,id;  
    point(int id,int val):id(id),val(val){}  
    bool operator <(const point &x)const{  
        return val>x.val;  
    }  
};  
void dijkstra(int s)  
{  
    memset(vis,0,sizeof(vis));  
    for(int i=0;i<n;i++)  
        dis[i]=INF;   
  
    priority_queue<point> q;  
    q.push(point(s,0));  
    dis[s]=0;  
    while(!q.empty())  
    {  
        int cur=q.top().id;  
        q.pop();  
        if(vis[cur]) continue;  
        vis[cur]=true;  
        for(int i=head[cur];i!=-1;i=e[i].next)  
        {  
            int id=e[i].to;  
            if(!vis[id] && dis[cur]+e[i].val < dis[id])  
            {  
                dis[id]=dis[cur]+e[i].val;  
                q.push(point(id,dis[id]));  
            }  
        }         
    }  
} 

猜你喜欢

转载自blog.csdn.net/weixin_42137874/article/details/82751230
今日推荐