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

Increment/Decrement Operator

$
0
0

Programming in C: I have run the following code: .. int I = 5; printf("%d,%d,%d",I++,I,++I); ..

The output I expected was 667.After running this code it was 677. Could anyone explain this?


here`s my code in c. It`s giving me a wrong answer. could u explain why?

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

taking input in a list in python

$
0
0

how to take an input which contains elements seperated by spaces into a list in python3.5

Buying Sweets

$
0
0

Sachin likes sweets a lot. So, he goes to a market of sweets. There is a row of sweet stalls. Every sweet stall has different sweets. To save some time, he decided to buy sweets from contiguous stalls. So, he can buy from as many stalls as he wants, but all of those stalls need to be contiguous. He also decided to buy only 1 kg of sweets from each of those stalls. Cost of 1 kg of sweets for each stall is given. There is a strange rule of billing in that market. And that rule is as follows- Total cost of all sweets bought is sum of the cost of all sweets multiplied by the cost of sweet he bought at the end. e.g. if he buys sweets having cost 2, 3, 4 in the same order than total cost of sweets will be 24+34+4*4=36. Now he wonders what will be the total cost of all possible ways of buying sweets. Can you help him. Because this number could be large, you should take modulo of the final result by 10^9+7.

INPUT SPECIFICATION Your function contains a single argument- A One dimensional Integer array of Size N in which ith element denotes the cost of 1 kg sweets from ith stall. First line of input contains an Integer N denoting the size of Array. (1<=N<=10^5) Next N lines of input each containing a single integer from 1 to 9.

OUTPUT SPECIFICATION You must return an integer- sum of the cost of all possible ways of buying sweets modulo 10^9+7.

EXAMPLES Sample Test Case 1- Input 3 1 2 3

Output 53

Explanation Possible ways of buying sweets are- a) 1 b) 1 2 c) 2 d) 1 2 3 e) 2 3 f) 3 cost of each of these is following- a) 11= 1 b) 12+22= 6 c) 22= 4 d) 13+23+33= 18 e) 23+33= 15 f) 33= 9

Hence total cost will be 1+6+4+18+15+9=53

MTRXMOD - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Yuri Shilyaev
Tester:Hasan Jaddouh
Editorialist:Daniil Melnichenka

DIFFICULTY:

Simple

PREREQUISITES:

Absolute value equations.

PROBLEM:

Given a matrix $B$ of size $N \times N$, made by following rule: $B_{i, j} = |A_{i}-A_{j}|$. Find a lexicographically minimal sequence $A$ of $N$ numbers that could have been used to build matrix $B$ with $A_1 = 0$. Also answer $Q$ queries of changing a row and corresponding column of matrix to the new one.

QUICK EXPLANATION:

Let's restore the sequence in $O(N)$. Find a first non-zero element (let it be element number $i$) and assign it to $-B_{1, i}$. Now restore all the other elements using equations with $A_1$ and $A_i$.

The total complexity would be $O(N^2+NQ)$.

EXPLANATION:

Firstly let's maintain matrix $B$. Besides it's easy to see the following fact. Suppose we have some array $A$ that is suitable for current matrix $B$. Let's replace all elements in $A$ with the additive inverses. Obviously, the new array fits matrix $B$.

Let's do the following after every query. We know that $A_1$ is equal to 0. Let's find the smallest $i$ that $B_{1, i}$ is not zero with a simple loop. Evidently all $A_j$ ($j$ < $i$) are equal to 0. Now we should take advantage of a fact that was mentioned above and assign $A_i = -B_{1, i}$ as we want to get the lexicographically smallest answer. After that let's make a loop for all $j$ ($i$ < $j$ $\le$ $N$). Easy to note that we have a system of equations:

$|A_i - A_j| = B_{i, j}$
$|A_1 - A_j| = B_{1, j}$

where $A_1 \neq A_i$ and all the values are known except $A_j$. Now we should just solve this system of equations and find out $A_j$.

AUTHOR'S AND TESTER'S SOLUTIONS:

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

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

how can i solve this question in practice section ?


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

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)

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>