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

A Game of Consecutive Piles- Editorial


The 1st subtask test cases for PRPALN (November Long 2014) might be weak. Can anyone confirm?

$
0
0

I submitted a bad solution and it got AC for the 1st subtask.

Had put a wrong relational operator somewhere: < instead of <=

Thankfully, the 2nd subtask caught it as WA in some of its cases so I didn't get a 100 score.

Dfs implementation for undirected graph to check for cycles

$
0
0

Trying to solve SPOJ problem Is it a tree?

Based this on this tutorial

But I am always getting NO as on output. Please help where am I going wrong?

#include<iostream>
#include<cmath>
#include<vector>
#include<climits>
#include<algorithm>
#include<list>

using namespace std;

class graph
{
      public:
    long v;
    bool cyc();
    bool dfs(long v,bool visited[],long parent);

    void addedge(long v,long w);

 graph(long v);
    list<long> *adj;




};

graph::graph(long v)
{
    this->v = v;
    adj = new list<long>[v];
}

void graph::addedge(long v,long w)
{
    adj[v].push_back(w);
    adj[w].push_back(v);
}



bool graph::dfs(long v,bool visited[],long parent)
{
    visited[v] = true;
    //cout<<v<<" ";

    list<long>::iterator i;

    for(i=adj[v].begin();i!=adj[v].end();++i)
    {
        if(!visited[*i])
            {
            if (dfs(*i,visited,v))
            return true;
            }

            else if(*i!=parent)

               {
                   return true;
               }
    }

    return false;


    }









bool graph::cyc()
{
    bool *visited = new bool[v];
    long i;
    for(i=0;i<v;i++)
    {
        visited[i] =false;
    }
    for(i=0;i<v;i++)
        if(!visited[i])
           if (dfs(i,visited,-1))
            return true;
            else
                return false;


    return false;
}








int main()
{
    long m,n,v,w;
    cin>>n>>m;
    graph g(n);


    for(long i=0;i<m;i++)
    {
        cin>>v>>w;
        g.addedge(v-1,w-1);
        g.addedge(w-1,v-1);

    }

    if(m!=n-1)
    {
        cout<<"NO"<<endl;
        return 0;
    }


  if(g.cyc())
    cout<<"NO"<<endl;
  else
    cout<<"YES"<<endl;




}

ATM problem C++ help

$
0
0

I have submitted by code 3 times but codechef still says my answer is wrong, I have tested it multiple times and I cannot seem to find whats wrong, if someone could point this out it would really help me:

const double fee = 0.50;
double balance = 0;
int withdraw_amount = 0;




int main()
{
cin >> withdraw_amount >> balance;

if (withdraw_amount % 5 != 0)
    {
        cout << balance << endl;
    }
else if (withdraw_amount > balance)
    {
        cout << balance << endl;
    }
else
    {
        balance -= withdraw_amount + fee;
        cout << setprecision(2) << fixed << balance << endl;
    }



return 0;
}

Run time error

$
0
0

tell me the possible reasons for NZEC error

lif,universe....

$
0
0

// c code

include<stdio.h>

void main() { int a; while(1) {

scanf("%d",&a);

if(a==42)

break; else

printf("%d",a); }

}

//java code

import java.util.*;

class prog1 { Scanner var=new Scanner(System.in); int a; while(1) { a=var.nextInt(); if(a==42) break; else System.out.println(a);

}

}

lif,universe....

$
0
0
// c code
#include<stdio.h>

void main()
{
int a;
while(1)
{

scanf("%d",&a);

if(a==42)

break;
else

printf("%d",a);
}

}




//java code

import java.util.*;

class prog1
{
Scanner var=new Scanner(System.in);
int a;
while(1)
{
 a=var.nextInt();

 if(a==42)

 break;

 else

 System.out.println(a);

}

}

need faster io for python programming !!


Which scripting language should I learn ?

$
0
0

I would like to learn some scripting language. But I am confused which one to choose Python, Perl or Ruby or any other language.

Can someone suggest me a scripting language also with comparisons with other scripting languages ?

Thank you.

NZEC in Python

$
0
0

I kept getting NZEC in Python for problem.
code:

def main():
N=int(input())
M=int(input())
a=0
for i in range(N):
num=input()
a,b,c,d=num.split(" ")
if M in (a,b,c,d):
a=1
if a==1:
print("YES")
else:
print("NO")
return 0
if __name__ == "__main__":
main()

You can look at all my codes at : tries

Bytelandian gold coins using c++

$
0
0

