ACM_最短路模板(SPFA,Dijkstra,Floyd)

#define Max 0x3f3f3f3f
#define maxn 10010
int n,m;
int Map[maxn][maxn];
int dist[maxn];
int vist[maxn];

Floyd:

void floyd()
{
    int i,j,k;
    for (k=1; k<=n; k++)
        for(i=1; i<=n; i++)
            for (j=1; j<=n; j++)
                Map[i][j]=min( Map[i][j],Map[i][k]+Map[k][j] );

}

Dijkstra

void Dijkstra(int s)
{
    int i,j;
    int u;
    int Min;
    for (i=1; i<=n; i++)
    {
        vist[i]=0;
        dist[i] = Map[s][i];
    }
    vist[s] = 1;
    for (i=1; i<=n; i++)
    {
        Min=Max;
        u = -1;
        for (j=1; j<=n; j++)
        {
            if (vist[j]==0&&dist[j]<Min)
            {
                u = j;
                Min = dist[j];
            }
        }
        if (u==-1)
            break;
        vist[u] = 1;
        for (j=1; j<=n; j++)
        {
            if(vist[j]==0)
            {
                if(dist[u]+Map[u][j]<dist[j])
                    dist[j] = dist[u]+Map[u][j];
            }
        }
    }
}

SPFA

void spfa(int s)
{
    int i,now;
    for( i=1;i<=n;i++ )
    {
        dist[i]=Max;
        vist[i] = 0;
    }
    dist[s] = 0;
    queue<int>q;
    q.push(s);
    vist[s] = 1;
    while (!q.empty())
    {
        now = q.front();
        q.pop();
        vist[now] = 0;
        for( i=1;i<=n;i++)
        {
            if (dist[i]>dist[now]+Map[now][i])
            {
                dist[i] = dist[now]+Map[now][i];
                if (vist[i] == 0)
                {
                    q.push(i);
                    vist[i] = 1;
                }
            }
        }
    }

}
    原文作者:Dijkstra算法
    原文地址: https://blog.csdn.net/changjiale110/article/details/77394650
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