Quantcast
Channel: CodeChef Discuss - latest questions
Viewing all 39796 articles
Browse latest View live

Code of War by MNIT (Copied questions from Hackerearth)

$
0
0

Question in the competition (Q5): https://www.codechef.com/COW2018/problems/KLV Question in Hackerearth : https://www.hackerearth.com/problem/algorithm/paul-hates-vk/

Question in the competition (Q6) : https://www.codechef.com/COW2018/problems/BP Question in Hackerearth : https://www.hackerearth.com/problem/algorithm/bits-please/

Please check the solutions of all the teams of top 30 teams of the contest. Even the links of Question 4 is available when searched. Many of the solutions are same. Please ban this type of contests which have questions copied from other platforms since their solutions are easily available. @admin


XORIER length of frequency array

$
0
0

why length of frequency array is taken 1100001? please solve asap

EQUALMOD - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Vaibhav Tulsyan
Testers:Jakub Safin
Editorialist:Praveen Dhinwa

DIFFICULTY:

easy-medium

PREREQUISITES:

prefix-sums, data structures

PROBLEM:

You are given two arrays $A, B$ each containing $N$ integers. In a single operation, you can choose any index $i$ ($1 \leq i \leq N$) and increment $A_i$ by $1$.

Find out minimum number of operations required such that $A_i \bmod B_i$ is equal for all $i, 1 \leq i \leq N$.

SOLUTION

We want to make $A_i \bmod B_i$ equal for all the $1 \leq i \leq N$. Let $K$ be this value. Note that $K$ can't greater than $min(B_i) - 1$.

The obvious approach is to iterate over all possible values of $K$, and for each of its value find the minimum cost required, and simply output the minimum of these costs.

So, lets see how to calculate the minimum cost to set all of the modulos to some particular value $K$.

  1. For all the positions having $A_i \bmod B_i < K$, you need to increment them until the value reaches $K$.
  2. For all the positions with $A_i \bmod B_i > K$, you need to make the values of $A_i \bmod B_i$ reach zero first, and then increment them each $K$ times.

Let us first rearrange the elements of the arrays $A$ and $B$ in increasing order of values $A_i \bmod B_i$.

Now, let's see how to calculate the total number of operations required for first type. For each element $i$, we have to increment it $K - A_i \bmod B_i$ times. Let $L$ be the number of such elements of type 1. You can see that these elements will form a prefix of the rearranged array. Summing over all such elements, we get the total number of opeartions $= K \cdot L - \sum\limits_{i = 1}^{L} {A_i \bmod B_i}$. The quantity $\sum\limits_{i = 1}^{L} {A_i \bmod B_i}$ can be computed by maintaining prefix sums over the values $A_i \bmod B_i$.

Now, let's see how to calculate the second type of costs. All the positions that have $A_i \bmod B_i > K$ will be some suffix of the rearranged array. You need to make the values of $A_i \bmod B_i$ reach zero first. For each of the element $i$, such that $A_i \bmod B_i > K$, the cost required to make $A_i \bmod B_i = 0$ will be $B_i - (A_i \bmod B_i)$ (note that it's guaranteed that $A_i \bmod B_i \neq 0$ as $A_i \bmod B_i > K, K \geq 0$. The sum of the above quantity for each $i$ in the suffix can be found using the suffix sums. Afterwards, we increase each of these elements by $K$, which contribution will be $K \times$ number of such elements.

You can see #hemanth_1's solution for a detailed explanation of this idea along with some examples.

Alternate approaches.

Please check meooow's solution. It's an alternate view of seeing this solution.

Setters and Tester Solution Codes

Tester's solution

OJUMPS - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Dmytro Berezin
Tester:Sergey Kulik
Editorialist:Lalit Kundu

DIFFICULTY:

CAKEWALK

PREREQUISITES:

AD-HOC

PROBLEM:

Chef is at x=0.
1-jump: he will move from x -> x + 1
2-jump: he will move from x -> x + 2
3-jump: he will move from x -> x + 3
He will perform a lot of jumps in such a sequence: 1-jump, 2-jump, 3-jump, 1-jump, 2-jump, 3-jump, 1-jump, and so on.
Given an integer 0 ≤ a ≤ 1018, find will he ever arrive at a.

QUICK EXPLANATION:

In one sequence of 1-jump, 2-jump and 3-jump, he moves from x -> x + 6. So, if intermediate jumps are removed for a minute, x will always be a multiple of 6. Now, if we consider intermediate jumps, we will also consider points of form 6*k - 3, 6*k - 5.

Therefore,

a=input()    
if a%6==0 || a%6==1 || a%6==3:    
     print "yes"    
else:
     print "no"

Complexity: O(1)

AUTHOR'S AND TESTER'S SOLUTIONS:

Author's solution
Setter's solution

ALTARAY - Editorial

$
0
0

PROBLEM LINK:

Contest
Practice

Authors:Jaub Safin
Testers:Vasya Antoniuk
Translators:Vasya Antoniuk (Russian), Team VNOI (Vietnamese) and Hu Zecong (Mandarin)
Editorialist:Praveen Dhinwa

