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

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


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!)

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.

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:

GEEK04 - Editorial

$
0
0

Problem Link

Practice

Contest

Author:Bhuvnesh Jain

Tester:Bhuvnesh Jain

Editorialist:Bhuvnesh Jain

Difficulty

MEDIUM

Prerequisites

Recursion, Bitmasks, Dynamic Programming.

Problem

Find the minimum time taken to cross the river by $N$ people if we can allow almost 2 people to use a boat such that the rowing time is equal to the minimum of the rowing time of both the people. Note that, slowing rowing time is given by larger integers.

Explanation

First of all, any type of greedy algorithm will only pass the first subtask and not any other. As the constraints are small and greedy solution will not work, we will try to come up with a dynamic programming solution.

Let us assume we denote the side where all the persons are initially standing by left and their destination, i.e. where they want to reach by right.

The first observation is that we will always try to send 2 people in the boat. This is because the slower person rowing time will then not contribute to the answer. The next observation is that once few people have crossed the river and reached "right", the boat will be brought to the left side by the person whose rowing time is the minimum among the persons at the right side. Next is that we can represent each person by a "bit-mask". The "left" and "right" bitmask denote that if the ${i}^{th}$ bit is one, then the ${i}^{th}$ person is present there else he is not present. The last observation is that the person can be present either in the "left" side or "right" side, not both ways. Thus, we only care about "left" side masks. The "right" mask can be calculated from the "left" ones, by setting the bits to 1 which are not present in "left".

With all these observations, we try to build a recursive solution as follows: (in the code, "turn" means, whether we send people from right to left or reverse)

//call with recurse((2^n)-1, 0) void recurse(LEFTMASK, turn): if (LEFTMASK == 0): return 0 //we transferred all the people RIGHTMASK = ((2^n)-1) ^ LEFTMASK if (turn == 1): //we want to transfer people to the left min_row = infinity, person = -1 for i in [0 .. n-1]: if (RIGHTMASK & (2^i)): if (min_row > row[i]): min_row = row[i] person = i return row[person] + recurse(LEFTMASK ^ (2^person), turn ^ 1) else: //we want to transfer people to the right if (number of set bits in LEFTMASK == 1): //only 1 person is left) for i in [0 .. n-1]: if (LEFTMASK & (2^i)): return row[i] + recurse(left ^ (2^i), turn ^ 1) else: //try every pair of people by sending them to right) ans = infinity for i in [0 .. n-1]: for j in [i+1 .. n-1]: if ((LEFTMASK & (2^i)) && (LEFTMASK & (2^j)): val = max(row[i], row[j]) val += recurse(LEFTMASK^(2^i)^(2^j), turn ^ 1) ans = min(ans, val) return ans

To optimise the above code for the full score, we can use dynamic programming so that each state is visited only once. This is also known as "top-down DP" or "recursion with memoization".

Time Complexity

$O(2^N * N * N)$

Space Complexity

$O(2^N)$

Solution Links

Setter's solution

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

$
0
0

please suggest efficient solution.

Teams Selected for Amritapuri and Kanpur

$
0
0

How do you plan to travel between Kanpur (24th Dec) and Amritapuri(26th Dec) ?

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!!! :)

D2D - Editorial

$
0
0

Problem Link:

Contest
Practice

Author:Parth Trehan
Editorialist:Parth Trehan

Difficulty:

Easy-Medium

Prerequisites:

Graph Theory, BFS

Problem:

We need to traverse a graph from node 1 to node N. Some nodes of the graph are dependent on other nodes i.e. we can cross/pass some nodes iff we have already visited the nodes provided in the information.

Explanation:

