多源点最短路径

给出s个起点,给出t个终点,求出所有起点到终点的最短路中的最短的一个.

构建一个超级源点,与每一个起点相连,权值为0;构建一个超级终点,与每一个终点相连,权值为0。然后求超级源点到超级终点的最短路径。

#include<iostream>
#include<queue>
using namespace std;

int first[1010], dist[1010];
int point[202010], weight[202010], next[202010];
int q[50000];
bool f[1010];
int n,m,s,t,tot;

void addEdge(int x, int y, int w)  //边集数组保存图
{
    tot++;
    point[tot] = y;
    next[tot] = first[x];
    first[x] = tot;
    weight[tot] = w;

    tot++;
    point[tot] = x;
    next[tot] = first[y];
    first[y] = tot;
    weight[tot] = w;
}

void spfa_slf()
{
    int h = 0;
    int t = 0;
    q[t] = 0; f[0] = true;
    while (h <= t)
    {
        int now = q[h];
        h++;
        f[now] = false;
        int k = first[now];
        while (k != 0)
        {
            int New = point[k];
            if (dist[now] + weight[k] < dist[New])
            {
                dist[New] = dist[now] + weight[k];
                if (!f[New])
                {
                    t++;
                    q[t] = New;
                    f[New] = true;
                }
            }
            k = next[k];
        }
    }
}

int main()
{
    while (cin>>n>>m>>s>>t && n && m && s && t)
    {
        tot = 0;
        for (int i=1; i<=m; i++)
        {
            int x, y, w;
            cin>>x>>y>>w;
            addEdge(x,y,w);
        }
        for (int i=1; i<=s; i++)  //构建超级源点
        {
            int x;
            cin>>x;
            addEdge(0,x,0);
        }
        for (int i=1; i<=t; i++)  //构建超级终点
        {
            int x;
            cin>>x;
            addEdge(x,n+1,0);
        }

        for (int i=0; i<=n+1; i++)
        {
            dist[i] = (1<<30);
            f[i] = false;
        }
        dist[0] = 0;
        spfa_slf();  //spfa求最短路径
        if (dist[n+1] < (1<<30))
            cout<<dist[n+1]<<endl;
        else
            cout<<"What a pity!"<<endl;

        for (int i=0; i<=n+1; i++)
            first[i] = dist[i] = f[i] = 0;
        for (int i=0; i<=tot; i++)
            point[i] = next[i] = weight[i] = 0;
    }

    return 0;
}


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值