Hi, I recently solved the Bytelandian gold coins problem. It's running successfully on my laptop in Turbo C++. but whenever I submit it, it shows compilation error and says "conio: No such file or directory". I am checking C++11 as the language while submitting my code. So, is there any problem with the language selection? What should I do?

How can I find my total score and rank in the current challenge?

$
0
0

Hi all How can I find my total score and rank in the current challenge? Thanks.

ACM14AM5-Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:
Tester:
Editorialist:Jingbo Shang, Suhash

DIFFICULTY:

Medium-Hard

PREREQUISITES:

Dynamic Programming, Fast Power Method, A little Math

PROBLEM:

Given a number N, find the sum of f(x) for all x such that 1 <= x<= N. f(x) is defined as the sum of all digits in base 10 representation of the number x.

The special condition is that the total number of different consecutive digits are limit to M–1. That is, in the base 10 representation of N, there are only M blocks and each block contains the same digits.

EXPLANATION:

Simpler Version 1

Before we begin solving the actual problem, let’s try to solve the following problem:

Given an integer x, let g(x) denote the sum of the digits of all integers from 1 to (10^x)-1.

It can be proved very easily that g(x) = 45 * x * 10^(x-1). Because for each digit 0..9 (0+1+2…+9 = 45), it could occurs in x different positions and there are 10^(x-1) different combinations for other positions. By this formula and fast power method, for a given x, g(x) can be calculated in O(log x).

Simpler Version 2

Now, coming to the actual problem, let’s again first try and solve a simpler version of the problem: Given an integer N, find h(N) = sum{f(i), i=1 to N}, where length(N) <= 10^6.

First, let N = (n1 n2 n3 … nk) in base 10 representation. Here, k = length(N), and the digits 0 <= ni <= 9.

Then, define dp[i] as sum of all numbers <= N, such that the first i-1 digits of N remain unchanged, and remaining digits can be filled in anyway, such the integer formed is <= N. This can be done as follows.

At position i,

  1. if we put any digit from 0 to ni–1, then the resulting number is always < N. In this scenario, we can fill the remaining k-i positions with any digits. This value is exactly g(k-i), which we have discussed in simpler version 1. The number of ways of filling is 10^(k-i). Summing the above cases, we get

    (0 + 1 + 2 + ... + (ni-1)) * 10^(k-i) + ni * g(k-i)
    
  2. If we put a digit = ni at position i, problem reduces to dp[i+1].

Therefore, we can write it as follows:

dp[i] = (0 + 1 + 2 + ... + (ni-1)) * 10^(k-i) + ni * g(k-i) + dp[i+1].

With a little simplification, it can be seen that this can be done in O(k * log k), while dp[1] is the required answer.

If k<= 10^6, then this can be easily solved. But in our case, k<= 10^18. We need to do something smarter.

Final Version

The trick is that a contiguous block of digits have the same value. In the above dynamic programming, instead of going from dp[i] to dp[i+1], we can go from dp[i] to dp[i+L], where a contiguous block of L digits have the same value.

It can basically be reduced to the following form:

dp[i] = sum(j=i to i+L) (k1 * 10^(k-j) + k2 * (k-j) * 10^(k-j)) + dp[i+L].

where, k1 and k2 are two constants depend on ni could be derived from previous discussion. The sum part above can be found in O(log L) using the similar idea to the fast power method. And we only need to calculate the value of dp at most M points, where M is the number of blocks of digits given. Thus, the problem can be solved in O(M log L).

AUTHOR'S AND TESTER'S SOLUTIONS:

The links will be fixed soon.

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

ACM14AM4-Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author: Suhash
Tester:
Editorialist:Jingbo Shang, Anudeep

DIFFICULTY:

Simple

PREREQUISITES:

Enumeration

PROBLEM:

Given a 2D array of size N*M. Find a cross which has maximum sum of values. Check question for definition of cross.

EXPLANATION:

It is easy to find that there are two types of cross:

  1. has intersection on some element, which corresponding to the diagonals of squares with odd length.
  2. No intersections, which corresponding to the diagonals of squares with even length.

Because there are only O(N^3) possible crosses, if we can efficiently compute the sum of a given cross, either by preparation or incremental update, this problem could get resolved.

Here, we choose to use the incremental update method to deal with this problem. For both odd and even squares, we can enumerate their centers (some of them are not at the element itself, but still enumerable). Then, we can extend the cross one unit based on previous cross. And thus, the sum of cross could be incrementally updated in O(1) time.

Therefore, after scanned all possible crosses and their sums, you can easily take the maximum.

AUTHOR'S AND TESTER'S SOLUTIONS:

The links will be fixed soon.

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

ACM14AM3-Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author: Utkarsh
Tester:
Editorialist:Jingbo Shang, Anudeep

