Almost Equal - Advanced


Problem Statement :


A Sumo wrestling championship is scheduled to be held this winter in the HackerCity where N wrestlers from different parts of the world are going to participate. The rules state that two wrestlers can fight against each other if and only if the difference in their height is less than or equal to K,
(i.e) wrestler A and wrestler B can fight if and only if |height(A)-height(B)|<=K.

Given an array H[], where H[i] represents the height of the ith fighter, for a given l, r where 0 <= l <= r < N, can you count the number of pairs of fighters between l and r (both inclusive) who qualify to play a game?

Input Format

The first line contains an integer N and K separated by a single space representing the number of Sumo wrestlers who are going to participate and the height difference K.
The second line contains N integers separated by a single space, representing their heights H[0] H[1] ... H[N - 1].
The third line contains Q, the number of queries. This is followed by Q lines each having two integers l and r separated by a space.

Output Format

For each query Q, output the corresponding value of the number of pairs of fighters for whom the absolute difference of height is not greater that K.

Constraints

1 <= N <= 100000
0 <= K <= 109
0 <= H[i] <= 109
1 <= Q <= 100000
0 <= l <= r < N



Solution :



title-img


                            Solution in C :

In   C++ :








#include <algorithm>
#include <iostream>
#include <iomanip>
#include <complex>
#include <cstring>
#include <cstdlib>
#include <string>
#include <vector>
#include <cstdio>
#include <cmath>
#include <map>
#include <set>
using namespace std;
//#pragma comment(linker,"/STACK:102400000,102400000")

int n, K;

struct element
{
	int val;
	int index;
	bool operator <(element that) const
	{
		return val < that.val;
	}
}E[100001];

int toLeft[100001], toRight[100001];
int indexToRank[100001];

int s[1000001];
int lowbit(int x){return x&(-x);}

inline void update(int pos, int v)
{
	while(pos <= n)
	{
		s[pos] += v;
		pos += lowbit(pos);
	}
}

inline int query(int pos)
{
	int ret = 0;
	while(pos)
	{
		ret += s[pos];
		pos -= lowbit(pos);
	}
	return ret;
}

int SQRTN = 330;
int nQuery;
long long ans[100001];

struct query
{
	int L, R;
	int index;
	bool operator <(query that) const
	{
		if(L / SQRTN != that.L / SQRTN)
			return L / SQRTN < that.L / SQRTN;
		if((L / SQRTN) % 2 == 0)
			return R / SQRTN < that.R/SQRTN;
		return R / SQRTN > that.R/SQRTN;
	}
}Q[100001];

int curL = 1, curR = 0;
long long curAns = 0;

inline long long evaluation()
{
	long long ret = 0;
	for(int i = 2; i <= nQuery; i++)
		ret += abs(Q[i].L - Q[i-1].L) + abs(Q[i].R - Q[i-1].R);
	return ret;
}

inline void addIt(int x)
{
	x = indexToRank[x];
	curAns += query(toRight[x]) - query(toLeft[x]-1);
	update(x, 1);
}

inline void delIt(int x)
{
	x = indexToRank[x];
	update(x, -1);
	curAns -= query(toRight[x]) - query(toLeft[x]-1);
}

