Queries with Fixed Length


Problem Statement :


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 second query uses all of the subarrays of length : . The maxima of the subarrays are . The minimum of these is .

Return .



Function Description

Complete the solve function below.

solve has the following parameter(s):

int arr[n]: an array of integers
int queries[q]: the lengths of subarrays to query
Returns

int[q]: the answers to each query
Input Format

The first line consists of two space-separated integers, n  and q.
The second line consists of n space-separated integers, the elements of arr.
Each of the q  subsequent lines contains a single integer denoting the value of d for that query.



Solution :



title-img


                            Solution in C :

In C ++ :




#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

#define li long int
#define INT_MAX 1000000007
li tree[1000000];
li A[200000];

void build(int node, int start, int end)
{
    if(start == end)
    {
        tree[node] = A[start];
    }
    else
    {
        int mid = (start + end) / 2;
        build(2*node, start, mid);
        build(2*node+1, mid+1, end);

        tree[node] = max(tree[2*node] , tree[2*node+1]);
    }
}

int query(int node, int start, int end, int l, int r)
{
    if(r < start or end < l)
    {
        return 0;
    }
    if(l <= start and end <= r)
    {
        return tree[node];
    }

    int mid = (start + end) / 2;
    int p1 = query(2*node, start, mid, l, r);
    int p2 = query(2*node+1, mid+1, end, l, r);
    return max(p1 , p2);
}

int main() {
   
    li q,n,d;
    
    cin >> n >> q;
    
    for(int i=0;i<n;++i) cin >> A[i];
    
    build(1,0,n-1);
    
    while(q--)
        {
        
        cin >> d;
        
        li min=INT_MAX;
        for(int i=0;i<=n-d;++i)
        {
            li temp_max=query(1,0,n-1,i,i+d-1);
            
            if(temp_max<min) min = temp_max; 
            
        }
        
        cout<<min<<endl;
    }
    
    
    return 0;
}








In Java :





import java.util.Scanner;

public class Solution
{
  public static void main(String[] args)
  {
    Scanner scan = new Scanner(System.in);
    int dataCount = scan.nextInt();
    int queriesCount = scan.nextInt();
    int[] data = new int[dataCount];
    for (int i = 0; i < dataCount; ++i)
      data[i] = scan.nextInt();
    for (int i = 0; i < queriesCount; ++i)
      System.out.println(findMinMax(data, scan.nextInt()));
  }

  private static int findMinMax(int[] data, int range)
  {
    if (range >= data.length)
      return easyMax(data, 0, data.length);
    int maxV = easyMax(data, data.length - range, data.length);
    int minV = maxV;
    for (int i = data.length - range - 1; i >= 0; --i)
    {
      if (data[i] == data[i+range]) //nothing changed
        continue;
      if (data[i] > maxV)
        maxV = data[i];
      else if (data[i + range] == maxV)
        maxV = easyMax(data, i, i + range);
      if (maxV < minV)
        minV = maxV;
    }
    return minV;
  }

  private static int easyMax(int[] data, int fromInclusive, int toExclusive)
  {
    int pos = toExclusive;
    int max = data[--pos];
    while (--pos >= fromInclusive)
      if (data[pos] > max)
        max = data[pos];
    return max;
  }
}








In C :






#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <stdlib.h>

struct queue{
    int front,rear,size;
    unsigned capacity;
    long *array;
    int *index;
};

struct queue *create(unsigned capacity){
    struct queue *q=(struct queue *)malloc(sizeof(struct queue));
    q->front=0;
    q->rear=capacity-1;
    q->size=0;
    q->capacity=capacity;
    q->array=(long *)malloc(q->capacity*sizeof(long));
    q->index=(int *)malloc(q->capacity*sizeof(int));
    for(int i=0;i<q->capacity;i++){
        q->array[i]=0;
        q->index[i]=0;
    }
    return q;
}

int full(struct queue* q){
    if(q->size==q->capacity)    return 1;
    else    return 0;
}

int empty(struct queue* q){
    if(q->size==0)  return 1;
    else    return 0;
}

void enque(struct queue* q, long x, int i){
    if(!full(q)){
        q->size++;
        q->rear=(q->rear+1)%(q->capacity);
        q->array[q->rear]=x;
        q->index[q->rear]=i;
    }
}

void deque(struct queue *q){
    if(!empty(q)){
        q->size--;
        q->front=(q->front+1)%(q->capacity);
    }
}

long top_array(struct queue *q){
    if(!empty(q))   return q->array[q->front];
    return INT_MAX;
}

int top_index(struct queue *q){
    if(!empty(q))   return q->index[q->front];
    return INT_MAX;
}

void deque_back(struct queue *q){
    if(!empty(q)){
        q->size--;
        q->rear=(q->rear-1);
        if(q->rear<0)   q->rear=q->capacity+q->rear;
    }
}

long bottom_array(struct queue *q){
    if(!empty(q))   return q->array[q->rear];
    return INT_MAX;
}

int main(){
    
    int n,Q,i,j,k;
    scanf("%d%d",&n,&Q);
    long *a=(long *)malloc(n*sizeof(long));
    for(i=0;i<n;i++){
        scanf("%li",&a[i]);
    }
    int d;
    
    
    
    for(i=0;i<Q;i++){
        long max,min=INT_MAX;
        scanf("%d",&d);
        struct queue *q=create(n);
        j=0;
        //printf("%d %d ",q->rear,q->size);
        while(j<d){
            if(empty(q))    enque(q,a[j],j); 
            else{
                while(a[j]>=bottom_array(q)){   deque_back(q);  }
                enque(q,a[j],j);
            }
            //for(k=0;k<n;k++){ printf("%li ",q->array[k]);  }
            //printf("%d ",bottom_array(q));
            j++;
        }
        min=top_array(q);
        
        
        
        while(j<n){
            while(j-top_index(q)<d && j<n){
                if(top_array(q)<min)    min=top_array(q);
                while(a[j]>=bottom_array(q)){
                    deque_back(q);
                }
                enque(q,a[j],j);
                j++;
            }
            if(j-top_index(q)==d && j<n){
                if(top_array(q)<min)    min=top_array(q);
                deque(q);
                while(a[j]>=bottom_array(q)){
                    deque_back(q);    
                }
                enque(q,a[j],j);
                j++;
            }
        }
        
        
        
        
        if(top_array(q)<min)    min=top_array(q);
        printf("%li\n",min);
        free(q);
    }
    
    
    
    
    
    return 0;
}









In Python3 :





from collections import deque
n, q = map(int, input().split())
a = list(map(int, input().split()))
for _ in range(q):
    d = int(input())
    l = deque()
    m = 0
    for i in range(d - 1, -1, -1):
        if m < a[i]:
            m = a[i]
            l.appendleft(i)
    for i in range(d, n):
        if l[0] + d <= i:
            l.popleft()
        while l and a[l[-1]] < a[i]:
            l.pop()
        l.append(i)
        m = min(m, a[l[0]])
    print(m)
                        








View More Similar Problems

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 →

Ticket to Ride

Simon received the board game Ticket to Ride as a birthday present. After playing it with his friends, he decides to come up with a strategy for the game. There are n cities on the map and n - 1 road plans. Each road plan consists of the following: Two cities which can be directly connected by a road. The length of the proposed road. The entire road plan is designed in such a way that if o

View Solution →