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

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

$
0
0

Hello guys,

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


OPTSSET - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Trung Nguyen
Tester:Oleksandr Kulkov
Editorialist:Oleksandr Kulkov

DIFFICULTY:

MEDIUM

PREREQUISITES:

DP optimizations

PROBLEM:

You're given convex polygon $p_1, \dots, p_n$ and each point has weight $w_i$. Choose subsequence of its vertices such that $\dfrac{|p_{i_1}-p_{i_2}|+\dots+|p_{i_k}-p_{i_1}|}{w_{i_1}+\dots+w_{i_k}}$ is maximized and $i_1=1$.

QUICK EXPLANATION:

Use binary search to reduce the problem from $\max \dfrac a b$ to $a-b\cdot c >^? 0$. After that use some DP optimization to check this.

EXPLANATION:

Basic ideas: There is common trick to solve problems in which one is asked to optimize fraction. If we will make binary search of answer then we will just have to check whether there exist any $\{i_1,\dots,i_k\}$ such that $(|p_{i_1}-p_{i_2}|+\dots+|p_{i_k}-p_{i_1}|)-(w_{i_1}'+\dots+w_{i_k}')>0$. Here $w_i'=m \cdot w_i$ where $m$ is the answer we want to check. Indeed instead if trying to find sequence for which $\dfrac a b > c$ we will try to find sequence for which $a - bc > 0$.

Let's consider $O(n^2)$ solution first. Let $d_i=\max[(|p_{i_1}-p_{i_2}|+\dots+|p_{i_{k-1}}-p_{i_k}|)-(w_{i_1}+\dots+w_{i_{k}})]$. Then we can see that

$$d_i=\max\limits_{j < i} (d_j + |p_i-p_j| - w_i)$$

and sequence exists iff $d_i+|p_i-p_1|>0$ for some $i$. Thus we can solve problem in $O(n^2 \log n)$ for first two subtasks and $40$ points.

DP optimzation: The generic solution to such kind of problems can be found in the following article. In this editorial however the different kind of solution will be described.

