The greedy algorithm solves the coin-seeking problem.

Source: Internet
Author: User

The greedy algorithm solves the coin-seeking problem.

If a currency has a coin with a nominal value of 1 cent, 2 cent, 5 cent, and 1 cent, how many coins are needed to find the change with K cent?

According to the greedy algorithm, we need to constantly use coins with the largest face value. If the value to be zero is smaller than the largest coin value, try the second largest coin, and so on.

The Code is as follows:

# Include <iostream> using namespace std; # define ONE 1 # define TWO 2 # define FIVE 5 # define TEN 10int main () {int money; int one = 0, two = 0, five = 0, ten = 0; cout <"Enter the money (in units) for the Change:"; cin> money; // try every coin while (money >=ten) {TEN ++; money-= ten ;}while (money >=five) {FIVE ++; money-= FIVE;} while (money >=two) {TWO ++; money-= two;} while (money >=one) {ONE ++; money-= ONE;} // output result cout <"1 cent coin count:" <ten <endl; cout <"5 cent coin count: "<five <endl; cout <" 2 cent coin count: "<two <endl; cout <" 1 cent coin count: "<one <endl; return 0 ;}

Although the greedy algorithm does not obtain the overall optimal solution for all problems, many problems in practical application can use the greedy algorithm to obtain the optimal solution. Sometimes, even if the greedy algorithm cannot obtain the optimal solution, the final result is a better solution.

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.