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

Request for Editorial

$
0
0

I was waiting for September LITME editorial but it is still not there why it is late. I request to problem setters, please prepare editorials while setting problems. It will be good for us(beginners).
Thanks in advanced to all problem setters. I wish you will consider my request.


Eligibility for ZCO

$
0
0

I have passed my 12th class in 2017.Am i eligible for ZCO this year. Also i have not taken admission to any college.

CHEFPCHF - Editorial

$
0
0

PROBLEM LINK

Practice
Contest

Author:Hanlin Ren
Tester:Xellos
Editorialist:Xellos

DIFFICULTY

MEDIUM

PREREQUISITIES

counting palindromes using hashing

PROBLEM

Count the number of odd-length palindromes in a sequence of numbers. The sequence has length $N$ and contains $K$ non-zero numbers, where $K \ll N$.

QUICK EXPLANATION

Using direct+reverse hashes and binary search, find the largest palindrome centered at each non-zero number and between each pair of adjacent non-zero numbers. Add palindromes containing only zeroes.

EXPLANATION

We've got here a variation on the classic problem of counting (or finding the longest) odd-length palindromes, which is solved by finding prefix hashes of the original sequence, reversed sequence, and binary-searching the longest palindrome centered at each index. Subtask 2 is basically this. There's the usual caveat of choosing the right hashing method - the tests were made to fail hashing mod $2^{64}$ :D

The main complication is that the sequence is too long to even keep in memory. Fortunately, non-trivial palindromes can only be centered at very few indices. Let's handle the following cases:

  1. palindromes containing only zeroes
  2. palidromes centered at a non-zero number
  3. palindromes centered at a zero, but containing a non-zero

Case 1

We can find all $K+1$ sequences (possibly empty) of consecutive zeroes. In a sequence of length $L$, we can find $(L/2)(L/2+1)$ odd-length palindromes if $L$ is even and $(L+1)^2/4$ if $L$ is odd.

Case 2

It's clear that if a palindrome is centered at $p_c$, then all non-zero numbers appearing in it form a odd-length palindromic subsequence of $q$ centered at $c$. Also, $p_{c+x}-p_c = p_c-p_{c-x}$ for all indices $p_{c-x},p_{c+x}$ in this palindrome - therefore, we can compute a new sequence $d_{1..K-1}$ of consecutive differences $d_i=p_{i+1}-p_i$, and then we need an even-length (possibly empty) palindrome in this array centered between $d_{c-1}$ and $d_c$.

These two conditions are sufficient - if a substring centered at $p_c$ contains non-zero numbers in the range $[c-x,c+x]$ such that subsequences $q_{c-x..c+x}$ and $d_{c-x..c+x-1}$ are palindromic, then it is a palindrome.

We can use a modification of the usual algorithm: compute normal and reverse prefix hashes of $q$ and $d$, try all $c$, binsearch for the largest $x$ which gives these two palindromes, find the maximum length $2l+1$ of a palindrome which doesn't contain indices $p_{c-x-1}$ or $p_{c+x+1}$, and add $l+1$ to the answer.

Case 3

Let's consider the pair of non-zero numbers closest to the center. They need to be equal and at equal distances from the center, so they must be adjacent in seq. $p$ - if they are $p_c$ and $p_{c+1}$, then $p_c+p_{c+1}$ must be even and the palindrome is centered at $\frac{p_c+p_{c+1}}{2}$.

Now we can proceed in a similar way to case 2. Palindromes in $s$ containing $[c-x,c+1+x]$ correspond to palindromes $q_{c-x..c+1+x}$ and $d_{c-x..c+x}$.

Note that palindromes in this case are automatically distinct from all palindromes in case 2, but not in case 1. We need to subtract $\frac{p_{c+1}-p_c}{2}$ to exclude palindromes containing only zeroes.

Case 1 takes $O(K)$ time; in cases 2 and 3, we need to check $O(K)$ centers and do an $O(\log{K})$ binary search; mrecomputing hashes takes $O(K)$ time as well, so the total time complexity is $O(K\log{K})$. Memory complexity: $O(K)$.

AUTHOR'S AND TESTER'S SOLUTIONS

Setter's solution
Tester's solution

for C programmers

$
0
0

Here are two codes one uses 2d array and other uses pointers.
The catch is the code with pointers runs fine and the other with 2d array gives segmentation fault in some test cases(not all). It passes all testcases n<=1000 .

Limit of n is 1< n <10000.

The logic of both code are correct.
Problem:https://www.hackerrank.com/challenges/dynamic-array/problem

I need to know why the use of 2d array is giving segmentation fault. Is it bad to use 2d array and use pointers instead. But both are same things.

This is the code which gives segmentation fault

int main()
{

    /* Enter your code here. Read input from STDIn. Print output to STDOUT */
    int n, q, o, x, y, ti, pi, la, j;

    scanf("%d%d",&n,&q);
    int v[n][n],a[n];

    for (j = 0; j<n; j++)
        a[j] = 0;

    la=0;
    while(q-->0)
    {
        scanf("%d%d%d",&o,&x,&y);
        ti=((x^la)%n);
        switch(o)
        {
        case 1:
            v[ti][a[ti]]=y;
            a[ti]++;
            break;

        case 2:
            pi = y % a[ti];
            printf("%d\n", v[ti][pi]);
            la = v[ti][pi];

            break;
        }
    }
    return 0;
}

This code run fine

int main()
{
    int n, q, o, x, y, ti, pi, la;
    int *a, *s;
    int **v;
    scanf("%d %d", &n, &q);
    v = (int **)malloc(n * sizeof(int *));
    a = (int *)malloc(n * sizeof(int));
    s = (int *)malloc(n * sizeof(int));
    for (int i = 0; i < n; i++)
    {
        s[i] = 1;
        v[i] = (int *)malloc(s[i] * sizeof(int));
        a[i] = 0;
    }
    la = 0;
    for (int i = 0; i < q; i++)
    {
        scanf("%d %d %d", &o, &x, &y);
        ti = (x ^ la) % n;
        if (o == 1)
        {
            v[ti][a[ti]] = y;
            a[ti] ++;
            if (a[ti] == s[ti])
            {
                 s[ti] *= 2;
                v[ti] = realloc(v[ti], s[ti] * sizeof(int));
            }
        }
        else
        {
            pi = y % a[ti];
            printf("%d\n", v[ti][pi]);
            la = v[ti][pi];
        }
    }
    free(s);
    free(a);
    free(v);
    return 0;
}

view full testcase here
http://www.writeurl.com/text/z2qlksiktbd7aeuvy3zj/dvgaqxcmeugthbkutrtn

ZCOPRAC Video Game Help

$
0
0

I am trying to solve thisproblem. I have implemented the code but there seems to be some mistake with the logic that I am using. Can you please help me figure this out.

#include <iostream>

using namespace std;

int main() {
    int n,h;
    cin>>n>>h;
    int a[n];
    for(int i=0;i<n;i++)
        cin>>a[i];
    int c;
    cin>>c;
    int j=0;
    while(c!=0)
    {
        bool check = false;
        if(c==4 && a[j])
        {
            check = true;
        }
        else if(c==1 && j!=0)
        {
            j--;
        }
        else if(c==2 && j!=n)
        {
            j++;
        }
        else if(c==3 &&a[j]!=0 && check == false)
        {
            a[j]--;
        }
        else if(c==4 && a[j]!=h)
        {
            a[j]++;
        }
        else if(c==3 && a[j]!=0 && check == true)
        {
            a[j]++;
        }
        cin>>c;
    }
    for(int i=0;i<n;i++)
        cout<<a[i]<<" ";
    return 0; }

C00K0FF - Editorial

$
0
0

PROBLEM LINK

Practice
Contest

Author:Hanlin Ren
Tester:Xellos
Editorialist:Xellos

