赛后填坑系列QAQ
贴代码呀
1 #include<iostream> 2 #include<algorithm> 3 #include<cstdio> 4 #include<cstdlib> 5 #include<cstring> 6 #include<string> 7 8 using namespace std; 9 10 void setIO(const string& a) { 11 freopen((a+".in").c_str(), "r", stdin); 12 freopen((a+".out").c_str(), "w", stdout); 13 } 14 15 const int N = 1000 + 10, INF = ~0u>>2; 16 17 int n; 18 #include<vector> 19 struct Edge{ 20 int to, w; 21 Edge(int to = 0, int w = 0) : to(to), w(w) {} 22 }; 23 vector<Edge> G[N], G2[N]; 24 25 void AddEdge(int u, int v, int w) { 26 G[u].push_back(Edge(v, w)); 27 G2[v].push_back(Edge(u, w)); 28 } 29 30 int dis[N]; 31 32 #include<queue> 33 namespace SPFA { 34 int* d; 35 bool inq[N]; 36 queue<int> q; 37 38 void insert(int x, int dis) { 39 if(d[x] <= dis) return; 40 d[x] = dis; 41 if(!inq[x]) q.push(x), inq[x] = 1; 42 } 43 44 void main(int st, int dis[], const vector<Edge> G[]) { 45 d = dis; 46 for(int i = 1; i <= n; i++) { 47 d[i] = INF; 48 inq[i] = 0; 49 } 50 insert(st, 0); 51 while(!q.empty()) { 52 int u = q.front(); q.pop(); inq[u] = 0; 53 for(unsigned i = 0; i < G[u].size(); i++) { 54 insert(G[u][i].to, d[u] + G[u][i].w); 55 } 56 } 57 } 58 } 59 60 struct Node { 61 int g, h, v; 62 Node(int g = 0, int h = 0, int v = 0) : g(g), h(h), v(v) {} 63 bool operator < (const Node& rhs) const { 64 return h > rhs.h; 65 } 66 }; 67 68 namespace A_star { 69 priority_queue<Node> q; 70 int inq[N]; 71 72 int main(int st, int ed, int k) { 73 if(dis[st] == INF) return -1; 74 if(st == ed) k++; 75 76 q.push(Node(0, 0 + dis[st], st)); 77 while(!q.empty()) { 78 Node cur = q.top(); q.pop(); 79 int u = cur.v; 80 81 inq[u]++; 82 if(inq[ed] == k) return cur.g; 83 if(inq[u] > k) continue; // mark1 84 85 for(unsigned i = 0; i < G[u].size(); i++) { 86 const Edge& e = G[u][i]; 87 q.push(Node(cur.g + e.w, cur.g + e.w + dis[e.to], e.to)); 88 } 89 } 90 return -1; 91 } 92 } 93 94 int main() { 95 #ifdef DEBUG 96 freopen("in.txt", "r", stdin); 97 freopen("out.txt", "w", stdout); 98 #endif 99 100 int m, k, st, ed; 101 scanf("%d%d", &n, &m); 102 for(int i = 1; i <= m; i++) { 103 int u, v, w; 104 scanf("%d%d%d", &u, &v, &w); 105 AddEdge(u, v, w); 106 } 107 108 scanf("%d%d%d", &st, &ed, &k); 109 110 SPFA::main(ed, dis, G2); 111 printf("%d ", A_star::main(st, ed, k)); 112 113 return 0; 114 }