POJ 1502 MPI Maelstrom (Dijkstra)

题目链接:http://poj.org/problem?id=1502

题意是给你n个点,然后是以下三角的形式输入i j以及权值,x就不算

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <queue>
 5 using namespace std;
 6 const int MAXN = 105;
 7 const int INF = 1e9;
 8 typedef pair <int , int> P;
 9 struct data {
10     int next , to , cost;
11 }edge[MAXN * MAXN];
12 int head[MAXN] , d[MAXN] , cont;
13 void init(int n) {
14     for(int i = 1 ; i <= n ; i++) {
15         head[i] = -1;
16         d[i] = INF;
17     }
18     cont = 0;
19 }
20 
21 inline void add(int u , int v , int cost) {
22     edge[cont].next = head[u];
23     edge[cont].to = v;
24     edge[cont].cost = cost;
25     head[u] = cont++;
26 }
27 
28 void dijkstra(int s) {
29     priority_queue <P , vector<P> , greater<P> > que;
30     while(!que.empty()) {
31         que.pop();
32     }
33     d[s] = 0;
34     que.push(P(0 , s));
35     while(!que.empty()) {
36         P temp = que.top();
37         que.pop();
38         int u = temp.second;
39         if(d[u] < temp.first)
40             continue;
41         for(int i = head[u] ; ~i ; i = edge[i].next) {
42             int v = edge[i].to;
43             if(d[v] > d[u] + edge[i].cost) {
44                 d[v] = d[u] + edge[i].cost;
45                 que.push(P(d[v] , v));
46             }
47         }
48     }
49 }
50 
51 int main()
52 {
53     int n , cost;
54     while(~scanf("%d" , &n)) {
55         char str[40];
56         init(n);
57         for(int i = 2 ; i <= n ; i++) {
58             for(int j = 1 ; j < i ; j++) {
59                 scanf("%s" , str);
60                 if(str[0] == 'x')
61                     continue;
62                 int temp = 0;
63                 for(int k = 0 ; str[k] != '\0' ; k++) {
64                     temp = temp * 10 + (str[k] - '0');
65                 }
66                 add(j , i , temp);
67                 add(i , j , temp);
68             }
69         }
70         dijkstra(1);
71         int res = 0;
72         for(int i = 1 ; i <= n ; i++) {
73             res = max(res , d[i]);
74         }
75         printf("%d\n" , res);
76     }
77 }

 

,边是双向的,求其中起点到最远的点的最短距离。

直接dijkstra优先队列,速度确实快。

 

posted @ 2016-03-19 14:57  Recoder  阅读(211)  评论(0编辑  收藏  举报