Waiter


Problem Statement :


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 same with the values in stack . Once the required number of iterations is complete, store the remaining values in Ai  in answers , again from top to bottom. Return the answers  array.


Function Description

Complete the waiter function in the editor below.

waiter has the following parameters:

int number[n]: the numbers on the plates
int q: the number of iterations
Returns

int[n]: the numbers on the plates after processing
Input Format

The first line contains two space separated integers, n and q.
The next line contains n space separated integers representing the initial pile of plates, i.e., A.



Solution :



title-img


                            Solution in C :

In C ++ :




#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <climits>
#include <set>
#include <map>
using namespace std;

int m, n;

const int mycount = 10000;
vector<int> prime_results;
vector<int> sieve(int n)
{
    set<int> primes;
    vector<int> vec;

    primes.insert(2);

    for(int i=3; i<=n ; i+=2)
    {
        primes.insert(i);
    }       

    int p=*primes.begin();
    vec.push_back(p);
    primes.erase(p);

    int maxRoot = sqrt(*(primes.rbegin()));

    while(primes.size() > 0)
    {
        if(p > maxRoot)
        {
            while(primes.size() > 0)
            {
                p=*primes.begin();
                vec.push_back(p);
                primes.erase(p);        
            }
            break;
        }

        int i = p*p;  
        int temp = (*(primes.rbegin()));

        while(i<=temp)
        {
            primes.erase(i);
            i += p;
            i += p;
        }

        p=*primes.begin();
        vec.push_back(p);
        primes.erase(p);
    }

    return vec;
}

void prepare() {
	prime_results = sieve(mycount);
}

int a[100005];
vector<int> thearray[mycount];
void process() {
    int i, j, k, q, l;
    
    prepare();
    scanf("%d %d", &n, &q);
    
    for (i = 0; i < n; i++) {
        scanf("%d", &a[i]);
    }
    
    for (i = 0; i < n; i++) {
        for (j = 0; j < q; j++) {
            k = prime_results[j];
            if (a[i] % k == 0) {
                thearray[j].push_back(a[i]);
                break;
            }
        }
        
        if (j == q) {
            thearray[j].push_back(a[i]);
        }
    }
    
    for (i = 0; i < q; i++) {
        if ((i & 1) == 0) {
            for (j = 0; j < thearray[i].size(); j++) {
                printf("%d\n", thearray[i][j]);
            }
        } else {
            for (j = thearray[i].size() - 1; j >= 0;j--) {
                printf("%d\n", thearray[i][j]);
            }
        }
    }
    
    if (q & 1) {
        for (j = 0; j < thearray[i].size(); j++) {
            printf("%d\n", thearray[i][j]);
        }
    } else {
        for (j = thearray[i].size() - 1; j >= 0;j--) {
            printf("%d\n", thearray[i][j]);
        }
    }
    
}

int main() {
    process();
    
    return 0;
}









In Java  :






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

public class Solution {
    
    public static void main(String[] args) {
      
        
        Scanner sc = new Scanner(System.in);
        String nq[] = sc.nextLine().split(" ");
        int n = Integer.parseInt(nq[0]);
        int q = Integer.parseInt(nq[1]);
        String nums[] = sc.nextLine().split(" ");
        int pnum = 2;
        int primes[] = new int[q];
        MyStack first = new MyStack();
        MyStack rest = new MyStack();
        MyStack dpst = new MyStack();
        for(int i = 0; i < nums.length; ++i){
            first.push(Integer.parseInt(nums[i]));
        }
        for(int i = 0; i < q; ++i){
            if(first.head == null) break;
            primes[i] = pnum;
            while(first.head != null){
                int number = first.pop();
                if(number%pnum == 0)
                    dpst.push(number);
                else
                    rest.push(number);
            }
            while(dpst.head != null){
                System.out.println(dpst.pop());
            }
            pnum = nextPrimeNumber(pnum, i, primes);
            MyStack temp = rest;
            rest = first;
            first = temp;
        }
        while(first.head != null){
            System.out.println(first.pop());
        }
    }
    static int nextPrimeNumber(int num,int idx,int[] primes){
        if(num == 2) return 3;
        while(true){
            num = num + 2;
            boolean isPrime = true;
            for(int i = 0; i <= idx; ++i){
                if(num%primes[i] == 0){
                    isPrime = false;
                    break;
                }
            }
            if(isPrime) break;
        }
        return num;
    }
}

class MyStack{
    Node head;
    MyStack(){
        head = null;
    }
    void push(int data){
        Node newNode = new Node(data);
        newNode.next = head;
        head = newNode;
    }
    
    int pop(){
        int data = head.data;
        head = head.next;
        return data;
    }
}
class Node{
    int data;
    Node next;
    Node(int d){
        data = d;
        next = null;
    }
}








In C :





#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define MAX 50005
int top=-1;
int pri[MAX],q,b[MAX],stack[MAX];
void push(int sym){
    stack[++top]=sym;
}
int pop(){
    return stack[top--];
}
int isempty(){
    if(top==-1)
        return 1;
    return 0;
}
void prime(){
    
    pri[0]=2;
    int count,c,i=3;
for ( count = 1 ; count < 1250 ;  )
   {
      for ( c = 2 ; c <= i - 1 ; c++ )
      {
         if ( i%c == 0 )
            break;
      }
      if ( c == i )
      {
         pri[count]=i;
         count++;
      }
      i++;
   }
}
int main() {

     
    prime();
    int n,i,a[MAX];
    scanf("%d %d",&n,&q);
    for(i=0;i<n;i++)
        {
        scanf("%d",&a[i]);
    }
    int k=0;
    for(i=0;i<n;i++)
        {
        if(a[i]%pri[k]==0)
            printf("%d\n",a[i]);
        else
            push(a[i]);
    }
  
    k++;
    int s;
    
    while(k<q)
        {
         int z=0;
         while(!isempty())
             {
              b[z++]=pop();
         }
             for(i=0;i<z;i++)
                 {
                 if(b[i]%pri[k]==0)
                     printf("%d\n",b[i]);
                 else
                     push(b[i]);
             }
        k++;
         }
    int x=0,c[MAX];
    if(k==q)
    {
        while(!isempty())
        {
            c[x++]=pop();
    }
        for(i=x-1;i>=0;i--)
            printf("%d\n",c[i]);
    }
    
    return 0;
}








In Python3 : 





a,b = map(int, input().split(" "))
nums = list(map(int, input().split(" ")))
def prime(x):
    x = x + 1
    primes = []
    for a in range(1, 10000):
        for b in range(2, a):
            if a % b == 0: break
        else:
            primes.append(a)
        if len(primes) == x:
            return primes[1:]

primes = prime(b)
L = []
for i in primes:
    temp_nums = []
    L2 = []
    for j in range(len(nums)):
        num = nums[j]
        if num % i == 0:
            L2 += [num]
        else:
            temp_nums += [num]
    L += L2
    nums = list(reversed(temp_nums))

for i in L:
	print(i)
for i in list(reversed(nums)):
	print(i)
                        








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 →