DIFFICULTY:

Simple

PREREQUISITES:

Simple observations, dp

PROBLEM:

An array is called alternating if any two consecutive numbers in it have opposite signs (i.e. one of them should be negative, whereas the other should be positive).

You are given an array $A$ of size $N$ consisting of non-zero elements. For each index $i$ from $1$ to $N$, you have to find the length of longest subarray starting at $i$.

QUICK EXPLANATION:

We can observe that if an array is alternating, then all of its subarrays are also alternating.

So, we can divide the array into maximal alternating subarrays. For doing that, we will iterate over array from left to right, if the sign of current number is different than previous number, then this number can be used to extend previous alternating subarray, Otherwise we will have to start constructing a new maximal alternating subarray.

In this way, we can partition the array into various maximal alternating subarrays.

After this, finding length of longest subarray starting at index $i$ is quite easy, as it can be done easily by finding the position of $i$ in the corresponding maximal alternating subarray. If $p$ be position and $L$ be the length of the maximal subarray, then $L - p + 1$ will be the length of longest subarray starting at index $i$.

EXPLANATION:

Observation 1:
Values of the number don't matter, only their signs do.

So, we can change the array $A$ such that it consists of -1 and 1's only.

Observation 2:
If an array $A$ is alternating, then all of it's subarrays are alternating.

Let us take an example to understand how we can apply the above observation to solve the problem.
Let $A = [1, 1, -1, 1, 1, -1, -1]$
So, we start from $A_1$ and note that $A_1$ is equal $A_2$. So the maximal subarray starting from $1$ will be $[1]$ itself.

Now, we go to $A_2$, we can see that $A_2, A_3, A_4$ have different signs, and $A_4$ has same sign as $A_5$.
So the maximal subarray starting from index $2$ will be [1, -1, 1].

So, we break the array into several parts such that each part is maximal alternating subarray. In our example, the parts will be
[1] [1, -1, 1] [1, -1], [-1]

We can formalize the above idea to write a pseudo code to break an array into various parts of maximal alternating subarrays.

vector<vector<int> > parts;
vector<int> curPart;
subpart.push_back(a[0]);
for (int i = 1; i < n; i++) {
    // If signs of current and previous number are different, 
    // then it means that we can extend the current part.
    if (a[i] * a[i - 1] == -1) {
        curPart.push_back(a[i]);
    } else {
        // We add the curPart into parts.
        parts.push_back(curPart);
    }
} 
// Check at the end whether the curPart has non-zero length or not.
// If it has, then add curPart into parts.
if (curPart.size() > 0) {
    parts.push_back(subpart);
}

Now, let us find the length of longest alternating subarray ending at each index $i$ for our example subarray $A$.
We get [1] [3, 2, 1], [2, 1], [1]

So, this means that for an maximal alternating subarray of length $L$, the answers (length of longest alternating subarray start from that index) will be $L, L-1, \dots, 1$.

We can use this idea to solve our problem.

// i denotes the current index of array at which we currently are.
int i = 1;
for (vector<int> curPart : parts) {
    int L = curPart.size();
    while (L > 0) {
        answer[i] = L;
        // increment i
        i++;
        // decrement L
        L--;
    }
}
// Note the fact that we didn't use the explicit values of curPart, only its size matter.

Dynamic programming based Solution

You can also solve the problem by a very simple dp.

Let $len[i]$ denote the maximum length of alternating subarray starting at position $i$.
We can observer that if $a[i]$ and $a[i + 1]$ has opposite signs, then $len[i]$ will be $1$ more than $len[i + 1]$.
Otherwise in the case when they have same sign, then $len[i]$ will be just $1$.

len[N] = 1;
for (int i = N - 1; i >= 1; i--) {
    // a[i] and a[i + 1] have different signs. 
    // Note that the a[i] can go upto 10^9, 
    // So if a is stored in int data type, then the a[i] * a[i + 1] might not fit in int.
    // So, we cast it to long long
    if (a[i] * (long long) a[i + 1]< 0) {
        len[i] = len[i + 1] + 1;
    } else {
        len[i] = 1;
    }
}

Time Complexity:

As we have seen in both the solutions we have to iterate over the array $A$ only once or constant number of times. So, time complexity of the algorithm will be $\mathcal{O}(N)$ which will easily fit in time with $N = 10^5$ and $T = 10$.

AUTHOR'S AND TESTER'S SOLUTIONS:

setter
tester

Getting runtime error NZEC: in magicchef problem using java

$
0
0

