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

Wealth Disparity

$
0
0

Well this is the question:

Boing Inc, has N employees, numbered 1 ... N. Every employee other than Mr. Hojo (the head of the company) has a manager (P[i] denotes the manager of employee i). Thus an employee may manage any number of other employees but he reports only to one manager, so that the organization forms a tree with Mr. Hojo at the root. We say that employee B is a subordinate of employee A if B appears in the subtree rooted at A.

Mr. Hojo, has hired Nikhil to analyze data about the employees to suggest how to identify faults in Boing Inc. Nikhil, who is just a clueless consultant, has decided to examine wealth disparity in the company. He has with him the net wealth of every employee (denoted A[i] for employee i). Note that this can be negative if the employee is in debt. He has already decided that he will present evidence that wealth falls rapidly as one goes down the organizational tree. He plans to identify a pair of employees i and j, j a subordinate of i, such that the wealth difference between i and j is maximum. Your task is to help him do this.

Suppose, Boing Inc has 4 employees and the parent (P[i]) and wealth information (A[i]) for each employee are as follows:

i 1 2 3 4 A[i] 5 10 6 12 P[i] 2 -1 4 2

P[2] = -1 indicates that employee 2 has no manager, so employee 2 is Mr. Hojo.

In this case, the possible choices to consider are (2,1) with a difference in wealth of of 5, (2,3) with 4, (2,4) with -2 and (4,3) with 6. So the answer is 6.

I tried doing it by checking which p[i] is less than p[j] then finding m = a[i]-a[j] then see if it is greater than ans and if yes then ans = m.

But is not giving me the right ans and TLE for a few test cases. Is there something which i missed about the question or implementing the logic wrong


Getting multiple answers for same input and same code (Squence Land INOI 2013)

$
0
0

I have tried to read input from file and then I get the write output but when I use scanf() or cin to read inputs then i get different outputs on eclipse every time I run it , even I have tried running the code on online IDEs then also I get different output for same code and input. Here is my code:

    #include <iostream>
#include <queue>
#include <algorithm>
#include <vector>
using namespace std;
bool bin_search(vector<int> a,int k){
    int left=0;
    int right=a.size()-1;
    int mid;
    int p;
    while(true){
        mid=(left+right)/2;
        if(left+1==right){
            if(k==a[right]||k==a[left]){
                return true;
            }else {
                return false;
            }
        }
        p=a[mid];
        if(p==k){
            return true;
            break;
        }
        if(p>k){
            right=mid;
        }else{
            left=mid;
        }

    }
        return true;
}
int main() {
    // your code goes here

    int n,m,s,k1,k2,p,ma=0;
    scanf("%d %d ", &n, &m);
    vector<vector<int> > abc;
    vector<int> ab;
    for(int i=0;i<n;i++){
        scanf("%d",&p);

        for(int j=0;j<p;j++){
            scanf("%d",&k1);
            ab.push_back(k1);
        }
        sort(ab.begin(),ab.end());
        abc.push_back(ab);
        ab.clear();

    }
    queue<int> q;
    bool vis[300];
    int temp_k=0;
    int family=0;
    q.push(0);
    while(!q.empty()){
        int s=q.front();
        q.pop();
        for(int i=1;i<n;i++){
            temp_k=0;

                int j=0;
                if(vis[i]==0){

                while(j<=abc[i].size()-1){
                    if(bin_search(abc[s],abc[i][j])==1){
                        temp_k++;
                        if(temp_k>=m){
                            q.push(i);
                            vis[i]=1;
                            family++;
                            break;
                        }
                    }
                    j++;
                }
            }
        }
    }
    cout<<family+1;

    return 0;
}

C++ Switch statement !!

$
0
0

So I recently learned about switch statements so I know that they are used as a replacement for if statements. For example,
if statement-
if (x == 1){do function(a)}
if (x == 2){do function(b)}
...

So, this can be written as-
switch(x){
case 1: do function(a);
case 2: do function(b);
}

But what if the if statement was-
if (x > 0){do function(a)}
else if (x < -10){do function(b)}
else{do function(c)}

How do we write this as a switch statement?

C++ Debugging Tricks !!!

$
0
0

So, I am having problems debugging my code in C++. It takes about like 1/2 hour to debug and then I realize how silly the mistake was. I am new to C++ so please help.

Programming tutorials/guide blog for beginners

