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

Truck Tour

Suppose there is a circle. There are N petrol pumps on that circle. Petrol pumps are numbered 0 to (N-1) (both inclusive). You have two pieces of information corresponding to each of the petrol pump: (1) the amount of petrol that particular petrol pump will give, and (2) the distance from that petrol pump to the next petrol pump. Initially, you have a tank of infinite capacity carrying no petr

View Solution →

Queries with Fixed Length

Consider an -integer sequence, . We perform a query on by using an integer, , to calculate the result of the following expression: In other words, if we let , then you need to calculate . Given and queries, return a list of answers to each query. Example The first query uses all of the subarrays of length : . The maxima of the subarrays are . The minimum of these is . The secon

View Solution →

QHEAP1

This question is designed to help you get a better understanding of basic heap operations. You will be given queries of types: " 1 v " - Add an element to the heap. " 2 v " - Delete the element from the heap. "3" - Print the minimum of all the elements in the heap. NOTE: It is guaranteed that the element to be deleted will be there in the heap. Also, at any instant, only distinct element

View Solution →

Jesse and Cookies

Jesse loves cookies. He wants the sweetness of all his cookies to be greater than value K. To do this, Jesse repeatedly mixes two cookies with the least sweetness. He creates a special combined cookie with: sweetness Least sweet cookie 2nd least sweet cookie). He repeats this procedure until all the cookies in his collection have a sweetness > = K. You are given Jesse's cookies. Print t

View Solution →

Find the Running Median

The median of a set of integers is the midpoint value of the data set for which an equal number of integers are less than and greater than the value. To find the median, you must first sort your set of integers in non-decreasing order, then: If your set contains an odd number of elements, the median is the middle element of the sorted sample. In the sorted set { 1, 2, 3 } , 2 is the median.

View Solution →

Minimum Average Waiting Time

Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes. Different kinds of pizzas take different amounts of time to cook. Also, once h

View Solution →