program is totally working in my system but i am getting NZEC error while sumitting it codechef import java.util.Scanner; public class Main { public static void magic(int a[])

{
    Scanner in = new Scanner(System.in);
    int x;
    x = in.nextInt();
    x=x-1;
    a[x]=1;
    int s;
    s=in.nextInt();
    for(int i=0;i<s;i++)
    {
        int a1,b1;
        a1=in.nextInt();
        b1=in.nextInt();
        a1=a1-1;
        b1=b1-1;
        int temp;
        temp=a[a1];
        a[a1]=a[b1];
        a[b1]=temp;
    }
    for(int i=0;i<a.length;i++)
    {
        if(a[i]==1)
        {   
            System.out.println(i+1);

        }
    }
}
    public static void main(String args[])
    {
        int n;
        Scanner in=new Scanner(System.in);
        int t;
        do
        {   
            System.out.println("Enter t:");
            t=in.nextInt();
        }while(!(t>=1 && t<=100));
        for(int j=0;j<t;j++)
        {
            n=in.nextInt();
            int a[]=new int[n]; 
            for(int i=0;i<n;i++)
            {
                    a[i]=0;
                }
            magic(a);
        }
}

}

a hard problem

$
0
0

Given N non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. It'easy. So you can inc some bar,but the sum of the height you inc no more than M. Now,maximize the answer. 1 <= N <= 1000 0 <= M <= 1000; 0 <= ai <= 1000

For example, n = 3,m = 0 A : [1 , 0 , 1] answer : 1 n = 3, m = 2 A : [1 , 0 , 1] answer : 2 (you can inc a[1] and a[3])

Codechef goodies still not delivered!!

$
0
0

I placed an order last month at 21 th ,but still haven't received my goodies...

Usually i used to get it by the first week,but this time it is taking really long...

@admin,@vijju123

Please check into this...,and do the needful

Thanx in advance!!


SPLST - Editorial

$
0
0

Problem Link

Practice

Contest

Author:Ivan Fekete

Tester:Misha Chorniy

Editorialist:Bhuvnesh Jain

Difficulty

CAKEWALK

Prerequisites

None

Problem

You are 3 piles of stones containing $a, b, c$ stones respectively. You can chose one of the piles and split it into 2 parts (possibly empty) and put the stones for the first part in one pile and the second one in another. Is it possible to have 2 piles with $x, y$ stones?

Explanation

Author's Solution

Let us first sort the piles in increasing number of stones. So, $a <= b <= c$. Also, assume $x <= y$. The first condition which should be satisfied is that the number of stones in the beginning and the end should remain same as none of the stones is thrown away, they are just rearranged into different piles.

Condition 1: a + b + c == x + y

Next thing is to observe is that the size of a pile can only increase and if it decreases it becomes 0 only. So, if the number of stones in the smallest pile, in the beginning, is more is than the number of stones in the smallest pile, in the end, we can't achieve our target.

Condition 2: a <= x

Similar case applies to the second smallest pile as well.

Condition 3: b <= y

The above 3 conditions are necessary for us to have a solution. But are they sufficient? Apparently yes, as we can always achieve our target as follow when the above 3 conditions hold:

Consider the third pile ($c$) as the pile with excess stones. Move the required number of stones to the first pile and the remaining stones to the second pile. As the total number of stones is same and the number of stones in both remaining piles can only increase, such a move will exist.

For more details, you can refer to the author's or tester's solution below.

Editorialist Solution

Since the constraints are small, we can simply simulate the above process, by trying to eliminate each pile and moving the required number of stones to the other 2 piles. Writing the cases for this can be tedious and some cases might not be handled as well if not implemented correctly. So, one idea is to try each possible pairing using permutations of the piles such that you always consider the last piles as the one with excess stones which would be removed by splitting stones into other piles. The conditions to check are simply:

  1. Find the number of stones required in the first and second pile.
  2. Check if the required number of stones is non-negative or not.
  3. Check if the sum of the number of required stones can be exactly satisfied by the excess pile.

Once, you are clear with the above idea, you can see the editorialist implementation below for help.

Feel free to share your approach, if it was somewhat different.

Time Complexity

$O(1)$

Space Complexity

$O(1)$

AUTHOR'S AND TESTER'S SOLUTIONS:

Author's solution can be found here.

Tester's solution can be found here.

Editorialist's solution can be found here.

swift code for organizing car and motorcycle races.

$
0
0

Project name: Rally

An organizer of motorcycle and car rallies asks your help for organizing his races. Description:

Write your code according to the description that follows:

  • You are asked to create a Swift project for a rally organizer.
  • You should create a Swift protocol that each requested class must adopt and implement that protocol and return a printable version of their properties.
  • You may create abstract classes wherever is required.
  • In order to test the output, you should follow the execution example.

1) Vehicle class You should firstly implement a class Vehicle that allows to represent a vehicle that participates in the races.

A vehicle is characterized by: • Its name of type String like “Ferrari” for example • Its maximal speed of type Double • Its weight in kg of type integer • And the level of fuel in the tank of type integer

The class vehicle will include: • An initializer initializing the attributes using values passed as parameters and a default initializer initializing the name with “Anonym”, the level of fuel with zero, the maximal speed with 130 and the weight with 1000.

• The class Vehicle must be able to represent itself by producing a String containing all the characteristics of the Vehicle except for the level of fuel, representing the following format: <name> -> speed max = <speedmax> km/h, weight = <weight> kg Where <name> is the name of the Vehicle, <speedmax> is its maximal speed and <weight>, its weight.

