poj 2449 A*求k短路
A*的入门题目,需要注意的是当图中只有一个点的时候k短路是不存在的。
1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 #include <queue> 5 using namespace std; 6 7 const int INF = 0x3f3f3f3f; 8 const int N = 1001; 9 const int M = 100000; 10 int head[N]; 11 int rhead[N]; 12 int dist[N]; 13 int visit[N]; 14 int n, m, e; 15 16 struct Edge 17 { 18 int v, next, w; 19 } edge[M], redge[M]; 20 21 void addEdge( int u, int v, int w ) 22 { 23 edge[e].v = v; 24 edge[e].w = w; 25 edge[e].next = head[u]; 26 head[u] = e; 27 redge[e].v = u; 28 redge[e].w = w; 29 redge[e].next = rhead[v]; 30 rhead[v] = e; 31 e++; 32 } 33 34 void spfa( int t ) 35 { 36 memset( dist, 0x3f, sizeof(dist) ); 37 memset( visit, 0, sizeof(visit) ); 38 int q[N], top = 0; 39 dist[t] = 0; 40 q[top] = t; 41 top = ( top + 1 ) % n; 42 visit[t] = 1; 43 for ( int i = 0; i != top; i = ( i + 1 ) % n ) 44 { 45 int u = q[i]; 46 visit[u] = 0; 47 for ( int j = rhead[u]; j != -1; j = redge[j].next ) 48 { 49 int v = redge[j].v, w = redge[j].w; 50 if ( dist[v] > dist[u] + w ) 51 { 52 dist[v] = dist[u] + w; 53 if ( !visit[v] ) 54 { 55 q[top] = v; 56 top = ( top + 1 ) % n; 57 visit[v] = 1; 58 } 59 } 60 } 61 } 62 } 63 64 struct Node 65 { 66 int u, g; 67 Node(){} 68 Node( int _u, int _g ) 69 { 70 u = _u, g = _g; 71 } 72 bool operator < ( const Node & o ) const 73 { 74 return dist[u] + g > dist[o.u] + o.g; 75 } 76 }; 77 78 int a_star( int s, int t, int k ) 79 { 80 priority_queue<Node> q; 81 q.push( Node( s, 0 ) ); 82 memset( visit, 0, sizeof(visit) ); 83 while ( !q.empty() ) 84 { 85 Node cur = q.top(); 86 q.pop(); 87 visit[cur.u]++; 88 if ( visit[t] == k ) return cur.g; 89 if ( visit[cur.u] > k ) continue; 90 for ( int i = head[cur.u]; i != -1; i = edge[i].next ) 91 { 92 int v = edge[i].v, w = edge[i].w; 93 q.push( Node( v, cur.g + w ) ); 94 } 95 } 96 return -1; 97 } 98 99 int main () 100 { 101 while ( scanf("%d%d", &n, &m) != EOF ) 102 { 103 e = 0; 104 memset( head, -1, sizeof(head) ); 105 memset( rhead, -1, sizeof(rhead) ); 106 while ( m-- ) 107 { 108 int u, v, w; 109 scanf("%d%d%d", &u, &v, &w); 110 addEdge( u, v, w ); 111 } 112 int s, t, k; 113 scanf("%d%d%d", &s, &t, &k); 114 spfa(t); 115 if ( dist[s] == INF ) 116 { 117 printf("-1\n"); 118 continue; 119 } 120 if ( s == t ) k++; 121 printf("%d\n", a_star( s, t, k )); 122 } 123 return 0; 124 }