浅谈最短路常用的三种求法

浅谈最短路常用的三种求法

前言:

​ 最短路是图论的基本算法之一,常用到三种算法: d i j k s t r a dijkstra dijkstra , S P F A SPFA SPFA , F l o y d Floyd Floyd

1. d i j k s t r a dijkstra dijkstra:

数组介绍:

d i s [ i ] dis[i] dis[i]表示 i i i到起点最短路权值

v i s [ i ] vis[i] vis[i]表示 i i i点是否被扩展过

原理:

​ 1.找到距离起点最近的点

2.扩展该点

优劣点分析:

优:适用于稠密图、稀疏图,时间复杂度低

劣:无法处理负权值图

方法1:矩阵

a[i][j]表示由i指向j的道路的权值

例: V I J O S − P 1635 VIJOS-P1635 VIJOSP1635 城市连接

D e s c r i p t i o n Description Description

天网恢恢,疏而不漏,经过上一次的抓捕, O I OI OI总部终于获取了怪盗的特征!现在,我们需要在基德再次来之前就把他的特征送到超级大牛的手上,可惜超级大牛不在总部.所以飞过海必须尽快把资料送到大牛家里.已知 O I OI OI总部到大牛家中间有 n − 2 n-2 n2个城城市,为了尽快达到目的地,飞过海通过水晶球(够先进吧)了解到 O I OI OI总部到大牛家的路线图,图上显示了 n n n个城之间的连接距离。 可是飞过海很忙,需要请你来帮忙写个程序.

I n p u t Input Input

第一行 n n n

第二行到第 n + 1 n+1 n+1行 每行 n n n个数字 (第 i + 1 i+1 i+1行,表示第 i i i个城市与其他城市之间的连接关系 0 0 0表示不连接 其他数字表示连接的距离 )

O u t p u t Output Output

1 1 1 n n n个用空格间隔的整数 表示所选的线路

2 2 2行 一个数字 最短距离

S a m p l e   I n p u t Sample\ Input Sample Input

7 0 3 5 0 0 0 0 0 0 0 7 8 6 0 0 0 0 0 4 5 0 0 0 0 0 0 0 4 0 0 0 0 0 0 7 0 0 0 0 0 0 6 0 0 0 0 0 0 0

S a m p l e   O u t p u t Sample\ Output Sample Output

1 2 4 7 14
H I N T HINT HINT

n < = 1000 n<=1000 n<=1000

代码如下

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<cstring>
int const inf=1000000ll;
int a[1001][1001];//城市i到城市j的距离
int dis[1001];//从起点到i的最短距离
int from[1001];//i是有谁来的
bool vis[1001];//i是否被扩展过 
int main()
{
    int n;
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++)
            scanf("%d",&a[i][j]);
    }
    //read over;
//  check();
    memset(dis,inf,sizeof(dis));    
    dis[1]=0;
    for(int i=1;i<=n;i++)
    {
        int f=inf;//极大值 
        int idx;//最小的下标 
        for(int j=1;j<=n;j++)
        {
            if(dis[j]<f&&vis[j]!=1)
            {
                f=dis[j];
                idx=j;
            }   
        }       
        if(idx==n)
        break;
        for(int j=1;j<=n;j++)
        {
            if(vis[j]!=1&&a[idx][j]!=0)//未被走过且能走到 
            {
                if(a[idx][j]+dis[idx]<dis[j])
                {
                    from[j]=idx;
                    dis[j]=a[idx][j]+dis[idx];
                }   
            }
        }   
        vis[idx]=1; 
    }
/*  for(int i=1;i<=n;i++)
    printf("%d ",from[i]);
    printf("\n");
    for(int i=1;i<=n;i++)
    printf("%d ",dis[i]);
*/
    int out[1001];
    int pos=n;
    int cnt=1;
    while(pos!=1)
    {
        out[cnt++]=from[pos];
        pos=from[pos];
    }
    for(int i=cnt-1;i>=1;i--)
    printf("%d ",out[i]);
    printf("%d \n%d",n,dis[n]);
}
方法2:连接表

连接表类似于哈希挂链

h e a d [ i ] head[i] head[i]表示以i为起点的路的链上的第一个元素

v [ i ] v[i] v[i]表示第i条路的权值

t o [ i ] to[i] to[i]表示第i条路指向谁

n x t [ i ] nxt[i] nxt[i]表示第i条路的下一条路是谁

常见建边的方式

void add(int x,int y,int z)
{
  to[++tot]=y;
  v[tot]=z;
  nxt[tot]=head[x];
 head[x]=tot;      
}
例:城市连接

代码如下