• A method name better returning true if the current instance has a better performance than the other vehicle

• The getters: gets the name, gets the maximal speed, gets the weight, gets the level of fuel Finally, this class will include and use a tool method performance. This method must return an estimation of the performance of the vehicle like the ratio between the maximal speed and its weight (the lighter and the faster the vehicle is, the better is its performance because it consumes less energy) You are asked to implement the class Vehicle respecting a good encapsulation.

2) Cars and motorcycles The vehicles participating in the rally can be either cars or motorcycles. A car (class Car) is characterized by additional information indicating its category (“race car” or “touring car”). A motorcycle (class Moto) is characterized by a Boolean indicating if it has sidecar. By default, a Moto does not have a sidecar. The class Car will also contain a property category and a getter for that property.

• The representation of a car in the format of String will respect the following format: <name> -> speed max = <speedmax> km/h, weight = <weight> kg, car category = <category> Where <name> is the name of the vehicle, <speedmax> is the maximal speed, <weight> its weight and <category> its category. • The representation of a motorcycle in the format of String will respect the following format:

<name> -> speed max = <speedmax> km/h, weight = <weight> kg, Moto, with sidecar If it has a sidecar or: <name> -> speed max = <speedmax> km/h, weight = <weight> kg, Moto If not. Where <name> is the name of the vehicle, <speedmax> is the maximal speed, <weight> its weight 3) The classes GrandPrix and Rally you are now asked to code a class GrandPrix as a “heterogenous collection” of vehicles. This collection represents the set of vehicles participating in a race. This class inherits from a class Rally which contains uniquely one method “check” [check () -> Bool)]. This method must allow to verify if the vehicles have the right to race together. The method “check” cannot be concretely defined in the class Rally. The class GrandPrix will have:

• A method “add” allowing to add a vehicle in the set of participants (the insertion will be done in the end of the collection)

• For a rally of the type GrandPrix the cars don’t have the right to race with two-wheeled; the motorcycles having a “sidecar” are not considered as vehicles with two wheels; the two-wheeled have the right to race together. In order to test the compatibility of the vehicles, you will add to the hierarchy of Vehicle a method: “isTwoWheeled” [isTwoWheeled() -> Bool] returning true when the vehicle is of type two-wheeled and false in the contrary case. You will consider that a basic vehicle is not a two-wheeled.

4) The race is launched Complete the class GrandPrix by adding to it a method “run” [run(turn: Int)] simulating the progress of the race according to the following algorithm:

• Start by testing if the vehicles have the right to race together; if not, the message “Not Grand Prix” will be displayed and the method run should terminate its execution.

• When the race takes place, for every vehicle deduce as much fuel as the “turns”; only the vehicles that still have fuel (>0) arrive to finishing line. • Among the vehicles that reaches the finishing line, select the most efficient one (the one which is better than all others) and display it respecting the following format:

The winner of the Grand Prix is: <representation> Where <representation> is the representation of the winning vehicle in the format of String; if no vehicle reaches the starting line, display the message: All the vehicles failed to finish the rally Execution example: Test part 1 :


Anonym -> speed max = 130.0 km/h, weight = 1000 kg Ferrari -> speed max = 300.0 km/h, weight = 800 kg Renault Clio -> speed max = 180.0 km/h, weight = 1000 kg The first car is better than the second Test part 2 :


Honda -> speed max = 200.0 km/h, weight = 250 kg, with sidecar Kawasaki -> speed max = 280.0 km/h, weight = 180 kg Lamborghini -> speed max = 320.0 km/h, weight = 1200 kg, car category = race car BMW -> speed max = 190.0 km/h, weight = 2000 kg, car category = touring car Test part 3 :


true false true false Test part 4 :


First round: The winner of the Grand Prix is: Lamborghini -> speed max = 320.0 km/h, weight = 1200 kg, car category = race car Second round: All the vehicles failed to finish the rally Third round: Not Grand Prix Program ended with exit code: 0

How to solve the problem Two Paths here?

XORIER - Sep18 - Can anyone help me out?

$
0
0

link text

Above is my solution to War of xor, can anyone tell me what is wrong in my solution ?

INDIAN COMPUTING OLYMPIAD[2019]

$
0
0

Hello community,

Like previous many years, IARCS is this year also going to conduct the INDIAN COMPUTING OLYMPIAD.

The registration for the first round(That's ZCO and ZIO ) will start from September 27 2018 . The contest is a nationwide competition organized annually by IARCS. The goal of the competition is to identify school students with outstanding skills in algorithms and computer programming.(Copied from the official website)

Here is a link to website.

Hope so you have fun. Happy Coding.

Invitation to CodeChef September Long Challenge 2018 sponsored by ShareChat!

$
0
0

Hello CodeChef Community!

We’re excited to announce the September Long Challenge sponsored by ShareChat. Along with the opportunity to boost your ratings and win some cool laddus, there are some exciting full-time job opportunities with ShareChat for professionals across the globe. More details about the job opportunities can be found on the contest page. solaimanope I hope you will join your fellow programmers and enjoy the contest problems. Joining me on the problem setting panel are:

Contest Details:

Time: 7th September 2018 (1500 hrs) to 17th September (1500 hrs). (Indian Standard Time — +5:30 GMT) — Check your timezone.).

Contest link:www.codechef.com/SEPT18

Registration: You just need to have a CodeChef handle to participate. For all those, who are interested and do not have a CodeChef handle, are requested to register in order to participate.

Prizes: Top 10 performers in Global and Indian category will get CodeChef laddus, with which the winners can claim cool CodeChef goodies. Know more here: discuss.codechef.com/questions/51999/how-do-i-win-a-codechef-goodie. First to solve each problem individually: 100 laddus (For problems common to both Divisions, only one user will get laddus for that problem). (For those who have not yet got their previous winning, please send an email to winners@codechef.com)

Good Luck!
Hope to see you participating!!

Practice for SnackDown

$
0
0

Hello Everyone, I haven't participated in snakdown this is my first time. I just want to know, what type to questions are asked in snackdown and what algorithms i need to prepare ?


TABGAME - sept18 Can you tell me whats wrong with this code.. Thanks :)

FCTR - Editorial

$
0
0

PROBLEM LINK:

Div1
Div2
Practice

Setter-Rajat De
Tester-Teja Vardhan Reddy
Editorialist-Abhishek Pandey

DIFFICULTY:

HARD

PRE-REQUISITES:

Mathematics, Randomized Solutions, Euler's Totient Function and Carmichael's function (please see relation between both of these :) ), Euler's Theorem

PROBLEM:

Given $N$ and $\phi(N)$, factorize $N$, where $N$ can be $\le 10^{500}$.

QUICK-EXPLANATION:

Key to AC- Realizing that you have to use randomization and exploring the properties of above-mentioned functions in this regard.

Strip $N$ of any powers of $2$ which might be present. Now, perform the following steps-

  • Check if $N$ is prime. Setter did that by simulating algorithm of step $3 \approx 30$ $times$. If $N$ couldn't be factored even after that he concluded it with good accuracy that its prime.
  • Check if $N$ is power of prime via finding $N'th$ root.
  • Take a random number in between $[2,n-1]$. Call if $x$. Now check $gcd(N,x)$, if its $>1$ then we found a factor by pure luck - not very likely. If its $1$, then $x$ and $N$ are coprime. Use $x^{\phi(N)}\equiv 1 \space mod \space N$. Now, write $\phi(N)=2^K*t$ and find smallest $k \le K $ such that our equivalence holds ,i.e $x^{2^k*t} \equiv 1 \space mod \space N$ (We want to find $k \le K$) . Since $\phi(N)$ is even for all numbers greater than $2$, we know that $K \ge 1$. Now, if found, then we get that $x^{2^k*t} \equiv 1 \space mod \space N$. Let $a=x^{2^{k-1}*t}$. We get $a^2 \equiv 1 \space mod \space N \implies (a^2-1) \equiv 0 \space mod \space N \implies (a-1)*(a+1)\equiv 0 \space mod \space N$. Check for $gcd(a\pm 1,N)$ and proceed to factorise likewise.

EXPLANATION:

I will first provide "pre-readings" which would give you a fair idea of what the solution is going to look like. Dont worry if things dont seem familiar in first look, just have a read to see what is to be expected.

  • This answer by spam..@nil.nil .
  • Unofficial editorial by @algmyr (dont forget to thank and upvote!)
  • The pre-requisite links should be visited to know relation between Euler's Totient and Carmichael's function.

With this, lets begin with the solution.

Full Solution-

a. Such Large input, Very Much Wow-

The very first thing which intrigues us is, that $N \le 10^{500}$, and $\phi(N)$ is of around that value as well. So...what now? C++? Better no!

We will be doing LOT of computations in this problem, including fast exponentiation, finding $N'th$ root, finding $gcd$ etc. Its advisable to use a language with in-built support for such big numbers. Python, Pypy and then JAVA were three popular languages used for this, in decreasing order of popularity.

First I will tell the general algorithm on what to do, and then tell its counterpoints or weak points, and how to cover them.

b. General Algorithm-

We have a $N$ which has nothing special, its just any random $N$ which setter threw upon us. Now, we know its $\phi(N)$, and thus know $k \lambda(N)$ where $\lambda(N)$ is Carmichael's function. We will be making use of Carmichael's function mostly.

Now, by good Euler's theorem we know that-

$a^{\phi(N)} \equiv 1 \ mod \ N$ provided our $a$ and $N$ are co-prime.

Now, lets have a look at Carmichael's function as well. It states that-

$\lambda(N) \ is \ defined \ as \ smallest \ m \ such \ that \ -$

$a^m \equiv 1 \ mod \ N$ for every positive integer between $1$ and $N$ co-prime to $N$.

Also, notice that the relation between $\phi(N)$ and $\lambda(N)$ is that $\phi(N)$ is always a multiple of $\lambda(N)$. Naturally, the Carmichael's function seems to be more useful for our case.

