首页 > 代码库 > POJ 3268 Silver Cow Party
POJ 3268 Silver Cow Party
http://poj.org/problem?id=3268
有一个点X开party 求其他所有点 去的路程和返程的和的最小值中的最大值
这里有一个小技巧
总是把X当做原点
返程是正常的最短路
去程就把路径翻转 求最短路
这样只需要两次求最短路
1 #include <iostream> 2 #include <stdio.h> 3 #include <string.h> 4 #include <queue> 5 #include <algorithm> 6 #define MAXV 1007 7 #define MAXE 100007 8 #define INF 0x3f3f3f3f 9 using namespace std; 10 11 typedef pair<int,int> P ;//first 是距离 second是编号 12 struct Edge 13 { 14 int to, cost, next; 15 Edge() {} 16 Edge(int to, int cost, int next) : to(to), cost(cost), next(next) {} 17 }edge1[MAXE], edge2[MAXE]; 18 19 int head1[MAXV], head2[MAXV]; 20 int num1 = 0, num2 = 0; 21 void Add1(int from, int to, int cost) 22 { 23 edge1[num1] = Edge(to, cost, head1[from]); 24 head1[from] = num1++; 25 } 26 27 void Add2(int from, int to, int cost) 28 { 29 edge2[num2] = Edge(to, cost, head2[from]); 30 head2[from] = num2++; 31 } 32 33 int N, M, X; 34 35 int dijkstra(int s,int dist[], int head[], Edge edge[]) 36 { 37 //int dist[MAXV]; 38 priority_queue<P> que; 39 fill(dist, dist+MAXV, INF); 40 dist[s] = 0; 41 que.push(P(0, s)); 42 while (!que.empty()) 43 { 44 P p = que.top(); 45 que.pop(); 46 int t = head[p.second]; 47 if (dist[p.second] < p.first) continue; 48 while (t != -1) 49 { 50 Edge e = edge[t]; 51 if(dist[e.to] > dist[p.second] + e.cost) 52 { 53 dist[e.to] = dist[p.second] + e.cost; 54 que.push(P(dist[e.to], e.to)); 55 } 56 t = e.next; 57 } 58 } 59 } 60 61 int main() 62 { 63 int ans[MAXV]; 64 int dist1[MAXV], dist2[MAXV]; 65 freopen("in.txt", "r", stdin); 66 scanf("%d%d%d", &N, &M, &X); 67 memset(head1, -1, sizeof(head1)); 68 memset(head2, -1, sizeof(head2)); 69 memset(edge1, -1, sizeof(edge1)); 70 memset(edge2, -1, sizeof(edge2)); 71 memset(ans, 0, sizeof(ans)); 72 for (int i = 0; i < M; i++) 73 { 74 int from, to, cost; 75 scanf("%d%d%d", &from, &to, &cost); 76 Add1(from, to, cost); 77 Add2(to, from, cost); 78 } 79 dijkstra(X, dist1, head1, edge1);//正常返回的路径 80 dijkstra(X, dist2, head2, edge2);//路径翻转之后 得到的dist就是 i到达X的路径 81 for (int i = 1; i <= N; i++) 82 { 83 ans[i] = dist1[i] + dist2[i]; 84 } 85 sort(ans+1, ans+N+1); 86 printf("%d\n", ans[N]); 87 return 0; 88 }
POJ 3268 Silver Cow Party
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。