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

Getting Runtime Error


quickmatch 10 coming soon with 3 hiring companies

$
0
0

This time we have 3 hiring companies and good ones, good coders working in them...

Will update details once problems are ready. Readying it. https://www.codechef.com/KQ102018

Edit: Codechef to share 250 laddus to top contestants (number of tops depends on number of participants). Thank you codechef.

Cancelling contest, I made mistakes in tests and judging mechanism. Possibly I might end contest hosting here after such grievous mistakes, one person is not enough. I know I will make mistakes again and bring down reputation of cc.

Edit: Thanks for all your encouragements.

I have tester now.... A good news machine learning startup is impressed. Says will hire for 2 positions when some project starts.

Big company wanted exp 1 yr but later said if good uni will do. But now want exp only.

.net will ask however .net one isnt that good. ML one is very good. Dont want to send to .net place. Lets see what happens. I will need hr too.. there might be error in this too.

Seg trees GSS1 SPOJ Runtime error

No reply from CodeChef

$
0
0

Hello,

I received an email from CodeChef on 31st May 2018 stating that my code matched with another user in the May Long Challenge 2018. I mailed back the same day, so did the person who had copied my code confessing to the same. Till now, I've not been informed whether the plagiarism case against me has been dropped or not.

I'd request someone from the CodeChef officials to please update me on the status of my case.

Thank you

CHEFGR-Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Dmytro Berezin
Tester:Jingbo Shang
Editorialist:Ajay K. Verma

DIFFICULTY:

Cakewalk

PREREQUISITES:

ad-hoc, basic math

PROBLEM:

Given an array of positive integers, determine if it is possible to make all the elements in the array equal by adding non-negative number to its elements such that the sum of the added numbers is exactly M.

EXPLANATION:

For the given array A of size N, we want to determine whether it is possible to make all its elements equal by adding non-negative numbers to them. Let as assume that it is possible to do so and the final value of the elements is x.

This means the following two conditions must hold:
1) x >= A[i], for all i, and
2) sum of (x - A[i]) is M.

From the second condition, we can actually compute the value of x:
(x - A[1]) + (x - A[2]) + ... + (x - A[N]) = M
x = (M + A[1] + A[2] + ... + A[N]) / N

If x is not an integer, then clearly we do not have a solution. Hence, we need to check the following two conditions for the existence of a valid x:
1) (M + A[1] + A[2] + ... + A[N]) must be divisible by N,
2) None of the elements of the array should exceed x = (M + A[1] + A[2] + ... + A[N]) / N.
3) The x must hold : x>= max(A[i]) of the original array. So that all array elements become equal in the end.

Time Complexity:

O (N)

AUTHOR'S AND TESTER'S SOLUTIONS:

Author's solution will be put up soon.
Tester's solution will be put up soon.

Doubt with AMSGAME1

Are we really competing against someone in 'CodeArena' of Hackerearth?

$
0
0

I've recently started participating in the 'CodeArena' 1-to-1 fight. However, not a single opponent has ever managed to submit even a partially correct solution in any of the fights I've participated in.

Some days ago, while ‘fighting', I saw my opponent compiling his code and then submitting it only to get a WA in all the test cases. The problem was far too easy to get a WA. I tried to locate his submission after the fight, but couldn't find it.

My suspicion increased when I looked into their profiles. All of them "hasn't added any details yet." Each profile name has the syntax: <first_name><dot><last_name>, sometimes followed by another <dot> and/or a random number.

Eg. Yesterday, I fought against someone called Niranjan Kumar (@niranjan.kumar1).">https://www.hackerearth.com/@niranjan.kumar1). Problem was Choosing the Judges; a standard DP problem. My opponent compiled his code, then submitted, and obviously got a WA.

alt text

After contest ends, I find the problem, view the "All submissions" page and.... Wow, my opponent is non-existent.

alt text

I admit I am new in Hackerearth, and I must not bluntly accuse someone; but am I really missing anything?

SUBINC - Editorial

$
0
0

Problem Link

Practice
Contest

Difficulty

Simple

Pre-requisites

Simple dynamic programming

Problem

Count the number of non-decreasing subarrays of the given array A[].

How to get 20 points

Let's choose the left bound, say L. After the left bound is fixed, let's choose the right bound, say R. And now, let's check that the subarray A[L, R] is non-decreasing.

