wenbao与K短路

 

 http://poj.org/problem?id=2449

 

 

 

 1 #include <iostream>
 2 #include <queue>
 3 #include <stdio.h>
 4 using namespace std;
 5 
 6 const int INF = 1e9;
 7 const int maxr = 100009;
 8 const int maxn = 1009;
 9 int n, m, index = 1, to1[maxr], to2[maxr], w1[maxr], w2[maxr], pre1[maxr], pre2[maxr], p1[maxn], p2[maxn], dis[maxn];
10 bool vis[maxn];
11 
12 struct Node{
13     int v, d;
14     bool operator < (const Node &b) const {
15         return dis[v] + d > dis[b.v] + b.d;
16     }
17 };
18 
19 int K_road(int s, int t, int k){
20     for(int i = 1; i <= n; ++i) dis[i] = INF;
21     dis[t] = 0;
22     queue<int> q;
23     q.push(t);
24     while(!q.empty()){
25         int v = q.front(); q.pop();
26         vis[v] = false;
27         for(int i = p2[v]; i; i = pre2[i]) if(dis[v] + w2[i] < dis[to2[i]]){
28             dis[to2[i]] = dis[v] + w2[i];
29             if(!vis[to2[i]]){
30                 q.push(to2[i]);
31                 vis[to2[i]] = true;
32             }
33         }
34     }
35     if(dis[s] == INF) return -1;
36     int cnt = (s == t ? -1 : 0);
37     priority_queue<Node> pq;
38     Node a, b;
39     a.v = s, a.d = 0;
40     pq.push(a);
41     while(!pq.empty()){
42         a = pq.top(); pq.pop();
43         int v = a.v, d = a.d;
44         if(v == t) cnt++;
45         if(cnt == k) return d;
46         for(int i = p1[v]; i; i = pre1[i]){
47             b.v = to1[i], b.d = d + w1[i];
48             pq.push(b);
49         }
50     }
51     return -1;
52 }
53 int main(){
54     scanf("%d%d", &n, &m);
55     int x, y, z;
56     for(int i = 0; i < m; ++i){
57         scanf("%d%d%d", &x, &y, &z);
58         to1[index] = y, w1[index] = z, pre1[index] = p1[x], p1[x] = index;
59         to2[index] = x, w2[index] = z, pre2[index] = p2[y], p2[y] = index++;
60     }
61     int s, t, k;
62     scanf("%d%d%d", &s, &t, &k);
63     printf("%d\n", K_road(s, t, k));
64     return 0;
65 }

 

 

 

 

 

 

只有不断学习才能进步!

 

posted @ 2018-04-14 13:55  wenbao  阅读(215)  评论(0编辑  收藏  举报