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

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

Unofficial Editorials November Long Challenge (Part 2)

$
0
0

Hello Guys

I have divided problems into posts according to difficulty. Hope u all don't mind this. ;)

This is the part 2 of two posts of unofficial editorials for November Long Challenge.

For editorials of problems VILTRIBE, CLRL, PERPALIN and CHEFHPAL, click here.

This post has editorials for problems SEGPROD and CSUBQ.

Problem SEGPROD

Problem Difficulty : Medium

Prerequisites:Modular Multiplicative Inverse (euclid's method), Simple maths, and patience.

Problem Explanation

Given an array and a number P (not necessarily prime), Answer range product queries modulo P. (Not as simple as it looks).

Solution

The first thing i want you all understood is the euclid method of finding modular multiplicative inverse, vital to my approach, about which you may read from wikipedia and find the algorithm here.

The naive brute force (not at all successful even for 20 points, due to integer overflow) would be to create a prefix product array (similar to prefix sum array) and for every query L to R, output prefixProd(R) / prefixProd(L-1) and output modulo P. That's correct, but incapable of giving us 100 points.

So, we move to modular multiplicative inverse (MMI) for help!!. We will to the same thing. Instead of prefix product, we will make an array storing prefix modular product (mod P ofcourse). Now, to answer queries, we are going to answer queries just as prefixModProduct(R)/prefixModProduct(L-1).

This is same as (prefoxModProduct(R) * ModInverse(L-1))%P.

If you have followed the logic upto here and understood MMI from geeksforgeeks page, you have earned 20 points. Hurray.

The reason of only 20 points is that Modular multiplicative inverse of a number A exists only when A and P are co-prime (gcd(A,P)==1). For first subtask, it was given that P is prime and all numbers are smaller than P. From that, it's obvious that gcd(A, P) is one for every element, so we get 20 points.

Now, for full solution, we will use the same technique, but with a slight change in plan. Now, we will first find prime factors of P (U'll understand why) and handle numbers in a different way, which will be explained by an example.

Suppose P = 6 and given array is 1 2 3 4 5 6 7 8 9 10

Now, Prime factors of 6 are 2 and 3.

Now, we will handle powers of 2,3 separately and rest numbers separately.

Create an array factors which will have value {2,3} for this example. create a 2d array factorPowSum[NumberOfFactors][N]

factorPowSum array will look like below (explained how to make this below that)

factor 0 1 2 3 4 5 6 7 8 9 10 11

2..... 0 0 1 1 3 3 4 4 7 7 8 8 (dots to adjust position, spaces are truncated automatically)

3..... 0 0 0 1 1 1 2 2 2 4 4 4

And we will think(it's necessary) we are given given array 1 1 1 1 5 1 7 1 1 5 11 (all numbers are divided by 2 and 3). Now, you will see that all numbers are co-prime to 6. Now we can use the algorithm to solve the queries for reduced array.

Let's assign factor 2 to index 0 and factor 3 to index 1.

Creation of factPowSum array

Just assign factPowSum{factorIndex}{0} = 0 and for 0<i<=N

factPowSum{factorIndex}{i} = factPowSum{factorIndex}{i-1} + Power of factor divided from ith number(1-based indexing).

For example, from 8, 3rd pow of 2 was divided, factorPowSum{0}{3} = factorPowSum{0}{4} + 3.

Hope i made the array clear.

Now, consider that we are given only powers of factors of P.

Continuing same example, The same array we were working with now becomes (I know this is lengthy as hell, but I tried making it as easy to understand as possible)

1 2 3 4 1 6 1 8 9 2 1 (Only powers of 2 and 3 are considered from given array).

Now, if someone ask us range query on this array, we can answer each query within O(number of factors of P) time.

This is simple, just refer to factPowSum array and give it a try. Read further only after a try.

let ans = 1.

for every factor of P, ans = ans*pow(factor, factPowSum{R+1}-factPowSum{L}).

Now, combining above two sub-problems, we get answer of query as

let ans = (prefixModProd(R+1)*MMI(L) * product(pow(factor, factPowSum[R+1]-factPowSum[L])) )%P.

// The queries in question are 0-indexed

You are about to lose 100 points if you do this. Shocked!!. Be sure to take modulo after every multiplication so as to lose your AC to Integer overflow, use long long int/long only.

Now you all deserve 100 points in this problem, but you will get TLE because test cases were too tight. Calculating powers with fast modulo exp even takes O(logN) time, which is too much for 10^7 queries. So we calculate powers of factors of P before answering queries and store in an array. I am not going to explain this but it's easily understandable from my code. In case you need help, feel free to ask.

Added Proof:

lemma: P can have at most 10 different prime factors.

Proof: Try multiplying first eleven prime numbers. The product will be greater than 10^9. but as P <= 10^9, it follows that maximum number of distinct prime factors P can have is 10.

Here's a link to my Code. (Took nearly 30 submissions for 100 points :D)

Problem CSUBQ

Problem difficulty:Medium

Prerequisites:Segment Tree, Too much patience unless u r a segment tree expert (msg me if u are, want a talk.)

Problem Explanation

An array of Size N and M queries, Tow Integers L and R (L<=R), handle following queries. 1. update ith value to X. 2. Find number of subarrays betweeen L and R, whose maximum values lie between L and R. (both inclusive)

Solution

One basic formula. (very basic)

let function c denote c*(c+1)/2 (The number of all the possible contigious subarrays from an array of length c.)

1+2+3+4+5 ... (N-1) + N = N(N+1)/2

Now, take L = 1, R = 10 and given array 2 0 11 3 0 (example given in problem)

(I'm directly taking an array instead of a series of updates to explain it).

Required subarrays between 1 to 5 are {1, 1}, {1,2},{4,4} and {4,5}

An interesting thing to observe is that ans = c(2)-c(1)+c(2)-c(1) (I'll explain how i came up with this.)

Two Facts: 1. Any element > R is never included in any subarray (like element 3). 2. Any number of elements smaller than L can be included in subarray as long as there is atleast one single element between L and R inclusive.

So, we are going to get 25 points first using this fact.

See this solution for details. in this solution, inc means consecutive elements till now which are smaller or equal to R, and exc means all consecutive elements < L till current position. Whenever we reach an element >= L, subtract excluded subarray count ( c(exc) ) from count and set exc = 0 and inc++ and whenever u get an element > R, add c(inc), subtract c(exc) and set both to 0. otherwise inc++, exc++.

Ans is count + c(inc)-c(exc). Got 25 points. This solution runs in O(QN) time.

I hope this logic is clear. Because if it isn't, be sure to read again once, twice, 10 times, 10^2 times, 2^ 10 times (I like this quote :P).

Now, Getting 52 points isn't difficult if You have heard about square root decomposition. I have submitted a solution using this technique too. :P. (I submitted too many solutions for this) I used in this solution apart from the counting technique we discussed above and one thing mentioned below

Cheers, now we got 52 points with this ease, but no longer. Problem setters aren't going to gift 52 points with this ease.

Now, think here, what information about a segment L to I and a segment from I+1 to R we need to find out all required information.

Refer to my solution (One more solution :P) alongwith to understand what's going on.

Let me help u. You need 8 variables (too much u feel i guess), as follows: 1. count => The count of subarrays already included in range, except those at borders. 2. incL => Number of elements from left to leftmost element which is > R. (0 if there's no element > R in range) 3. incR => Number of elements from right to rightmost element which is > R. (0 if there's no element > R in range) 4. excL => Number of elements from left to leftmost element which is >= L. (0 if there's no element >= L in range) 5. excR => Number of elements from right to rightmost element which is >= L. (0 if there's no element >= L in range) 6. size => size of range 7. found1 => boolean, which tells whether range contains atleast one element > R. 8. found2 => boolean, which tells whether range contains atleast one element >= L.

Any ideas how we are going to merge ranges?, it's simple enough.

Consider array 2 0 1 11 3 0 5

Answer of this Problems is c(3)-c(1)+c(3)-c(1) = 6-1+6-1 = 10

Think of this problem in two parts. for elements > R and for elements >= L.

For first part, consider any element > R as dividing element. for above example, 11 is dividing the total ranges into two sub-ranges of length 3 each.

For second part, consider any element >= L as dividing element. For above example, 2,1,11,3 and 5 are dividing elements, resulting in 2 ranges of length 1. ( {1,1} and {5,5} ).

If you understood this part, You can divide the given problem into two parts, the one dealing with elements to be included, and the one dealing with elements to be excluded.

Here comes the Main part of solution,The Segment tree. Now, as you may see, i have used an iterative segment tree,(I messed up recursive one and also, iterative is slightly faster if u take the trouble to understand it) about which you may read here. I first of all, created a class S (struct equivalent in java) which hold all this info about each segment of tree.

Now, the most important thing is to create a merge function, which will merge two segments into a larger one correctly.

You may see from my code, i have dealt with inclusion and exclusion separately, making my code simpler.

For first part, i check if both sides have element > R (our dividing element) (using boolean found1). if both has, include Left of large range will be outL of left segment and include right will be includeRight of right segment. count will be increase by c(left.incR + right.incL) because they are no longer boundary elements of segment.

In case only one segment has dividing element, incL and incR of output range is assigned accordingly.

Same way for large. And Here we go. We have solved the problem. Bet you didn't realize that.

All that is left to implement it. And Now, nothing is going to stop you from 100 points except a TLE in one file. (Not Sure, because i had use the following tip to save time.)

Link to My code.

PS: This was my first editorial using segment trees. So, i am sorry if any error might have crept in (without my knowledge, of course) Do give your review for this editorial.

As always, i wholeheartedly invite your suggestions and thank for your response to my previous editorials.

PS:Sorry for delay, was held up in something important. Delay gift will be posted as soon as I learn the technique of problem Polynomial. :D Hope you don't mind delay in delay gift. :D

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

SKIING - Editorial

$
0
0

Problem Link

Practice
Contest

Setter:Hasan Jaddouh
Tester:Amr Mahmoud
Editorialist:Bhuvnesh Jain

Difficulty

EASY-MEDIUM

Prerequisites

Strongly Connected Components, Bfs / Dfs

Problem

Find the minimum number of cells to select in a matrix so that we can reach every cell from it through a series of moves which is, "You can move from one cell to another only if they are adjacent (i.e. share a side) and the height of destination cell is not more than height of current cell."

Explanation

The edges in the graph will be between cells $(i, j)$ and $(x, y)$, only if they share a side. Also, the edges will be directed as the edge exists from a cell into another only if the height of destination cell is not less than the height of the current cell.

For example in the sample input 1, the edges will be as follows:

Now given a directed graph, we want to select a set of cells so that all cells are reachable from it. The first observation is 2 decompose the graph into Strongly connected components, as there may be cycles in the graph. This is because all the vertices in a cycle can be visited by starting from any vertex.

Now, we have a directed graph in which there are no cycles. (It is also called a DAG). In this graph, we claim that we chose only vertices with indegree $0$ to be in our set as the possible candidate solution.

Reason : Let us say there is an edge $P$ to $Q$ in the DAG. Let us denote the set of vertices reachable from $Q$ to be $S$. Then all vertices in $S$ are also reachable from $P$. But $P$ is not reachable from $Q$. So continuing this process, we will see that only vertices having indegree $0$ are not reachable from any other vertex but they as a set cover all the vertices reachable from it.

The DAG of input sample 1 is give below:

In the above figure, $1$ represents the set ${1}$, $2$ represents the set ${2,3}$, $3$ represents the set ${4,7}$ and $4$ represents the set ${5,6,8,9}$.

Thus, the algorithm is as below:

  1. Construct the directed graph from the grid. Complexity is $O(N * M)$. Also, the number of edges in the graph is bounded by $(8 * N * M)$ as each cell can have at most 4 neighbors and it can have edge in both directions.
  2. Decompose the graph into one with no cycles. You can use Tarjan's algorithm or Kosaraju algorithm for this step.
  3. Find the number of vertices with indegree $0$ in DAG.

Author's Solution

The solution counts the number of components having same heights, such that all adjacent components are less (strictly) than it.

Proof: Each such component consisting of all cells of same height can be represented by 1 cell only. Now, each component can either have all adjacent components less tha it or not. If all cells adjacent to it are smaller, the those can be reached from the current cell, so they are ot counted towards the answer. If we repeat this process, for each component, we are bound to find only those cells which will contribute to the answer. Also, if we assume some cell that shouldn't be in answer was counted by above process, the it would contradict the fact that all adjacent components are lesser than it.

The above process can be simply implemented by a dfs call from every vertex and check if all components adjacent to it are smaller than it or not. For details, refer to author's solution.

Time Complexity

$O(N * M)$, per test case.

Space Complexity

$O(N * M)$

Solution Links

Setter's solution
Tester's solution
Editorialist's solution


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.

@vijju123 @utkarsh1997 Prompting the user to fill the already created linked list c++

$
0
0

@vijju123@utkarsh1997

I'm trying to fill the already created linked list by traversing the linked list and then fill each node data with the user input but for some reason after 1040 times it stops asking further values. However let's say I have link list of size 1000 it will work just fine but for more than size of 1040 It doesn't prompt the user. I'm not entering value each time I generated random 1100 elements which I'm copying to the console.

inline void myArray<T>::init() {
 Node<T>* temp = head;
T input;
    while(temp!=NULL) {
    cin >> input;
    temp->data = input;
    temp = temp->next;

}
}

If I do something like this, it works just fine doesn't matter what the size of link list is..

inline void myArray<T>::init() {
 Node<T>* temp = head;
    while(temp!=NULL) {
    temp->data = 5;
    temp = temp->next;

}
}

So, Now I'm thinking the error has something to do with the input taking

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;

}

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

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

Viewing all 40121 articles
Browse latest View live


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