Library Query


Problem Statement :


A giant library has just been inaugurated this week. It can be modeled as a sequence of N consecutive shelves with each shelf having some number of books. Now, being the geek that you are, you thought of the following two queries which can be performed on these shelves.

Change the number of books in one of the shelves.

Obtain the number of books on the shelf having the kth rank within the range of shelves.

A shelf is said to have the kth rank if its position is k when the shelves are sorted based on the number of the books they contain, in ascending order.

Can you write a program to simulate the above queries?

Input Format

The first line contains a single integer T, denoting the number of test cases.
The first line of each test case contains an integer N denoting the number of shelves in the library.
The next line contains N space separated integers where the ith integer represents the number of books on the ith shelf where 1<=i<=N.

The next line contains an integer Q denoting the number of queries to be performed. Q lines follow with each line representing a query.
Queries can be of two types:

1 x k - Update the number of books in the xth shelf to k (1 <= x <= N).
0 x y k - Find the number of books on the shelf between the shelves x and y (both inclusive) with the kth rank (1 <= x <= y <= N, 1 <= k <= y-x+1).



Output Format

For every test case, output the results of the queries in a new line.


Constraints

1 <= T <= 5
1 <= N <= 104
1 <= Q <= 104
The number of books on each shelf is always guaranteed to be between 1 and 1000.



Solution :



title-img


                            Solution in C :

In   C++ :







#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <fstream>
#include <set>
#include <map>
#include <cmath>
#pragma comment(linker,"/STACK:16777216")
#define MAXN 100100

using namespace std;

string s1,s2;

int n,k,a[MAXN],x,q,l,r,cnt[1001],t;

int main()
{
    cin>>t;

    while(t--){
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
            scanf("%d",&a[i]);
        scanf("%d",&q);
        for(int i=0;i<q;i++)
        {
            scanf("%d",&x);
            if(x==1){
                scanf("%d %d",&l,&k);
                a[l]=k;
            }
            else
            {
                scanf("%d %d %d",&l,&r,&k);
                for(int j=1;j<1001;j++)
                    cnt[j]=0;

                for(int i=l;i<=r;i++)
                    cnt[a[i]]++;

                for(int j=1;j<1001;j++)
                    if(cnt[j]>=k)
                    {
                        printf("%d\n",j);
                        break;
                    }
                    else
                        k-=cnt[j];
            }
        }
    }

    return 0;
}








In   Java :









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

public class Solution
{
    public static long MOD = 1000000007L;
    public static void main(String[] args) 
    {
        Scan scan = new Scan(System.in);
        PrintWriter out = new PrintWriter(System.out);
                
        int tc = scan.nextInt();
        for (int t = 0; t < tc; t++)
        {
            int N = scan.nextInt();
            
            int[] arr = new int[N];
            for (int i = 0; i < N; i++)
                arr[i] = scan.nextInt();
            
            int Q = scan.nextInt();
            for (int q = 0; q < Q; q++)
            {
                int op = scan.nextInt();
                if (op == 1)
                {
                    int x = scan.nextInt() - 1;
                    int k = scan.nextInt();
                    arr[x] = k;
                }
                else
                {
                    int x = scan.nextInt() - 1;
                    int y = scan.nextInt() - 1;
                    int k = scan.nextInt();
                    
                    int i;
                    int[] temp = new int[1001];
                    for (i = x; i <= y; i++)
                        temp[arr[i]]++;
                    
                    for (i = 0; i < 1001 ; i++)
                    {
                        k -= temp[i];                        
                        if (k <= 0) break;
                    }
                    out.println(i);
                }
            }                            
        }
        out.close();        
    }    
}

final class Scan
{
    private InputStream in = null;
    private int pos,count;
    private byte[] buf = new byte[1<<16];
    
    public Scan(InputStream in)
    {
        this.in = in;
        pos = 0;
        count = 0;
    }
    public int nextInt()
    {
        int c=read(), sign = 1;
        while (c <= ' ')
            c = read();
        if (c == '-')
        {
            sign = -1;
            c = read();
        }
        int n = c - '0';
        while((c = read() - '0') >= 0)
            n = n * 10 + c;
        return n * sign;        
    }    
public String next()
{
StringBuilder sb = new StringBuilder();
int c = read();
while (c <= ' ')
c = read();
while (c >= 33)
{
sb.append((char) c );
c = read();
}
return sb.toString();
}
public long nextLong()
{
int c = read(), sign = 1;
while (c <= ' ')
c = read();
if (c == '-')
{
sign = -1;
c = read();
}        
long n = 1L * (c - '0');
while((c = read() - '0') >= 0)
n = n * 10 + c;
return n * sign;        
}
public int read()
{
if( pos == count)
fillBuffer();

return buf[pos++];        
}
private void fillBuffer()
{
try
{
count = in.read(buf, pos = 0 , buf.length);
if (count == -1)
buf[0] = -1;
}
catch(Exception e)
{

}
}
}









In    C  :







#include<stdio.h>
struct node{
int v,i;
};
struct node a[10005],temp;

int part(int lo,int hi)
{int i=lo,j=hi,pivot=a[(i+j)/2].v;
while (i<=j)
   {while (a[i].v<pivot) i++;
    while (a[j].v>pivot) j--;
    if (i<=j)
    {temp=a[j]; a[j]=a[i]; a[i]=temp; i++; j--;}


   }
   return i;
}
void sort(int lo,int hi)
{int x=part(lo,hi);
 if (lo<x-1) sort(lo,x-1);
 if (x<hi) sort(x,hi);
}

