Grouping dition code (c)
Address: http://blog.csdn.net/caroline_wendy
Question: The distance between a truck and 1 unit is required by the expeditionary team. At the beginning, there is a unit of P gasoline on the truck, and 1 unit of gasoline is required for each unit.
There are N gas stations a on the way, each gas station can be B, the tank capacity is infinite, if you can reach the end, find the minimum number of fuel.
For example, a distance of L = 25 is required, starting with P = 10 units of gasoline, and n = 4 gas stations,
The distance from the gas station to the starting position is a = {10, 14, 20, 21}. You can add gasoline B = {10, 5, 2, 4 },
Then result = 2, in (10, 10) () refueling, that is, added 15, starting 10, driving 25.
UseHeap), That isPriority_queue)Solve the problem.
When I arrived at the gas station, I got the right to add B unit gasoline at any time.
Determine whether to add the gasoline before each arrival at the gas station,Time complexity O (nlogn).
Code:
/** Main. CPP ** created on: 2014.7.20 * Author: Spike * // * eclipse CDT, GCC 4.8.1 */# include <stdio. h >#include <queue >#include <vector> # include <functional> using namespace STD; Class program {static const int max_n = 100; int L = 25, P = 10, N = 4; int A [max_n + 1] = {10, 14, 20, 21}, B [max_n + 1] = {10, 5, 2, 4 }; public: void solve () {A [n] = L; // The end point is also treated as a gas station B [N] = 0; n ++; priority_queue <int> que; int ans = 0, Pos = 0, tank = P; For (INT I = 0; I <n; ++ I) {int d = A [I]-Pos; while (tank-D <0) {If (que. empty () {puts ("-1 \ n"); return;} tank + = que. top (); que. pop (); ans ++;} tank-= D; Pos = A [I]; que. push (B [I]);} printf ("result = % d \ n", ANS) ;};int main (void) {program IP; IP. solve (); Return 0 ;}
Output:
result=2
Programming Algorithm-grouping dition code (c)