Advertisement
STANAANDREY

problema platii unei sume(greedy)

Dec 8th, 2020
1,040
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.95 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3. #define NMAX 10
  4. struct Banc {
  5.     int val, nr;
  6. } v[NMAX];
  7. int n, s, total;
  8.  
  9. void read() {
  10.     cin >> n;
  11.     for (int i = 1; i <= n; i++) {
  12.         cin >> v[i].val >> v[i].nr;
  13.         total += v[i].val * v[i].nr;
  14.     }
  15.     cin >> s;
  16.  
  17. }
  18.  
  19. void bsort() {
  20.     bool sorted = false;
  21.     while (!sorted) {
  22.         sorted = true;
  23.         for (int i = 1; i < n; i++)
  24.             if (v[i].val < v[i + 1].val) {
  25.                 sorted = false;
  26.                 swap(v[i], v[i + 1]);
  27.             }
  28.     }
  29. }
  30.  
  31. void greedy() {
  32.     int i = 1, nr;
  33.     while (s > 0 && i <= n) {
  34.         nr = 0;
  35.         while (s - v[i].val >= 0 && nr <= v[i].nr) {
  36.             s -= v[i].val;
  37.             nr++;
  38.         }
  39.         cout << v[i].val << '*' << nr << endl;
  40.         i++;
  41.     }
  42. }
  43.  
  44. int main() {
  45.     read();
  46.     if (total < s)
  47.         return cout << "Imposibil!", 0;
  48.     bsort();
  49.     greedy();
  50.     return 0;
  51. }
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement