Array and simple queries


Problem Statement :


Given two numbers N  and M. N  indicates the number of elements in the array  A[](1-indexed) and  M indicates number of queries. You need to perform two types of queries on the array A[] .

You are given  queries. Queries can be of two types, type 1 and type 2.

Type 1 queries are represented as 1 i j : Modify the given array by removing elements from i to j and adding them to the front.

Type 2 queries are represented as 2 i j : Modify the given array by removing elements from i to j and adding them to the back.

Your task is to simply print | A[1] -  A[N] | of the resulting array after the execution of  queries followed by the resulting array.

Note While adding at back or front the order of elements is preserved.

Input Format


First line consists of two space-separated integers, N and M .
Second line contains N integers,  which represent the elements of the array.
M queries follow. Each line contains a query of either type 1 or type 2 in the form type i j


Output Format

Print the absolute value i.e. abs(A[1] - A[N] )  in the first line.
Print elements of the resulting array in the second line. Each element should be seperated by a single space.



Solution :



title-img


                            Solution in C :

In C ++ :




#include <iostream>
#include <cstdlib>
#include <vector>
#include <ctime>

struct ctree {
	long value, size;
	int prio;
	ctree *left, *right;
};

static const long MAX_N = 100000l;
static ctree nodes[MAX_N];
static long values[MAX_N];

static long csize(ctree *t)
{ return t ? t->size : 0; }

static ctree *cmerge(ctree *l, ctree *r)
{
	if (!l) return r;
	if (!r) return l;

	if (l->prio > r->prio) {
		l->right = cmerge(l->right, r);
		l->size = csize(l->left) + csize(l->right) + 1;
		return l;
	}
	r->left = cmerge(l, r->left);
	r->size = csize(r->left) + csize(r->right) + 1;
	return r;
}

static void csplit(ctree *t, long idx, ctree *&l, ctree *&r)
{
	if (!t) {
		l = r = 0;
		return;
	}

	const long cur = csize(t->left) + 1;
	if (cur <= idx) {
		csplit(t->right, idx - cur, t->right, r);
		l = t;
	} else {
		csplit(t->left, idx, l, t->left);
		r = t;
	}
	t->size = csize(t->left) + csize(t->right) + 1;
}

static ctree *cextract(ctree *&t, long from, long to)
{
	ctree *l, *m, *r;

	csplit(t, from, l, m);
	csplit(m, to - from, m, r);
	t = cmerge(l, r);
	return m;
}

static long traverse(ctree *tree, long i)
{
	if (!tree)
		return i;

	i = traverse(tree->left, i);
	values[i++] = tree->value;
	return traverse(tree->right, i);
}

int main()
{
	srand(time(NULL));
	for (long i = 0; i != MAX_N; ++i) {
		nodes[i].prio = rand();
		nodes[i].size = 1;
	}

	long n, m;
	std::cin >> n >> m;

	ctree *tree = 0;
	for (long i = 0; i != n; ++i) {
		std::cin >> nodes[i].value;
		tree = cmerge(tree, nodes + i);
	}

	for (long i = 0; i != m; ++i) {
		long l, r;
		int type;

		std::cin >> type >> l >> r;

		ctree *sub = cextract(tree, l - 1, r);
		if (type == 1)
			tree = cmerge(sub, tree);
		else
			tree = cmerge(tree, sub);
	}

	traverse(tree, 0);
	std::cout << std::abs(values[0] - values[n - 1]) << "\n";
	for (long i = 0; i != n; ++i)
		std::cout << values[i] << " ";
	std::cout << "\n";

	return 0;
}








In C :




#include <stdio.h>
#include <stdlib.h>
typedef struct _ct_node{
  int size;
  int priority;
  int value;
  struct _ct_node *left,*right;
} ct_node;
void tar(ct_node *root);
int get_size(ct_node *root);
ct_node* merge(ct_node *L,ct_node *R);
int sizeOf(ct_node *root);
void recalc(ct_node *root);
void split(int x,ct_node **L,ct_node **R,ct_node *root);
void computeTree();
int P[100000],T[100000],st[100000],N;
ct_node pool[100000];