int main(){
int t,k,i,j,n,q,x,y,f,l,count;
scanf("%d",&t);
while(t--){
 scanf("%d",&n);
 for(j=1;j<=n;j++){
  scanf("%d",&a[j].v);
  a[j].i=j;
 }
 sort(1,n);/*
 for(j=1;j<=n;j++){
    printf("%d %d\n",a[j].v,a[j].i);
  }
 printf("\n");*/
 scanf("%d",&q);
 while(q--){
    scanf("%d",&f);
    if(f==0){
         scanf("%d%d%d",&x,&y,&k);
         count=0;
         for(j=1;count!=k;j++){
                  if( x <=a[j].i && a[j].i<=y )  count++;
            }
          printf("%d\n",a[j-1].v);
       }
    else{
       scanf("%d%d",&l,&k);
       for(j=1;j<=n;j++){
           if(a[j].i == l){
               a[j].v=k;
             }
        temp=a[j];
        while(temp.v<a[j-1].v && j>0){
                                   a[j]=a[j-1];
                                      j--;
                                  }
            a[j]=temp;
        while(temp.v>a[j+1].v && j<n){
                                    a[j]=a[j+1];
                                      j++;
                                  }
            a[j]=temp;


        }/*
         for(j=1;j<=n;j++){
      printf("%d %d\n",a[j].v,a[j].i);
      }
      printf("\n");*/

     }

  }
}
return 0;
}









In   Python3 :







class FenwickTree2D:
    def __init__(self, x,y):
        self.size_x = x
        self.size_y = y
        self.data = [[0]*self.size_y for _ in range(self.size_x)]
 
    def sum(self, x1, y1):
        if min(x1,y1) <= 0: return 0
        s = 0
        x = x1
        while x >= 0:
            y = y1
            while y >= 0:
                s += self.data[x][y]
                y = (y & (y+1)) - 1
            x = (x & (x+1)) - 1
        return s

    def sumrange(self, x1, y1, x2, y2): 
        return self.sum(x2, y2) \
               - self.sum(x1-1, y2) - self.sum(x2, y1-1) \
               + self.sum(x1-1,y1-1)

    def add(self, x1, y1, w):
        assert min(x1,y1) > 0
        x = x1
        while x < self.size_x:
            y = y1
            while y < self.size_y:
                self.data[x][y] += w
                y |= y + 1
            x |= x + 1

for t in range(int(input())):
    N = int(input())
    arr = list(map(int,input().split()))
    t = FenwickTree2D(10001,1001)
    for i in range(len(arr)):
        t.add(i+1,arr[i],1)
    Q = int(input())
    for q in range(Q):
        c = list(map(int,input().split()))
        if c[0]==1:
            t.add(c[1],arr[c[1]-1],-1)
            arr[c[1]-1] = c[2]
            t.add(c[1],arr[c[1]-1],1)
        else:
            def select(l,r,k):
                lo,hi=1,1000
                while lo < hi:
                    med = (hi+lo)//2
                    a = t.sumrange(l,0,r,med)
                    if a>=k:
                        hi = med
                    else:
                        lo = med+1

                if not t.sumrange(l,0,r,lo) >= k:
                    raise ValueError
                return lo
            print(select(c[1],c[2],c[3]))
                        








View More Similar Problems

The Strange Function

One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting

View Solution →

Self-Driving Bus

Treeland is a country with n cities and n - 1 roads. There is exactly one path between any two cities. The ruler of Treeland wants to implement a self-driving bus system and asks tree-loving Alex to plan the bus routes. Alex decides that each route must contain a subset of connected cities; a subset of cities is connected if the following two conditions are true: There is a path between ever

View Solution →

Unique Colors

You are given an unrooted tree of n nodes numbered from 1 to n . Each node i has a color, ci. Let d( i , j ) be the number of different colors in the path between node i and node j. For each node i, calculate the value of sum, defined as follows: Your task is to print the value of sumi for each node 1 <= i <= n. Input Format The first line contains a single integer, n, denoti

View Solution →

Fibonacci Numbers Tree

Shashank loves trees and math. He has a rooted tree, T , consisting of N nodes uniquely labeled with integers in the inclusive range [1 , N ]. The node labeled as 1 is the root node of tree , and each node in is associated with some positive integer value (all values are initially ). Let's define Fk as the Kth Fibonacci number. Shashank wants to perform 22 types of operations over his tree, T

View Solution →

Pair Sums

Given an array, we define its value to be the value obtained by following these instructions: Write down all pairs of numbers from this array. Compute the product of each pair. Find the sum of all the products. For example, for a given array, for a given array [7,2 ,-1 ,2 ] Note that ( 7 , 2 ) is listed twice, one for each occurrence of 2. Given an array of integers, find the largest v

View Solution →

Lazy White Falcon

White Falcon just solved the data structure problem below using heavy-light decomposition. Can you help her find a new solution that doesn't require implementing any fancy techniques? There are 2 types of query operations that can be performed on a tree: 1 u x: Assign x as the value of node u. 2 u v: Print the sum of the node values in the unique path from node u to node v. Given a tree wi

View Solution →