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

Finding all path to reach to end

$
0
0

Given a staircase that has 'n' step, and you climb the staircase by jumping over the steps. You can cover at max of 'k' steps in a single jump. List all the possible sequence of jumps you could take to climb the staircase.

input:
n=4, k=2

output:
1,1,1,1
1,1,2
1,2,1
2,1,1
2,2

counting total possible number of path http://www.geeksforgeeks.org/count-ways-reach-nth-stair/
but how to print all path ??


Chef and Sign Sequence: July Long 2017 Question | Please tell me If anything is wrong in this solution

$
0
0

Please, can anyone tell me what is wrong in this Code? This is the question of July 2017 Long challenge. Please help!!

Click to view the problem statement

https://www.codechef.com/JULY17/problems/CHEFSIGN

import java.util.*;
import java.io.*;

class chefsign
{
public static void main(String args[])throws IOException
{
    try
    {
        InputStreamReader is = new InputStreamReader(System.in);
        BufferedReader bf = new BufferedReader(is);

        int t = Integer.parseInt(bf.readLine());
        while(t>0)
        {
            String s = bf.readLine();
            int temp_num=1;
            int min=1, max=1;
            for(int i=0; i<s.length(); i++)
            {
                if(s.charAt(i)=='<')
                {
                    temp_num++;
                    if(temp_num>max)
                        max = temp_num;
                }
                else if(s.charAt(i)=='>')
                {
                    temp_num--;
                    if(temp_num<min)
                        min = temp_num;
                }
            }
            System.out.println(Math.abs(max-min)+1);
            t--;
        }
    }
    catch(Exception e)
    {
        return;
    }
}

}

Wrong Answer! code: CLEANUP. PLEASE HELP!!

$
0
0

I don't know what is wrong with my code. I admit that it's complicated but I'm a beginner. So please give it a try and help me finding the bug... Problem Code: CLEANUP Here's my code:https://ideone.com/Nf6kr7

Array Transform

$
0
0

Whats wrong with my logic or code i am constantly getting a WA inspite of checking the code for many test case....

#include<stdio.h>

int ans(int n, int k)
{
    int i,mod1,mod2,f1=0,f2=0;
    int ele;
    int flag=0;
    scanf("%d",&ele);
    mod1=ele%(k+1);
    f1++;
    for(i=1;i<n;i++)
    {
        scanf("%d",&ele);
        if((ele%(k+1))==mod1)
            f1++;
        else if(flag==0)
        {
            mod2=ele%(k+1);
            flag=1;
            f2++;
        }
        else if((ele%(k+1))==mod2)
            f2++;
        else return 0;
    }
    if(f1>1&&f2>1)
        return 0;
    else return 1;
}

int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int n,k;
        scanf("%d",&n);
        scanf("%d",&k);
        if(ans(n,k)==0)
            printf("%s\n", "NO");
        else printf("%s\n","YES");
    }
    return 0;
}

problems needed

$
0
0

Can someone suggest some problems(can be from anywhere) where I need to deal with lots of corner cases.. Thanks in advance. :)

can set of pairs can be created?

Help with this code?

$
0
0

I have been trying to solve the Gross Salary(FLOW011) problem under beginner section. I have written a code which is working fine for the inputs given in the page but the codechef compiler is showing error, can someone please point out the error.

Here is the code.

import java.util.Scanner;

class Flow011 {
public static void main(String[] args){
    Scanner in = new Scanner(System.in);
    double n = in.nextDouble();
    while(n-->0){
        int  salary = in.nextInt();
        double gross;
        if(salary<1500){
            gross = salary+(salary*0.1)+(salary*0.9);
        }
        else{
            gross = salary + 500 + (salary*0.98);
        }
        //System.out.println((new DecimalFormat().format(gross)));
        System.out.printf("%g",gross);
    }

    in.close();
}
}

Time Limit should be increased by 0.5 sec for Pishty and tree (JULY17)

$
0
0

My code is running in O(nlogn) but still getting TLE...only hardware level optimisation required.I am wasting my time to optimise it for more 0.5 sec..so please increase its Time limit by 0.5 sec because in java object takes more time than struct in cpp.

Why so strict Time limit O(n^2) solution won't even run in 10 sec?

author of the problem


Please help with this code. I am getting WA for counting inversions using merge sort. What's going wrong here?

$
0
0

Here's the code:


    typedef long long int ll
    int merge( vector<int> &v, int start, int mid, int end )
    {
     ll count = 0 ;
     int n = (end - start + 1) ;
     int i=start, j=mid+1, k=0 ;
     vector <int> temp(n);
     while( i <= mid && j <= end )
     {
        if(v[i] <= v[j])
            temp[k++] = v[i++];
        else
        {
            count += (mid - (i+start) + 1) ;
            temp[k++] = v[j++];
        }
     }
     while( i <= mid )
        temp[k++] = v[i++];
     while ( j <= end )
        temp[k++] = v[j++];
     k = 0;
     for( i = start; i <= end; i++)
        v[i] = temp[k++];
     return count;
    }
    ll mergesort( vector <int> &v, int start, int end )
    {
     ll count=0;
     if( start < end )
     {
        int mid = start + ( end - start )/2;
        count += mergesort( v, start, mid );
        count += mergesort( v, mid + 1, end );
        count += merge( v, start, mid, end );
     }
     return count;
     }

POLL/VOTE: There should be feedback for WA's on live Contests/Challenges.(Atleast for coders upto 3-4 stars)

$
0
0

Hey Guys, This is really a concern, specially for beginners like me...after finally understandin a slightly confusin question...and coding what I believe is logically and syntactically correct(also gettin the expected output in the sample of the given problem).

But gettin a WA(wrong Answer) after submitting, just makes us dumbfounded and with no feedbacks and the protocols of CodeChef (for on goin challenges) there is nothing left to do and we end up wastin our time(coz we cant get help from experienced Coders).

So I request you to show your support(in any way comment,answer,upvote...so that admin can make it happen) if u agree and face the same problem, please do vote.

And for the contrary please guide us on what to do (i believe that gettin WA must be due to edge cases, for most parts)better still helps us.

Answer/comments in "yes" or "no"(and kindly guide us after that ).

Thanks!

Jiraiya and Rasengan Attacks Hackerearth

$
0
0

How to approach the question Jiraiya and Rasengan Attacks given on Hackerearth. I think we should compute the probability that each pair of numbers in the array will become an inversion. But I can't think more than that. Problem link

beautiful arrays wa

marbles question,it is displaying wrong answer,can someone help.below link is solution link

Help with this code?(Stuck)

$
0
0

I have been trying to solve the Gross Salary(FLOW011) problem under beginner section. I have written a code which is working fine for the inputs given in the page but the codechef compiler is showing error, can someone please point out the error.

(UPDATED) Still it's giving same error. Here is the code.

   import java.util.Scanner;

class Flow011 {
public static void main(String[] args){
    Scanner in = new Scanner(System.in);
    double n = in.nextDouble();
    while(n-->0){
        int  salary = in.nextInt();
        double gross;
        if(salary<1500){
            gross = salary+(salary*0.1)+(salary*0.9);
        }
        else{
            gross = salary + 500 + (salary*0.98);
        }
        if(gross==Math.floor(gross)){
            System.out.println((int)gross);
        }
        else
        System.out.printf("%g\n",gross);
    }

    in.close();
}
}

My solution for PSHTTR

$
0
0

Initially I constructed the given tree but assigned all the edges 0 weight.

Now we should find XOR of all edges from U to V which are less than K. We sort the queries and the given edges by weight in increasing order(both in the same array).Iterate through each element of the array, if it is a Tree edge node, Assign the value of the weight to edge of the tree. If it is a query node find the XOR of all edges between U and V ,because all the edge weights of your current tree are less than your Query's K. I created a vector of nodes where type 0 indicates Tree edge and Type 1 indicates Query.my node looks something like this

class qnode{

public:
 int type,u,v,value,qidx,aidx;
 bool operator<(const qnode &n) {
    if (value != n.value) return value < n.value;
    else return type <= n.type;
 }
 qnode(int a,int b,int c,int d,int e,int f){

  type = a;
  value = b;
  u = c;
  v = d;
  qidx = e;
  aidx = f;
}
};

type denotes wether it is a tree edge or a query ,value denotes the edge weight,U and V are the nodes between which the edge is present,qidx is the query number

So now the problem is simplified to this, Given two types of queries 1)Increment a Edge weight by T 2)what is the XOR of edge weights from U to V.Answer to the second query will be stored in its corresponding query number.

How to solve query 2?, let f(U,V) denotes Xor of all edges between U to V.f(u,v) = f(u,root) ^ f(v,root), because the the portion above lca(u,v) will be cancelled out by the XOR operation and only the part from (u to lca(u,v)) and (v to lca(u,v)) remains.

Using DFS order convert the tree into array and solve it using segment tree.

This is my solution My code

This is my first post so any suggestions are Welcome :)


An advice for competitive programming

$
0
0

Hello,

By no means, am I a very successful programmer or something, if you don't want to read it its alright and also, if you think I am not qualified to write stuff like this, I will say that it's just personal thoughts. In a hope that I will be helping some of the people here I will continue.

So, I was selected for the IPC Camp this year. I don't know how, I thought I won't because of my codeforces rating. I am just a green there. Thing is the topics that were taught in the lectures mostly consisted of rare topics that bridge the gap between purple and red. Things like palindrome trees and suffix automata were taught, many people did not even understand(Except a handful who are really good programmers). They almost never appear in any short contest. Yes, some topics like geometry and maths are actually helpful for the short contests but most weren't.

I thought maybe this wasn't the right camp for me, but then I came to a realization that this camp was really great, teaching us so many new stuff(Isn't that the whole goal behind organizing any camp?), the problem is with me. I am a big-time procrastinator and never practice. All I do is look at the other "How to be better in competitive programming" type of questions on quora, codeforces and codechef. Most of the times while practicing, I open a problem, think of a solution, if I think of it, I look at the editorial and see if my thinking was correct and then if I can't, I go to the editorial read it and leave it. I almost never implement and submit because of laziness. And I realized, this way it won't work. Just cheating myself and doing long contests more than short contests is only hampering me. Even learning new topics now is not as important as practice. If you solve till div2 D on codeforces, you are a purple/high blue. New topics are only needed for div1 C/div2 E and if you solve them fast, you have a high chance of being a yellow or red.

I was having a talk with kevinsogo the other day, I told him that this is my last try for the IOI this year and asked him about how and what I should practice. Firstly, he told me about how, he said,"You are worrying about it too much. Even I didn't qualify for ICPC World Finals, but I don't care, all that matters is that I enjoyed solving the problems and will continue enjoy solving problems." I asked when to see the editorials, he said,"If you really enjoy solving problems, you will never see the editorial and ruin the joy of problem solving. And if you don;t enjoy problem solving then what's the point of programming competitively? It's ok to see hints or the topics that are needed to solve the problem from editorial only. But that's just how I have practiced." He was really inspiring to me as a competitive programmer.

To sum it up, there is really no new advice, just to the procrastinators and the skeptics, there is no way to get better without practicing; even if you learn all the topics in the world, you will never be able to apply them in problems unless you practice problems. Just take it from someone who was the second lowest rated coder in the camp.

Please do comment and tell me if something I said here was wrong, I can assure there is no wrong intent from my side.
Hope you have a good day and happy coding :)