One thing to note is that, factorizing a large number, completely by itself and no additional information, is a hard problem which is essence of cryptography and security. So, we need to use the given additional information cleverly to solve be able to solve the problem. But chances of deterministic algorithm seem slim, especially because we can't even store primes so many as to factorize numbers with $500$ digits, and even if we could they'd be too many that we would get TLE before we finish checking even half of them. Usually, this is a hint that we should try to explore for a randomised algorithm, which can give give answer with good probability/accuracy.

Okay, lets give a very trivial try to the problem now. The most randomised brute force way of doing the question would be, to pick any random number $< N$ and see if it divides $N$. If it does, then yay, I found a factor, else try again. What are the chances for success? Less than $1\%$..:( . We will require too many guesses this way...

Can we do something about the case when our guess is not a factor of $N$? If we can, then our randomized algorithm will work! Turns out, there is a very clever trick we can use.

Notice the Carmichael function - its always even! Also, it gives us a $m$ such that $a^m \equiv 1\ mod\ N$, or, because $m$ is even, let me rewrite it as $a^{2k} \equiv 1\ mod \ N \implies \ a^{2k}-1 \equiv 0 \mod \ N$ $\implies (a^k-1)*(a^k+1) \equiv 0 \ mod \ N$ $(using$ $(x^2-1)=(x+1)*(x-1))$. While we get no clear picture just directly looking at it, it is enough to spark a curiosity to explore this approach further. Lets do it!

Now, since $m$ (let me refer to Carmichael's function $\lambda(N)$ as $m$ ) is even, let us write it in form -

$m= 2^K *b$ where $b$ is odd.

Lets take a random integer $x$ in range $[1,N-1]$. If $x$ divides $N$, then good for us! We found a factor, else we know for sure that $x^m \equiv 1 \ mod \ N$. Now, there one thing we should pay attention to. Carmichael's function is a $m$ such that every number in range $[1,N-1]$ which is co-prime to $N$ gives $1$ as remainder on modding. But, for one particular value, $x$ in our case, there can exist a $smaller$ such value $k$ such that $x^k \equiv 1 \mod \ N$. In other words, Carmichael's function is not the smallest $m$ for above equivalence to hold.

Keep in mind that we are exploring form of $x^{2k} \equiv 1 \ mod \ N$, and have currently represented Carmichael's function $m=2^K*b$. Lets try to find the $smallest$ value of $k$ such that $x^m \equiv 1\ mod\ N$. Lets call it $q$. Obviously, $q$ is even, so let me say $q=2k$ where $k$ is an integer (pardon my frequent definition of variables XD). Now, look at $x^{2k}$ and read carefully what equations I am going to write below.

$x^{2k} \equiv 1 \ mod \ N$
$\implies (x^k+1)*(x^k-1) \equiv 0 \ mod \ N$ using the same derivation cited before.

Now, two cases can arise, one is bad, and one is good.

  • Either $(x^k+1)$ or $(x^k-1)$ is a multiple of $N$. This will happen if $x^k \equiv \pm 1\ mod\ N$ This is a bad case as no information can be derived from here :( .
  • Neither $(x^k+1)$ nor $(x^k-1)$ is a multiple of $N$. This holds if $x^k \not \equiv \pm 1\ mod \ N$. This case is good, why? Because, NEITHER $(x^k-1)$ is divisible by $N$, NOR $(x^k+1)$ is divisible by $N$ BUT THEIR PRODUCT IS DIVISIBLE BY $N$! This means that, there must be some factors of $N$ common to $N$ and $(x^k \pm 1)$, and for factors present in $(x^k-1)$, the complement factors must be present in $(x^k+1)$ (as to give a multiple of $N$.). But thats not important. Whats important is that, $N$ and $(x^k \pm 1)$ have common factors! We an hence, find $gcd(x^k \pm 1,N)$ to find the factors out. Lets call the common factor $F$. Now we recurse for $N/F$ and $F$ to get full prime factorization, and at the end of recursion we will be done!

Now, what are the chances of success here? That this bad case does not occur, i.e. we should not find $x^k \equiv \pm 1\ mod \ N$. Also, note that we found smallest value of power (which we called $q$ earlier) so that $x^q \equiv 1 \ mod \ N$. And then we defined $q=2k$ as $q$ was even. We know that $k < q$, and hence chances of $x^k \equiv 1 \ mod\ N$ are almost NIL unless $x \equiv 1\ mod\ N$ from start (which is a very bad random choice for $x$). This was used to optimize the algorithm by many.

I hope that after the pre-reading, the way I explained the general algorithm was clear to you guys, if not then please let me know! :)

Now, lets analyze where our algorithm may fail and try to cover them up!

c. Reallllly nasty cases-

If $N$ is prime, then what? All our life will go on factorizing something which is not factorizable. One solution of this is, to see that our algorithm has a good chance of success. So, we can use something like "If no successes found even after $X$ tries, this means its not factorizable." How does this work? Lets say, our algorithm had a $75\%$ chance of success, what s the probability it fails $30$ times a row? Less than $1\%$. So, we can heave a sigh of relief XD.

Another nasty case is, if $N$ is power of prime. For this case, very less good values of $x$ are possible. If not careful, we will call $N$ prime by following above fix! Hence, before going to our general algorithm, we can first check if $N$ is power of prime or not. Many contestants observed that highest power possible is $log_2(N)=500*log_2(10)$ at max, which is not very high. So, for all powers $p$ they binary searched the base $a$ so that $a^p \le N$. At last if they found $a^p =N$, then handle this case likewise.

Alternatively, what setter did was, he tried getting $p'th$ root for $N$ for all $p$ from $1$ to $log_3(N)$. Call this root as $r$. He now checked if $r^p=N$ or not and handled this case.

Now, we have used "co-prime" word so much in general algorithm, theres another small nasty case. What if $N$ is even? It wont be co-prime to at least $half$ the values in range $[1,N-1]$. Not a big deal as we have a lot more chance of "guessing" a value of $x$ such that $gcd(x,N)>1$ then, but it will save some time and recursion calls if we strip $N$ of all powers of $x$ immediately :)

With this, we are done with the idea of the question :). Hope you enjoyed the editorial so far!