In other words, let's iterate through all possible subarrays and then, for each of them, check whether it is a non-descreasing one or not.

Choosing the left bound takes O(N) operations, choosing the right bound takes O(N) operations too, and checking subarray also takes O(N) operations. Since these operations are nested, hence the total complexity will be O(N3).

This solution is good enough to solve the first subtask.

How to get 50 points

Let's choose the left bound, say L. Let the right bound, say R, be equal to L initially. Then while the elements are non-decreasing keep increasing the right bound R. At some moment, you will certainly stop. The amount of non-decreasing subarrays with the left bound at L will be equal to R-L+1 for every fixed L. The sum of all this values is the answer to the problem.

Choosing the left bound takes O(N) operations, and finding the right bound takes O(N) operations. Since these operations are nested, the complexity of the whole solution will be O(N2).

This solution solves the first and the second subtask, but is still not good enough to get the full points.

How to get 100 points

Let's introduce an array B[] of N elements, where the ith element of B[] defines the amount of the correct subarrays with the right bound equal to i.

Now, let's give the rules for calculating the ith element of B[]:

  • if A[i-1] ≤ A[i], then B[i] = B[i-1] + 1 since every non-decreasing subarray that ends at the (i-1)th element can be continued with the ith element without loss of non-decreasingness and one more non-decreasing subarray that ends at the ith element is A[i, i].
  • if A[i-1] > A[i], then B[i] = 1 since any subarray that ends at the (i-1)th element will lose its' non-decreasingness if continued with the ith element, so the only suitable subarray will be A[i, i].

So, the answer will be equal to the sum of all elements of B[]. The complexity is O(N), because the computation of the array B turns out to be a single for-loop with a condition for the computation of B[i] inside.

Setter's Solution

Can be found here

Tester's Solution

Can be found here


Please someone help me for solving this problem.

[June Cook-Off 2k18] Is this a valid algorithm/approach to solve Good Permutations Problem ?

$
0
0

Hello, I was trying to solve the 2nd most solved problem in the June cook-off 2k18 contest, even though I believe my approach is valid however still i would like to seek your review and suggest me any better approach or flaw in my existing approach, I will not be posting entire code but just basic algorithmic idea. My code isn't getting accepted (WA) probably due to side cases, and since I urgently want to know the validity of my approach I'm posting it here.

APPROACH (for the single test case)

  1. input N, K
  2. input an array ARR of size N
  3. scan the ARR for 0s and create another array "indices" that will store index i , where ARR[i] is 0
  4. replace 0s in ARR by unused numbers ( for example [2,0,0] becomes [2,1,3] ) (I'm not going into detail of how this is done)
  5. Permute the array "ARR" for only those indices where 0 was replaced by another value using the call to the method given below

https://ideone.com/s9eeax

here, in the first ever call to permute, beg = 0 and end = ind.size()-1 where k is mentioned in the problem statement of the question. Time complexity of the permute method is O(N^2 * fact(N))

If in case anyone is interested to check out entire code for further detail, please check this out https://www.codechef.com/viewsolution/18947214

If the algorithm is not clear please do let me know so I can write it more clearly.

BINSHFFL : Codechef giving WA

$
0
0
enter code here
#include <iostream>

using namespace std;

int countDigits(long long a){ int count=0; while(a){ a=(a&(a-1)); count++; } return count;

}

int main(){ ios_base::sync_with_stdio(false);

int T;
cin>>T;
while(T--){
    long long A,B;
    cin>>A>>B;
    int ans;
    if(B==0){
        ans=-1;

    }
    else if(B==1 ){
        if(A==0)
        ans=1;

        else{
            ans=-1;

        }
    }
   else if(A==B){
        ans=0;

    }
    else{
        int digitsA=countDigits(A);
        int digitsB=countDigits(B-1);
        //cout<<"Digit A:"<<digitsA;
        //cout<<"Digit b:"<<digitsB;
        //cout<<endl;

        if(digitsB<digitsA)
        ans=2;
        else
        ans=digitsB-digitsA+1;

    }
    cout<<ans<<'\n';
}

}

Please look into solution. I am getting WA. Unable to resolve error

STONES - Editorial

$
0
0

PROBLEM LINKS

Practice
Contest

DIFFICULTY

EASY

EXPLANATION

This was the easiest problem of the contest. All one had to was to move over all characters is S and check if they were present in J as well. Checking could be done either by iterating over all character of J which takes time O(|J|) or by keeping an array/hashset for O(1) look up.

SETTER'S SOLUTION

Can be found here.

TESTER'S SOLUTION

Can be found here.

what is wrong in my program

$
0
0
https://www.codechef.com/problems/KTTABLE


#include<stdio.h>
    int main()
    {
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int n,i;
        scanf("%d",&n);
        int a[n],b[n],s=0,m=0;
        for(i=0;i<n;i++)
        {
            scanf("%d",&a[i]);
        }
        for(i=0;i<n;i++)
        {
            scanf("%d",&b[i]);
        }
        for(i=0;i<n;i++)
        {
            s=s+b[i];
            if(s<=a[i])
                m++;
        }
        printf("%d\n",m);
    }
    return 0;
    }