List of some spammers here...

$
0
0

[1] anjelikahassan, [2] ansondavid, [3] charlescolin, [4] clinic, [5] mbacourse, [6] teamouting, [7] texiservices

I will be adding more if i find till then admin please delete the account of these users so that in future they can't post more spams

Fastest sorting algorithm .

$
0
0

Which is the fastest sorting algorithm?

Help needed for INOI 2017.

$
0
0

I am in class 8 and I gave ZIO this year and I am getting a score 55-60 so I'll probably qualify. But I want to ask that how to prepare for INOI.

I currently know Python, Javascript, HTML and CSS and just started to learn C++ for INOI.
I have done about 150-160 problems on codechef using python. I know topics like binary search, merge sort, selection sort, insertion sort and a bit of dp.
I am learning c++ completely from youtube.
I am learning data structures and algorithms from places like khan academy, youtube, iarcs, commomlounge etc.
I tried to do some online courses but I can't do a course for more than 1 day. I just don't understand it.
I also don't quite understand from books.

Now, so from where should I learn and prepare.


Paying up ,MARCHA1 ,Wrong Answer...please help me..

$
0
0

import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args) throws Exception{
BufferedReader s= new BufferedReader(new InputStreamReader(System.in));
int n;
n=Integer.parseInt(s.readLine());
for(int t=0;t<n;t++){
String[] m;
m=s.readLine().split(" ");
int value=Integer.valueOf(m[1]);
int[] v=new int[Integer.valueOf(m[0])];
int pa=Integer.valueOf(m[0]);
if(Integer.valueOf(m[0])>20)
{
    break;
}
for(int i=0;i<Integer.valueOf(m[0]);i++){
        int cv =Integer.parseInt(s.readLine());
        if(cv>1000){
            break;
        }else{
            v[i]=cv;
        }
}
Arrays.sort(v);

boolean ca=false;

for(int i=1;i<=Math.pow(2,pa);i++){ int sum=0; for(int j=0;j<pa;j++){ if((i & (1<<j))!=0){ sum=sum+v[j]; } if(sum==value){ ca=true; break; } } if(sum==value){ ca=true; break; } } if(ca==true){System.out.println("Yes");}else{System.out.println("No");} }}}

Why does a large array declared in main give RE but not when declared globally?

$
0
0

I was solving the Highway Bypass question. I made an int array which would be of at most 500 by 500 size, and it was getting an RE on some cases. Solution

However when I declared the DP array and the safe array outside main (globally) it did not RE. What is the reason behind this? Is this a coincidence or is it just a better practice to declare global variables statically (in competitive programming)?

How to use Code::Blocks ?

$
0
0

So I want to ask the following questions on how to use code::blocks -

  1. How do we use code::blocks with linux terminal?
  2. How do we submit a problem on codechef by coding on code::blocks? (Currently I am using the codechef ide)
  3. How do we debug on code::blocks? I have seen people clicking some buttons and the next step executed, so this helps them debug. Is this feature available on code::blocks? If yes then how to use it?

Dynamic programming

SETELE - Editorial

$
0
0

PROBLEM LINK:

Contest
Practice

Author:Istvan Nagy
Tester:Kevin Atienza
Translators:Sergey Kulik (Russian), Team VNOI (Vietnamese) and Hu Zecong (Mandarin)
Editorialist:Kevin Atienza

DIFFICULTY:

Easy-Medium

PREREQUISITES:

Minimum spanning tree, Kruskal's algorithm, union-find

PROBLEM:

You are given a weighted undirected tree. Two nodes are randomly chosen to be connected with an edge of $0$ cost. Find the expected cost of the MST of the resulting graph.

QUICK EXPLANATION:

We want the value $C_{MST} - \frac{S}{T}$ where

  • $C_{MST}$ is the MST cost of the original graph (i.e. just the sum of the costs of all edges).
  • $S$ is the sum of the largest edge weight across all paths.
  • $T$ is the number of paths (i.e. $N(N-1)/2$).

$S$ is the only nontrivial thing to compute. Perform Kruskal's algorithm, but for each connected component, also keep track of its size. Then, $S$ is the sum of $\mathrm{size}(a)\cdot \mathrm{size}(b)\cdot c$ for every step $(a,b,c)$ of the Kruskal algorithm.

EXPLANATION:

