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

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 →