Silver Cow Party
Time Limit : 4000/2000ms (Java/Other) Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 1 Accepted Submission(s) : 1
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?
题意:一群牛分别从1~n号农场赶往x号农场参加聚会,农场与农场之间的路时单向的,在n个农场之间有m条路,给出 a ,b , t表示从a号农场到b号农场需要t时间。 每头牛都会选择最短的路,问来回路上(i→x+x→i)花费时间最长的牛花费的时间是多少?
题解:一眼看过去很简单,先计算x农场到其他农场用的最短时间,在枚举其他农场到x农场的最短时间,记录下最大来回时间即可。的确,不过我们算一算时间复杂度,在枚举其他农场到x农场的最短时间时,最大复杂度为O(n^3)。也就是1000^3,很明显超过了2000ms。所以我们要想办法把枚举过程的复杂度降下来。 这里可以采用置换矩阵,因为是路径时单向的,我们交换 map[i][j] 与 map[j][i] 的值,那么枚举过程就变成了求x到其他农场的最短时间,这里就变成了O(n^2)的算法。
我用了两次dijkstra
1 #include <iostream> 2 #include <algorithm> 3 #include <cstring> 4 #include <string> 5 #include <cstdio> 6 #define inf 0x3f3f3f3f; 7 using namespace std; 8 int n, m, s; 9 int e[1005][1005]; 10 int d1[1005]; 11 int d2[1005]; 12 int v[1005]; 13 void dijstra(int s, int *d) 14 { 15 int i,j; 16 for (i = 1; i <= n; i++) 17 { 18 d[i] = e[s][i]; 19 v[i] = 0; 20 } 21 v[s] = 1; 22 for (i = 1; i <= n - 1; i++) 23 { 24 int k = -1; 25 int mi = inf; 26 for (j = 1; j <= n; j++) 27 { 28 if (v[j] == 0 && d[j] < mi) 29 { 30 mi = d[j]; 31 k = j; 32 } 33 } 34 if (k == -1) break; 35 v[k] = 1; 36 for (j = 1; j <= n; j++) 37 { 38 if (v[j] == 0 && d[j] > d[k] + e[k][j]) 39 { 40 d[j] = d[k] + e[k][j]; 41 } 42 } 43 } 44 } 45 int main() 46 { 47 int i, j; 48 cin >> n >> m >> s; 49 memset(e, 0x3f3f3f3f, sizeof(e)); 50 for(i=1;i<=1000;i++) e[i][i]=0; 51 for (i = 1; i <= m; i++) 52 { 53 int x, y, z; 54 cin >> x >> y >> z; 55 if (e[x][y] > z) 56 { 57 e[x][y] = z; 58 } 59 } 60 dijstra(s, d1); 61 for (i = 1; i <= n; i++) 62 { 63 for (j = 1; j < i; j++) 64 { 65 int temp = e[i][j]; 66 e[i][j] = e[j][i]; 67 e[j][i] = temp; 68 } 69 } 70 dijstra(s, d2); 71 int mm = 0; 72 for (i = 1; i <= n; i++) 73 { 74 if (d1[i] + d2[i] > mm) 75 { 76 mm = d1[i] + d2[i]; 77 } 78 } 79 cout << mm << endl; 80 return 0; 81 }