Setter's solution is attached for reference, also, I will try to give some interesting exercises for curious to see. Thats it from my end for now :)

SOLUTION

Setter

View Content

Tester

Editorialist

$Time$ $Complexity=O(???)$ (for time ccomplexity, check @algmyr's editorial in pre-reading section.)
$Space$ $Complexity=O(T.B.A.)$ (TBA are not variables...)

CHEF VIJJU'S CORNER :D

1. Hall of fame for noteworthy solutions-

  • @gorre_morre - Shoutout to GORRE-MORRE for an elegant solution. Hes one of the best guys to follow around if you're hunting for code :D
  • @algmyr - You all saw it coming XD
  • @karolis_kusas - Best JAVA submission
  • @pwild - $0M$ memory AND best time :D
  • $??????$ - Who might take this place here? :o

2. Setter's Notes

View Content

3. Prove the bad case. That is, prove that we cannot derive any information from $(a^k-1)*(a^k+1)\equiv 0\ mod\ N$ if either one of them is a multiple of $N$.

4. Prove that $\phi(N)$ and $\lambda(N)$ are always even for $N>2$

BSHUFFLE - Editorial

$
0
0

PROBLEM LINK:

Div1
Div2
Practice

Setter-Bogdan Ciobanu
Tester-Teja Vardhan Reddy
Editorialist-Abhishek Pandey

DIFFICULTY:

EASY

PRE-REQUISITES:

Observation, Simulation, Probability, Implementation and Data Structures - namely vectors and unordered maps/HashMaps/Hash tables, Hashing, Logic and Knack of Programming.

PROBLEM:

Given a value $N$ and an algorithm in the statement, find the most and least probable permutation of $N$ which the given algorithm can generate.

QUICK-EXPLANATION:

Key to AC- Simulating the algorithm for small $N$ huge number of times, and observing pattern for different values of $N$ led to an easy AC

This type of question must be specially handled. Write a brute force program which would simulate the algorithm given in the question a large number $(\approx 2*10^6)$ times. Observe the pattern for various values of $N$. You'd observe the following pattern-

Maximum Possible Permutation- $[2,3,4,\dots ,\lceil \frac{N}{2} \rceil,1,\lceil \frac{N}{2} \rceil+1,\lceil \frac{N}{2} \rceil+2, \dots, N$

Here $\lceil \frac{N}{2} \rceil$ represents $\frac{N}{2}$ rounded up to nearest integer (if decimal).

Least Possible Permutation- $[N,1,2,3,\dots,N-1]$

EXPLANATION:

I had been eternally waiting for such type of a question to come on codechef :) . The beauty of such a problem is, that you HAVE to think out of the box. The typical way of "making a program which would do all computations and simulations quickly with Time limit of the question and get AC" doesnt work, and this causes lot of contestants to go puzzled on what to do.

Lets first discuss about these questions in general and then use the conclusion to solve this problem. Editorial is divided into $3$ parts, the beginning one is a just a short note on how and why we came to use the given approach, second tells details about how to make simulator, and third is final answer.

Editorialist's Solution-

1. Why Simulation?-

Lets begin it by discussing about first subtask. $N \le 7$, which seems strange to contestants. Too large to make cases by hand and see/print the handwritten result, and still too "small" for some reason, (perhaps too small to make a dp table to find the answer).

Turns out, there is a method for which this value is "just-fine" :). That method is Simulation!

Usually, for these type of questions, the math required is too high. We are computer programmers, not math scientists! (No offence intended for anyone who is a computer programmer AND math scientist). The first principle of computer programming is, "Let the Machine do things for you :)". But anyways, I have attached a research paper which might help you guys get an insight on the question, the link is in my bonus corner as usual :)