DIFFICULTY

CAKEWALK

PREREQUISITIES

none

PROBLEM

Determine if it's possible to select 5 problems with required difficulties for a Cook-Off, given a list of $N$ problems with known difficulties.

QUICK EXPLANATION

Straightforward - check the given conditions.

EXPLANATION

As the easiest problem in this contest, there isn't much to be said about its solution.

Notice that there are no overlaps among the difficulties required for the 5 problems, so we can just independently check for each problem if at least one of the required difficulties for it appears among the input strings.

We don't even need to remember all the input strings - it's enough to remember how many times each of them appeared in the input. That makes checking the required conditions even easier.

Time complexity: $O(N)$. Memory complexity: $O(1)$.

CHALLENGE

Too easy? You can think about how this problem could be generalised. An arbitrary number of difficulties, arbitrary lists of allowed difficulties for each spot, upper or lower bounds on the total number of used problems of each difficulty, etc...

AUTHOR'S AND TESTER'S SOLUTIONS

Setter's solution
Tester's solution

Invitation to KJSCE CodeSpree 2017

$
0
0

KJSCE Codecell presents CodeSpree, with CodeChef as Programming Partner.

Contest will last for 3 hours. It will be an ACM-ICPC style contest. It will start on 1st October 2017 at 21:00 hours IST.

Anyone can participate in this contest. This is a part of Abhiyantriki, technical fest of KJSCE.

Prizes worth 2000/- and laddus are up for grabs.

Contest link is https://www.codechef.com/KJCS17

You can register here.

Join the Facebook page here.

P.S:-Only Indian participants are eligible for cash prizes or to get selected for the onsite round.

Announcement: Regarding defamation threads

$
0
0

The members of discuss are reminded that any defamation thread is not allowed at discuss forum strictly. If you have any issues with some member or some report of malpractice, please mail one of the moderators (@vijju123 or @meooow) or mail codechef at their official mails.

If you feel extremely obliged to put up such a thread, please obtain permission from moderator before hand. Failing to do so, will lead to immediate deletion of thread (irrespective of validity of your claims) along with temporary suspension and/or karma penalties.

Defamation thread spoil the mood and atmosphere of discuss, hence must be reported privately to admins.

With Regards@vijju123


I am new user of codechef. I execute this program using C++.But it does not execute on IDE.Why?

$
0
0
#include<iostream.h>
#include<conio.h>
int prefixsum(int i,int a[])
{
    int sum=0;
    for(int j=0;j<=i;j++)
    {
    sum+=a[j];
    }
    return sum;
}
int suffixsum(int i,int a[],int n)
{
    int sum=0;
    for(int j=n-1;j>=i;j--)
    {
    sum+=a[j];
    }
    return sum;
}
void main()
 {
    // your code goes here
    int a[100],b[100],min,n,i,p,t,s,c[10];
    clrscr();
    cout<<"\n Enter no. of test cases";
    cin>>t;
    for(s=0;s<t;s++)
    {
        cout<<"Enter the size of array";
        cout<<"\n";
        cin>>n;
        cout<<"Enter elements of array";
        for(i=0;i<n;i++)
        cin>>a[i];
        for(i=0;i<n;i++)
        {
        b[i]=prefixsum(i,a)+suffixsum(i,a,n);
        }
        min=b[0];
        p=1;
        for(i=1;i<n;i++)
        {
            //min=b[i];
            if(min>b[i])
            {
            min=b[i];
            p=i+1;
            }
        }
        c[s]=p;
    }
    cout<<"\n Output";
    for(s=0;s<t;s++)
    {
        cout<<"\n";
        cout<<c[s];
    }
    getch();
}

Tentative date for next Codechef certification examination for Data Structures and Algorithms

$
0
0

The first date is 15th October 2017 . What is the tentative date for the next test ? And how frequent would the exam be conducted ?

intentional upvotes at the last minute for being in top 5.

