POJ3635 Full Tank?

【题解】

        用dijkstra算法求最短路。同时考虑在每个节点加油(一单位)与否。

【代码】

  1 #include <iostream>
  2 #include <map>
  3 #include <cstring>
  4 #include <string>
  5 #include <queue>
  6 using namespace std;
  7 #define maxn 1005
  8 #define maxm 10005
  9 
 10 /* 
 11 * dp[i][j] denodes the least cost on the ith node
 12 * with j oil left.
 13 */
 14 int price[maxn], dp[maxn][105], vis[maxn][105];
 15 int Ecnt, capacaity, sp, ep;
 16 
 17 struct Node
 18 {
 19     int node, cost, oil;
 20     Node(int n, int c, int o) :
 21         node(n), cost(c), oil(o) {}
 22     bool operator < (const Node &N) const{
 23         return cost > N.cost;
 24     }
 25 };
 26 
 27 struct Edge
 28 {
 29     int node;
 30     int len;
 31     Edge* next;
 32 }edges[2*maxm];
 33 
 34 Edge* head[maxn];
 35 
 36 void init()
 37 {
 38     Ecnt = 0;
 39     fill(head, head + maxn, (Edge*)0);
 40 }
 41 
 42 void build(int u, int v, int w)
 43 {
 44     edges[Ecnt].node = u;
 45     edges[Ecnt].len = w;
 46     edges[Ecnt].next = head[v];
 47     head[v] = edges + Ecnt++;
 48 
 49     edges[Ecnt].node = v;
 50     edges[Ecnt].len = w;
 51     edges[Ecnt].next = head[u];
 52     head[u] = edges + Ecnt++;
 53 }
 54 
 55 void dijkstra()
 56 {
 57     memset(vis, 0, sizeof(vis));
 58     memset(dp, 1, sizeof(dp));
 59     priority_queue<Node> pq;
 60     pq.push(Node(sp, 0, 0));
 61     dp[sp][0] = 0;
 62     while (!pq.empty()) {
 63         Node np = pq.top();
 64         pq.pop();
 65         int n = np.node, c = np.cost, o = np.oil;
 66         vis[n][o] = 1;
 67         if (n == ep) {
 68             printf("%d\n", c);
 69             return;
 70         }
 71         /* decide to add oil or not */
 72         if (o + 1 <= capacaity && !vis[n][o + 1] && dp[n][o] + price[n] < dp[n][o + 1]) {
 73             dp[n][o + 1] = dp[n][o] + price[n];
 74             pq.push(Node(n, dp[n][o + 1], o + 1));
 75         } 
 76         /* drive to the next node */
 77         for (Edge *Ep = head[n]; Ep; Ep = Ep->next) {
 78             int N = Ep->node, Len = Ep->len;
 79             if (o >= Len && !vis[N][o - Len] && c < dp[N][o - Len]) {
 80                 dp[N][o - Len] = c;
 81                 pq.push(Node(N, dp[N][o - Len], o - Len));
 82             }
 83         }
 84     }
 85     printf("impossible\n");
 86     return;
 87 }
 88 
 89 int main()
 90 {
 91     int city_n, road_m, queries;
 92     cin >> city_n >> road_m;
 93     init();
 94     for (int i = 0; i < city_n; i++)
 95         cin >> price[i];
 96     for (int i = 0; i < road_m; i++) {
 97         int u, v, d;
 98         cin >> u >> v >> d;
 99         build(u, v, d);
100     }
101     cin >> queries;
102     for (int i = 0; i < queries; i++) {
103         cin >> capacaity >> sp >> ep;
104         dijkstra();
105     }
106     //system("pause");
107     return 0;
108 }

猜你喜欢

转载自www.cnblogs.com/Jeffrey-Y/p/10158930.html