POJ_3268 Silver Cow Party 【最短路】
一、题面
二、分析
该题的意思就是给定了一个由每个节点代表农场的有向图,选定一个农场X办party,其余农场的都要去,每个农场的cow都走最短路,走的时间最久的cow耗时多少。
了解题意后,最开始想的是直接用floyd,但是复杂度已经到10的9次方了。这题比较特殊的一点就是无论是回来还是去都与X这个点有关,所以,当我们思考去求X到其他点的最短路径时,即根据输入的图求,其实就是在求返回的时长。如果我们把输入的图的路径的方向都反一下,即$a-b$变成$b-a$,这样相当于就是求其他所有点到X的时长了,两个对应相加求最大值就是最终的结果了。求的时候用dijkstra即可。
三、AC代码
1 #include <cstdio> 2 #include <cstring> 3 #include <iostream> 4 #include <algorithm> 5 #include <queue> 6 7 using namespace std; 8 9 typedef pair<int, int> P; 10 const int MAXN = 1e3; 11 const int INF = 0x3fffffff; 12 int map[MAXN+3][MAXN+3], map2[MAXN+3][MAXN+3]; 13 int dist[MAXN+3], dist2[MAXN+3]; 14 int N, M, X; 15 16 void Max(int &a, int b) 17 { 18 if(a < b) 19 a = b; 20 } 21 22 void dijkstra(int s, int graph[][MAXN+3], int d[]) 23 { 24 priority_queue<P, vector<P>, greater<P> > pq; 25 fill(d, d+N, INF); 26 d[s] = 0; 27 pq.push(P(0, s)); 28 while(!pq.empty()) 29 { 30 P t = pq.top(); 31 pq.pop(); 32 if(d[t.second] < t.first) 33 continue; 34 for(int i = 0; i < N; i++) 35 { 36 if(d[i] > d[t.second] + graph[t.second][i]) 37 { 38 d[i] = d[t.second] + graph[t.second][i]; 39 pq.push(P(d[i], i)); 40 } 41 } 42 } 43 } 44 45 int main() 46 { 47 //freopen("input.txt", "r", stdin); 48 int a, b, c, Ans; 49 scanf("%d %d %d", &N, &M, &X); 50 for(int i = 0; i < N; i++) 51 { 52 53 for(int j = 0; j < N; j++) 54 { 55 map[i][j] = INF; 56 map2[j][i] = INF; 57 } 58 map[i][i] = 0; 59 map2[i][i] = 0; 60 } 61 for(int i = 0; i < M; i++) 62 { 63 scanf("%d %d %d", &a, &b, &c); 64 map[a-1][b-1] = c; 65 map2[b-1][a-1] = c; 66 } 67 dijkstra(X-1, map, dist); 68 dijkstra(X-1, map2, dist2); 69 Ans = 0; 70 for(int i = 0; i < N; i++) 71 { 72 Max(Ans, dist[i] + dist2[i]); 73 } 74 printf("%d\n", Ans); 75 }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步