poj3268 spfa 最短路

题目链接:点击打开链接


题意:

给定一个有向图;

问每头牛到固定地点聚会的花费加上回家的花费之和最大的花费是多少;

其中去和回都是最小的花费;


理解:

此题看上去可以先算回去的最小花费;

但是每头牛来的最小花费怎么算呢?

由于这个图是有向图;

如果把方向翻转了,那么去就是回,回就是去;

再算一次最短路就可以求出每头牛去和回的最短路之和了;

那么两次spfa就可以了;


代码如下:


#include <cstdio>
#include <cstring>
#include <cmath>

#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <algorithm>

using namespace std;

typedef long long LL;

const int MAXN = 1e6 + 10;
const int MOD = 1e9 + 7;
const int INF = 0x7fffffff;
const int N = 10000000;

typedef pair<int, int> PII;

#define X first
#define Y second

const int MAXE = MAXN;
const int MAXV = 1011;

struct node {
    int to, next, cost;
}e[MAXE];

int head[MAXV], tot;
int n, m;

void init() {
    memset(head, -1, sizeof head);
    tot = 0;
}

void add_edge(int u, int v, int cost) {
    e[tot].to = v;
    e[tot].next = head[u];
    e[tot].cost = cost;
    head[u] = tot++;
}

int dis[2][MAXV];
int outque[MAXV];
bool vis[MAXV];

bool spfa(int s, int t) {
    for (int i = 1; i <= n; ++i) {
        vis[i] = false;
        dis[t][i] = INF;
        outque[i] = 0;
    }

    queue<int> que;
    que.push(s);
    dis[t][s] = 0;
    vis[s] = true;
    while (!que.empty()) {
        int u = que.front();
        que.pop();
        vis[u] = false;
        if (++outque[u] > n) {
            return false;
        }
        for (int i = head[u]; i != -1; i = e[i].next) {
            int v = e[i].to;
            if (dis[t][v] <= dis[t][u] + e[i].cost) {
                continue;
            }
            dis[t][v] = dis[t][u] + e[i].cost;
            if (vis[v] == true) {
                continue;
            }
            vis[v] = true;
            que.push(v);
        }
    }
    return true;
}

int edge[MAXV][MAXV];

int main() {
    int x;
    cin >> n >> m >> x;
    memset(edge, -1, sizeof edge);
    for (int i = 0; i < m; ++i) {
        int u, v, cost;
        scanf("%d%d%d", &u, &v, &cost);
        edge[u][v] = cost;
    }
    init();
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= n; ++j) {
            if (edge[i][j] != -1) {
                add_edge(i, j, edge[i][j]);
            }
        }
    }
    spfa(x, 0);
    
    init();
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= n; ++j) {
            if (edge[i][j] != -1) {
                add_edge(j, i, edge[i][j]);
            }
        }
    }
    spfa(x, 1);

    int ans = -1;
    for (int i = 1; i <= n; ++i) {
        ans = max(ans, dis[0][i] + dis[1][i]);
    }
    cout << ans << endl;

    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值