int main(){
  int M,x,y,z,i;
  ct_node *root,*l,*m,*r,*t;
  scanf("%d%d",&N,&M);
  for(i=0;i<N;i++){
    scanf("%d",&pool[i].value);
    P[i]=pool[i].priority=rand();
    pool[i].left=pool[i].right=NULL;
  }
  computeTree();
  for(i=0;i<N;i++)
    if(T[i]==-1)
      root=&pool[i];
    else
      if(i<T[i])
        pool[T[i]].left=&pool[i];
      else
        pool[T[i]].right=&pool[i];
  get_size(root);
  for(i=0;i<M;i++){
    scanf("%d%d%d",&x,&y,&z);
    switch(x){
      case 1:
        split(y-2,&l,&t,root);
        split(z-y,&m,&r,t);
        root=merge(merge(m,l),r);
        break;
      default:
        split(y-2,&l,&t,root);
        split(z-y,&m,&r,t);
        root=merge(merge(l,r),m);
    }
  }
  N=0;
  tar(root);
  printf("%d\n",(T[0]>T[N-1])?T[0]-T[N-1]:T[N-1]-T[0]);
  for(i=0;i<N;i++)
    printf("%d ",T[i]);
  return 0;
}
void tar(ct_node *root){
  if(!root)
    return;
  tar(root->left);
  T[N++]=root->value;
  tar(root->right);
  return;
}
int get_size(ct_node *root){
  if(!root)
    return 0;
  root->size=get_size(root->left)+get_size(root->right)+1;
  return root->size;
}
ct_node* merge(ct_node *L,ct_node *R){
  if(!L)
    return R;
  if(!R)
    return L;
  if(L->priority>R->priority){
    L->right=merge(L->right,R);
    recalc(L);
    return L;
  }
  R->left=merge(L,R->left);
  recalc(R);
  return R;
}
int sizeOf(ct_node *root){
  return (root)?root->size:0;
}
void recalc(ct_node *root){
  root->size=sizeOf(root->left)+sizeOf(root->right)+1;
  return;
}
void split(int x,ct_node **L,ct_node **R,ct_node *root){
  if(!root){
    *L=*R=NULL;
    return;
  }
  int curIndex=sizeOf(root->left);
  ct_node *t;
  if(curIndex<=x){
    split(x-curIndex-1,&t,R,root->right);
    root->right=t;
    recalc(root);
    *L=root;
  }
  else{
    split(x,L,&t,root->left);
    root->left=t;
    recalc(root);
    *R=root;
  }
  return;
}
void computeTree(){
  int i,k,top=-1;
  for(i=0;i<N;i++){
    k=top;
    while(k>=0 && P[st[k]]<P[i])
      k--;
    if(k!=-1)
      T[i]=st[k];
    if(k<top)
      T[st[k+1]]=i;
    st[++k]=i;
    top=k;
  }
  T[st[0]]=-1;
  return;
}







In Java :




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

public class Solution {
    
    Node root;
    
    public Solution() {
        root = null;
    }
    
    public int size(Node root) {
        if (root == null)
            return 0;
        return root.size;
    }
    
    private void update(Node root) {
        if (root != null)
            root.size = 1 + size(root.left) + size(root.right);
    }
    
    public DNode split(Node root, int key) {
    	DNode pair = new DNode();
        if (root == null) {
            return pair;
        }
        if (size(root.left) >= key) {
            pair = split(root.left, key);
            root.left = pair.right;
            update(root);
            pair.right = root;
        } else {
            pair = split(root.right, key - size(root.left) - 1);
            root.right = pair.left;
            update(root);
            pair.left = root;
        }
        return pair;
    }
    
