Greedy method (classic example articles)

Ideas : the optimal strategy continues to select the current

Difference : spoken with on a different dynamic programming, dynamic programming is when you select the optimal solution in a variety of strategies, and greedy only one strategy.

Example a :

Coin issue
 

Description

 

There are $ 1, $ 5, $ 10, $ 50, $ 100, $ 500 each coin C1, C5, C10, C50, C100, C500 pieces. Now use these coins to pay for A Yuan, how many coins requires a minimum? (Subject to some solvable.)

 

Input

 

Input comprising a plurality of sets of test cases for each test:

Integer input 7, the first six Ci integer representing the number of six kinds of coins, and then enter an integer A (0 <= Ci <= 109,1 <= A <= 109).

 

Output

 

Output requires a minimum number of coins.

 

Sample Input 1

3 2 1 3 0 2 620

Sample Output 1

6

Hint

5 yuan two coins, one 10 coins, 50 coins 2 500 a coin.

Ideas: previous coin problem (as much as possible the use of large denomination coins) differ, the previous topic that is not limited to the number of each coin (at that time the idea is to put each denomination ku [], circulation traversal, each operation is: = current number of coins of the money cents on the dollar, the current amount of money - = number of coin changer off), and this limits the number of coins means that the number of coins to be redeemed in accordance with the original face value of the coin the number of changes.

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <string>
#include <cstring>
using namespace std;
int main(){
    int ku[6] = {1, 5, 10, 50, 100, 500};
    int num[6];
    while(cin >> num[0]){
        for(int i = 1; i < 6; i++){
            cin >> num[i];
        }
        int money;
        cin >> money;
        int cnt = 0;
        for(int i = 5; i >= 0; i--){
            int t = min(num[i], money / ku[i]);
            money -= t * ku[i];
            cnt += t;
        }
        cout << cnt << endl;
    }
    return 0;
}
View Code

Two examples :

Interval Problems

 

Guess you like

Origin www.cnblogs.com/nibaba131237/p/12359342.html