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

Print the Elements of a Linked List

This is an to practice traversing a linked list. Given a pointer to the head node of a linked list, print each node's data element, one per line. If the head pointer is null (indicating the list is empty), there is nothing to print. Function Description: Complete the printLinkedList function in the editor below. printLinkedList has the following parameter(s): 1.SinglyLinkedListNode

View Solution →

Insert a Node at the Tail of a Linked List

You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty. Input Format: You have to complete the SinglyLink

View Solution →

Insert a Node at the head of a Linked List

Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and the data value should be replaced with a given value. Return a reference to the new head of the list. The head pointer given may be null meaning that the initial list is empty. Function Description: Complete the function insertNodeAtHead in the editor below

View Solution →

Insert a node at a specific position in a linked list

Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is e

View Solution →

Delete a Node

Delete the node at a given position in a linked list and return a reference to the head node. The head is at position 0. The list may be empty after you delete the node. In that case, return a null value. Example: list=0->1->2->3 position=2 After removing the node at position 2, list'= 0->1->-3. Function Description: Complete the deleteNode function in the editor below. deleteNo

View Solution →

Print in Reverse

Given a pointer to the head of a singly-linked list, print each data value from the reversed list. If the given list is empty, do not print anything. Example head* refers to the linked list with data values 1->2->3->Null Print the following: 3 2 1 Function Description: Complete the reversePrint function in the editor below. reversePrint has the following parameters: Sing

View Solution →