Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 11348 | Accepted: 5077 |
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
题意:
给出 N(1~1000),M(1 ~ 100000),X(1 ~ N),代表有 N 个地方,M条路,目的地是X。后给出 M 条路,每条路都是单向的,代表 A 到 B 需要花费 T (1 ~ 100)的时间。每个地点都要到达终点且从终点返回原地方,每条路都要求时间最短。求出这么多地点中的所需最长时间。
思路:
最短路。一看以为是Floyd,但是TLE之后分析了下时间复杂度O(n ^ 3)就是 1000 ^ 3 = 10 ^ 9 = 10 ^ 7 * 100 = 1s * 100,100s的时间,题目给的是2000ms = 2s,果断超时不能用Floyd。故只能用 Dijkstra 一个个单源算最短路,因为没有负环的情况故用 Dijkstra。顺便总结下时间复杂度(N为节点数,M为边数):
Floyd :O(N ^ 3);
Dijkstra :邻接矩阵 O(N ^ 2);邻接表 + 优先队列:O(NlogN + M)从优先队列取元素出来是logN,一共需要取N次,故为NlogN,每次最多可能要遍历M条边故为NlogN + M;
Bellman Ford :O(N * M);
SPFA :O(kM)= O(M);
所以,用 Dikstra 邻接表 + 优先队列是能够满足题目要求的。
AC:
#include <cstdio> #include <queue> #include <utility> #include <iostream> #include <string.h> #include <vector> #define MAX 100005 #define INF 99999999 using namespace std; typedef pair<int,int> pii; int v[MAX],w[MAX],fir[1005],next[MAX]; int d[1005][1005],vis[1005]; int ind,n; void add_edge(int f,int t,int val) { v[ind] = t; w[ind] = val; next[ind] = fir[f]; fir[f] = ind; ind++; } void Dijstra(int s) { for(int i = 1;i <= n;i++) d[s][i] = INF; memset(vis,0,sizeof(vis)); d[s][s] = 0; priority_queue<pii,vector<pii>,greater<pii> > q; q.push(make_pair(d[s][s],s)); while(!q.empty()) { pii k = q.top();q.pop(); int x = k.second; if(vis[x]) continue; vis[x] = 1; for(int e = fir[x];e != -1;e = next[e]) { if(d[s][v[e]] > d[s][x] + w[e]) { d[s][v[e]] = d[s][x] + w[e]; q.push(make_pair(d[s][v[e]],v[e])); } } } } int main() { int m,p; memset(fir,-1,sizeof(fir)); scanf("%d%d%d",&n,&m,&p); ind = 0; while(m--) { int f,t,val; scanf("%d%d%d",&f,&t,&val); add_edge(f,t,val); } for(int i = 1;i <= n;i++) Dijstra(i); int max_time = -1; for(int i = 1;i <= n;i++) { if(i == p) continue; if(max_time < d[i][p] + d[p][i]) max_time = d[i][p] + d[p][i]; } printf("%d\n",max_time); return 0; }