Honestly though, after trying and brainstorming for a few attempts, we cannot come at any link/conclusion which would help us decipher this mathematical mystery. While its easy to see how many possibilities are there, its not intuitive to count how probable they are, except from the few which are impossible (if any). Also, we are to answer it with respect to the algorithm given in the question. Usually, it does good to first study and observe the behavior of the algorithm.

So, lets first discuss how to write the simulator :)

2. Writing Simulator-

A knowledge of Data Structures is needed. Go through links in pre-requisites if you dont know about vectors (dynamic arrays) and unordered_map (Hashmap/Hashtable).

The first thing to do is, to decide how many times we must simulate. This value is derived experimentally. Ideally, the value should be such that-

  • Its small enough so that simulation finishes within reasonable time.
  • Its large enough to give a stable answer. Meaning, irrespective of number of times I compile the same code again with same inputs, the answer permutation must be in the output, with no wrong permutation.

Once that is done, all we have to do is to copy the algorithm given in the question. A C++ implementation is given below, its simply converting the pseudocode given in question to your language.

View Content

Now, comes the tricky part. After doing above, we got a permutation, but how do we count a permutation's frequency?!

There are multiple ways to get over it :). Some of them are-

  • Use vector and maps. map can be used to even count frequency of vectors! Just use map< vector<int>,int> in declaration to suggest that you want to count frequency of vector (i.e. dynamic array or permutation)!
  • Use lexicographically ordering as index. Eg, assign 1 to lexicographically smallest permutation, then 2 to next largest, and so on. But this method is really not recommended.
  • Use hashing! Hash the permutation to some integer and count its frequency. But make sure there are absolutely no collisions!! Or..find a way to handle them!

Once we get that, simply print the permutations appearing maximum and minimal number of times. A sample code is shown below. I used vectors and maps, the easy way out XD. However, my original/alternate simulation used unordered map and string, which is given in bonus corner :). You can also find some tips in my bonus corner for simulator :)

Remember that, the simulation in the program must go for sufficiently large number of times, and you must run simulator to check even same value of $N$ multiple times. If the answer is stable, then number of simulations is sufficiently good for that value of $N$ (note that more simulations are needed to get an accurate result as $N$ increases), else try increasing it more. :)

View Content

3. Concluding notes and final answer-

Now once you find a set of candidate permutations, try to find a pattern on how to generate them. The permutations which I found were of patter as shown in quick explanation-

Maximum Possible Permutation- $[2,3,4,\dots ,\lceil \frac{N}{2} \rceil,1,\lceil \frac{N}{2} \rceil+1,\lceil \frac{N}{2} \rceil+2, \dots, N$

Here $\lceil \frac{N}{2} \rceil$ represents $\frac{N}{2}$ rounded up to nearest integer (if decimal).

Least Possible Permutation- $[N,1,2,3,\dots,N-1]$

You can refer to my code on how to generate it, although this type of implementation is trivial :).

My code for generation-

View Content

SOLUTION

The solutions are given in tab below in case the links dont work. This is done as to avoid any delay in solutions being accessbile to you guys. Copy them to your favorite editor and give a read :)

Setter

Tester

Editorialist

View Content

$Time$ $Complexity=O(N)$
$Space$ $Complexity=O(N)$

CHEF VIJJU'S CORNER :D

1. Some tips on simulator-

  • Unordered map in C++ doesnt by default support vector! You need to make your own function for that. An easy fix is, convert the permutation into a string of characters, (the characters need not be necessary '0'-'9', eg - we can represent '0' by '/' in string, 10 by 'p' etc. Any character of your choice). Since all permutations are unique, the strings they map to are also unique, and hence can be used with unordered map :). We can count frequency of strings, cant we?
  • Unordered map, with proper allocation (reserve and fill size reconfiguration as told here ) works in $O(1)$ while map works in $O(LogN)$. But map directly supports vectors, while unordered map does not :(
  • Avoid any memory declaration inside simulation loop. This can potentially speed up your code a HUGE fraction, because constantly allocating small memory numerous times is very expensive. My runtime went from $8$ to $3.57$ seconds after this :)

2. Research paper link - https://arxiv.org/pdf/math/0010066.pdf

3. Unordered map +Strings simulator.

View Content

4. Setter's proof on least-likelihood permutation-

View Content

5. Related Problems-
- Roman Digits - Make a brute force and finding pattern is key to AC!! - Fooling Around

Code of War by MNIT (Copied questions from Hackerearth)

$
0
0

Question in the competition (Q5): https://www.codechef.com/COW2018/problems/KLV Question in Hackerearth : https://www.hackerearth.com/problem/algorithm/paul-hates-vk/

Question in the competition (Q6) : https://www.codechef.com/COW2018/problems/BP Question in Hackerearth : https://www.hackerearth.com/problem/algorithm/bits-please/

Please check the solutions of all the teams of top 30 teams of the contest. Even the links of Question 4 is available when searched. Many of the solutions are same. Please ban this type of contests which have questions copied from other platforms since their solutions are easily available. @admin

XORIER length of frequency array

$
0
0

why length of frequency array is taken 1100001? please solve asap

Viewing all 39796 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>