Skip to content

Instantly share code, notes, and snippets.

@misgeatgit
Last active October 10, 2015 08:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save misgeatgit/17badc6d78f3b81ef012 to your computer and use it in GitHub Desktop.
Save misgeatgit/17badc6d78f3b81ef012 to your computer and use it in GitHub Desktop.
/*
* From https://www.hackerrank.com/challenges/playing-with-numbers
*
*/
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <sstream>
using namespace std;
// Sum_j = Sum_i0_to_n( abs ( a_i + sum_j0_n(q_j)))
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int size;
cin >> size;
int arr [size];
for(int i=0; i< size; i++)
int f = scanf("%d",&arr[i]);
int qsize;
cin >> qsize;
long long int QSUM [qsize];
cin >> QSUM[0];
int temp;
for(int i=1; i< qsize; i++){
int f = scanf("%d",&temp);
QSUM[i] = QSUM[i-1] + temp;
}
sort(arr, arr+size); // if sumj+arr[i] > 0 then sumj+arr[i+...] > 0 so sum = sum_i_k(ai) + k*sumj
long long int ARR_SUM[size];
ARR_SUM[0] = arr[0];
for(int i = 1 ; i < size; i++){
ARR_SUM[i] = arr[i] + ARR_SUM[i-1];
}
long long int sum=0;
//stringstream ss;
for(int i = 0; i < qsize; i++ ){
for(int j=0; j< size; j++){
if(QSUM[i]+arr[j] > 0){
sum += ((size-j)*QSUM[i] + (ARR_SUM[size-1]-ARR_SUM[j] + arr[j]));
break;
}
sum += abs(arr[j]+QSUM[i]);
}
//ss << sum << "\n";
printf("%lld\n",sum);
sum = 0;
}
//cout << ss.str();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment