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

How to find maximum spanning tree in BEERUS?Please help


If there is + or -sign in ahead of a variable, then what does it means??

Can u help for SUMQ of june17

Can anyone help me with SUMQ from JUNE17 ?

KMXOR - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Yuri Shilyaev
Tester:Hasan Jaddouh
Editorialist:Yury Shilyaev

DIFFICULTY:

Easy

PREREQUISITES:

Xor operation, constructive.

PROBLEM:

You are given two integers $N$ and $K$. Your task is to construct a sequence $g_1, \dots, g_N$, that $1 \le g_i \le K$ for all $i$ and $g_1 \oplus g_2 \oplus \cdots \oplus g_N$ is maximum possible.

QUICK EXPLANATION:

Let $m$ be the maximum integer that $2^m \le K$. The maximum possible answer is somewhere near $2^{m + 1} - 1$.

EXPLANATION:

Let's first print $2^m$ and $2^m - 1$. This numbers give xor $2^{m + 1} - 1$. Now, if let's complete the sequence with ones. The xor would not change if $N$ is even, otherwise, let's swap $2^m - 1$ we added with $2^m - 2$.

Of course, we should also consider some corner cases, on which our solution doesn't work. They are $N = 1; K = 1; K = 2; K = 3$.

AUTHOR'S AND TESTER'S SOLUTIONS:

Author's solution can be found here.
Tester's solution can be found here.

COOK82C - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Hussain Kara Fallah
Primary Tester:Hasan Jaddouh
Secondary Tester:Istvan Nagi
Editorialist:Udit Sanghi

DIFFICULTY:

EASY-Medium

PREREQUISITES:

Queue

PROBLEM:

Given an array of numbers and m queries. You have the keep doing the following operation -
Divide the take the maximum number and divide it by 2. Now for each query, tell the number we were taking in the Q[i]th operation

QUICK EXPLANATION:

Take 2 queues, q1 and q2. Push all elements in decreasing order to q1. Now as you are taking the elements see the maximum of q1 and q2, store it and then divide it by 2 and push it in q2. When q1 becomes empty then only look at q2.

EXPLANATION:

First let's calculate the constraint on Q[i]. So a[i] < $2^{63}$. This means that at most an element will can be divided 63 times before reaching 0. And, there are totally $10^6$ items. That means that Q[i] will be at max 63($10^6$).

First of all, can u think of a brute-force solution.
Just keep doing all stuff manually like taking the maximum in an array and then dividing it by 2 and putting in the array again. This will take time O($n*6.3*{10^6}$).

Now, can we do better.
So taking the max right now takes O(n). We can reduce this to O(log n) by using a priority_queue.
Now the complexity will be This will take time O($logN*6.3*{10^6}$).

Hmm... Too slow. We need to do this operation in constant time.

Here's a key observation -

After every number has been once divided, you only need to divide the numbers again in the same order as before. So, currently it doesn't make much sense but it will once you see an example.
Before that, you only need to compare between the highest number which has been divided yet and which has not been divided yet.

n = 5
old_a = [28,25,17,14,13]
new_a = []
// old array contains the element which have not yet been divided yet and new array contains those which have been divided atleast once.
operation 1 - 28
old_a = [25,17,14,13]
new_a = [14]

operation 2 - 25
old_a = [17,14,13]
new_a = [14,12]

operation 3 - 17
old_a = [14,13]
new_a = [14,12,8]

operation 4 - 14
old_a = [13]
new_a = [14,12,8,7]

operation 5 - 14
old_a = [13]
new_a = [12,8,7,7]

operation 6 - 13
old_a = []
new_a = [12,8,7,7,6]

// Now you will realize that we only select [12,8,7,7,6] in order now and keep dividing them.
Like 12,8,7,7,6,12/2,8/2,7/2,7/2,6/2,(12/2)/2,(8/2)/2 etc.

For these purposes we can use a queue.
Make 2 queue, q1 and q2.
Push all elements in q1 in decreasing order.
Now for the first operation u'll choose the maximum element which is the front of q1 and push half of that number in q2.
After that, you''l have 2 queues to choose from q1,q2, choose the queue which has has the maximum element and keep repeating this until.. q1 is empty.
Then, you can just repeat the process with the elements of q2.
Remember to store the answer after each operation. Then, process the queries and answer the queries with the answers you stored.

EDITORIALIST's, AUTHOR'S AND TESTER'S SOLUTIONS:

EDITORIALIST's solution: Here
AUTHOR's solution: Here
TESTER's solution: Here

String question

Can someone please explain TWOFL i am not getting it?


Whats wrong in my code of COPS?

New blog for Competitive Programmers

$
0
0

Hey guys I have started a new blog. The first article is on dfs lowlinks . You can read it up here. Feel free to comment if anything is wrong or suggest any changes you want me to make. Also feel free to suggest topics you want me to write some article on . Thanks. :D

CAREFUL - Editorial

$
0
0

PROBLEM LINKS:

Practice
Contest

DIFFICULTY

MEDIUM

EXPLANATION

(Note that it's well-known that if N = p1k1 p2k2... pmkm, where all pi are distinct primes, then φ(N) = p1k1-1(p 1-1) p2k2-1(p 2-1) ... pmkm-1(p m-1)).

This problem can be solved by fast simulation of the process. For each prime less than 105 (there are 9592 of them) let's maintain its power which is the actual power of this prime in the current value Ni and its delta which shows how the power will change when we move on to Ni+1. From the formula for φ(N) it can be seen that no delta will change before the set of prime divisors of Ni (without repetitions) changes. That means that there are two types of important events for us:

  • one of the prime divisors of Ni is no longer present in Ni+1, and
  • a prime which is not a divisor of Ni is now a divisor of Ni+1.
    Now no delta changes between neigboring events. This allows us to process a lot of iterations between neigboring events quickly. It's easy to find out which of the deltas change during the event and how (if we precalculate the factorizations of positive integers less than 105). To find out which of the events is going to happen next, one may use a data structure called heap.containing one entry for each prime number, where each entry contains the number of iterations with the current set of deltas that will pass before the presence of this prime in the current value Ni changes. The smallest of these numbers should be kept at the top of the heap so that we can quickly find the next event. After changing the corresponding deltas during the event, we shouldn't forget to change some of the corresponding entries in the heap.

This still requires some speed-up, as we can't afford changing the powers by the deltas before each event (there are at least m events, so our solution's running time will become at least O(m2)). Instead, let's keep another variable lastChange for each prime denoting the index of the last iteration when this prime's delta changed. Now any prime's power can be found in O(1) when needed as power + delta * (currentIteration - lastChange) (don't forget to update power and lastChange after that), and we don't need to make O(m) additions before each event anymore.

The overall complexity of the solution is thus O(E(D + log P)), where E is the number of events, D is the largest number of distinct prime divisors of a number less than 105 (that is, 6) and P is the number of primes less than 105 (that is, 9592). It can also be easily shown that E ? P log P in the worst case (and in fact E is even less).

As the problem tester, Aleksey came up with a simpler solution to this problem. Note that φ(N) is even for N > 2 (as N either contains an odd prime divisor or is a power of 2). This means that Ni becomes equal to 1 only when all 2's in the prime factorization of Ni disappear, so we may forget about primes other than 2 and only care about the power of 2 in the factorization. Using this observation, the solution becomes really simple. We can precalculate the power of 2 generated by each prime less than 105 by iterations of φ. After that, we can simply add the corresponding powers for all primes given in the input. This number (possibly increased by 1 if initially N is odd) is in fact the answer to the problem.

SETTER'S SOLUTION

Can be found here.

TESTER'S SOLUTION

Can be found here.

Plagiarism Help - False Positive MOSS

$
0
0