    public Node merge(Node left, Node right) {
        if (left == null) return right;
        if (right == null) return left;
        
        if (left.pri > right.pri) {
            left.right = merge(left.right, right);
            update(left);
            return left;
        } else {
            right.left = merge(left, right.left);
            update(right);
            return right;
        }
    }
    
    public Node getFirst() {
    	if (root == null)
    		return null;
    	return getFirst(root);
    }
    
    private Node getFirst(Node root) {
    	if (root.left != null)
    		return getFirst(root.left);
    	return root;
    }
    
    public Node getLast() {
    	if (root == null)
    		return null;
    	return getLast(root);
    }
    
    private Node getLast(Node root) {
    	if (root.right != null)
    		return getLast(root.right);
    	return root;
    }
    
    public void query1(int left, int right) {
    	DNode pair1 = split(root, right);
    	DNode pair2 = split(pair1.left, left-1);
    	
    	root = merge(pair2.left, pair1.right);
    	root = merge(pair2.right, root);
    }
    
    public void query2(int left, int right) {
    	DNode pair1 = split(root, right);
    	DNode pair2 = split(pair1.left, left-1);
    	
    	root = merge(pair2.left, pair1.right);
    	root = merge(root, pair2.right);
    }
    
    public void add(int val, int pri) {
        Node n = new Node(val, pri);
        root = merge(root, n);
    }
    
    public void inorder() {
        inorder(root);
        System.out.println();
    }
    
    private void inorder(Node n) {
        if (n == null)
            return;
        inorder(n.left);
        System.out.print(n + " ");
        inorder(n.right);
    }
    
    private static class DNode {
        Node left;
        Node right;
        
        DNode() {
            left = null;
            right = null;
        }
        
        public String toString() {
            return "L:" + left + " R:" + right;
        }
    }
    
    private static class Node {
        int val;
        int pri;
        int size;
        
        Node left;
        Node right;
        
        Node(int val, int pri) {
            this.val = val;
            this.pri = pri;
            size = 1;
            left = null;
            right = null;
        }
        
        public String toString() {
        	return String.valueOf(val);
        }
    }
    
    public static void main(String[] args) {
        Solution t = new Solution();
        Scanner sc = new Scanner(System.in);
        Random rd = new Random();
        int n = sc.nextInt();
        int m = sc.nextInt();
        for (int i = 0;  i < n; i++) {
            int v = sc.nextInt();
            t.add(v, rd.nextInt(n * 10));
        }
        for (int i = 0; i < m; i++) {
        	int op = sc.nextInt();
            int low = sc.nextInt();
            int high = sc.nextInt();
            if (op == 1)
            	t.query1(low, high);
            else
            	t.query2(low, high);
        }
        System.out.println(Math.abs(t.getFirst().val - t.getLast().val));
        t.inorder();
        sc.close();
    }
}








In python3 :




from array import array

n, n_queries = map(int, input().split())
data = array('L', map(int, input().split()))
assert len(data) == n
for m in range(n_queries):
    t, i, j = map(int, input().split())
    if t == 1:
        aux1 = i-1
        aux2 = j - aux1
        data[:aux2], data[aux2:j] = data[aux1:j], data[:aux1]
    else:
        aux1 = i-1
        aux2 = aux1 + n - j
        data[aux1:aux2], data[aux2:] = data[j:], data[aux1:j]
print(abs(data[0] - data[-1]))
print(*data)
                        








View More Similar Problems

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 →

Waiter

You are a waiter at a party. There is a pile of numbered plates. Create an empty answers array. At each iteration, i, remove each plate from the top of the stack in order. Determine if the number on the plate is evenly divisible ith the prime number. If it is, stack it in pile Bi. Otherwise, stack it in stack Ai. Store the values Bi in from top to bottom in answers. In the next iteration, do the

View Solution →

Queue using Two Stacks

A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. A basic que

View Solution →

Castle on the Grid

You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal. Function Description Complete the minimumMoves function in the editor. minimumMoves has the following parameter(s):

View Solution →