#include<stdio.h>
#include<algorithm>
#include<cstring>
int n;
struct node{
    int v,to,nxt;
}r[1000001];
int h[10001];
int tot=0;
bool vis[10001];
int dis[10001];
int from[10001];
int const inf=1000000l;
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)    
    {
        for(int j=1;j<=n;j++)
        {
            int x;
            scanf("%d",&x);
            if(x!=0)
            {
            r[++tot].v=x;
            r[tot].to=j;
            r[tot].nxt=h[i];
            h[i]=tot;
            }               
        }
    }
    //read over;
    memset(dis,0x3f3f3f,sizeof(dis));
    dis[1]=0;
    for(int i=1;i<=n;i++)
    {
        int f=inf;
        int idx=0;
        for(int j=1;j<=n;j++)
        {
            if(dis[j]<f&&vis[j]!=1)
            {
                f=dis[j];
                idx=j;      
             

            }
        }   
        vis[idx]=1; 
        if(idx==n)
        break;
        for(int j=h[idx];j>0;j=r[j].nxt)
        {
            int y=r[j].to;
            if(vis[y]!=1)
            {
                if(dis[y]>r[j].v+dis[idx])
                {
                dis[y]=r[j].v+dis[idx];
                from[y]=idx;
                }
            }
         
        }
     
    }
     int out[1001];
    int pos=n;
    int cnt=1;
    while(pos!=1)
    {
        out[cnt++]=from[pos];
        pos=from[pos];
    }
     for(int i=cnt-1;i>=1;i--)
    printf("%d ",out[i]);
    printf("%d \n%d",n,dis[n]);

}
方法3:优化版dij
原理:
对两个操作进行优化

1.对于寻找dis最小的点,使用小根堆

2.遍历边时使用连接表

例:短

D e s c r i p t i o n Description Description

给出无向图 G = ( V , E ) G=(V,E) G=(V,E),求点 V 1 V1 V1和点 V N VN VN之间的最短路。

I n p u t Input Input

第一行两个整数 ∣ V ∣ |V| V ∣ E ∣ |E| E

2 2 2~ E + 1 E+1 E+1行,每行 3 3 3个整数 X i , Y i , W i Xi,Yi,Wi Xi,Yi,Wi,表示点 V x i Vxi Vxi和点 V y i Vyi Vyi之间存在权值为 W i Wi Wi的边。

O u t p u t Output Output

一个整数表示最短路的权值。

S a m p l e I n p u t Sample Input SampleInput

3 3 1 2 1 2 3 1 3 1 1
S a m p l e O u t p u t Sample Output SampleOutput

1 1 1
H I N T HINT HINT

对于 50 50 50%的数据, V < = 103 V<=103 V<=103

对于 100 100 100%的数据, V < = 105 , E < = 106 , 1 < = W i < = 2 。 V<=105,E<=106,1<=Wi<=2。 V<=105E<=1061<=Wi<=2

代码如下

#include<stdio.h>
#include<algorithm>
#include<cstring>
using namespace std;
int v[2000001];
int nxt[2000001];
int to[2000001];
int head[100001];
int dis[100001];
bool vis[100001];
int a[2000001];
int tot=0;  
int n,m;
int cnt=0;
int S,T;
void restart()
{
    memset(dis,0x3f3f3f3f,sizeof(dis));
    dis[S]=0;
      
}
void pop()
{
    std::swap(a[1],a[cnt]);
    cnt--;
    int pos=1;
    while(pos*2<=cnt)
    {
            int x=pos*2;
            int y=x+1;
              

            if(y>cnt)
            {           
                    if(dis[a[x]]<dis[a[pos]])
                    swap(a[x],a[pos]),pos=x;
                    else
                    break;
            }
            else
            {
                if(dis[a[pos]]>dis[a[x]]||dis[a[pos]]>dis[a[y]])
                {
                if(dis[a[x]]>dis[a[y]])
                swap(a[y],a[pos]),pos=y;
                else
                swap(a[x],a[pos]),pos=x;
                }
                else
                break;
            }
    }       

}
void push(int x)
{
    a[++cnt]=x;
    int pos=cnt;
    while(pos!=1&&dis[a[pos]]<dis[a[pos/2]])
    {
        std::swap(a[pos],a[pos/2]);     
        pos/=2;
    }   
}
void dij()
{
     

    for(int i=S;i<=T&&cnt!=0;i++)
    {
        while(vis[a[1]]==1)
        pop();
        int idx=a[1];
        pop();
        for(int j=head[idx];j;j=nxt[j])
        {
                int y=to[j];
            if(dis[y]>dis[idx]+v[j])
            dis[y]=dis[idx]+v[j],push(y);//,check();;
        }
      
        vis[idx]=1;     
    }

}void add(int x,int y,int z)
{
    v[++tot]=z;
    to[tot]=y;
    nxt[tot]=head[x];
    head[x]=tot;
}
int main()
{

    scanf("%d%d",&n,&m);
    S=1,T=n;
    for(int i=1;i<=m;i++)
    {
        int x,y,z;
        scanf("%d%d%d",&x,&y,&z);
        add(x,y,z);                 
        add(y,x,z);
    }   

   restart();
    push(S);    
    dij();
    printf("%d",dis[T]);
}

2.SPFA

原理:

​ 1.调出队首元素

2.以该元素为起点,对所有能到的的点进行松弛