First of all i would like to say, i am really sry but i am kind of worried about false positive MOSS hit i got in May18B. I totally understand codechef team is busy but it has been over 14 days since i submitted my request for restoration of rank through mail but i received no reply yet. (and i was kinda scared of ending up like this guy - https://discuss.codechef.com/questions/126366/damn-what-just-happened/126532)

According to the mail i received, the two solutions bellow were found same: https://www.codechef.com/viewsolution/18555493 (Mine) https://www.codechef.com/viewsolution/18408704 (Egors)

I would like to point out, that the solutions written by us are totally different and may have triggered the MOSS cuz of us using the same IO library (ya, i know we both didn't credit but i don't even remember where i got it from lol). A look at that those links can tell you that the time complexity of the solutions are different. (Mine is brute force and only passed 4 cases while egors passed all of them). Also, umm, the main code is totally different if you go into the main function.

At the end, i hope my ranking for May18B and solution will be restored.

Thanks

@admin@vijju123

100 percent attendance related query

$
0
0

i have a query related 100% attendance that suppose when i am in 1 division and not able to do 1 question can i do just 1 question from division 2 such that my 100% attendance will be secure because i never miss a single major contest for 5 months

DOUBT BASED ON QUESTION "NUKES"

PLUSEQ - Editorial

$
0
0

Problem Link

Practice

Contest

Author:Stacy Hong

Tester:Misha Chorniy

Editorialist:Bhuvnesh Jain

Difficulty

HARD

Prerequisites

Branch and Bound, Dynamic Programming, Big Integers, Hashing, DFS/Recursion

Problem

You are given a string $S$ and integer $N$. So need to place some '+' symbols in the strings $S$ so that the value of the expression equals $N$.

Explanation

Subtask 1: N < 1000000

A simple knapsack like dynamic programming is sufficient to pass this subtask. The dp state is as follows:

$$dp[i][j] = \text{1 if first 'i' characters of S can be partitioned such that the sum is 'j' else 0}$$

A recursive pseudo-code for the above logic is given below:


    def solve(int idx, int remain):
        if idx == len(s):
            return remain == 0
        if dp[idx][remain] != -1:
            return dp[idx][remain]
        dp[idx][remain] = 0
        num = 0
        for i in [idx, len(s) - 1]:
            num = num * 10 + s[i] - '0'
            if (num > remain):
                break
            if (solve(i + 1, remain - num)):
                PLUS[i] = 1;
                return dp[idx][remain] = 1
        return dp[idx][remain];

    solve(0, N)     # N = integer value of string s in input
    for i in [0, len(s) - 1]:
        if i and PLUS[i]:
            print '+'
        print s[i]

The above code works in time complexity $O(|S| * N)$ where $|S|$ is the length of string $S$ and $N$ is the given integer. The space complexity is also same. Note that Codechef servers allow programs using such large memory (around 1G) to pass but you can you bitset or other equivalent structures to reduce the memory of your program too. See the linked solution below for subtask 1 for more details.

The solution for this subtask also exists using hashing and dynamic programming.

Subtask 2: N < |S|

Adding 2 numbers of sizes $x$ and $y$ leads to final result having size at most $max(x, y) + 1$. This is easy to prove. The size will be $max(x, y)$ if there is no carry-over in the end otherwise it will increase by 1. Extending the above logic to addition of $m$ number, we can conclude that if the numbers have lengths $x_1, x_2, \cdots, x_m$, then the length of final result is bounded by $(max(x_1 + x_2 + \cdots + x_m) + m - 1)$. You can easily prove it using induction.

Note that number of ways to partition the string $S$ into different expression is exponential. But using the above observation, you can the conclude the following fact:

Given a string $S$ and integer $N$, having the length as $n$, there is very less number way to achieve the target $N$ if $n$ is comparable to $|S|$. This is because most of the partitions will either have the maximum number in them as too low. Equivalently, if the number of partitions we put in $S$ is large, then achieving a larger target $N$ is not possible. This hints that for sufficiently large integers, the greedy technique of choosing a larger size partition and checking if the remaining part can add up to desired $N$ will run very fast in practice as the number of iterations will not be large. For example: $S = 114390211, N = 43915$

Considering greedily large size partition of $S$ such that their value is less than $N$, we have the following numbers: [11439, 14390, 43902, 39021]. (Note that the size of this selected numbers can be at most (|S| - n + 1).) Let us greedily start with $43902$. The remaining parts of $S$ are $(11, 11)$ and the required sum now is $(43915 - 43902) = 13$. Note that there are 2 ways to achieve it $(11 + 1 + 1) \text{ or } (1 + 1 + 11)$. As you can see, the number of iterations were less. The example is just a short one to make to understand how greedy recursion might behave for larger test cases.

But the other case where the integer $N$ is small but $|S|$ is very large, there can be large number of ways to achieve the desired result. For this, we have already seen that a dynamic programming solution already exists (Subtask 1). Trying the above greedy approach can be very bad in this case, a simple example being $(S = 99999999999, N = 108)$.

With some of the above ideas, we design a simple branch and bound based algorithm for the problem:


    range_tried = [0 for i in [1, len(S) - 1]]
    # Find all range in S such that their value is less than N and sort
    # them in decreasing order of their value. Let it be called "RANGES"

    def recurse(range_idx, remain):
        if remain < 0:
            return false
        if remain < LIMIT:      # LIMIT ~ 100000
            use dp based subtask_1 solution
        else:
            for i in [range_idx, len(RANGES) - 1]:
                if conflict(current_range, range_tried):
                    # If current range we are trying conflicts with one
                    # already tried in recursion before.
                    continue

                X = value of integer for RANGES[i]
                # Update range_tried
                if recurse(range_idx, remain - X):
                    return True
                # Update range_tried to old value
        return False

Note the above is a simple solution based on the initial observations. But do we need to really check for all possible ranges? Can we decide greedily at some point that given range can never result in an answer as $N$, i.e. Say we have selected some ranges, can we say that with the remaining ones we can never achieve the target $N$ without checking all possible partitions or greedily checking large number ranges.

Actually, given initial choice of our ranges, we can bound the maximum number we can achieve with the remaining ones. A simple check which ignores the digits of remaining parts of $S$ and considers all of them to be $9$ and finds the maximum value possible is a good starting point. If this value is already less than $N$, then we can simple prune our solution. Even stronger checks based on actual values of digits in string $S$ can lead to better pruning. So, the loop in the above code modifies as follows:


    for i in [range_idx, len(RANGES) - 1]:
        if conflict(current_range, range_tried):
            # If current range we are trying conflicts with one
            # already tried in recursion before.
            continue
        MAX_POSSIBLE = get_max(ranges_set)
        if MAX_POSSIBLE < N:
            # As we iterate in decreasing order of numbers, the
            # MAX_POSSIBLE can only decrease as 'i' increases
            break

        X = value of integer for RANGES[i]
        # Update range_tried
        if recurse(range_idx, remain - X):
            return True
        # Update range_tried to old value

Another thing we can do is to remove the early exit of recursion where a check is based on "remain < 0". This can be easily done by directly starting from ranges such that value of considered numbers is always less than "remain". This is again helpful as after greedily choosing a large size partition, it is possible in most case the other large size partitions should be ignored in further recursion either due to conflicts in common ranges or "remain" decreasing too fast to become less than $0$. For this, a simple binary search can help us to find the first index in "RANGES" from where we should begin our search. This is possible as we had initially stored our ranges in decreasing order of the value of integers they represent.

With the above ideas, the recursive solution based on branch and bound works quite fast in practice. A small analysis of the time complexity is as follows:

  1. $N < 100000$: Assuming we set LIMIT to this value in above pseudo-code. A dynamic programming based solution is run with complexity $O(|S| * N)$. Again to optimise this, we can use recursive version instead of iterative version. This is because will work in exactly the above complexity but in recursive solution, most of the states will be unvisited due to our initial choices of the ranges. This will significantly reduce the constant factor in your code.

  2. For most of the other cases, as $N$ becomes larger i.e. size $n$ reaches closer to $|S|$, the possible solutions reduce significantly as explained before.

A more detailed analysis of time complexity is will available soon.

Ashmelev solution (Fastest in the contest): Branch and Bound with strong bound checking

View Content

Tips for Big integer library (mostly for C++ users)

Languages like python and java already have big integer library implemented in them. But C++ users need to implement the same for their usage in this problem. A small tip is to store the numbers as groups instead of single digits. For example: $S = 123456789123456789$. Below are 2 possible ways to store $S$:

$$S = 1|2|3|4|5|6|7|8|9|1|2|3|4|5|6|7|8|9$$

$$S = 123456|789123|456789$$

This helps to perform operations on base different than 10 and reduces the constant factor of your program. Generally, the base is chosen as ${10}^{9}$ so that all possible operations like $(+, -, * , /)$ fit inside the datatypes provided by the language. You can see setter's library for example.

Time Complexity

To be described in detail later.

Space Complexity

To be described in detail later.

Solution Links

The solution for subtask 1 can be found here

Setter's solution can be found here

Ashmelev's solution can be found here


SHKSTR problem in editorial

$
0
0

I have used almost the same approach as the online one. Instead of a vector, i just stored the first occurence of the alphabet and another field which told me the index of the first word which ends there. But, I am getting a TLE for it. Could you help me find why it is happening? The link to my solution https://www.codechef.com/viewsolution/18809047

Whats wrong in this code?

$
0
0
#include <iostream>
using namespace std;

int t,n[1000];
void input(int);
void output(int);

int main()
{

    cin>>t;
    input(t);
    output(t);

    return 0;
}

void input(int t)
{

    {
        for (int i=0; i<t;i++)
            cin>>n[i];
    }
}

void output(int t)
{
    int temp=0, ans;
    int i=0;

    {
        for (i=0; i<t ; i++)
        {

            temp = n[i];
            ans=0;
            while (temp>=1 && temp<=100000)
            {
                int r=temp%10 ;
                ans=(ans*10) + r;
                temp=temp/10 ;
            }
            cout << ans <<endl;
        }
    }
}

How to solve KRILLIN

Someone, please help me out!

$
0
0

Hi all, After messing whole day with my code i'm still not able to figure out why this code is failing and other code which is exactly same passes all the testcase?

MYCODE

OTHER CODE

I just want to know what is failing my code? Thank You..

H1 A puzzle game

$
0
0

Please share its tutorial. Or explain how we would do it.

Viewing all 39796 articles
Browse latest View live


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