P.S. When I said "Short contest" I meant if you want a good ranking in the short contests, or else if you want to be among the top 10, of course topics like centroid decomposition and fft appear as div1 D or E many a times.

PSHTTR - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Ivan Fekete
Primary Tester:Misha Chorniy
Editorialist:Hussain Kara Fallah

DIFFICULTY:

Medium

PREREQUISITES:

Graph Theory,Sorting,Data Structures

PROBLEM:

Given a rooted weighted tree with N nodes and M queries of the form (u , v , K). For each query, you must report to xor sum of edges which has weight less than or equal to K on the path from u to v.

N,M ≤ 10^5

EXPLANATION:

First of all let's solve the easier version of this problem. Queries which asks for the xor sum of edges on the path between 2 fixed nodes (without the restriction of K). Let's choose an arbitrary root for our tree and call a Depth-First search starting from this node.Let's maintain a table S[N], such that Si denotes the xor sum of edges weights starting from the root and ending at node i. The answer of each query (u,v) would be (Su xor Sv). Edges of the chain starting from the root and ending at LCA(u,v) (lowest common ancestor) would be excluded because (V xor V = 0).

Now let's solve our problem. First thing we should take advantage of, is that we can answer our queries offline (reading then processing all queries, after that reporting the answer of each one). Each edge weighted W must be included in the answer of all queries with K ≥ W. For queries with K < W we can assume that this edge's weight is zero (so it won't affect the answers).

Let's sort our queries in ascending order according to their magic numbers K, and sort our edges in ascending order according to their weights W. Let's process our queries in ascending order, and maintain a pointer iterating on our sorted edges list. So before processing a query with magic number K, we add all edges with W ≤ K through our pointer.

Now Let's discuss adding edges, and how will we get our table S[].

Let's maintain a timer incremented by one every time we visit a new node in our Depth-First-Search, and keep for the ith node a variable sti (denoting the value of the timer once entering this node),and a variable eni denoting the value of the timer after finishing this node's subtree (before exiting). This is a famous technique called euler tour on tree (dfs order). So we can represent nodes located in the subtree of the ith node by interval [sti , eni]

Regarding adding edges, each edge will link between 2 nodes (u,v) such that u = par[v], this edge's weight will be added to the xor sum (cumulative xor sum from the root) of all nodes located in the subtree of v. That means we should apply the operation

Si = Si xor V

for each i : (stv≤ i ≤ env)

This can be done using a binary indexed tree, segment tree (with/without) lazy probagation. Since our modification query is done on a segment of array S and we are querying the value of only one element we can do the following:

Let's maintain an array X which is all zeros at the beginning. When handling an edge of weight W added to the results of nodes in node v subtree.

X[sti] = X[sti] xor V

This means that we are adding V to the xor sum of all nodes with enterance timer ≥ stv

X[eni + 1] = X[eni + 1] xor V

This means that we are excluding V from the xor sum of all elements with entrance timer > en[v] (since it was added in the first operation so doing xor again is equivalent to exclusion).

You can notice now that the value of Si is:

Si = X1 xor X2 xor X3 xor X4 xor X5 xor ... Xi

Now we can easily iterate through our queries, and for each one we should make sure that all edges with weight less than or equal to this query magic number are added. After that, each query can be solved in O(log N).

Total complexity O(N log N + M (log M + log N))

AUTHOR'S AND TESTER'S SOLUTIONS:

AUTHOR's solution: Will be found here
TESTER's solution: Will be found here
EDITORIALIST's solution: Will be found here

java v/s C++

$
0
0

Is it better to use c++ instead of Java for competitive Programming??

Sorry for posting question

$
0
0

Sorry for posting wrong question in this forum.

Hashmap Implementation for negative numbers c++

$
0
0

How do I implement a hashmap using stl or any other method for a negative number in C++? A small description along with an example for the same would be appreciated.

Viewing all 39796 articles
Browse latest View live


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