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

What the heck. Codechef is down. 502 bad gateway.

$
0
0

At the start of cook off why do codechef generally go down?


Why am i getting nzec?

Sorting In an array

$
0
0

How to sort Element in array For Example arr[] = {"Code1","Code10","Code2","Code20",code30}; output should be code1,code2,code10,code20,code30 but when i use arrays.sort in java it gives the output code1,code10,code2,code20;

Header files included in bits/stdc++.h

$
0
0

I recently came across bits/stdc++.h . However, it turns out that it isn't there on OSX. Can someone please share the contents of the file with me, so that I can add this header file manually?

Can anyone provide a hint to this ques?

Problem regarding Binary Heap

$
0
0

How to find out the minimum number of swaps required to convert the given array into a max heap??

https://www.codechef.com/SEPT17/problems/SEACO

$
0
0

void exec(int x, int y,int j){ for(int i=x-1;i<y;i++)b[j][i]=(b[j][i]+1)%mod; } void exec2(int x, int y,int j,int n){ for(int i=x-1;i<y;i++){ for(int k=0;k<n;k++){ b[j][k]=(b[j][k]+b[i][k])%mod; } } }

void solve()
{
    int t=ni();
    while(t-->0){
        int n=ni();
        int m=ni();
        int[] sum=new int[n];
        b=new int[m][n];
        a=new int[m][3];int i=0,x=0,y=0,z=0,c=1;
        while(i<m){
            a[i][0]=ni();a[i][1]=ni();a[i][2]=ni();
                if(a[i][0]==1 && 1<=a[i][1] && a[i][1]<=a[i][2] && a[i][2]<=n)
                    try{
                        exec(a[i][1],a[i][2],i);
                    }catch(Exception e){}
            else{
                    if(1<=a[i][1] && a[i][1]<=a[i][2] && a[i][2]<=i)
                        try{
                            exec2(a[i][1],a[i][2],i,n);
                        }catch(Exception e){}
            }
            i++;
        }
            for(i=0;i<n;i++){
                for(int j=0;j<m;j++){
                    sum[i]=(sum[i]+b[j][i])%mod;
                }
            }
        for(i=0;i<n-1;i++){
                out.print(sum[i]+" ");
            }
            out.println(sum[n-1]);
    }
}

why am i getting nzec exception?? Above solution is correct for 1st 5 test cases

BUYING2 SWEET

$
0
0

I just started looking at the problem BUYING SWEET my hunch tells me that correct condition/logic to solve the above problem is this ...

(sum % total_sweet) if find any note else then remainder then the customer is not an adequate customer. Work properly on the all the Test case found

Test case 1

4 7
10 4 8 5

Answer

[10,4,8 ,5].sum
## sum is 27
rem = 27 % 7  6
##rem = 6
i = 0;
adequate = true
for i < a.length:
     if a[i] < 6
        adequate = false
        break

Customer is not adequate

Test Case 2

1 10
12

Answer

   [12].sum
   rem = 12%10
   ## rem is 2
   No number less them 2 hence customer is adequate.

Test Case 3

2 10
20 50

Answer

[20, 50].sum
## 70
rem = 70 % 10
## 0
No number less then 0

Customer is adequate.

But with Limited Test case I'm not sure if the above logic is correct can some please provide some more TEST case so that I can verify them.

EDITED: I just wrote the initial implementation Getting WRONG ANSWER but the editorial https://discuss.codechef.com/questions/3250/buying2-editorial matched with my belief.

Here the Code I submitted https://www.codechef.com/viewsolution/15221523


C language that will read the value of x

$
0
0

WAP in C language that will read the value of x and evaluate the following function 1 for x < 0 y = { 0 for x = 0−1 for x > 0 Using (a) nested if statements (b) using else if statements (c) using conditional operator

How to search a user on CodeChef?

$
0
0

How do I search an individuals profile on CodeChef. Is there any way to search for a specific username? I just want to view the profile of a username.

Wrong ansewer!!!

small factorial (Why wrong?)

$
0
0

include<stdio.h>

long long int fact(int n); int main() { int n,i,k[i]; long int d[i]; scanf("%d",&n); for(i=0;i<n;i++) {="" if(1<="n&lt;=100" &&="" 1<="k&lt;=100)" scanf("%d",&k[i]);="" }="" for(i="0;i&lt;n;i++)" {="" d[i]="fact(k[i]);" printf("%lld\\n",d[i]);="" }="" return="" 0;="" }="" long="" long="" int="" fact(int="" n)="" {="" if(n="">=1) return(n*fact(n-1)); else return 1; }

Wrong Answer!!! (Dividing stamps)

why does this factorial program does not return the number of trailing zeroes for 25! as 6?

$
0
0

http://www.codechef.com/viewsolution/1017061

when I give input as follows:

5
5
10
15
20
25

the output I get is:

1
2
3
4
0

    import java.util.Scanner;
class Factorial
{
    public static void main(String args[])
    {
        int i,n;
        Scanner sc= new Scanner(System.in);
        n=sc.nextInt();
        long a[]=new long[n];
        long cnt[]=new long[n];
        for(i=0;i<n;i++)
        {
            a[i]=fact(sc.nextLong());
            cnt[i]=0;
            while(a[i]%10==0)
            {
                cnt[i]++;
                a[i]=a[i]/10;
            }
        }
        for(i=0;i<n;i++)
            System.out.println(cnt[i]);
    }
     public static long fact(long n)
    {
        if (n == 0) return 1;
        else
            return n * fact(n-1);
    }
}

when I give input as follows:

5
5
10
15
20
25

the output I get is:

1
2
3
4
0

Doubt in Traverse problem of Innerve's summer code challenge.

$
0
0

Where this logic is giving wrong answer??? Traverse problem of innerve....

while(t--){
scanf("%d",&m);
if(m%3 == 0){
    printf("%d %d\n",m/3,2*(m/3));
}
else{
    double n=m;
    i=ceil(n/3);
    j=i-1;
    while(j<2*i){
        if(i+j == n)
            {
                goto label;
            }
            j++;
    }
    label:
    printf("%d %d\n",i,j);
}

} return 0;


my approach is correct or not for chef and rods of TSEC codeathon?

$
0
0

Problem link-https://www.codechef.com/TSCO2017/problems/TSECJ106

solution-

import java.util.Arrays; import java.util.Scanner;

/ * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor./

//package codechef;

/ * @author DELL/ public class rods { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); } int cnt=1;

 int maintain=0;


  Arrays.sort(a);

  for(int i=0;i<n;i++)

  {
      if(i==0)
  maintain=(a[i]+6);

  else
      {
          if(a[i]>maintain)
          {

            maintain=a[i]+6;

            cnt++;
           }

      }
  }

      System.out.println(cnt);

      }

}

plz tell whats wrong in my code

$
0
0

plz tell me whats wrong in my code

question link-link text

import java.util.Scanner;
class practice
{
public static void main(String[] arg)
{
    Scanner kb=new Scanner(System.in);
    int test=kb.nextInt();
    for(int j=0;j<test;j++)
    {
        int size=kb.nextInt();
        int arr[] =new int [size];
        int cust=kb.nextInt();
        for(int i=0;i<arr.length;i++)
        arr[i]=kb.nextInt();
        int sum=0;
        for(int i=0;i<arr.length;i++)
        sum=sum+arr[i];
        if((sum/cust)<size)
        System.out.println("-1");
        else
        System.out.println(sum/cust);
    }
}

}

What are the possible errors in this code? It gives me SIGABRT.

$
0
0

//a program to perform the following operations on a linked list

 #include < stdio.h>

include < stdlib.h>

//node of the linked list typedef struct Node{ int data; struct node *link; }Node;

//handle of the list. the head pointer in in points towards the first node of the list typedef struct List{ Node *length; int length; }List;

//create an empty list List* create_list();

//insert a new node at the beginning of the linked list void insert_beginning(List *list,int data);

//delete the first node having the element "data" //No operation if there is no such node void delete_element(List *list,int data);

//display the elements of the linked list separated by spaces on a single line void disp_list(List *list);

//delete the linked list along with any nodes in it void delete_list(List *list);

