链接:http://poj.org/problem?id=3268
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 19500 | Accepted: 8907 |
Description
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?
Input
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.
Output
Sample Input
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
Sample Output
10
Hint
Cow 4 proceeds directly to the party (3 units) and returns via farms 1 and 3 (7 units), for a total of 10 time units.题意:给定n, m分别代表边数和点数, 下面m行包含三个数字a, b, c。代表有向边a到b的长度为c。
求max(§(1, n) + §(n, 1));
在求§(n, 1)的过程中, 我们反向建图, 求跑1到n的最短路径。代码:
#define _CRT_SBCURE_MO_DEPRECATE
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<cmath>
#include<algorithm>
#include<string>
#include<string.h>
#include<set>
#include<queue>
#include<stack>
#include<functional>
using namespace std;
const int maxn = 2000 + 10;
const int INF = 0x3f3f3f3f;
struct node {
int v, len;
node(int v = 0, int len = 0) :v(v), len(len) {}
bool operator < (const node &a)const { //距离从小到大排序
return len > a.len;
}
};
vector<node>G[maxn];
vector<node>T[maxn];
int dis1[maxn];
int dis2[maxn];
bool vis[maxn];
int n, m, x;
void init() {
for (int i = 0; i<maxn; i++) {
G[i].clear();
T[i].clear();
vis[i] = false;
dis1[i] = INF;
dis2[i] = INF;
}
}
void dijkstra_heap(vector<node>G[], int dis[],int s) {
memset(vis, false, sizeof(vis));
priority_queue<node>Q;
Q.push(node(s, 0));//加入队列并排序
dis[s] = 0;
while (!Q.empty()) {
node now = Q.top(); //取出当前最小的
Q.pop();
int v = now.v;
if (vis[v]) continue; //如果标记过了 直接continue
vis[v] = true;
for (int i = 0; i<G[v].size(); i++) { //更新
int v2 = G[v][i].v;
int len = G[v][i].len;
if (!vis[v2] && dis[v2] > dis[v] + len) {
dis[v2] = dis[v] + len;
Q.push(node(v2, dis[v2]));
}
}
}
}
int main()
{
while (scanf("%d %d %d", &n, &m, &x) != EOF) {
init();
for (int i = 0; i < m; i++) {
int a, b, len;
scanf("%d %d %d", &a, &b, &len);
G[a].push_back(node(b, len));
T[b].push_back(node(a, len));
}
dijkstra_heap(G, dis1, x);
dijkstra_heap(T, dis2, x);
int m = -1;
for (int i = 1; i <= n;i++){
int k = dis1[i] + dis2[i];
if (m < k)m = k;
}
printf("%d\n", m);
}
system("pause");
return 0;
}