why my code is not working for the problem chef and notebooks its problem code is CNOTE

$
0
0
#include<iostream>
using namespace std;
int main()
{
    int t,x,y,k,n,i;
    cin>>t;
    while(t--)
    {
        cin>>x>>y>>k>>n;
        int b[n][2],f=0;
        for(i=0;i<n;i++)
        cin>>b[i][0]>>b[i][1];
        for(i=0;i<n;i++)
        if((b[i][0]>=(x-y))&&(b[i][1]<=k))
        {
            f=1;
            break;
        }
        if(f==1)
        cout<<"LuckyChef"<<endl;
        else
        cout<<"UnLuckyChef"<<endl;
    }
    return 0;
}

DIGJUMP - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Tester:Shiplu Hawlader
Editorialist:Praveen Dhinwa

DIFFICULTY:

Easy

PREREQUISITES:

bfs, dijkstra

PROBLEM:

Given a string s of N. You have to go from start of the string(index 0) to the end of the string (index N - 1). From position i, you can go to next (i + 1) or previous (i - 1) position. You can also move from the current position to the indices where the character is same as current character s[i].

QUICK EXPLANATION

  • Minimum number of operations can not be greater than 19.
  • By your moves, you will never be visiting a single digit more than twice.
  • You can solve this problem by a modified bfs.
  • You can also make use of simple dijkstra's algorithm.

EXPLANATION

Few observations

  • Minimum number of operations can not be greater than 19.Proof:
    You can start from first position and go to rightmost index where you can directly go. Then from that position go to next position and keep repeating the previous step. Note that you will be visiting a single number at most twice. Hence you can at most make 19 moves because first digit will be visited once.

    They will 19 in the cases of 001122334455667788999.

  • By your moves, you will never be visiting a single digit more than twice.
    Proof:
    If you are using more than 2 moves for going from a digit to another, you can simply reduce one of the move by simply going from one of the position to other in just a single move. So you can simply keep the at most 2 moves for moving from a digit to another.

Wrong greedy strategies
Let us first discuss about some greedy strategies and figure out the reason why they are wrong.

From the current position, go to the rightmost index having same character/digit as the current character/digit. If this number does not occur again in the right part of array, then go to next position (ie. i + 1).

Please see the following recursive implementation of this strategy.

Pseudo Code

def greedy(int cur):
    // cur = N denotes end/ target position.
    if (cur = N) return 0;
    last = cur + 1;
    for i = cur + 1 to N:
        if (s[i] == s[pos]):
            last = i;
    return 1 + greedy(cur);

The above strategy will fail in these kind of cases: 010000561
According to greedy strategy, From 0, you will go to rightmost 0, then from that position to 5, then to 6 and finally you will go to 1. Total number of operations required are 4. But you can do it in simply 2 operations. Go from 0 to 1 and then go to rightmost 1 (target position).

Wrong dp algorithm
Some contestants have used wrong dp algorithm. Let dp[i] denote the minimum number of moves needed to reach position i from position 0. Some wre considering the transition from (i - 1) th position to i or from some position j < i (such that digit at j is same as digit at i.) to i.

Note that this kind of dp solutions are wrong because they don't consider the moves going backwards (from position i to i - 1), they are only considering the forward moves.

A simple test case where they will fail.
In the case: 02356401237894, dp program will give answer 6, but we can go from position 0 to 6 and then to 4 on the left side of second 0 (backward move) and then directly go to 4. So total number of operations required are 3.

Bfs Solution
Now consider the movement operations from one position to other to be edges of the graph and indices of the string as nodes of the graphs. Finding minimum number of operations to reach from 0 to N - 1 is equivalent to finding shortest path in the graph above mentioned. As the weights in the give graph are unit weights, we can use bfs instead of using dijkstra's algorithm.