int MAIN()
{
	scanf("%d %d", &n, &K);
	//cin >> n >> K;
	for(int i = 1; i <= n; i++)
	{
		scanf("%d", &E[i].val);
		//cin >> E[i].val;
		E[i].index = i;
	}
	sort(E + 1, E + 1 + n);
	
	for(int i = 1; i <= n; i++)
		indexToRank[E[i].index] = i;
	int p = 1;
	for(int i = 1; i <= n; i++)
	{
		while(E[i].val - E[p].val > K) p ++;
		toLeft[i] = p;
	}
	p = n;
	for(int i = n; i >= 1; i--)
	{
		while(E[p].val - E[i].val > K) p --;
		toRight[i] = p;
	}

	scanf("%d", &nQuery);
	//cin >> nQuery;
	for(int i = 1; i <= nQuery; i++)
		scanf("%d %d", &Q[i].L, &Q[i].R), Q[i].index = i;
		//cin >> Q[i].L >> Q[i].R, Q[i].index = i;
	int old_sqrtN = SQRTN;
	long long bestSqurn = 0, bestV = 1000000000000LL;
	for(int i = old_sqrtN - 20; i <= old_sqrtN + 20; i += 10)
	{
		SQRTN = i;
		sort(Q + 1, Q + 1 + nQuery);
		long long v = evaluation();
		if(v < bestV)
		{
			bestV = v;
			bestSqurn = i;
		}
	}
	SQRTN = bestSqurn;
	sort(Q + 1, Q + 1 + nQuery);
	memset(s, 0, sizeof(s));

	for(int i = 1; i <= nQuery; i++)
	{
		//cout << Q[i].index << endl;
		int L = Q[i].L + 1, R = Q[i].R + 1;
		if(curL > R || curR < L)
		{
			while(curL <= curR)
			{
				delIt(curL);
				curL ++;
			}
			curL = L;
			curR = L-1;
		}
		while(curR < R)
		{
			addIt(curR + 1);
			curR += 1;
		}
		while(curL > L)
		{
			addIt(curL - 1);
			curL --;
		}
		while(curR > R)
		{
			delIt(curR);
			curR --;
		}
		while(curL < L)
		{
			delIt(curL);
			curL ++;
		}
		ans[Q[i].index] = curAns;
		//cout << curAns << endl;
	}

	for(int i = 1; i <= nQuery; i++)
		printf("%lld\n", ans[i]);
		//cout << ans[i] << endl;
	
	
	return 0;
}

int main()
{
	#ifdef LOCAL_TEST
		freopen("in.txt", "r", stdin);
		freopen("out.txt", "w", stdout);
	#endif
	//ios :: sync_with_stdio(false);
	//cout << fixed << setprecision(16);
	return MAIN();
}









In   Java :







import java.io.*;
import java.util.*;

public class Solution {

  static int nn;
  static int block;
  static int[] fenwick;
  static long cnt = 0;

  static class B implements Comparable<B> {
    int l;
    int r;
    int id;
    
    @Override
    public int compareTo(B o) {
      int i = l/block;
      int j = o.l/block;
      if (i != j) {
        return i - j;
      }
      if (r != o.r) {
        return r - o.r;
      }
      return l - o.l;
    }
  }
  
  static int getSum(int x) {
    int s = 0;
    for (; x != 0; x &= x-1)
      s += fenwick[x-1];
    return s;
  }

  static class Node {
    int l;
    int r;
    int h;

    public Node(int l, int r, int h) {
      this.l = l;
      this.r = r;
      this.h = h;
    }

    void remove() {
      add(h, -1);
      cnt -= getSum(r) - getSum(l);
    }

    void add() {
      cnt += getSum(r) - getSum(l);
      add(h, 1);
    }

    void add(int x, int v) {
      for (; x < nn; x |= x+1)
        fenwick[x] += v;
    }
  }

    
  static public int lowerBound(int[] arr, int len, int key) {
    if (key <= arr[0]) {
      return 0;
    }
    if (key > arr[len - 1]) {
      return 0;
    }
    
    int index = Arrays.binarySearch(arr, 0, len, key);
    if (index < 0) {
      index = - index - 1;
      if (index < 0) {
        return 0;
      }
    } 
    return index;
  }
  
  static public int upperBound(int[] arr, int len, int key) {
    int index = Arrays.binarySearch(arr, 0, len, key+1);
    if (index < 0) {
      index = - index - 1;
      if (index < 0 || index > len) {
        return 0;
      }
    }
    return index;
  }
  
  public static int unique(int[] arr) {
    if (arr.length == 1) return 1;
    int len = 1;
    while (len < arr.length && arr[len] != arr[len-1]) { 
      len++;
    }
    for (int i = len + 1; i < arr.length; i++) {
      if (arr[i] != arr[len - 1]) {
        len++;
        arr[len - 1] = arr[i];
      }
    }
    return len;
  }

  public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    BufferedWriter bw = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

    StringTokenizer st = new StringTokenizer(br.readLine());
    int n = Integer.parseInt(st.nextToken());
    int k = Integer.parseInt(st.nextToken());

    st = new StringTokenizer(br.readLine());
    int[] a = new int[n];
    int[] c = new int[n];
    for (int i = 0; i < n; i++) {
      int item = Integer.parseInt(st.nextToken());
      c[i] = a[i] = item;
    }
    Arrays.sort(c);
    nn = unique(c);
    
