Shortest path algorithm

34. Shortest path algorithm

1. Floyd Alogrithm

#include<bits/stdc++.h>
using namespace std;
#define maxn 20010
#define inf 100000000
int n,m,s;
int mp[maxn][maxn];
int main()
{
    cin>>n>>m>>s;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++)
        {
            if(i!=j)
            mp[i][j]=inf;
            else
            mp[i][i]=0;
        }
    }
    int x,y,z;
    for(int i=1;i<=m;i++)
    {
        cin>>x>>y>>z;
        //if(x>y) swap(x,y);
        mp[x][y]=min(z,mp[x][y]);
    }
    for(int k=1;k<=n;k++)
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++)
        {
            mp[i][j]=min(mp[i][j],mp[i][k]+mp[k][j]);
        }
    }
    for(int i=1;i<=n;i++)
    printf("%d ",mp[s][i]);
    return 0;
}

2. Dijkstra Algorithm

#include<bits/stdc++.h>
using namespace std;
#define maxn 100005
#define inf 2147483647
int n,m,s,cnt,G[maxn];
long long ans[1000000];
bool vis[1000000];
typedef struct edgenode
{
    int adjvex;
    int w;
    int next;
}edge[1000000];
edge e;
void addedge(int x,int y,int z)
{
    e[++cnt].adjvex = y;
    e[cnt].w=z;
    e[cnt].next=G[x];
    G[x]=cnt;
}
int main()
{
    cin>>n>>m>>s;
    int x,y,wt;
    for(int i=1;i<=m;i++)
    {
        ans[i] = inf;
    }
    ans[s]=0;
    for(int i=1;i<=m;i++)
    {
        cin>>x>>y>>wt;
        addedge(x,y,wt);
    }
    while(vis[s]==false)
    {
        long long minn = inf;
        vis[s]=true;
        for(int i = G[s];i!=0;i=e[i].next)
        {
            if(!vis[e[i].adjvex]&&ans[e[i].adjvex]>ans[s]+e[i].w)
            {
                ans[e[i].adjvex]=ans[s]+e[i].w;
            }
        }
        for(int i=1;i<=n;i++)
        {
            if(!vis[i]&&ans[i]<minn)
            {
                minn = ans[i];
                s= i;
            }
        }
    }
    for(int i=1;i<=n;i++)
        cout<<ans[i]<<" ";
    return 0;
}

3. The question for the algorithm

Question Link:https://www.luogu.com.cn/problem/P3371

The Floyd Algorithm only gain the 70 % scores and the Dijkstra algorithm can gain the 100 % scores!

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页