So we can simply do a bfs from our start node(index 0) to end node(index n - 1). Number of nodes in the graph are n, but the number of edges could potentially go up to N 2 (Consider the case of all 0's, entire graph is a complete graph.).

Optimized bfs Solution
Now we will make use of the 2 observations that we have made in the starting and we will update the bfs solution accordingly.
Whenever you visit a vertex i such that then you should also visit all the the indices j such that s[j] = s[i] (this follows directly from observation 2). Now you can make sure to not to push any of the indices having digit same as current digit because according to observation 2, we are never going to make more than 2 moves from a position to another position with same digit, So after adding that the current character, you should make sure that you are never going to visit any vertex with same value as s[i].

For a reference implementation, see Vivek's solution.

Another Easy solution
Credit for the solution goes to Sergey Nagin(Sereja).

Let dp[i] denote the number of steps required to go from position 0 to position i.
From the previous observations, we know that we wont need more than 20 steps.
So lets make 20 iterations.

Before starting all the iterations, we will set dp[1] = 0 and dp[i] = infinity for all other i > 1.
On each iteration, we will calculate Q[k] where Q[k] is the minimum value of dp[i] such that s[i] = k. ie. Q[k] denotes the minimum value of dp over the positions where the digit is equal to k.

We can update the dp by following method.
dp[i] = min(dp[i], dp[i - 1] + 1, dp[i + 1] + 1, Q[s[i]] + 1);

Here the term dp[i - 1] + 1 denotes that we have come from previous position ie (i - 1).
Here the term dp[i + 1] + 1 denotes that we have come from next position ie (i + 1).
The term Q[s[i]] + 1 denotes the minimum number of operations needed to come from a position with same digit as the current i th digit.

Pseudo code:

// initialization phase.
dp[1] = 0;
for (int i = 2; i <= N; i++) dp[i] = inf;
for (int it = 0; it < 20; i++) {
    // Compute Q[k]
    for (int k = 0; k < 10; k++)
        Q[k] = inf;
    for (int i = 1; i <= n; i++) {
        Q[s[i] - '0'] = min(Q[s[i] - '0'], dp[i]);
    }
    // Update the current iteration.
    for (int i = 1; i <= n; i++) {
        dp[i] = min(dp[i], dp[i - 1] + 1, dp[i + 1] + 1, Q[s[i] - '0'] + 1);
    }
}
// dp[n] will be our answer.

Proof
If you done proof of dijkstra's algorithm, you can simply found equivalence between the two proofs.

Complexity:
Complexity is O(20 * N). Here 20 is max number of iterations.

AUTHOR'S AND TESTER'S SOLUTIONS:

Tester's solution

MAXDIFF - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Vamsi Kavala
Tester:Hiroto Sekido
Editorialist:Anton Lunyov

DIFFICULTY:

CAKEWALK

PREREQUISITES:

Greedy algorithm, Sorting algorithms

PROBLEM:

You are given an array W[1], W[2], ..., W[N]. Choose K numbers among them such that the absolute difference between the sum of chosen numbers and the sum of remaining numbers is as large as possible.

QUICK EXPLANATION:

There are two possibilities to try - K largest numbers and K smallest numbers (see below why). So the solution could be like this:

  • Sort all numbers.
  • Find the sum of all numbers. Let it be S.
  • Find the sum of first K numbers. Let it be S1.
  • Find the sum of last K numbers. Let it be S2.
  • Output max(abs(S1 − (S − S1)), abs(S2 − (S − S2))) as an answer.

EXPLANATION:

Consider the following sub-problem: choose K numbers with largest possible sum. Then the solution obviously is K largest numbers. So that here greedy algorithm works - at each step we choose the largest possible number until we get all K numbers.

In our problem we should divide the set of N numbers into two groups of K and N − K numbers respectively. Consider two cases:

  • The group with largest sum, among these two groups, is group of K numbers. Then we want to maximize the sum in it, since the sum in the second group will only decrease if the sum in the first group will increase. So we are now in sub-problem considered above and should choose K largest numbers.

  • The group with largest sum, among these two groups, is group of N − K numbers. Similarly to the previous case we then have to choose N − K largest numbers among all numbers.

This reasoning justify the solution in the QUICK EXPLANATION.

Regarding implementation details. Since N and T are small, then every simple O(N2) sorting algorithm from here will work. Other steps of the solution seems trivial to implement.

ALTERNATIVE SOLUTION:

Let's go further and ask our self which of two above cases actually gives the answer. After short thinking it became clear that larger difference would be when more numbers are included to the group of largest numbers. Hence we could set M = max(K, N − K), find the sum of M largest numbers (let it be S1) and then the answer is S1 − (S − S1), where S is the sum of all numbers.

AUTHOR'S AND TESTER'S SOLUTIONS:

Author's solution will be provided soon.
Tester's solution can be found here.

RELATED PROBLEMS:

Will be provided soon. All readers are welcomed to provide related problems in comments.

HELP FOR Wrong answer in CHEFPCHF


tle in weaksmk spoj

$
0
0

Tle with rabin karp in weaksmk spoj, link is below

http://www.spoj.com/problems/WEAKSMK/

I am using double hashing, is any other optimization required, or am i wrong?

My Code is:

#include <bits/stdc++.h>
using namespace std;
int base1 = 29, base2 = 91, MOD1 = 1000000007, MOD2 = 100000007;
map<pair<int, int>, int> pr;
int fast_exp(int b, int exp, int MOD){
long long res = 1, base = (long long)b;
while(exp > 0){
    if(exp%2 == 1)
        res = (res*base)%MOD;
    base = (base*base)%MOD;
    exp/=2;
    }
    return res%MOD;
}
int int_mod(int a, int b){
long long x = a, y = b;
return (x%y + y)%y;
}
 int ds(char text[], int m, int x, int n){
     if(m > n) return 0;
         pr.clear();
     int ht1 = 0, ht2 = 0;
     int E1 =  fast_exp(base1, m-1, MOD1), E2 = fast_exp(base2, m-1, MOD2);
     for(int i = 0; i < m; ++i){
         ht1 = int_mod(ht1*base1 + text[i], MOD1);
         ht2 = int_mod(ht2*base2 + text[i], MOD2);
     }
     pr[pair<int, int>(ht1, ht2)]++;
     //printf("hashes:-> %d %d\n", ht1, ht2);
     for(int i = m; i < n; ++i){
        ht1 = int_mod(ht1 - int_mod(text[i-m] * E1, MOD1), MOD1);
        ht2 = int_mod(ht2 - int_mod(text[i-m] * E2, MOD2), MOD2);
        ht1 = int_mod(ht1 * base1, MOD1);
            ht2 = int_mod(ht2 * base2, MOD2);
        ht1 = int_mod(ht1 + text[i], MOD1);
        ht2 = int_mod(ht2 + text[i], MOD2);
        //printf("hashes:-> %d %d\n", ht1, ht2);
        pr[pair<int, int>(ht1, ht2)]++;
    }
    int ans = 0;
    for(map<pair<int, int>, int>::iterator i = pr.begin(); i != pr.end(); ++i){
        if((*i).second == x) ans++;
    }
    return ans;
     }
     int main(){
        char s[100000];
    int t, n, q, l, x;
    scanf("%d", &t);
    while(t--){
        scanf("%d %d", &n, &q);
        scanf("%s", s);
        for(int i = 0; i < q; ++i){
             scanf("%d %d", &l, &x);
         printf("%d\n", ds(s, l, x, n));
        }
     }
    return 0;
     }

Segmentation Fault Although Answer is Coming Correct

IS THERE ANY WAY?

$
0
0

i want to see what was wrong with my code..the difference between expected output and output of my code.. is there any way to see..coz i am not getting what was wrong

Why are practice questions removed from user profiles?

Practice Questions Done By me Have Been Removed From My Account

$
0
0

Why Are The Practice Questions Done By me Have Been Removed My Account?

Viewing all 39796 articles
Browse latest View live


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