zoj 2008 单源最短路 SPFA

/*
题意:一个有向带权图,求1到所有点的最小权值,再求所有点到1的最小权值

题解:典型单源最短路,用SPFA实现,要求1分别为起点和终点时的最小权值和,
当1为终点时只需将图建立一个反向图,即可将终点当作起点计算
*/
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>

#define Max 1000000001

using namespace std;

typedef struct
{
    int pr;
    int to;
}node;

int p;

vector<node> G[1000005],G0[1000005];
int dist[1000005];
bool vis[1000005];

void spfa(int start)
{
    for(int i=0; i<=p; i++)
    {
        dist[i] = Max;
        vis[i] = false;
    }
    queue<int> Q;
    dist[start] = 0;
    vis[start] = true;
    Q.push(start);
    while (!Q.empty())
    {
        int t = Q.front();
        Q.pop();
        for(int i=0; i<G[t].size(); i++)
        {
            if (dist[t]+G[t][i].pr < dist[G[t][i].to])
            {
                dist[G[t][i].to] = dist[t] + G[t][i].pr;
                if (!vis[G[t][i].to])
                {
                    Q.push(G[t][i].to);
                    vis[G[t][i].to] = true;
                }
            }
        }
        vis[t] = false;
    }
}

void spfa0(int start)
{
    for(int i=0; i<=p; i++)
    {
        dist[i] = Max;
        vis[i] = false;
    }
    queue<int> Q;
    dist[start] = 0;
    vis[start] = true;
    Q.push(start);
    while (!Q.empty())
    {
        int t = Q.front();
        Q.pop();
        for(int i=0; i<G0[t].size(); i++)
        {
            if (dist[t]+G0[t][i].pr < dist[G0[t][i].to])
            {
                dist[G0[t][i].to] = dist[t] + G0[t][i].pr;
                if (!vis[G0[t][i].to])
                {
                    Q.push(G0[t][i].to);
                    vis[G0[t][i].to] = true;
                }
            }
        }
        vis[t] = false;
    }
}

int main(void)
{
    int n,q,fr,to,price;
    cin >> n;
    while (n--)
    {
        cin >> p >> q;
        for(int i=0; i<=p; i++)
        {
            G[i].clear();
            G0[i].clear();
        }
        while (q--)
        {
            cin >> fr >> to >> price;
            node tmp;
            tmp.to = to;
            tmp.pr = price;
            G[fr].push_back(tmp);
            tmp.to = fr;
            G0[to].push_back(tmp);
        }
        spfa(1);
        int sum = 0;
        for(int i=1; i<=p; i++)
            sum += dist[i];
        spfa0(1);
        for(int i=1; i<=p; i++)
            sum += dist[i];
        cout << sum << endl;
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/toufu/p/3614968.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值