您的位置:首页 > 其它

poj3268 spfa 最短路

2016-11-19 10:40 162 查看
题目链接:点击打开链接

题意:

给定一个有向图;

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

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

理解:

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

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

由于这个图是有向图;

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

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

那么两次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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spfa 最短路