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

in python idle it is running correctly

$
0
0

question is: All submissions for this problem are available. The game of billiards involves two players knocking 3 balls around on a green baize table. Well, there is more to it, but for our purposes this is sufficient.

The game consists of several rounds and in each round both players obtain a score, based on how well they played. Once all the rounds have been played, the total score of each player is determined by adding up the scores in all the rounds and the player with the higher total score is declared the winner.

The Siruseri Sports Club organises an annual billiards game where the top two players of Siruseri play against each other. The Manager of Siruseri Sports Club decided to add his own twist to the game by changing the rules for determining the winner. In his version, at the end of each round the leader and her current lead are calculated. Once all the rounds are over the player who had the maximum lead at the end of any round in the game is declared the winner.

Consider the following score sheet for a game with 5 rounds:

Round     Player 1       Player 2

  1             140                 82
  2              89                 134
  3              90                 110
  4              112              106
  5              88                  90

The total scores of both players, the leader and the lead after each round for this game is given below:

Round      Player 1       Player 2     Leader     Lead

  1               140                82        Player 1     58
  2               229               216       Player 1     13
  3               319               326       Player 2      7
  4               431               432       Player 2      1
  5               519               522       Player 2      3

The winner of this game is Player 1 as he had the maximum lead (58 at the end of round 1) during the game.

Your task is to help the Manager find the winner and the winning lead. You may assume that the scores will be such that there will always be a single winner. That is, there are no ties.

Input

The first line of the input will contain a single integer N (N ≤ 10000) indicating the number of rounds in the game. Lines 2,3,...,N+1 describe the scores of the two players in the N rounds. Line i+1 contains two integer Si and Ti, the scores of the Player 1 and 2 respectively, in round i. You may assume that 1 ≤ Si ≤ 1000 and 1 ≤ Ti ≤ 1000.

Output

Your output must consist of a single line containing two integers W and L, where W is 1 or 2 and indicates the winner and L is the maximum lead attained by the winner.

Example

Input:

5 140 82 89 134 90 110 112 106 88 90 Output:

1 58

my code is:

n=int(input()) a=[] b=[] c=[]

for i in range(0,n): a.append(list(map(int,input().split())))

for i in a : if(int(i[0])>int(i[1])): b.append(i[0]-i[1]) else: c.append(i[1]-i[0])

d=b+c

m=max(d)

if m in b: print(1,m)

else: print(2,m)

it is showing wrong answer


help in https://www.codechef.com/problems/CHEFPRES

$
0
0

can anyone please help me to understand how to do it in less than O(N^2) ...i have read the editorial but couldn't understand that part! please help me

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

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

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);
    }
}

}

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

Why am i getting nzec?

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); }

How to run my c++ program?

$
0
0

I want to run my c++ program but it is not taking inputs from user and directly giving output

Can anyone give a hint for this problem?


"I want to ask a question" - Ask them all here!

$
0
0

Hello guys,

UPDATE- This thread is now for people who are unable to ask questions due to low-karma/losing-karma or time limit.

As you all are aware, many times there are genuine users who wish to ask a question, but dont have karma for it. They then, have to resort to means of either asking their question in other threads, or request someone to upvote them so they can ask a question.

As we have seen last month, some fake accounts were used in malpractices in discuss, and they also gained karma by "I want to ask a question" thing. Hence, now it is becoming increasingly difficult to differentiate between genuine users, and fake users.

This thread is my solution for it. Any user, with less than 3 karma who wants to ask a question is requested to ask it here, and if the question is upto standards (meaning it needs more than those "one line answers") then we (at least I ) will convert your "answer" here into a question.

In short, post your question here, and if its a good genuine question, it will get posted as a separate question by using "Convert to question" feature.

In case your question required only 1 line answers or such, we would comment it on your question.

You guys are requested to direct any such guy (who wants to ask a question) here and not "free-upvote" them, so that we can avoid any duplicate/irrelevant questions (as questions posted here would be verified first, before converting to question).

Note to @admin - We will require your active participation and help in events related to deletion of any spam content here. Also, since only admins are ones who could delete answers, it is requested that you keep an eye out on this thread.

With Regards

Vijju123

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

$
0
0

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

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)

MKTHNUM from SPOJ--help required

problem in formate of submission, what the wrong with this source code.

$
0
0

include<iostream>

include <cmath>

using namespace std;

int main() { int t; // no. of test cases cin>>t;

while(t--){
int n; //inputs

float t1,v1,v2,t2;
cin>>n>>v1>>v2;
t1= (sqrt(2)*n)/v1;

t2=(2*n)/v2;

if(t1>t2){

    cout<<"stairs"<<endl;
}
else
{
   cout<<"elevator"<<endl;
}
}

return 0; }

Viewing all 39796 articles
Browse latest View live


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