The Rating Dilemma codechef solution in c++
Here is a solution for the Rating Dilemma problem on CodeChef in C++:
#include<bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while(t--) {
int n;
cin >> n;
vector<int> a(n);
for(int i = 0; i < n; i++) {
cin >> a[i];
}
sort(a.begin(), a.end());
long long sum = 0;
long long total = 0;
for(int i = 0; i < n; i++) {
sum += a[i];
total += sum;
}
long long ans = total - (n-1) * sum;
cout << ans << endl;
}
return 0;
}
Explanation:
- First, we take the number of test cases as input using cin >> t
.
- We then enter a while loop that will run t
times, representing each test case.
- Inside the loop, we take the number of ratings as input using cin >> n
.
- We create a vector a
of size n
to store the ratings.
- We use a for loop to read the ratings and store them in the vector a
.
- Next, we sort the vector a
using the sort
function from the algorithm library.
- We initialize two variables, sum
and total
, to keep track of the sum of ratings and the total sum respectively.
- Using another for loop, we iterate through each rating in the vector a
.
- We add the current rating to sum
and add sum
to total
.
- After the loop, we calculate the answer by subtracting (n-1) * sum
from total
and store it in the variable ans
.
- Finally, we output the answer using cout << ans << endl
.
This solution calculates the sum of all possible subarrays of the sorted array and subtracts the sum of the remaining elements from the total sum.