DIFFICULTY:

Easy

PREREQUISITES:

Dynamic Programming

PROBLEM:

Given a string S which has ‘0’ - ‘9’. Find number of substrings, which when represented in base 10, whose remainder under mod M equals to L.

EXPLANATION:

Let F[i][j] denote the number of substrings ended at i-th character and the value mod M equals to j.

Therefore, we can try to extend F[i][j] to F[i + 1][(j * 10 + S[i + 1]] % 10] by simply add the next character. Or, one can also take the single character i+1-th into account.

So, we can formally have the algorithm as following:

  1. Initially, F[i][S[i] % M] is 1. Because we can only choose the single character.
  2. Then, F[i + 1][(j * 10 + S[i + 1]] % 10] += F[i][j], by extending substrings.
  3. The final answer should be the sum of F[1..|S|][L].

This algorithm’s time complexity is O(|S|L), which is efficient enough for this problem.

AUTHOR'S AND TESTER'S SOLUTIONS:

The links will be fixed soon.

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


ACM14AM2-Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:
Tester:
Editorialist:Jingbo Shang, Anudeep

DIFFICULTY:

Medium

PREREQUISITES:

Segment Tree, Depth First Search Order

PROBLEM:

Given a rooted tree (actually incrementally growing by add some new leaves on the current one), count how many unordered node pairs (P, Q) such that the P and Q are both in the subtree rooted at the given node V, and Distance(P, Q) is even. Distance(X, Y) = Number of roads in the unique path from X to Y, if the given road network were bi-directional.

EXPLANATION:

Offline Idea

Although the tree is growing along time, we can first load all operations and construct the final tree we will have. Therefore, we can solve this problem using an offline algorithm by activating the node one by one and maintaining some data structure.

Depth First Search Order

Because the query is about the subtree, it is natural to think about the depth first search (DFS) order of the tree, which could help us keep the nodes of a subtree in a consecutive interval. For example, the following tree’s DFS order is: 1 2 5 7 8 3 4 6, where all subtrees are consecutive intervals.

alt text

Specific Query Solution

Then, considering the specific query problem, it is equivalent to the problem that asking how many nodes are there in the subtree rooted at V and their distance to V has the same parity. That is, if there are A nodes at an even distance from V, then picking any two of them is valid; if there are B nodes at an odd distance from V, the situation is same. Therefore, answer = A * (A - 1) / 2 + B * (B - 1) / 2.

Well, the problem is transformed to count the number of nodes in the subtree rooted at node V have odd/even depth, because same depth lead to same parity. As we already constructed the tree, the depth information is observed. And the subtrees are consecutive in the dfs order. Take the odd depth as an example. When a node with odd depth is activated (i.e. added by the operation), we add 1 on its position in the dfs order. And the range sum query on the dfs order can help us the find out the number B. Similarly, A can be maintained too.

Data Structure Choices

To achieve the efficiency requirement, two segment trees (for odd and even depth separately) could be adopted to do the add/sum queries, such that the overall time complexity leads to O(NlogN), where N is the total number of operations.

AUTHOR'S AND TESTER'S SOLUTIONS:

The links will be fixed soon.

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

ACM14AM1-Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:
Tester:
Editorialist:Jingbo Shang, Anudeep

DIFFICULTY:

Cakewalk

PREREQUISITES:

For-loop

PROBLEM:

Given an array of integers and a number X. You need to tell how many of those integers are greater than or equal to X.

EXPLANATION:

You may follow the following steps:

  1. Load the integers and store them in an array
  2. Load the number X
  3. Loop over the array, compare each element with X.
  4. Maintain a counter to record the total number.

AUTHOR'S AND TESTER'S SOLUTIONS:

The links will be fixed soon.

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

Distinct Characters Subsequence

$
0
0

what is the meaning of subtask 1 (20 points):1 ≤ N ≤ 10 Subtask 2 (80 points):1 ≤ N ≤ 10^5

where N is coming or being used, as question is only about T

My rating decreased for no reason

$
0
0

Respected Admin,

My rating has decreased suddenly by 3000 points and I don't know the reason why ? I have not recieved any plagiarism mail/account blocked or any mail for that matter for the same.

Can I ask the reason in what context it has been done so ?

Thanks

Traveling Plan Sample Data

$
0
0

Hi

I am writing my first codechef program which is Traveling Plan. My program is working fine on the sample data provided in the problem statement but it gives wrong answer when i submit the code.

Can anyone please provide me the sample data against which I can test my implementation?

Thanks in Advance.

Viewing all 39796 articles
Browse latest View live


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