3.若被松弛点更新且不在队列中则将其放入队列

优劣点分析:

​ 优:可以处理负权值边

​ 劣:稠密图时间复杂度大

例:城市连接
#include<stdio.h>
#include<queue>
#include<cstring>
using namespace std;
#define MAX 1000000001ll
#define P 1001
#define C 1000001
queue<int>q;
int head[P],v[C],to[C],nxt[C];
int dis[P],from[P];
bool inQ[P];
int tot=0;  
int n;
void add(int x,int y,int z)
{
    v[++tot]=z;
    to[tot]=y;
    nxt[tot]=head[x];
    head[x]=tot;
}
void spfa()
{
    for(int i=1;i<=n;i++)
    dis[i]=MAX;
    dis[1]=0;
    q.push(1);
    inQ[1]=1;
    while(!q.empty())
    {
        int idx=q.front();
        inQ[idx]=0;
        q.pop();
        for(int i=head[idx];i;i=nxt[i])
        {
            int y=to[i];
            if(dis[y]>dis[idx]+v[i])
            {
                dis[y]=dis[idx]+v[i];
                from[y]=idx;
                if(inQ[y]==0)
                {q.push(y);
                inQ[y]=1;}
            }
        }
    }   
}
int main()
{

    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        int x;
        for(int j=1;j<=n;j++)
        {
            scanf("%d",&x);
            if(x==0)
            continue;
            else
            add(i,j,x);
        }
    }
     
    spfa();
    printf("1 ");
    int pos=n;
    int out[P];
    int cnt=0;
    while(pos!=1)
    {
        out[++cnt]=pos;
        pos=from[pos];  
    }
    for(int i=cnt;i>=1;i--)
    printf("%d ",out[i]);
    printf("\n%d",dis[n]);

}

3.Floyd

F [ i ] [ j ] F[i][j] F[i][j]表示由 i i i j j j的距离

原理

​ 1.枚举中间点

2.枚举起点

​ 3.枚举终点

​ 4.更新

优劣点分析:

优:可以维护出每两个点之间的距离

劣:时间复杂度高

例:USACO 2008 Open Silver 4.Clear And Present Danger

Description

Farmer John is on a boat seeking fabled treasure on one of the N
(1 <= N <= 100) islands conveniently labeled 1…N in the Cowribbean
Sea.

The treasure map tells him that he must travel through a certain
sequence A_1, A_2, …, A_M of M (2 <= M <= 10,000) islands, starting
on island 1 and ending on island N before the treasure will appear
to him. He can visit these and other islands out of order and even
more than once, but his trip must include the A_i sequence in the
order specified by the map.

FJ wants to avoid pirates and knows the pirate-danger rating (0 <=
danger <= 100,000) between each pair of islands. The total danger
rating of his mission is the sum of the danger ratings of all the
paths he traverses.

Help Farmer John find the least dangerous route to the treasure
that satisfies the treasure map’s requirement.

Input

  • Line 1: Two space-separated integers: N and M

  • Lines 2…M+1: Line i+1 describes the i_th island FJ must visit with
    a single integer: A_i

  • Lines M+2…N+M+1: Line i+M+1 contains N space-separated integers
    that are the respective danger rating of the path between
    island i and islands 1, 2, …, and N, respectively. The ith
    integer is always zero.

Output

  • Line 1: The minimum danger that Farmer John can encounter while
    obtaining the treasure.

Sample Input

3 4 1 2 1 3 0 5 1 5 0 2 1 2 0
Sample Output

7
HINT

INPUT DETAILS:

There are 3 islands and the treasure map requires Farmer John to
visit a sequence of 4 islands in order: island 1, island 2, island
1 again, and finally island 3. The danger ratings of the paths are
given: the paths (1, 2); (2, 3); (3, 1) and the reverse paths have
danger ratings of 5, 2, and 1, respectively.

OUTPUT DETAILS:

He can get the treasure with a total danger of 7 by traveling in
the sequence of islands 1, 3, 2, 3, 1, and 3. The cow map’s requirement
(1, 2, 1, and 3) is satisfied by this route. We avoid the path
between islands 1 and 2 because it has a large danger rating.

代码如下:

#include<stdio.h>
#include<cstring>
#define N 101
#define M 10001
#define inf 100000001
int pos[M];
int f[N][N];
int n,m;
int min(int x,int y)
{
    return x<y?x:y;
}
int main()
{
    scanf("%d%d",&n,&m);
memset(f,inf,sizeof(f));
    for(int i=1;i<=m;i++)
        scanf("%d",&pos[i]);        
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++)
        scanf("%d",&f[i][j]);
    }
    for(int k=1;k<=n;k++)
    {
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=n;j++)
            f[i][j]=min(f[i][j],f[i][k]+f[k][j]);
        }
    }       
    int ans=0;
    for(int i=1;i<m;i++)
    {
        ans+=f[pos[i]][pos[i+1]];
    }
    printf("%d",ans);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值