Updating the MST

Suppose we want to connect nodes $i$ and $j$ with an edge of $0$ cost. How will the MST be updated?

Here's one equivalent characterization of a (finite) tree: A tree is an acyclic graph with exactly $N-1$ edges. This gives us some clear requirements on how to turn the graph back into a tree again. Specifically, upon adding the edge $(i,j,0)$:

  • We are creating exactly one cycle, namely the cycle $i \rightarrow \ldots \rightarrow j \rightarrow i$, where the $\ldots$ represents the original path from $i$ to $j$. Thus, we need to remove at least one edge from this cycle.
  • The number of edges is now $N$, which means we must remove exactly one edge.

Together, this means that we must remove one edge from that cycle. Which edge? Well, we want the resulting graph to have the smallest possible cost, so naturally we want to remove the edge with the largest cost!

To summarize, by adding the edge $(i,j,0)$, the cost of the MST reduces by exactly the largest edge weight in the path from $i$ to $j$!

Expected value of the new MST

To answer the question, we want to find the expected cost of the new MST. Let $C_{MST}$ be the cost of the original tree. Then from the above, and from the fact that $(i,j)$ is uniformly chosen, we see that this expected value is simply $C_{MST} - \frac{S}{T}$, where

  • $S$ is the sum of the largest edge weight across all paths.
  • $T$ is the number of paths (i.e. $\binom{N}{2} = N(N-1)/2$).

$T$ is pretty easy to compute, (just be careful with overflow!) so all that remains is to compute $S$. Unfortunately, naïve ways of computing this would be too slow, because there are $O(N^2)$ paths! So instead of computing the sum across paths, let's try to compute the sum across all edges, and just figure out how many paths have that edge as the maximum-cost edge. In other words,

$$S = \sum_{\text{$(a,b,c)$ is an edge}} c\cdot F(a,b,c)$$

where $F(a,b,c)$ is the number of paths whose largest-cost edge is $(a,b,c)$.

How do we compute $F(a,b,c)$? Let's consider some path $x \leftrightarrow y$. This path has $(a,b,c)$ as its largest-cost edge if and only if the following two conditions are satisfied:

  • $x$ is connected to $a$ with edges of cost $< c$.
  • $y$ is connected to $b$ with edges of cost $< c$.

(Note that it might be the other way around, i.e. $x$ is connected to $b$ and $y$ is connected to $a$, but then again, paths are symmetric, so $x \leftrightarrow y$ should be considered the same as $y \leftrightarrow x$.)

So we find that $F(a,b,c)$ is simply $R(a,c)\cdot R(b,c)$, where $R(x,c)$ is the number of nodes reachable from $x$ with edges of cost $< c$. But how do we compute $R(x,c)$? Amazingly, Kruskal's algorithm can help us here. Remember that Kruskal's algorithm considers the edges in increasing order and unites the nodes into components in that order. This means that, during the step where we process the edge $(a,b,c)$, $R(a,c)$ and $R(b,c)$ are simply the sizes of the components currently containing $a$ and $b$!

This gives us the following solution: Perform Kruskal's algorithm, but for each connected component, also keep track of its size. Then, $S$ is the sum of $\mathrm{size}(a)\cdot \mathrm{size}(b)\cdot c$ for every step $(a,b,c)$ of the Kruskal algorithm!

In pseudocode:

size[1..N] = [1,1,...,1]
parent[1..N] = [1,2,...,N]

# 'find' operation in 'union-find'
def find(n):
    return parent[n] == n ? n : parent[n] = find(parent[n])


S = T = C = 0
for all edges (a,b,c) sorted according to c:
    # find
    a = find(a)
    b = find(b)

    # update values
    S += size[a]*size[b]*c
    T += size[a]*size[b]
    C += c

    # union
    if size[a] < size[b]:
        parent[a] = b
        size[b] += size[a]
    else:
        parent[b] = a
        size[a] += size[b]

print C - S/T  # use exact division!

Time Complexity:

$O(N \log N)$

AUTHOR'S AND TESTER'S SOLUTIONS:

setter
tester
editorialist

python help.!!!

$
0
0

i want to take integer input in an array ,and the integer input should be space separated.. how can i do it...

Taking input Python

$
0
0

