C++ code to find winner of math contest

C++Server Side ProgrammingProgramming

Suppose we have two arrays P and T of size n. And have another number c. Amal and Bimal are going to participate one math contest. There are n problems. The ith problem has initial score P[i], and takes T[i] to solve it. P and T both are sorted in increasing order. Here c is the constant for loosing points. If a problem is submitted at time x (x minutes after starting the contest), it gives max(0, P[i] - c*x) points. Amal is going to solve problems in order 1, 2, ... n and Bimal is going to solve them like n, n-1, ... 1. We have to find who will get the maximum score. If they have got the same, it will be a 'Tie'.

So, if the input is like c = 2; P = [50, 85, 250]; T = [10, 15, 25], then the output will be Amal.

Steps

To solve this, we will follow these steps −

n := size of P
m := 0
ans1 := 0
ans2 := 0
for initialize i := 0, when i < n, update (increase i by 1), do:
   m := m + T[i]
   ans1 := ans1 + maximum of (0, P[i] - c * m)
m := 0
for initialize i := n - 1, when i > 1, update (decrease i by 1), do:
   m := m + T[i]
   ans2 := ans2 + maximum of (0, P[i] - c * m)
if ans1 > ans2, then:
   return "Amal"
otherwise when ans1 < ans2, then:
   return "Bimal"
Otherwise
   return "Tie"

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
string solve(int c, vector<int> P, vector<int> T){
   int n = P.size();
   int m = 0, ans1 = 0, ans2 = 0;
   for (int i = 0; i < n; i++){
      m += T[i];
      ans1 += max(0, P[i] - c * m);
   }
   m = 0;
   for (int i = n - 1; i > 1; i--){
      m += T[i];
      ans2 += max(0, P[i] - c * m);
   }
   if (ans1 > ans2)
      return "Amal";
   else if (ans1 < ans2)
      return "Bimal";
   else
      return "Tie";
}
int main(){
   int c = 2;
   vector<int> P = { 50, 85, 250 };
   vector<int> T = { 10, 15, 25 };
   cout << solve(c, P, T) << endl;
}

Input

2, { 50, 85, 250 }, { 10, 15, 25 }

Output

Amal
raja
Updated on 30-Mar-2022 14:19:42

Advertisements