No error in program but codechef is not accepting it....

OUTPUT IS CORRECT BUT GETTING WRONG ANSWER DURING SUBMISSION

$
0
0

http://discuss.codechef.com/problems/TWTCLOSE

include<stdio.h>

include<string.h>

int main() { int n,k,click=1,count=0,i,tweetNo; scanf("%d%d",&n,&k); int tweet[1000]; char str[10]; for(i=1;i<=n;i++) tweet[i]=0; while(click<=k) { scanf("%s",str); if(strcmp(str,"CLEARALL")==0) { for(i=1;i<=n;i++) tweet[i]=0; count=0; } else { scanf("%d",&tweetNo); if(tweet[tweetNo]==0) { tweet[tweetNo]=1; for(i=1;i<=n;i++) { if(tweet[i]==1) count+=1; } } else if(tweet[tweetNo]==1) { tweet[tweetNo]=0; for(i=1;i<=n;i++) { if(tweet[i]==1) count+=1; }
} } printf("%d",count); click++; count=0; printf("\n"); } return 0; }

SHKSTR - Editorial

$
0
0

Problem Link

Practice

Contest

Author:Jitender

Tester:Misha Chorniy

Editorialist:Bhuvnesh Jain

Difficulty

EASY-MEDIUM

Prerequisites

Tries, Offline querying

Problem

You a given $N$ strings and $Q$ queries. For each query, given $R$ and string $P$, you need to find the lexicographically smallest string which has the largest common prefix with $S$.

Explanation

Subtask 1: N, Q ≤ 1000

A simple brute force which checks each string from index $1$ to $R$ and stores the answer at each step will suffice. Below is a pseudo-code for it:


    def find_max_prefix_match(string a, string b):
        ans = 0
        for i in [0, len(a), len(b) - 1]:
            if a[i] == b[i]:
                ans += 1
            else:
                break
        return ans

    def solve_query(index R, string P):
        ans = ""
        prefix = 0
        for i in [1, n]:
            if find_max_prefix_match(S[i], P) > prefix:
                prefix = find_max_prefix_match(S[i], P)
                ans = S[i]
            else if find_max_prefix_match(S[i], P) == prefix:
                ans = min(ans, S[i])
        return ans

The complexity of the above approach is $O(N * Q * 10)$ in the worst case as the maximum size of the string can be at most 10.

Subtask 2: N, Q ≤ 100000

The first idea which comes whenever you see string problems deal with prefixes if using tries or hashing. In this problem too, we will use trie for solving the problem. In case you don't know about it, you can read it here.

Let us first try to understand how to find the lexicographically smallest string with largest common prefix with $P$. Assume we have the trie of all the strings build with us. We just start traversing the Trie from the root, one level at a time. Say we are at level $i$, we will try to greedily go to the node whose character matches with our current character, $P[i]$. This will help us to maximise the longest common prefix. The moment we find a mismatch, i.e. a node with current character doesn't exist, we will try to now greedily find the lexicographically find the smallest string. For this, we just keep on traversing down the left-most node in the trie till a complete work is found.

But the above approach works when $R = N$ in all queries as without it we can't identify whether the string we are traversing lies in the required range of the query or not.

There are 2 different approaches to the full solution, Online solution and Offline solution.

Author/Tester Solution: Offline Approach

The problems where we can easily solve a problem given a full array but need to query for a prefix of the array can be easily handled using offline queries. The idea is as follows:

We first sort the queries based on the index of the array given. We now build out data structure (here trie), incrementally. Say the data structure is built using all the first $i$ elements, we now answer every query which has an index as $i$ in the query.