We maintain our graph in an adjacency list. We even maintain an array with the extra information. Now, we traverse this graph from node 1 using the BFS graph traversal technique. As usual we maintain a queue for the BFS traversal. In addition to the given contraint, we maintain another queue. If we are able to pass a node i.e. no extra information is entered about it, we simply mark the node visited. If we come across a node whose entry is present in the extra information, if we have already visited the node associated to it, we simply treat it as a regular node and mark it as visited too but the node associated to it is node visited, we push it in our other queue and remove it's entry from the queue we maintained for BFS traversal. After we have visited all the possible visitable nodes, we check our newly manitained queue. If some nodes are now visitable, we push those nodes back in our BFS queue and start the traversal again. In the process, if we pass through the Nth node, we return back to the calling function. Now, if at end, all the visitable nodes are visited and the nodes present in the new maintained queue cannot be visited according to the constraint, it will leave our BFS traversal queue empty and this could be the condition using which we would break out of the loop.

Solution:

Setter's solution

MACHO - Editorial

$
0
0

Problem Link:

Contest
Practice

Author:Parth Trehan
Editorialist:Parth Trehan

Difficulty:

Simple

Problem:

Count the number of pairs that can be formed holes in a character and the number of pairs of non-hold characters.

Explanation:

Given are two strings, we need to compare the two strings on a given constraint called the "toingness", which is nothing but the sum of pair of total holes and the pair of character that do not contain any hole. The number of holes in a character is given below: A-1 B-2 C-0 D-1 E-0 F-0 G-0 H-0 I-0 J-0 K-0 L-0 M-0 N-0 O-1 P-1 Q-1 R-1 S-0 T-0 U-0 V-0 W-0 X-0 Y-0 Z-0 1-0 2-0 3-0 4-1 5-0 6-1 7-0 8-2 9-1 0-1 a-1 b-1 c-0 d-1 e-1 f-0 g-1 h-0 i-0 j-0 k-0 l-0 m-0 n-0 o-1 p-1 q-1 r-0 s-0 t-0 u-0 v-0 w-0 x-0 y-0 z-0 To calculate the "toingness", just add the total number of holes and the total number of characters without any hole. The toingness then can be calculated by formula:

$toingness = (total holes)/2 + (total characters without any holes)/2$

Both the strings can be compared on the basis of the given attribute.

Time complexity: O(n) where n is the length of the string with maximum length

Solution:

Setter's solution

DAD - Editorial

$
0
0

Problem Link:

Contest
Practice

Author:Parth Trehan
Editorialist:Parth Trehan

Difficulty:

Easy-Medium

Prerequisites:

DP,Maths

Problem:

Given N number of enitities, we need to find the number of ways those entities could either occur independently or in pair.

Explanation:

We are given N entities as an integer input. We need to calculate the number of ways theses entities could either exist independently or in pair. For this purpose, we maintain an array which stores the number of ways that are possible when the enitities are equal to the indeces of the array. Now, for a single entity, it can either exist in a pair or it can exist independently. If there is just one entity, it always occurs independently and if there are two entities, there are two ways for them to exist. Using these two as the base conditions and the recurrence relation $ dp[i] = (dp[i-1] + (i-1)*dp[i-2]) mod 1000000007 $, we can calculate the number of ways and store them in the array. The required array is stored in dp[n].

Solution:

Setter's solution

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

cf 447 div2 Ralph And His Magic Field

$
0
0

i have understood the formula for it but i am unable to understand that when k=-1 and n and m have different parity the answer will be -1 but for k=1 answer will not be -1 why?problem

Zco 2018 pblm 2

$
0
0

I want someone to explain the algorithm clearly for zco question no 2 and explain me how does algorithm give answer to this input. U re allowed to make 1 change 12 cakes,5 children 0 based indexing The ranges are [1,2],[3,4],[0,4],[10,11]. Please also give a note about time complexity. Sry I couldn't completely understand the algorithm given in other thread zco discussion. Link to questionhttps://www.commonlounge.com/discussion/7ca7510fa3ad4ac6b07ea0fe2127db73/main The cake one


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

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!!!

UVa 11283 - Playing Boggle

$
0
0

ProblemMy solution

I can't understand why my solution is giving WA even I tried random cases with a AC solution (on github)

Solving SEACO with normal segment tree

Java Input

$
0
0

how to accept inputs on same line on console in java??? Plz help..

Viewing all 40121 articles
Browse latest View live


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