    Node[] nodes = new Node[n];
    for (int i = 0; i < n; i++) {
      int l = lowerBound(c, nn, a[i]-k);
      int r = upperBound(c, nn, a[i]+k);
      int h = lowerBound(c, nn, a[i]);
      nodes[i] = new Node(l, r, h);
    }
    
    st = new StringTokenizer(br.readLine());
    int q = Integer.parseInt(st.nextToken());
    
    B[] b = new B[q];
    block = (int) Math.max(1.0, Math.sqrt((double)(n)*n/Math.max(1, q)));
    for (int i = 0; i < q; i++) {
      st = new StringTokenizer(br.readLine());
      b[i] = new B();
      b[i].id = i;
      b[i].l = Integer.parseInt(st.nextToken());
      b[i].r = Integer.parseInt(st.nextToken()) + 1;
    }
    Arrays.sort(b);
    int l = 0;
    int r = 0;
    fenwick = new int[n];
    long[] result = new long[q];
    for (int i = 0; i < q; i++) {
      while (l < b[i].l) {
        nodes[l++].remove();
      }
      while (b[i].l < l) {
        nodes[--l].add();
      }
      while (b[i].r < r) {
        nodes[--r].remove();
      }
      while (r < b[i].r) {
        nodes[r++].add();
      }
      result[b[i].id] = cnt;
    }

    for (int i = 0; i < result.length; i++) {
      bw.write(String.valueOf(result[i]));

      if (i != result.length - 1) {
        bw.write("\n");
      }
    }

    bw.newLine();

    bw.close();
    br.close();
  }
}







In   Python3  :







def clean():
	put=input()
	put=put.split(" ")
	for i in range(len(put)):
		put[i]=int(put[i])
	return put	
	
dict=dict()

def calc(l,u):
	if(u==l):
		return 0
	global hgt,k,dict
	if (l,u) in dict.keys():
		return dict[(l,u)]
	sum=0
	for i in range(l,u):
		if(abs(hgt[u]-hgt[i])<=k):
			sum+=1
	dict[(l,u)]=sum+calc(l,u-1)
	return dict[(l,u)];	








put=clean()
n=put[0]#number of wlers
k=put[1]#h diff
hgt=clean()


q=int(input())
for xyz in range(q):
	put=clean()
	l=put[0]
	u=put[1]				
	print(str(calc(l,u)))
                        








View More Similar Problems

Equal Stacks

ou have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You can change the height of a stack by removing and discarding its topmost cylinder any number of times. Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means you must remove zero or more cylinders from the top of zero or more of

View Solution →

Game of Two Stacks

Alexa has two stacks of non-negative integers, stack A = [a0, a1, . . . , an-1 ] and stack B = [b0, b1, . . . , b m-1] where index 0 denotes the top of the stack. Alexa challenges Nick to play the following game: In each move, Nick can remove one integer from the top of either stack A or stack B. Nick keeps a running sum of the integers he removes from the two stacks. Nick is disqualified f

View Solution →

Largest Rectangle

Skyline Real Estate Developers is planning to demolish a number of old, unoccupied buildings and construct a shopping mall in their place. Your task is to find the largest solid area in which the mall can be constructed. There are a number of buildings in a certain two-dimensional landscape. Each building has a height, given by . If you join adjacent buildings, they will form a solid rectangle

View Solution →

Simple Text Editor

In this challenge, you must implement a simple text editor. Initially, your editor contains an empty string, S. You must perform Q operations of the following 4 types: 1. append(W) - Append W string to the end of S. 2 . delete( k ) - Delete the last k characters of S. 3 .print( k ) - Print the kth character of S. 4 . undo( ) - Undo the last (not previously undone) operation of type 1 or 2,

View Solution →

Poisonous Plants

There are a number of plants in a garden. Each of the plants has been treated with some amount of pesticide. After each day, if any plant has more pesticide than the plant on its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each of the plants. Determine the number of days after which no plant dies, i.e. the time after which there is no plan

View Solution →

AND xor OR

Given an array of distinct elements. Let and be the smallest and the next smallest element in the interval where . . where , are the bitwise operators , and respectively. Your task is to find the maximum possible value of . Input Format First line contains integer N. Second line contains N integers, representing elements of the array A[] . Output Format Print the value

View Solution →