Let $score_{j}(x)=d_j+|x-p_j|$. Consider some $j_1, j_2:score_{j_1}(p_i)\geq score_{j_2}(p_i)$. Let $D(j_1,j_2)$ be the first $i'>i$ such that $score_{j_1}(p_{i'}) < score_{j_2}(p_{i'})$. We can see that set of points for which $$score_{j_1}(x)= score_{j_2}(x) \Leftrightarrow |x-p_{j_1}|-|x-p_{j_2}|=d_{j_2}-d_{i_1}$$

Is hyperbolic line. Thus it splits our polygon in two parts, one containing $p_{j_1}$ and the second containing $p_{j_2}$. We can make some useful observations here.

  1. $D(j_1, j_2)$ can be found by binary search in $O(\log n)$.
  2. If $p_a$ at some point became worse than $p_b$ after being better then it will be worse till the very end. Thus position of optimal $p_j$ only increases when we increase $i$.
  3. If $D(a, b) > D(b, c)$ then $b$ can never be optimal $j$ since it is covered by $b$ before it can cover $a$.

Given this we can maintain monotonic queue $q$ of candidats to be the best $j$. Such that $$score_{q_1}(p_i)>score_{q_2}(p_i)>\dots>score_{q_k}(p_i)$$

and

$$D(q_1,q_2)< D(q_2,q_3)< \dots< D(q_{k-1},q_k)$$

If we keep this then optimal candidate is always kept in the queue and order of scores can change only between first two elements of queue. If it happened, we simply pop first element from queue. Also before adding new element to queue we pop elements from the back of queue until second kind of inequality holds. Thus all operations with queue will take $O(n \log n)$ time overall which gives us $O(n\log^2 n)$ solution to the initial problem.

AUTHOR'S AND TESTER'S SOLUTIONS:

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

RELATED PROBLEMS:

Getting TLE

$
0
0

Problem:- DIGJUMP

Please help me in optimizing this code which uses BFS to find the shortest distance between start and end vertices.

My code:- Solution

Help in IPCTRAIN

$
0
0

i am unable to understand author's solution

link to the problem:-https://www.codechef.com/problems/IPCTRAIN

here is the author's solution:-https://s3.amazonaws.com/codechef_shared/download/Solutions/JULY17/Setter/IPCTRAIN.cpp

the part i am unable to undrstand is

   for (auto it: persons)
 {
 int lec = lectures[it.second];

        for (int i = 0; i < lec; i++) {
            auto iter = daySet.lower_bound(startDay[it.second]);
            if (iter == daySet.end()) {
                break;
            } else {
                lecturesTaken[it.second]++;
              daySet.erase(iter);
            }
        }
    }

what is this part doing

write a program to generate unique substrings(contains only unique characters) of given string.

$
0
0

please suggest efficient solution.

WSITES01 - Editorial

$
0
0

Problem Link

Practice

Contest

Author:Azat

Tester:Pawel Kacprzak and Misha Chorniy

Editorialist:Bhuvnesh Jain

Difficulty

EASY-MEDIUM

Prerequisites

Tries, State Transitions

Problem

You are given a list of websites, some of which are blocked. You need to find a set of prefixes such that each of the blocked websites are recognised by some prefix but none of the non-blocked websites are. The aim is to minimise the sum of the length of the prefixes found.

Quick Explanation

Build a tries of the words, storing information regarding the words, their type (blocked or non-blocked). Use transitions during the traversal of trie (dfs) to find the optimal answer, if it exists.

Explanation

First of all, the problem deals with prefixes. Generally, problems on strings related to prefixes can be solved using hashing or trie. We will use trie to solve this problem.

Before starting to solve the problem, like what kind of data structure we would require and what information it should store, let us first analyse when the solution exists or not. The solution will not exist only when the blocked site is a prefix of a non-blocked website.. In all other cases the solution will exist because in the worst case, we might select the whole word for all the blocked websites.

Now, suppose the solution exist. We would like to minimise the total length of the selected prefixes. Now, since the length of one prefix is independent of the other, the total length would be minimum when we minimise each prefix selected. For minimising each prefix selected, we just want to selected the first character which differentiates between 2 blocked and non-blocked websites. Such a letter will exist as otherwise the solution would not have existed.

Let us understand this through examples. Let the blocked website be "codeforces" and allowed website be "codechef". Now, the $5^{th}$ letter ("f" vs "c") is the one which differentiates the 2 websites. Let the blocked website be "bing" and allowed website be "google". In this case, the $1^{st}$ letter will only differentiate the 2 websites. Let the blocked be "cs" and allowed website be "csacademy". In this case the solution will definitely not exist. As all the prefixes, "c" and "cs" would block both the websites.

From the examples, above our data structure should be able to handle 2 type of operations. They are :

  1. Detecting whether the blocked website is a prefix of any non-blocked website.
  2. Finding efficiently the first point of difference between 2 websites names.

Doing this through brute force will take complexity $O(\sum_{i=1}^{i=n} \sum_{j=i+1}^{j=n} min(L_i, L_j)$, where $L_i = $ length of string $i$. This is because the comparison between 2 strings to do the above operations can be done using a simple for loop, which terminates in worst case when either of the string to be processed finishes. In the worst case, it will be quadratic in the sum of length of strings given. Thus, it will only be able to solve subtask 1. For the complete solution, we use tries and store the following information in it to be able to handle above operations efficiently.

  1. State 0 = no websites.
  2. State 1 = non-blocked websites only.
  3. State 2 = blocked websites only.
  4. State 3 = both blocked and non-blocked websites.

After building of the trie, we just do a traversal (dfs) on it. Now, few things should be noted. Whenever we are in state $3$, we can go to state $\{0, 1, 2, 3\}$ in the child node. When we are in state $1$, we can only go to state $\{0, 1\}$ and when we are in state $2$, we can only go to $\{0, 2\}$ in the child node. This information will be enough to be able to handle above operations. Below are the claims for it :

  1. Whenever, we make have a node at state $3$ and all of its children have state $\\{0, 1\\}$ only, we see that a blocked website is a prefix of a non-blocked website. Thus we should terminate our search here and claim that it is "impossible" to constrict an answer.
  2. Otherwise in all cases, the solution exist. To find the minimal length, whenever we see that a state $3$, has a child with states $\\{0, 1, 2\\}$, we are sure to have found a point of difference between the blocked websites and non-blocked websites. This is when we should stop are search together on this current branch and add the required prefix to our solution.
  3. Otherwise, the whole search space would only consist of wither blocked or non-blocked websites. This is easy as non-blocked website are not required to be searched. Also, for blocked websites, the $1^{st}$ character would only differentiate between the blocked and non-blocked website and thus we can terminate the search here too.

All the above operations can be done in $O(\sum_{i=1}^{i=n} {L}_{i})$, where $L_i = $ length of string $i$. This is because the trie can be build in above complexity and can be traversed in above complexity too.

If you had some other logic/algorithm to solve the above problem, feel free to discuss below

Time Complexity

$O(\sum_{i=1}^{i=n} {L}_{i})$, where $L_i = $ length of string $i$

Solution Links

Setter's solution

Tester's solution

Editorialist solution

StopStalk: Tool to maintain your algorithmic progress

$
0
0

Hello Coders,

Hope you are having a great time coding hard. Here I present to you a Utility tool - StopStalk which will encourage you to keep your algorithmic progress going by coding with your friends and improve.

It retrieves your friends’ recent submissions from various competitive websites (CodeChef, Codeforces, Spoj, HackerEarth, HackerRank and UVa Online Judge for now) and shows you in one place. It includes lots of other features like - User streak notification, Global Leaderboard, Filter submissions, search problems by tags, Trending problems across these sites, Unified Todo list, View/Download submissions directly, cool analytics graphs and a lot more…

You can add friends who are already on StopStalk or you can also add a Custom User and start coding collectively by keeping a close watch on your algorithmic progress as compared to that of your friends.

If you want to increase your Custom User limit, you can share your StopStalk handle and you can get 1 extra user for every 3 users who register with your handle as Referrer's StopStalk handle.

Register here - StopStalk

The goal is to involve more and more people to Algorithmic Programming and maintain their streak. Also the project is completely Open Source - Github

Feel free to contribute. :)

We would be happy to hear from you - bugs, enhancements, feature-requests, appreciation, etc. In the end - Stop stalking and start StopStalking! Happy coding!

EDIT: 5100+ users already registered globally :) (Thanks a lot guys for your love!)

Does threading really work's in speeding up our solution. (Trying for a hack :) )

$
0
0

I don't know much about threading. I just want to ask does using threading technique make our solution faster.


Beginner/NITIKA - python 3.5 - need some help

$
0
0

Hello guys! Could you please tell me what's wrong with my code? It looks to work well, but CodeChef says my answer is wrong.Thanks!

My solution / Problem link

November Cook-Off rating calculation

need optimization help..

$
0
0

//Developer : ruhul1995 || Time : 00:58 AM ||Date : 23/11/2017 //how to optimize this code..... i want the program to execute value of 10 power 6 and give the value for fibanacci and factorial...please help

include<iostream>

define MOD 1000000007

using namespace std; const int MAX = 2 * 1000000;

long long int f[MAX] = {0};

long long int fib(long long int n) { / Declare an array to store Fibonacci numbers. /

long long int f[n+1]; long long int i;

/ 0th and 1st number of the series are 0 and 1/ f[0] = 1; f[1] = 1;

for (i = 2; i <= n; i++) {

  f[i] = f[i-1] + f[i-2];

}

return f[n]; }

long long int fact( long long int n) {

if(n == 0 || n == 1)
    return 1 ;

else
    return n*fact(n-1);

}

int main() {

int testcase;

cin>>testcase;
while(testcase--)
{
    long long int n , m , k1 , i , p = 0 , final_answer = 0  ;
    cin>>n>>m>>k1;
    for( i = n ; i <= m ; i++)
    {
        p += fib(i) * fact(i) ;
    }

  //  cout<<"p="<<p<<endl;

    final_answer = p/k1 ; // x * k <= p

    cout<<(final_answer % MOD)<<endl;
}
return 0;

}

Getting TLE - Please Help!!!

$
0
0

Problem:- DIGJUMP

Please help me in optimizing this code which uses BFS to find the shortest distance between start and end vertices.

My code:- Solution

Please help me in RECEPIES

$
0
0

Can anyone take a look on my code? It gives me correct output, no idea why codechef says W/A. I was tring my best to make this code readable. Thanks!

Cutting Recipes Problem Code: RECIPE

It's Python 3.5.

Links:Problem /code

Chef and his software - TSECJ05 - Editorial

$
0
0

PROBLEM LINK:

Chef and his software

Author:Yogesh Malpani
Editorialist:Yogesh Malpani

DIFFICULTY:

MEDIUM.

PREREQUISITES:

ArrayList, Binary Search, Heap

PROBLEM:

Given the values of N transactions, the task is to insert these to records and print the value of Kth highest transaction in the records at each insertion.

QUICK EXPLANATION:

Find the index for the each new transaction using efficient Sorting algorithms which work well on an almost sorted list. Next find the Kth highest transaction and print it.

EXPLANATION:

How to process a new transaction of record, Ni?
For every Ni, check if it is smaller than current Kth largest element.
If yes, then ignore it. If no, then a modification of Binary Search can be used to find the index for the Ni. This can be done in O(LogN) time.
The transaction value is added at an index in the ArrayList which runs in amortized constant time, O(N) time.
So the Time complexity of processing a new transaction is O(N + LogN).
The Kth highest transaction is found in the ArrayList in constant time, O(1).

ALTERNATIVE SOLUTION:

Another Solution is to use Min Heap of size N to store N largest transactions of records. The Kth highest transaction is always at root and can be found in O(1) time.
How to process a new transaction of record?
Compare the new transaction value, Ni, with root of heap. If Ni is smaller, then ignore it. Otherwise replace root with Ni and call heapify for the root of modified heap. Time complexity of finding the Kth highest transaction is O(LogN).

AUTHOR'S SOLUTION:

Solution can be found here.

THENDO - Editorial

$
0
0

Problem Link
Contest
Practice

Author:Sahil Rajput

Tester:Sahil Rajput

Editorialist:Sahil Rajput

Difficulty
Easy

Prerequisites
Maths

Problem
The points can be vertices of regular N-polygon, if, and only if, for each pair, difference of their polar angles (as viewed from center of polygon) is a multiple of 2pi/N. All points should lie on the circle with same center as the polygon. We can locate the center of polygon/circle [but we may avoid this, as a chord (like, say, (x1,y1)-(x2,y2)) is seen at twice greater angle from center, than it is seen from other point of a cricle (x3,y3)]. There are many ways to locate center of circle, the way I used is to build midpoint perpendiculares to segments (x1,y1)-(x2,y2) and (x2,y2)-(x3,y3) in form y = ax + b and find their intersection. Formula y = ax + b has drawback that it cannot be used if line is parallel to y, possible workaround is to rotate all points by random angle (using formulae x' = xcos(a) - ysin(a), y' = ycos(a) + x*sin(a) ) until no segments are horizontal (and hence no perperdiculares are vertical).
After the coordinates of the center are known, we use fancy function atan2, which returns angle in right quadrant: a[i] = atan2(y[i]-ycenter, x[i]-xcenter)
Area of  regular polygon increases with increasing N, so it is possible just to iterate through all possible values on N in ascending order, and exit from cycle as first satisfying N is found.
Using sin(x) is makes it easy: sin(x) = 0 when x is mutiple of pi. So, for points to belong to regular, N-polygon, sin( N * (a[i]-a[j]) /2 )=0 because of finite precision arithmetic, fabs( sin( N * (a[i]-a[j]) /2 ) ) < eps

Solution Link
Setter's solution


BUGCAL - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Trung Nguyen
Tester:Oleksandr Kulkov
Editorialist:Oleksandr Kulkov

DIFFICULTY:

CAKEWALK

PREREQUISITES:

None

PROBLEM:

You're given two numbers. Sum them up without carrying.

QUICK EXPLANATION:

Just do what is written in statement.

EXPLANATION:

One of possible codes to solve the problem:

    int a, b;
    cin >> a >> b;
    vector<int> A, B;
    while(a) {
        A.push_back(a % 10);
        a /= 10;
    }
    while(b) {
        B.push_back(b % 10);
        b /= 10;
    }
    while(A.size() < B.size()) A.push_back(0);
    while(B.size() < A.size()) B.push_back(0);
    for(int i = 0; i < A.size(); i++) {
        A[i] += B[i];
    }
    int ans = 0;
    reverse(begin(A), end(A));
    for(auto it: A) {
        ans = ans * 10 + it % 10;
    }
    cout << ans << endl;

AUTHOR'S AND TESTER'S SOLUTIONS:

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

RELATED PROBLEMS:

If anyone came to know about the ACM ICPC Onsite Regional Contest Schedule,then please share!!!

$
0
0

If anyone came to know about the ACM ICPC Onsite Regional Contest Schedule, then please share!!!

Skiing unofficial editorial november cook off

$
0
0

problem:Skiing

Recursive easy problem

Solution:
we have to find minimum no of boxes(let it be set S), such that i can visit any other box in grid by choosing any starting box from that set S.

For getting out maximum no of visit from a box we will choose the box with maximum height, and we will mark all the adjacent boxes which can be visited from that box.
we will keep doing the same until all the boxes are visited and count the no of times we have to do this work.

i will be choosing maximum value which is unvisited all the time.

for getting maximum heights i have maintained a priority queue, solution is easy u can understand it easily.. this is something like flood filling..

mysolution: solution

share ur views in the comment box. :)