Hello, I am a rookie programmer and only recently started using CodeChef. I was testing out the CodeChef ide and realised that I got an error everytime i tried to take input on the Python ide. The error triggered for both the input() and raw_input() functions.If someone could suggest a fix or an alternative method of taking input, I'd appreciate it.
My code:

x = input()

Error:
Traceback (most recent call last):
File "./prog.py", line 2, in <module>
EOFError: EOF when reading a line


Find two points with the closest Euclidean distance.

$
0
0

Please help me to solve this :
S is a Set of n points on a 2D plane , find two points with the closest Euclidean distance?

Wrong login or password!

$
0
0

When I try to submit for LTIME42 it gives me this message Wrong login or password!

DS and Algo + Competitive Programming - All you need

$
0
0

Syllabus

Motivational

Competitive Programming

Problem Sets

Articles

Code Repository

Coding Calendar

Toolkit

Algorithm and Data Structures PDFS

C++ Books

It just a beginning will keep on adding here, Bookmark this page
Hope it helps!
Thank you!! :D

BALANPOL - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Praveen Dhinwa
Tester:Animesh Fatehpuria
Editorialist:Pawel Kacprzak

DIFFICULTY:

MEDIUM

PREREQUISITES:

Geometry, dp

PROBLEM:

For a given convex polygon with $N$ vertices and $M$ additional points on a plane, where each of them is colored either red or blue, the goal is to find the number of subsets of $N$ vertices of the polygon, such that each of these subsets describes a convex polygon with equal number of red and blue points inside it (or on its boundary).

EXPLANATION:

One crucial fact used basically in all approaches described below is that any subset of vertices of a convex polygon describes also a convex polygon. Here we define a polygon to be described by some points as a polygon described by them in an anticlockwise order.

The problem has also an additional difficulty: notice that two or more colored points in the input can share the same coordinates.

A very useful subroutine in this problem is the ability of checking if a given point is inside a convex polygon. This case is easier than checking this for any polygon, and a very efficient method of doing it is described here: How to test if a point is inside of a convex polygon in 2D integer coordinates?.

Subtask 1

In the first subtask both $N, M \leq 12$, so it is possible to generate all possible subsets of these $N$ points, and then for each of these subsets iterate over all $M$ colored points and count the number of blue and red points inside the polygon formed by the selected subset. If these two amounts are equal, just add $1$ to the result.

Subtask 2

In the second subtask, $N$ and $M$ can be both up to $50$, but we know that all colored points have different coordinates and that all them lie on the vertices of the input polygon. In this case the problem is not hard at all. Let’s say that we want to count the number of valid choices of exactly $k$ vertices of the polygon corresponding to chosen $k$ blue points and exactly $k$ other vertices of the polygon corresponding to the chosen $k$ red points. The first thing to notice is that every such choice describes a valid convex polygon with exactly $k$ blue and $k$ red points in it (well, exactly on it’s boundary), and no two different ways of choosing such points produces the same polygon, and also there are $2^W$ ways to choose vertices not sharing coordinates with any colored points, where $W$ is the number of such vertices. Thus the total number of valid polygons containing exactly $k$ blue and exactly $k$ red points is given by $\binom{B}{k} \cdot \binom{R}{k} \cdot 2^W$, where $B$ is the total number of blue points and $R$ is the total number of red points. In order to get the final answer, it is sufficient to return the sum of such sub-results computed for all possible $k$ from $2$ to $\min(B, R)$.

Subtask 3

In the third subtask we have a similar situation as in the second one. $N$ and $M$ also can be up to $50$ and all colored points lie on the vertices of the input polygon. However, colored points can now share the same coordinates, so the method given as the solution to the second subtask cannot be applied to this one. The main difference is that if we take a vertex of the polygon into the subset, then the resulting polygon will contain all the colored points lying on this vertex, and they can have also different colors as well. However, if we first preprocess colored points and create a mapping $cnt[(x, y)][b]$ denoting the number of blue points with coordinates $(x, y)$ and similarly $cnt[(x, y)][r]$ denoting the number of red points with coordinates $(x, y)$, we can use dynamic programming to solve this subtask.

