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

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 →

Merging Communities

People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w

View Solution →

Components in a graph

There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu

View Solution →

Kundu and Tree

Kundu is true tree lover. Tree is a connected graph having N vertices and N-1 edges. Today when he got a tree, he colored each edge with one of either red(r) or black(b) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex a to b, vertex b to c and vertex c to a . Note that

View Solution →

Super Maximum Cost Queries

Victoria has a tree, T , consisting of N nodes numbered from 1 to N. Each edge from node Ui to Vi in tree T has an integer weight, Wi. Let's define the cost, C, of a path from some node X to some other node Y as the maximum weight ( W ) for any edge in the unique path from node X to Y node . Victoria wants your help processing Q queries on tree T, where each query contains 2 integers, L and

View Solution →

Contacts

We're going to make our own Contacts application! The application must perform two types of operations: 1 . add name, where name is a string denoting a contact name. This must store name as a new contact in the application. find partial, where partial is a string denoting a partial name to search the application for. It must count the number of contacts starting partial with and print the co

View Solution →