Solution P1744

· · 题解

\texttt{Update:}

这题就是一道SPFA裸题啊。。本蒟蒻在此讲解一下SPFA的做法。

SPFA的时间复杂度:

最好:O(m)

最坏:O(n*m)

不稳定的。

SPFA的思路如下:

思路就是上面这亚子。一句话概括就是:

Spfa就是定义一个队列,将所有有可能能优化最短路的点全都放进去,最后拿出来一个个判断就可以了

SPFA的模板带注释(不是这题答案):

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
int n,m,h[N],e[N],ne[N],dist[N],w[N],idx;
bool st[N];
void add(int a,int b,int c)
{
    e[idx]=b;w[idx]=c;ne[idx]=h[a];h[a]=idx++;
}//邻接表存储
void Spfa()
{
    memset(dist,0x3f,sizeof dist);
    dist[1]=0;
    queue<int> q;
    q.push(1);
    st[1]=true;
    while(!q.empty())
    {
        int t=q.front();//取出来
        q.pop();
        st[t]=false;
        for(int i=h[t];i!=-1;i=ne[i])//所有相邻的
        {
            int j=e[i];
            if(dist[j]>dist[t]+w[i])//如果更优
            {
                dist[j]=dist[t]+w[i];//更新
                if(!st[j])//不在队列里面
                {
                    q.push(j);//放进去
                    st[j]=true; //标记已在队列里
                }   
            }   
        }   
    }
}
int main()
{
    cin>>n>>m;
    memset(h,-1,sizeof h);
    while(m--)
    {
        int a,b,c;
        cin>>a>>b>>c;
        add(a,b,c);//建一条边
    }
    Spfa();//调用
    if(dist[n]==0x3f3f3f3f) cout<<"impossible";//如果不行输出impossible
    else cout<<dist[n];
    return 0;
}
/**
 * 注意:此模板默认1->n
 * 如果想自定义起点终点,把其中的1改成起点,输出改成终点就可以了
 * 
 *
 * 这个模板在我的CSDN博客上也有。
 * 链接:https://blog.csdn.net/user_qym/article/details/104107107
 */

标注:以上模板来自 AcWing

好了,这题就是把SPFA稍微改一改就行了。

上代码!!(无注释,上面都有):

#include<bits/stdc++.h>
using namespace std;
const int N=110,M=1010;
int h[N*2],e[M*2],ne[M*2],n,m,x[N*2],y[N*2],s,end,idx;
double w[M*2],dist[N*2];
bool st[N*2];
double distance(int x1,int y1,int x2,int y2)
{
    return sqrt(abs(x1-x2)*abs(x1-x2)+abs(y1-y2)*abs(y1-y2));
}
void add(int a,int b,double c)
{
    e[idx]=b,w[idx]=c,ne[idx]=h[a],h[a]=idx++;
}
void spfa()
{
    for(int i=1;i<=n;i++) dist[i]=1000000000.0;
    dist[s]=0;
    queue<int> q;
    q.push(s);
    st[s]=true;
    while(!q.empty())
    {
        int t=q.front();
        q.pop();
        st[t]=false;
        for(int i=h[t];i!=-1;i=ne[i])
        {
            int j=e[i];
            if(dist[j]>dist[t]+w[i])
            {
                dist[j]=dist[t]+w[i];
                if(!st[j])
                {
                    st[j]=true;
                    q.push(j);
                }
            }
        }
    }
    cout<<fixed<<setprecision(2)<<dist[end];
}
int main()
{
    cin>>n;
    memset(h,-1,sizeof h);
    for(int i=1;i<=n;i++) cin>>x[i]>>y[i];
    cin>>m;
    while(m--)
    {
        int a,b;
        cin>>a>>b;
        add(a,b,distance(x[a],y[a],x[b],y[b])),add(b,a,distance(x[a],y[a],x[b],y[b]));
    }
    cin>>s>>end;
    spfa();
    return 0;
}

走之前别忘了点赞哟~