题目描述:
One cow from each of N farms (1 ≤ N ≤ 1000) conveniently numbered 1..N is going to attend the big cow party to be held at farm #X (1 ≤ X ≤ N). A total of M (1 ≤ M ≤ 100,000) unidirectional (one-way roads connects pairs of farms; road i requires Ti (1 ≤ Ti ≤ 100) units of time to traverse.
Each cow must walk to the party and, when the party is over, return to her farm. Each cow is lazy and thus picks an optimal route with the shortest time. A cow's return route might be different from her original route to the party since roads are one-way.
Of all the cows, what is the longest amount of time a cow must spend walking to the party and back?
输入:
Line 1: Three space-separated integers, respectively: N, M, and X
Lines 2..M+1: Line i+1 describes road i with three space-separated integers: Ai, Bi, and Ti. The described road runs from farm Ai to farm Bi, requiring Ti time units to traverse.
输出:
Line 1: One integer: the maximum of time any one cow must walk
输入样例:
4 8 2 1 2 4 1 3 2 1 4 7 2 1 1 2 3 5 3 1 2 3 4 4 4 2 3
输出样例:
10
解题思路:
两结点之间来回的距离问题,要建立一个正向图和一个反向图,把终点作为源点,找出正向和反向的最短路径,然后找出每个顶点的两个最短路径加和的最大值。
代码实现:
#include <iostream>
#include <queue>
using namespace std;
#define maxn 1005
#define maxe 100005
int dis[maxn], rdis[maxn];
bool vis[maxn];
int n, m, x;
int head[maxn], rhead[maxn], cnt, rcnt;
class Edge
{
public:
int to;
int weight;
int next;
};
Edge edge[maxe], redge[maxe];
void InsertEdge(int* h, int& c, Edge* e, int u, int v, int w)
{
e[++c].to = v;
e[c].weight = w;
e[c].next = h[u];
h[u] = c;
}
void CreateG()
{
int u, v, w;
cin >> n >> m >> x;
for (int i = 1; i <= m; i++)
{
cin >> u >> v >> w;
InsertEdge(head, cnt, edge, u, v, w);
InsertEdge(rhead, rcnt, redge, v, u, w);
}
}
void SPFA(int* d, int* h, Edge* e)
{
memset(d, 0x3f3f, maxn * sizeof(int));
memset(vis, false, sizeof(vis));
queue<int> q;
d[x] = 0;
q.push(x);
vis[x] = true;
while (!q.empty())
{
int t = q.front();
q.pop();
vis[t] = false;
for (int i = h[t]; i; i = e[i].next)
{
int v = e[i].to;
if (d[v] > d[t] + e[i].weight)
{
d[v] = d[t] + e[i].weight;
if (!vis[v])
{
q.push(v);
vis[v] = true;
}
}
}
}
}
int main()
{
CreateG();
SPFA(dis, head, edge);
SPFA(rdis, rhead, redge);
int max = 0;
/*for (int i = 1; i <= n; i++)
{
cout << dis[i] << " " << rdis[i] << endl;
}*/
for (int i = 1; i <= n; i++)
{
if (i != x && max < dis[i] + rdis[i])
{
max = dis[i] + rdis[i];
}
}
cout << max << endl;
return 0;
}