Awesome resource for DS and Algorithms

$
0
0

Hi everyone,

i just want to share this link which consists of all the links and resources on different topics of Competitive ProgrammingData Structures and Algorithms

http://vicky002.github.io/AlgoWiki/

Google Chrome Extension for Ongoing and Upcoming Programming challenges which is very nice and also useful

and one more great and useful thing in this Algowiki is that there is a toolkit called Spoj-Toolkit which is a tool for SPOJ users to match the different outputs of their SPOJ problem solution with the correct output provided by the Toolkit.

Also book named Competitive Programming by Steven-Halim is completely about Competitive Programming U can find it's e-book in the below link.

https://www.instamojo.com/anudeepgupta/competitive-programming-by-steven-halim/?ref=store

Also, below is one more link from codechef forum which has almost all topics for Ds and algorithms.

http://discuss.codechef.com/questions/48877/data-structures-and-algorithms

Graph Algorithms in Competitive Programming

Learn Competitive Programming

Must Known algorithms for online programming contests

How to improve and how to train: Kuruma's personal experience and humble request

List of all algorithms needed for ACM-ICPC

Use of STL libraries in C++

DYNAMIC PROGRAMMING USEFUL LINKS:

Good resources or tutorials for dynamic programming besides the TopCoder tutorial

Mastering DP

Dynamic Programming

Examples of basic DP problems

All the best!!! :)

doubt in calculating expectations

$
0
0

i had recently learned expectation in math and trying to solve : https://www.codechef.com/problems/RRPLAYER

i read the editorial and able to understand it but i want to know where my approach is lacking? my approach : E(x) = ((1 + E(x-1))(1/n) + (2 + E(x-1))(1/n^2) + ...........)*n i thought that if we can take any song from list in one attempt(prob : 1/n) and then have to choose (n-1) different songs + (if i choose that song in two attempt (1/n^2) and then choose n-1 left songs E(x-1)) + ........ and finally i can choose any of the songs from the list as my current song(song that i have choosing 1 time+ 2 times+....) so, multiply my answer by n!

can anyone please explain where i am going wrong! and if possible please give some questions to practice :)

Viewing all 40121 articles
Browse latest View live


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