标签:end 变形 art price namespace for pos als 并且
算法:广搜变形(堆优化Dijkstra).
#include <cstring> #include <iostream> #include <algorithm> #include <queue> using namespace std; typedef pair<int, int> PII; const int N = 1010, C = 110, M = 20010; int n, m; int h[N], e[M], w[M], ne[M], idx; int price[N];//每个地区的油价 int dist[N][C];//存储距离 bool st[N][C];//判断是否走过 struct Ver { int d, u, c;//分别表示当前点到起点的距离,当前点,当前剩余油量 bool operator< (const Ver &W)const { return d > W.d; } }; void add(int a, int b, int c) { e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ; } int dijkstra(int start, int end, int cap) { memset(dist, 0x3f, sizeof dist); memset(st, false, sizeof st); priority_queue<Ver> heap; heap.push({0, start, 0}); dist[start][0] = 0; while (heap.size()) { auto t = heap.top(); heap.pop(); if (t.u == end) return t.d;//如果当前点已经是终点,返回当前点到起点的距离 if (st[t.u][t.c]) continue; st[t.u][t.c] = true; if (t.c < cap)//如果当前剩余油量小于车的油容量 { if (dist[t.u][t.c + 1] > t.d + price[t.u])//当前距离可以进行更新 { dist[t.u][t.c + 1] = t.d + price[t.u]; heap.push({dist[t.u][t.c + 1], t.u, t.c + 1});//更新,存入堆 } } for (int i = h[t.u]; ~i; i = ne[i])//第二种情况,枚举邻点 { int j = e[i]; if (t.c >= w[i])//当前剩余容量还可以到j点 { if (dist[j][t.c - w[i]] > t.d)//并且距离也更短 { dist[j][t.c - w[i]] = t.d;//更新 heap.push({dist[j][t.c - w[i]], j, t.c - w[i]}); } } } } return -1; } int main() { scanf("%d%d", &n, &m); memset(h, -1, sizeof h); for (int i = 0; i < n; i ++ ) scanf("%d", &price[i]); for (int i = 0; i < m; i ++ ) { int a, b, c; scanf("%d%d%d", &a, &b, &c); add(a, b, c), add(b, a, c); } int query; scanf("%d", &query); while (query -- ) { int a, b, c; scanf("%d%d%d", &c, &a, &b); int t = dijkstra(a, b, c); if (t == -1) puts("impossible"); else printf("%d\n", t); } return 0; }
标签:end 变形 art price namespace for pos als 并且
原文地址:https://www.cnblogs.com/programyang/p/11335439.html