Absolute Element Sums
Problem Statement :
Given an array of integers, you must answer a number of queries. Each query consists of a single integer, , and is performed as follows: Add to each element of the array, permanently modifying it for any future queries. Find the absolute value of each element in the array and print the sum of the absolute values on a new line. Tip: The Input/Output for this challenge is very large, so you'll have to be creative in your approach to pass all test cases. Function Description Complete the playingWithNumbers function in the editor below. It should return an array of integers that represent the responses to each query. playingWithNumbers has the following parameter(s): arr: an array of integers queries: an array of integers Input Format The first line contains an integer the number of elements in . The second line contains space-separated integers . The third line contains an integer , the number of queries. The fourth line contains space-separated integers where . Output Format For each query, print the sum of the absolute values of all the array's elements on a new line.
Solution :
Solution in C :
In C :
#include <stdio.h>
#include <stdlib.h>
void sort_a(int*a,int size);
void merge(int*a,int*left,int*right,int left_size, int right_size);
int get_i(int*a,int num,int size);
int med(int*a,int size);
int a[500000],sum[500000];
int main(){
int N,Q,offset=0,x,i;
long long ans;
scanf("%d",&N);
for(i=0;i<N;i++)
scanf("%d",a+i);
sort_a(a,N);
for(i=1,sum[0]=a[0];i<N;i++)
sum[i]=sum[i-1]+a[i];
scanf("%d",&Q);
while(Q--){
scanf("%d",&x);
offset+=x;
i=get_i(a,-offset+1,N);
if(!i)
ans=sum[N-1]+offset*(long long)N;
else
ans=sum[N-1]-2*sum[i-1]+offset*(long long)(N-2*i);
printf("%lld\n",ans);
}
return 0;
}
void sort_a(int*a,int size){
if (size < 2)
return;
int m = (size+1)/2,i;
int *left,*right;
left=(int*)malloc(m*sizeof(int));
right=(int*)malloc((size-m)*sizeof(int));
for(i=0;i<m;i++)
left[i]=a[i];
for(i=0;i<size-m;i++)
right[i]=a[i+m];
sort_a(left,m);
sort_a(right,size-m);
merge(a,left,right,m,size-m);
free(left);
free(right);
return;
}
void merge(int*a,int*left,int*right,int left_size, int right_size){
int i = 0, j = 0;
while (i < left_size|| j < right_size) {
if (i == left_size) {
a[i+j] = right[j];
j++;
} else if (j == right_size) {
a[i+j] = left[i];
i++;
} else if (left[i] <= right[j]) {
a[i+j] = left[i];
i++;
} else {
a[i+j] = right[j];
j++;
}
}
return;
}
int get_i(int*a,int num,int size){
if(size==0)
return 0;
if(num>med(a,size))
return get_i(&a[(size+1)>>1],num,size>>1)+((size+1)>>1);
else
return get_i(a,num,(size-1)>>1);
}
int med(int*a,int size){
return a[(size-1)>>1];
}
Solution in C++ :
In C++ :
#include<bits/stdc++.h>
#define s(a) scanf("%d",&a)
#define sl(a) scanf("%lld",&a)
#define ss(a) scanf("%s",a)
#define MP make_pair
#define PB push_back
#define REP(i, n) for(int i = 0; i < n; i++)
#define INC(i, a, b) for(int i = a; i <= b; i++)
#define DEC(i, a, b) for(int i = a; i >= b; i--)
#define CLEAR(a) memset(a, 0, sizeof a)
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef vector<int> VI;
typedef pair<int, int> II;
typedef vector<II> VII;
LL inp[500005];
LL cum[500005];
int main()
{
int t=1;
//s(t);
while(t--)
{
int n,Q,q;
LL add = 0;
s(n);
REP(i,n)
sl(inp[i]);
sort(inp,inp+n);
cum[0] = inp[0];
INC(i,1,n-1)
cum[i] = cum[i-1]+inp[i];
s(Q);
while(Q--)
{
s(q);
add+=q;
int pos = lower_bound(inp,inp+n,-add)-inp;
LL ans;
if(pos>0)
ans = (cum[n-1]-cum[pos-1]+add*(n-pos))-(cum[pos-1]+add*pos);
else
ans = (cum[n-1]+add*n);
printf("%lld\n",ans);
}
}
return 0;
}
Solution in Java :
In Java :
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class C {
static InputStream is;
static PrintWriter out;
static String INPUT = "";
static void solve()
{
int n = ni();
long[] a = new long[n];
for(int i = 0;i < n;i++)a[i] = ni();
Arrays.sort(a);
long[] cum =new long[n+1];
for(int i = 0;i < n;i++){
cum[i+1] = cum[i] + a[i];
}
long h = 0;
for(int Q = ni();Q >= 1;Q--){
int x = ni();
h -= x;
int ind = Arrays.binarySearch(a, h);
if(ind < 0)ind = -ind-2;
long ret = 0;
ret += cum[n]-cum[ind+1]-h*(n-(ind+1));
ret += -cum[ind+1]+h*(ind+1);
out.println(ret);
}
}
public static void main(String[] args) throws Exception
{
long S = System.currentTimeMillis();
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
solve();
out.flush();
long G = System.currentTimeMillis();
tr(G-S+"ms");
}
private static boolean eof()
{
if(lenbuf == -1)return true;
int lptr = ptrbuf;
while(lptr < lenbuf)if(!isSpaceChar(inbuf[lptr++]))return false;
try {
is.mark(1000);
while(true){
int b = is.read();
if(b == -1){
is.reset();
return true;
}else if(!isSpaceChar(b)){
is.reset();
return false;
}
}
} catch (IOException e) {
return true;
}
}
private static byte[] inbuf = new byte[1024];
static int lenbuf = 0, ptrbuf = 0;
private static int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private static double nd() { return Double.parseDouble(ns()); }
private static char nc() { return (char)skip(); }
private static String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private static char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private static char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private static int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private static int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private static long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); }
}
Solution in Python :
from collections import Counter
def q(arr, queries):
positive_n = [el for el in arr if el >= 0]
negative_n = [el for el in arr if el < 0]
pos_size = len(positive_n)
neg_size = len(negative_n)
positive = list(reversed(sorted(Counter(positive_n).items())))
negative = sorted(Counter(negative_n).items())
tot = sum(abs(el) for el in arr)
diff = 0 # cum sum of queries
for q in queries:
diff += q
tot += pos_size * q - neg_size * q
if q > 0:
while neg_size and negative[-1][0] + diff >= 0:
(n, count) = negative.pop()
positive.append((n, count))
pos_size += count
neg_size -= count
tot += abs(n + diff) * 2 * count
else:
while pos_size and positive[-1][0] + diff < 0:
(n, count) = positive.pop()
negative.append((n, count))
neg_size += count
pos_size -= count
tot += abs(n + diff) * 2 * count
yield tot
input()
arr = [int(s) for s in input().split()]
input()
que = [int(s) for s in input().split()]
for res in q(arr, que):
print(res)
View More Similar Problems
Jenny's Subtrees
Jenny loves experimenting with trees. Her favorite tree has n nodes connected by n - 1 edges, and each edge is ` unit in length. She wants to cut a subtree (i.e., a connected part of the original tree) of radius r from this tree by performing the following two steps: 1. Choose a node, x , from the tree. 2. Cut a subtree consisting of all nodes which are not further than r units from node x .
View Solution →Tree Coordinates
We consider metric space to be a pair, , where is a set and such that the following conditions hold: where is the distance between points and . Let's define the product of two metric spaces, , to be such that: , where , . So, it follows logically that is also a metric space. We then define squared metric space, , to be the product of a metric space multiplied with itself: . For
View Solution →Array Pairs
Consider an array of n integers, A = [ a1, a2, . . . . an] . Find and print the total number of (i , j) pairs such that ai * aj <= max(ai, ai+1, . . . aj) where i < j. Input Format The first line contains an integer, n , denoting the number of elements in the array. The second line consists of n space-separated integers describing the respective values of a1, a2 , . . . an .
View Solution →Self Balancing Tree
An AVL tree (Georgy Adelson-Velsky and Landis' tree, named after the inventors) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. We define balance factor for each node as : balanceFactor = height(left subtree) - height(righ
View Solution →Array and simple queries
Given two numbers N and M. N indicates the number of elements in the array A[](1-indexed) and M indicates number of queries. You need to perform two types of queries on the array A[] . You are given queries. Queries can be of two types, type 1 and type 2. Type 1 queries are represented as 1 i j : Modify the given array by removing elements from i to j and adding them to the front. Ty
View Solution →Median Updates
The median M of numbers is defined as the middle number after sorting them in order if M is odd. Or it is the average of the middle two numbers if M is even. You start with an empty number list. Then, you can add numbers to the list, or remove existing numbers from it. After each add or remove operation, output the median. Input: The first line is an integer, N , that indicates the number o
View Solution →