Programming Algorithm-grouping dition code (c)

Source: Internet
Author: User
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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.