The pseudo-code for it is below:


    queries = []
    for i in [1, q]:
        r, p = input()
        queries.push((r, p, i))
    queries.sort()

    cur_index = 0
    for (r, p, i) in queries:
        while (cur_index <= r):
            insert_element_to_ds_trie
            cur_index += 1
        ans[i] = query_from_ds_trie(S)      //parameter r is not required

    for i in [1, q]:
        print ans[i]

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

Editorialist Solution: Online Solution

The idea is simple. With every node in the trie, we keep a vector of indices which it is a part of. Using this vector we can easily decide whether the string we are traversing lies within our required range or not. But before discussing the full solution, we need to be sure that this will fit into memory limits because seeing it in a naive manner seems to consume quadratic memory as each node can have a vector of length $N$.

To prove that the above-modified trie also uses linear memory in order of sum of the length of strings, we see that each index appears in any vector of a node in trie as many characters are there in the string. So, out trie just uses twice the memory that the normal trie (the one in author or tester solution) uses.

Once, the above modified Trie is built, we can answer our queries easily. Since the strings are added incrementally, we are sure that the vector containing the indices will always be in sorted order. To check whether any string at a given node lies in modified range, we can use binary search. But, we can be clever here too, as the binary search will be an overkill. Since the range we want is always a prefix of the array we can just check the first element of the vector and decide whether any string lies in the required range or not. To get a clear picture of the above, you can see the below picture of the trie build from the sample case in the problem. It also contains how the answer to different queries are arrived at.

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(Q\log{Q} + \text{Sum of length of strings} * \text{ALPHABET})$ for offline solution

$O(\text{Sum of length of strings} * \text{ALPHABET})$ for online solution

where $\text{ALPHABET} = $ number of distinct english character (26 for this problem).

Space Complexity

$O(\text{Sum of length of strings})$

AUTHOR'S AND TESTER'S SOLUTIONS:

Author's solution can be found here.

Editorialist's solution can be found here.


why getting wrong answer? Fibonacci String Problem Code: CLFIBD

$
0
0

//fibonici string again

include<stdio.h>

include<stdlib.h>

long int i,j;

int main()

{

int t;

scanf("%d",&t);

getchar();// toa absorb the /n of the previous scanf

while(t--)

{

    i=j=0;

    long int count[27]={0};

    long int flag=0,temp=0;

    char ch=0,arr[100000];

    int alpha[27]={0};

    scanf("%s",arr);

    while(arr[i]!='\0')

    {

// ch=getchar();

// if(ch<97||ch>122)

// break;

            for(j=0;j<flag;j++)

            {

                if(arr[i]==alpha[j])

                {

                    count[j]+=1;

                    break;

                }

            }

            if(j==flag)

            {

                alpha[j]=arr[i];

                count[j]=1;

                flag++;

            }

        i++;



    }

// printf("the array has stored \n");

// for(i=0;i<flag;i++)

// printf("%c==%ld\n",alpha[i],count[i]);

    // now we will sort the array

    for(i=0;i<(flag-1);i++)

    {

        for(j=(i+1);j<flag;j++)

        {

            if(count[i]>count[j])

            {

                temp=count[i];

                count[i]=count[j];

                count[j]=temp;

            }

        }

    }

    // after sorting the array becomes

// for(i=0;i<flag;i++)

// printf("%ld ",count[i]);

    if(flag<3)

    {

        printf("Dynamic\n");

        continue;

    }

    for(i=0;i<(flag-2);i++)

    {

        if(count[i]+count[i+1]==count[i+2])

        continue;

        else

        {

            printf("Not\n");

            break;

        }

    }

    if(i==(flag-2))

    printf("Dynamic\n");



}

}

Help in Polynomial Multiplication

TREEORD WA SPOJ

Domain Handling

$
0
0

I do not understand how to correctly format my domain handling for code chef questions. eg. if the inputs are 0 < a < 2000, 10 <= b then I can force input a, b to obey the domain with something like: if a > 0: a = 1 if a > 2000: a = 1999 if b < 10: b = 10 otherwise I can use logic that only allows correct domain inputs such as if 0 < a < 2000, b >= 10: [block of code] else: return error

Or codechef may have some other format for domain handling. What is the desired format for handling extraneous inputs?

ERROR: TLE, MAJIIN VEGETA

Viewing all 39796 articles
Browse latest View live


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