int main() { int choice=1; int element; List *list=create_list(); while(choice>0 && choice<4) { scanf("%d",&choice);// 1:insert an element in the beginning. // 2:delete a specified element. // 3:display the list. switch(choice){ case 1: scanf("%d",&element); //enter the element to be inserted
insert_beginning(list,element); break; case 2: scanf("%d",&element); //enter the element to be deleted delete_element(list,element); break; case 3: disp_list(list); break; } } delete_list(list); return 0; }

List create_list() { List list; list=(List*)malloc(sizeof(List)); list->head=NULL; list->length=0; return list; }

void insert_beginning(List list,int data) { Node temp; temp=(Node*)malloc(sizeof(Node)); temp->data=data;

if(list->head==NULL){ temp->link=NULL; list->head=temp; } else{ temp=list->head; list->head=temp; } list->length++; temp=NULL; }

void delete_element(List list,int data) { Node iter=list->head,temp=list->head; int i=1; while(iter!=NULL) { if(temp->data==data){ if(i<2){ list->head=temp->link; } else{ iter->link=(Node )temp->link; } free(temp);list->length--; } else{ temp=temp->link;i++; if(i>2){ iter=iter->link; } } }iter=NULL;temp=NULL; }

void disp_list(List list) { Node temp; if(list->head!=NULL){ temp=list->head; while(temp->link!=NULL){ printf("%d ",temp->data); temp=temp->link; } printf("%d\n",temp->data); }temp=NULL; }

void delete_list(List list) { Node temp=NULL,*iter=list->head; while(iter!=NULL && iter->link!=NULL){ temp=iter; iter=iter->link; free(temp); } free(iter);free(list); }

Codechef Rating Predictor

$
0
0

Hello everyone!

alt text

Codechef Rating Predictor

The delay in previous month rating changes + inspiration from CF Predictor and for the practice of a web-application, i tried to write a script that can predict rating changes from ongoing live contests @ Codechef.

While the actual delays in rating changes s/would be fixed, this script can help in predicting rating changes as new submissions are made, so hopefully it can be useful for Long contests :).

The script is written in nodejs and is based on open rating formulas available at this link. The code for the project can be accessed here

Website is currently hosted on Openshift free servers and has few restrictions on use. Therefore the server might be slow or not responding during the period rating changes are calculated. Currently, ratings are expected to be updated every 15 minutes

I also tested rating changes on few past contests and the predictions were accurate within an error of 2 for almost everyone except the first rank (I have no idea why first rank predictions are wrong in some contests using current formulas)

Please note that project is still in beta stage and also actual changes might differ more due to changes in ranklist after plagiarism detection

Your feedback/suggestions would be appreciated

JUNE17 Links:

All: http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/JUNE17/all/

Long: http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/JUNE17/long/

Few stats on JUNE17 Predictions. I matched ratings (All) of first 6391 users and the results were as follows:

Difference - No of users

  • 0 - 5868
  • 1 - 275
  • 2 - 125
  • 3 - 68
  • >= 4 - 55

There were around 40 users having difference > 50. Turns out some usernames appears to be missing in the ranklist when sorted by rank and hence they were showing as last in the prediction list.

I ran the code again after fixing the above bug and results are better now (Maximum difference is 8)

  • 0 - 5900
  • 1 - 485
  • >= 2 - 6

COOK83 Links:

All: http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/COOK83/all/

Short: http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/COOK83/short/

The ratings are expected to update every 5 minute

Few stats, 4811/4820 predictions (for both all and cook-off predictions) were right. Rest have diff < 3 with the exception of rating prediction of first rank in cook off. Also, as @vikasj554 pointed out, few users got rating changed after initial update. (I still need to figure out why this happened). But even after this 4794/4820 predictions were accurate.

LTIME49 Links:

All: http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/LTIME49/all/

Lunchtime : http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/LTIME49/ltime/

The ratings are again expected to update every 5 minute

JULY17 Links:

All: http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/JULY17/all/

Long : http://codechef-rating-predictor.7e14.starter-us-west-2.openshiftapps.com/contest/JULY17/long/

Update frequency: 10 mins

MATTEG - Editorial

$
0
0

Problem Link

Practice
Contest

Author:Alexandru Valeanu
Tester:Hasan Jaddouh
Editorialist:Bhuvnesh Jain

Difficulty

MEDIUM

Prerequisites

Recursion, Bitmask Dynamic Programming, Hashing

Problem

You are given a grid, $R*C$, where each location has some number written on it. You are also given $N$ teleportation pairs (dx, dy), meaning that you can go from $(a, b)$ to $(e, f)$ iff $|a-e| = dx$ and $|b-f| = dy$, where $|x|$ denotes the absolute value of $x$. You are required to find a sequence of steps so that you use as maximum number of teleportation pairs (atmost $N$), each one only once, and try to maximise the sum of the number on the locations you visited.

Quick Explanation

Since, we need to use each teleportation pair once, we can store a bitmask where the set bits denotes which what teleportation pairs are still not used up. Then we can simply iterate over the possible next states based on the current location and bitmask and use dynamic programming to solve the above problem. Since, the number of locations that might be visited are limited, try to optimise the dynamic programming solution using hashing to handle the case of excess memory usage.

Explanation

Subtask - 1

No dynmaic programming or any advanced techniques are required to solve this subtask. Only simple recursion which traverses all the possible positions depending on the remaining teleportation pairs is enough. But this solution is quite slow to pass other subtasks.

Subtask - 2

We can simply see that subproblems of many recursive calls of above solution are overlapping. To clearing differentiaite between the different states, we create an dynamic programming array consisiting of 3 states, namely the current x-coordinate, current y-coordinate and the mask denoting the teleportation pairs still to be used. Thus our dynamic programming array looks like $dp[x][y][mask]$.

Building the above the dynamic programming bottom up, would lead to complexity of $O(R*C*N*{2}^{N})$, which is quite slow for final 2 subtasks. Also, the memory used by the above approach will be of the order of $O(R*C*{2}^{N})$, which would cause memory limit issues with last 2 subtasks as well.

Subtask - 3

In the above approach it is easy to see that most of the states would be unreachable. For example, there might not exist any sequence of steps (of length <= $N$), such that we can reach from $(a, b)$ to $(c, d)$. Also, there might be cases we could reach from $(a, b)$ to $(c, d)$ only through particular sequence of moves, meaning that all "mask" positions might not be visited also. Thus, we need to avoid these redundant calculations in the above approach and also try to find an more strict upper-bound on the number of visited states in the above dynmaic programming solution.

Let us first define what a valid teleportation is. A teleporation is said to be valid if from a location on a grid, we can go to a location present on the grid. It is invalid, if we go to a location outside the grid.

We try to find a tighter upperbound for the number of states visited. Now, let us say, we are at a particular location, $(a, b)$, then we have 5 possible choices to take from the current location, i.e. either stay in the current location (since we can't use any valid teleporation) or jump in any of the 4 directions (if jump is valid i.e. inside the grid). Also, at each steps, we would have to choose from $K$ of the remaining teleportation pairs to go to next point. Thus, we can say that we have an upperbound of $O(min(N*{5}^{N}, R*C*N*2^{N}))$ on the number of states that are visited. (Why minimum is taken is because, we either visit all the states in which case the bound is simply $R*C*N*{2}^{N}$ or we can't take some valid teleportation pair at some location and visit less states, leading to $N*{5}^{N}$ bound).

Now, let us try to write the above solution in top-down appraoch i.e. using recursion with memoisation. This, will lead us to visiting only those states which are reachable from starting state i.e $dp[Sx][Sy][{2}^{N}-1]$. Thus, in recursive solution for subtask - 1, we simply add the dynamic programming approach. But there is still a catch here i.e the memory requirement. The memory required by this solution is still $O(R*C*{2}^{N})$, which limits us from passing this subtask. But our time complexity of the solution has decreased. To get a trade of between the time and space complexity, we can use "maps" or "unordered maps" to store the list of possible "masks" or "locations" as per implementation. This will increase the time complexity by logarithmic factor, but the space complexity would now be order of the number of possible states. Using this optimisation, we can easily pass the given subtask.

Subtask - 4

We are almost close to the full solution now. We just need to lower the trade off we did between memory and time in the last approach. For this, we will use hashing approach, to remove the logarithmic factor from the above last approach. (It may seem that unordered_map would suffice for this subtask too, but since they number of states in the unordered map are large, rehash would be called many times, which is a costly operation and lead to the solution becoming slower).

First let us consider mapping 3 states into a single number without any collision at all. Since, $(a, b)$ are grid points, we can represent each grid point into a single integer as $a * C + b$. Thus now, the states reduce to $2$. We can again apply similar operation to reduce the states to $1$. For example mapping $(a, b, mask)$ to single integer $(a * C + b) * {2}^{N} + mask$. The order of this number is $O(R*C*{2}^{N})$. We can simply hash this number to another value, i.e. build a hash table for these values. Suppose, we have successfully build our hash table, then we can easily see that we can retrieve the elements in $O(1)$, thus removing the logarithmic factor from above solution. Care must be taken while choosing the size of hash table. Taking it too small would be of no use due to large number of collisions. We should chose the size around the number of states that can be reached, thus reducing the number of collisions while inserting the keys into it. Also, we can either implement hashing using linear probing or separate chaining. The author chose linear-probing to implement the hashing technique.

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

Tester's Solution for full problem

The tester's solution used the fact that we have $5$ choices at each and every point on the grid. Thus similar to bitmask where we have $2$ bits to represent a states, he represented each states used base $5$ encoding where $0$ means we stay at the same location, and $1$ to $4$ means we chose one of the 4 directions. Simliar to iterative bitmasking solution which are written traversing each mask from $0$ to $2^N - 1$, the solution traverse each base $5$ mask from $0$ to $5^N - 1$. Then based on the values in the mask, we just perform the teleportation and check whether we land at valid grid point or not. If yes, we update the answer for that mask. The final answer is the maximum over all the mask values calculated. The time complexity of this solution is exactly $N * 5^N$, and it doesn't use any hashing. Also, the 2 dimensions where we store the current $x$ and $y$ coordinate in above solution is not required here as it is captured in the base case, where we store the cost of starting point.

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

Time Complexity

$O(min(N*{5}^N, R*C*N*{2}^{N}))$

Space Complexity

Size of Hash Table ~ $O(min({5}^N, R*C*{2}^{N}))$

Solution Links

Setter's solution
Tester's solution
Editorialist solution - For 70 points, (No implementation of hash table)

Viewing all 39796 articles
Browse latest View live


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