C++ program to find at least how much score it needs to get G amount of score

C++Server Side ProgrammingProgramming

Suppose we have two arrays p and c both are with D number of elements each, and another number G. Consider in a coding contest, each problem has its score based on difficulty. The problem p[i] has score 100i. These p[1] + ... + p[D] problems are all of the problems present in the contest. a user in the coding site has a number total_score. The total_score of an user is the sum of the following two elements.

  • Base score: the sum of score of all solved problems

  • Bonus: when a user solves all problems with a score of 100i, he or she earns the perfect bonus c[i] aside the base score.

Amal is new in the contest and has not solved any problem. His objective is to have total score of G or more points. We have to find at least how many problems does he need to solve for this objective.

So, if the input is like G = 500; P = [3, 5]; C = [500, 800], then the output will be 3

Steps

To solve this, we will follow these steps −

D := size of p
mi := 10000
for initialize i := 0, when i < 1 << D, update (increase i by 1), do:
sum := 0
count := 0
at := 0
an array to store 10 bits b, initialize from bit value of i
for initialize j := 0, when j < D, update (increase j by 1), do:
   if jth bit in b is 1, then:
      count := p[j]
      sum := sum + ((j + 1) * 100 * p[j] + c[j]
   Otherwise
      at := j
if sum < G, then:
   d := (G - sum + (at + 1) * 100 - 1) / ((at + 1) * 100)
   if d <= p[at], then:
      sum := sum + (at + 1)
      count := count + d
if sum >= G, then:
   mi := minimum of mi and count
return mi

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(int G, vector<int> p, vector<int> c){
   int D = p.size();
   int mi = 10000;
   for (int i = 0; i < 1 << D; i++){
      int sum = 0;
      int count = 0;
      int at = 0;
      bitset<10> b(i);
      for (int j = 0; j < D; j++){
         if (b.test(j)){
            count += p.at(j);
            sum += (j + 1) * 100 * p.at(j) + c.at(j);
         } else {
            at = j;
         }
      }
      if (sum < G){
         int d = (G - sum + (at + 1) * 100 - 1) / ((at + 1) * 100);
         if (d <= p.at(at)){
            sum += (at + 1) * 100 * d;
            count += d;
         }
      }
      if (sum >= G) {
         mi = min(mi, count);
      }
   }
   return mi;
}
int main() {
   int G = 500;
   vector<int> P = { 3, 5 };
   vector<int> C = { 500, 800 };
   cout << solve(G, P, C) << endl;
}

Input

500, { 3, 5 }, { 500, 800 }

Output

3
raja
Updated on 02-Mar-2022 12:24:07

Advertisements