More specifically, let $dp[k][i][j][taken]$ be the number of subsets of $k$ first vertices of the input polygon where there are exactly $i$ blue and $j$ red points on the chosen vertices and where taken is the integer from $0$ to $3$ and denotes that there are that many taken vertices in the subset, where $taken = 3$ is an exception and denotes at least $3$ taken vertices. This last parameter is required, because we want to include in the result only non-degenerated polygons, so the ones with at least $3$ vertices. Then the final answer to the problem is the sum over $dp[N][i][i][3]$ for $i = 0$ to $\min(B, R)$, where $B$ is the number of blue points and $R$ is the number of red points. Entries of the $dp$ table can be computed in a very straightforward way. Let’s say that we have computed all the entries for $x < k$ and we want to compute $dp[k][i][j][y]$ now. Then depending on how many blue and red points the $k$-th vertex of the polygon shares coordinates, it always yields two possiblities depending on the fact if we either take this $k$-th vertex to the subset or not. For example, let’s assume that it shares coordinates with $b$ blue points and $r$ red points. Then taking this vertex into the subset adds $dp[x-1][i-b][j-r][z]$ ways to $dp[x][i][j][y]$, while not choosing it adds $dp[x-1][i][j][y]$ to $dp[x][i][j][y]$ for some valid $y, z$. The total time complexity of this approach is therefore $O(N \cdot M^2)$ since this is the number of entries in the $dp$ table and each entry is filled in a constant time.

Subtask 4

Description for this subtask will be added later.

AUTHOR'S AND TESTER'S SOLUTIONS:


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

CHEFSTUD - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Praveen Dhinwa
Tester:Animesh Fatehpuria
Editorialist:Pawel Kacprzak

DIFFICULTY:

CAKEWALK

PREREQUISITES:

None

PROBLEM:

For a given string $S[1..N]$ consisting of characters ‘>’, ‘<‘ and ‘*’, the goal is to find the number of its adjacent characters $S[i]$ and $S[i+1]$, such that after replacing each ‘<‘ in with ‘>’ and each ‘>’ with ‘<‘ in the original string, we have $S[i] =$ ‘>‘ and $S[i+1] =$ ‘<‘.

QUICK EXPLANATION:

If one pays enough attention to the statement, he can notice that each ‘>’ has corresponding ‘<‘ to its right and each ‘<‘ has corresponding ‘>’ to its left. This observation can lead to one simple solution. On the other hand, a solution not taking any advantage of this fact is also simple and possible. Both these approaches are described below.

EXPLANATION:

Approach 1:

Since each ‘>’ has corresponding ‘<‘ to its right and each ‘<‘ has corresponding ‘>’ to its left in the original string, then after all swaps of characters are made, each consecutive blocks of $K$ characters, where no character is ‘*’ will produce $(K-2) / 2$ adjacent pairs of characters we are looking for. As an example, let’s consider such a block of characters “><><><”. Then after swaps are made it looks like this: “<><><>” and each character with the exception of the first and the last one participates in exactly one pair of consecutive characters we are looking for.

Based on the above approach we can solve the problem as follows.

Since in the first subtask there is no ‘*’ in the input string, then the answer is $(N-2) / 2$, where $N$ is the length of the input string.

In the general case, one can at the beginning split the input string into substring containing only ‘<‘ and ‘>’ characters and then compute the final answer as the sum of results for all these substrings computed in the same way as described above as the solution for the first subtask.

Approach 2:

Since each ‘>’ is swapped with ‘<‘ and vice versa, then we can just find the number of adjacent characters $S[i]$ and $S[i+1]$ in the original string for which we have $S[i] =$ ‘<‘ and $S[i] =$ ‘>’. This is true because after all swaps are made then each such pair corresponds to a pair that we are interested in. Moreover, on the other hand, each pair of adjacent characters we are interested in the string after all swaps are performed is formed from a pair of adjacent characters ‘<‘ and ‘>’ in the original string. This observation allows us to not perform any swap operations at all.

The second observation is that no two pairs of characters we are interested in can overlap, which is quite straightforward.

Both these two observation can lead to approach based on just counting the number of adjacent pairs of characters ‘<‘ and ‘>’ in the original string. The following pseudocode illustrates this approach:

result = 0 for i = 1 to |s| - 1 if s[i] == ‘<‘ and s[i+1] == ‘>’: result += 1 print result

Both these approaches runs in linear time in terms of the length of the input string.

AUTHOR'S AND TESTER'S SOLUTIONS:


Setter's solution can be found here.
Tester's solution can be found here.
Editorialist's solution can be found here.

Viewing all 39796 articles
Browse latest View live