CodeChef is a non-commercial competitive programming community
Login
Username (New User? Signup) Password (Forgot Password?)
Signup
Login or
Signup with
Connect
Note
  • Publicize your achievements on your Facebook Wall.
  • Challenge your friends or ask them for help.

Site Navigation

  • PRACTICE
    • Easy
    • Medium
    • Hard
    • Challenge
    • Peer
  • COMPETE
    • All Contests
    • June Long 2012
    • May Cook-Off
    • May Long 2012
  • DISCUSS
    • Forums
    • Blog
    • Wiki
    • Facebook
    • Twitter
  • COMMUNITY
    • CodeChef Meetups
    • Campus Chapters
    • Host your Contest
    • User Groups
    • CodeChef TechTalks
    • All Educational Initiatives
  • HELP
    • Frequently Asked Questions
    • FAQ for problem setters
    • Problem Setting
    • Tutorials
    • Long Contest Ranks
    • Short Contest Ranks
    • Event Calendar
  • ABOUT
    • About CodeChef
    • Team CodeChef
    • Press Room
    • CodeChef Financials
    • CodeChef Sponsorships
    • CEO's Corner
    • Contact Us
    • About Directi
Home » Wiki » June 2011 Contest Problem Editorials

June 2011 Contest Problem Editorials

 

Problem Tester for the June 2011 contest was Shilp Gupta.


CLONES (written by Ivan Mistreanu)

 

 

Let the number of variables be n. We will calculate the amount of functions in different possible intersection of our clones. There are a total of 2^2^n different n-ary Boolean functions. This is derived from the fact that there are 2^n different binary sequences of length n. We can set a certain function to have value 0 or 1 for each sequence. So we have 2^2^n possibilities to do so.

Now considering 0-preserving functions we have to set each such function a value of 0 for the sequence (0, …, 0). So we are left with one less sequence and there 2^(2^n-1) such functions. The same goes for 1-preserving function.

For the self-dual function we can see that setting the value f(a1, …, an) = b, forces us to set the value f(!a1, …, !an) = !b. So we have only half of the choices. That gives the amount of such functions to be 2^2^(n-1).

It can be shown that the affine function are those that can be represented in a form: f(x1, …, xn) = a0 + a1x1 + … + anxn, where ai = {0, 1}. We can choose each ai to be either 0 or 1. We have 2^(n+1) possibilities to do so. So there are 2^(n+1) affine function.

Using the same logic we can derive the cardinalities for any intersection of those clones. We can use the calculated cardinalities to count the number of functions in any set formed by those clones.

Now let’s consider the following sets: function belonging to none of those clones, functions that belong to Z only, that belong to P only, that belong to D only, that belong to A only, that belong to both and Z and P only, …, that belong to all of Z and P and D and A. There will be a total of 16 such sets. Those sets will be disjoint and their union will be the set of all Boolean functions. The cardinalities of those sets can be calculated using inclusion-exclusion principle using the cardinalities calculated before.

So now we parse the given expression and calculate of what sets it is formed and just sum the cardinalities of those sets. This can be easily done using the bitmask (as there are just 16 disjoint sets) and bitwise logical operations.

 

You can view solutions here:

Problem Setter Solution

Problem Tester Solution

-------------------------------------------------------

RG_01 (written by Rahul Gulati)

 

 

The problem is of finding a path such that the weight of the edge with minimal weight, on the path, is maximized for all pairs of distinct vertices (u, v). Let us call such a path, a maximal path for (u, v). Let's first try to understand a simple and slower dynamic programming solution similar to that of Floyd-Warshall's All Pairs Shortest Paths. Let minimal[u][v][k] denote the minimal weight of an edge for a path that starts at node u, ends at node v, and the only intermediates are vertices 1, 2, ..., k where the nodes are numbered from 1. We set minimal[u][v][0] to the weight of the edge (u, v), if it exists, or otherwise we set it to 0. We can compute minimal[u][v][k + 1] given minimal[x][y][k], for all x, y in V, as follows:

Clearly, the maximal path either passes through vertex k + 1, or it does not. This allows us to write:

minimal[x][y][k + 1] = MAX(MIN(minimal[x][k + 1][k], minimal[k + 1][y][k]), minimal[x][y][k])

So we can use O(V ^ 3) time and O(V ^ 3) space to solve the problem, but clearly the constraints are much higher.

Let us look at a next approach: Let us maintain a disjoint set data structure to keep track of vertices which are in same/different components. We start with the heaviest weight edge, and process edges in order of decreasing weight. Each time we find an edge that connects two vertices u and v, with different components, we merge the two components and for each vertex x that is in the first component, and for each vertex y in the second component, we set the value of minimal[x][y] to the weight of the edge (u -> v). We do this since there will be always be an edge on a path connecting x and y such that the weight of this edge will be lesser than or equal to the weight of the edge (u -> v), and so we know that this strategy will result in an optimal solution. We can reduce this problem further by seeing that we are computing nothing but the maximum spanning tree of the graph. We can compute the maximum spanning tree of the graph using Kruskal's Algorithm in O(E * log(V)) time by sorting the edges, but this is likely to timeout because sorting the edges will take O(V ^ 2 * log(V)) time. We can use Radix Sort in base 2 ^ 15 (to speed up modulus calculations) and sort the edges in linear time, O(E) (2 ^ 15 is much less than the maximal number of edges). If we use path compression, and the union by rank heuristic, we'll get a running time of O(V ^ 2 * alpha(V)), where alpha(n) is the inverse of the ackermann function. Once the maximum spanning tree has been computed, we can run a dfs/bfs from each vertex of the graph and fill the entries of the minimal array in O(V ^ 2) time. The time limits of this problem were kept strict so that solutions using weaker methods could not pass the system tests.

 

You can view solutions here:

Problem Setter Solution: Fast Solution & Slow Solution

Problem Tester Solution

-------------------------------------------------------

CAVE (written by David Stolp)

 

 

This problem is a variant of the longest-path problem, which is NP-hard. The simplest solutions simply attempted to find any path from the northwest to southeast corner, for example using a modified version of Dijkstra's algorithm.

A better algorithm proceeds in two phases:

The first phase is to construct a graph where the vertices correspond to torches, and edges exist between 2 torches that can be reached within K steps of eachother. Then a longest-path algorithm is used to find a path that picks up as many torches as possible. For small values of K, it is difficult to visit all the torches, but for larger values of K it is quite common to be able to visit all or almost all of the torches.

The second phase is to then translate this path into a path in the original graph. The goal here is to visit as many cells as possible between each torch, and also minimize the number of cells that are visited multiple times. This can be accomplished by starting with a simple path, then augment it by adding unvisited cells to it.

 

You can view solutions here:

Problem Tester Solution

-------------------------------------------------------

CTEAMS (written by Tomaz Hocevar)

 

Lets have a look at what happens with existing teams when a new chef enters the kitchen. Depending on his age, he is assigned to the old or to the young team. But this change might throw the size of our teams off balance. Note that a single reassignment of a chef from the young to the old team or the other way around is enough to restore the balance. To perform the first mentioned reassignement we need to find the oldest chef in the young team and move him to the old team. We can perform these operations efficiently if we maintain both teams sorted by age. For example, in C++ you can make use of a STL set to achieve time complexity O(N*log N). The same thing can be accomplished with two heaps - max heap for the young team and min heap for the old.

 

You can view solutions here:

Problem Setter Solution

Problem Tester Solution

-------------------------------------------------------

MINESREV (written by Tomaz Hocevar)

 

 

If you're not familiar with minesweeper, you might want to play around with it before attempting this problem. Start by marking every cell with the number of neighbouring mines. Let's take a look at what do these sets of simultaneously opened cells look like. Each such set consists of a connected component of zeroes and a set of cells a with positive number of neighbouring mines, which are the border of this connected component - let's call them border cells. Clicking on some zero cell will close the connected component and its border. But if you click on some border cell, you might close several components and their borders. Therefore, it's always optimal to aim for the border cells unless there is no border - be careful with entirely empty grids. You have no choice but to click on all cells which have no neighbouring zeros (this includes cells with mines).

You still have to choose minimum number of border cells to close all the components. This looks very much like the set covering problem. Next important observation is that each border cell can close at most 2 components. Try drawing a valid example with three components of zeroes around some positive cell and don't forget that you have to include at least one mine in its neighbourhood. You can model this situation with a graph. Nodes represent components of zeroes and if it's possible to close two components with a single click on some border cell, draw an edge between them. Notice the correspondence between a valid set of clicks and a matching in this graph. Look at it in the following way. You could use one click for every component. In comparisson, you can save one click by closing two components using a matched edge. What you're looking for is a maximum matching in this general graph, which is easier said than done. The famous algorithm for general matchings is Edmonds' blossom algorithm. It was probably a relief if you had a prewritten version. In case you don't, it might be worth reading Gabow's "Efficient Implementation of Edmonds' Algorithm".

 

You can view solutions here:

Problem Setter Solution

Problem Tester Solution

-------------------------------------------------------

RESTOCK (written by Tomaz Hocevar)

 

 

The request that the distance has to decrease with every pass is a very nice property although it might seem like a complication at first. Begin by sorting the cells by their distance to the storage. Now you can take a dynamic programming approach. Define f(i,j) as the cost of moving an item to the storage from position (i,j). You can compute f(i,j) from the previously computed costs of other closer positions which are within the passing range. You could simply scan the entire passing range and get a complexity O(N*M*D^2), which is too slow. But this query operation "which solution within passing range is the cheapest?" can be done faster with a data structure that supports updates and range queries in logarithmic time. A 2-dimensional segment tree is a good candidate. You have to pay some attention to equidistant cells. Process them in batches and perform the updates of the data structure at the end of the batch. The intended time complexity for this problem was O(N*M*(log D)^2). The timelimit is a bit on the strict side to prevent solutions with 1-dimensional segment trees, which would iterate over all rows within the passing range and perform 1-dimensional range queries within a row.

However, many contestants came up with a different solution. It is based on Dijsktra's shortest path algorithm with some optimizations. The important thing to notice is that all edges in the graph have the same weight. Therefore, when you process a node and insert adjacent nodes into priority queue, you will never have to update them again so you can simply remove them. You can maintain a sorted list of cells for each row and when you update some cell and push it into priority queue, you can also delete it from its row list. For small passing range D you only have to iterate over a few rows. This solution also works for large D. The cell lists will shrink rapidly because you will be deleting big rectangular chunks of cells with each update.

 


You can view solutions here:

Problem Setter Solution

Problem Tester Solution

-------------------------------------------------------


Comments

  • Login or Register to post a comment.

perhaps the worst editorial

ritesh_gupta @ 13 Jun 2011 04:59 PM
perhaps the worst editorial so far.. No proper explanation...please make good editorials so that we can learn something and identify ,where we went wrong during the contest ...where is the link to problem setter solution and problem tester solution?

The earlier tutorials were

ritesh_gupta @ 13 Jun 2011 06:05 PM
The earlier tutorials were much better,to be honest

This was my first

gultus @ 13 Jun 2011 06:54 PM
This was my first participation in challenge and it was a nice experience. I always knew that we had to find maximum matching in the minesweeper reversed problem but I was lazy to not implement the Edmond's algorithm. Next time I will try to put in a bit more serious participation.

Nice editorial .. no

manoharsingh23 @ 13 Jun 2011 08:17 PM
Nice editorial .. no doubt.! @ritesh_gupta : to understand the explanations of the problems of 3rd or higher levels require understanding of many basic algorithms+ various data structures .Please get an edge on them and you will eventually understand all the editorials easily.

For RG_01, you can actually

lg5293 @ 13 Jun 2011 08:53 PM
For RG_01, you can actually still sort the edges in O(E log E) time, but I had a different way of merging the components (this would have timed out if I didn't calculate the matrix at the same time that I was performing the MST algorithm). Also, I don't like how these problems time limits were formed. I did make a 2d segment tree for restock, but it timed out, and I also did do maximum matching for minesrev but it also timed out (though for minesrev, it was probably due to my inefficient implementation). It seems that you are looking for too specific optimizations, but I guess I could have found them if I had spent a little more time (since the contest is about ten days). Nevertheless, I still enjoyed the problems. Nice editorials by the way.

@ manmoharsingh23::thnx for d

ritesh_gupta @ 13 Jun 2011 09:19 PM
@ manmoharsingh23::thnx for d suggestion...Initially i found difficult,but after seeing the problem setter solution...I understood the editorials nicely..... The june long contest was really fabulous....... The majority portions were frm the data structure and algorithm....Especially the chef team problems that includes the concept of priority queue

Can anyone tell what tourist

mkagenius @ 13 Jun 2011 11:24 PM
Can anyone tell what tourist is doing in RESTOCK and MINESREV. Thanks in advance.

Gennady's solution for RG_01

mkagenius @ 14 Jun 2011 12:35 AM
Gennady's solution for RG_01 was nice. :)

Gennady's solution for RG_01

mkagenius @ 14 Jun 2011 12:37 AM
Gennady's solution for RG_01 was nice. :) although I guess it was O(max(O(Elog(E)) , O(EV))) :P But was very nice. Union by naming ,great !!!

CTEAMS as well :)

mkagenius @ 14 Jun 2011 01:52 AM
CTEAMS as well :)

I can try to explain

tomaz_adm @ 14 Jun 2011 02:38 AM
I can try to explain Gennady's solution for Restock. He first sorts the cells by distance and starts computing solution for batches of equidistant cells as described in editorial but he avoids the use of 2D segment tree. Instead, he maintains another table min[x,y] which represents minimum solution for cells that are in column x and in range d of cell (x,y). Query operation requires iteration over all columns in range where he uses previously computed values min[x',y]. When doing an update, he only has to fix values min[x,y'] which are in range and within the same column as the current cell for final complexity O(n*m*d). I have no idea how his solution for Minesweeper works, but it looks very similar to standard bipartite matching. There was another quite unique solution for that task by s.max which computes the rank of some matrix to get the cardinality of maximum matching - google says it should beTutte matrix.

@lg5293: I had a quick look

tomaz_adm @ 14 Jun 2011 02:51 AM
@lg5293: I had a quick look at your solutions. For Restock you seem to implement a kd-tree which can be unbalanced because you're inserting new elements one by one. I'm a bit puzzled about your Minesweeper solution which uses max flow to compute the maximum matching. I would be very interested in how this works, because as far as I know you can only use this on bipartite graphs.

I like the time span of 11

sushilnath @ 14 Jun 2011 05:17 AM
I like the time span of 11 days that makes everyone find his suitable time to try for the problems , But to avoid large number of ties I would suggest that except for the challenge problem there should be penalties for unsuccessful submissions say 0.01/0.02 but only till the score of the problem reaches some critical value say 0.5 .

I didn't meant the actual

sushilnath @ 14 Jun 2011 06:19 AM
I didn't meant the actual parameters. Say, Penalties of 0.005 and critical value of 0.9 for a problem . Then a user will have 20 attempts ( of course he can have furthur unsuccessful attempts but without penalties ) and in any case person solving more problems will have more marks.

@tomaz_adm, for restock, I

lg5293 @ 14 Jun 2011 09:50 AM
@tomaz_adm, for restock, I can see now why it would time out, and for minesrev, I thought max flow would work, since my original tried to implement Edmonds but didn't work correctly (and timed out). I'm looking at other people's solutions though, so I'm trying to fix my current ones. Thanks for the feedback.

@admin : How about asking

flying_ant @ 14 Jun 2011 10:48 AM
@admin : How about asking coders ( like gennady, s.max or any others who solved using different techniques ) to give a short writeup on how they solved. That would be very helpful. @all : If your approach was different from many others and the one mentioned in editorial, please comment here :)

very nice set of

chaitanyaanand @ 14 Jun 2011 10:50 AM
very nice set of problems....though i could solve only one. Concepts like maximum matching are not familiar to me as i have not read them in my course....could i know what book you guys read to get acquainted with these things?

From what I've heard, people

coders1122 @ 14 Jun 2011 10:57 AM
From what I've heard, people who use standard bipartite matching, do this- For every undirected edge u-v in the graph as suggested by editorial, they draw edges u-v',v-u' in the new graph of 2 * N vertices. This trick would avoid the odd length cycles that would otherwise be present in the undirected graph. I hope someone who has used this trick, can expand more on this. Seems like a very standard, interesting trick. Also, can anyone bind the complexity of quad tree for Restock? I had got TLE using a quad tree, but passed with a 2 D segment tree. (Intrigued)

I think EgorK also uses

lg5293 @ 14 Jun 2011 11:36 AM
I think EgorK also uses maxflow: http://www.codechef.com/viewsolution/566102, and it passes, so maxflow might also work for maximum matching. Can the two problems be solved similarly?

@flying_ant: my solution also

suh_ash2008 @ 14 Jun 2011 01:24 PM
@flying_ant: my solution also uses maxflow: http://www.codechef.com/viewsolution/568449 . As coders1122(ravi kiran) mentioned, create a copy of each vertex and for every undirected edge u-v in the graph as suggested by editorial, draw edges u-v',v-u' in the new graph. Now this new graph is bipartite. If 'x' is the maximum bipartite matching in this new graph, then 'x'/2 corresponds to the maximum matching in the original graph. Using this method you cannot exactly find a maximum matching, but you can always find the cardinality of the maximum matching. I'm not sure i know the exact proof for this though :), but i've used it before in other problems.

Bad news, both solutions

tomaz_adm @ 14 Jun 2011 01:52 PM
Bad news, both solutions turned out to be wrong. Maximum matching in so-called bipartite double cover gives you an upper bound for maximum matching in the original graph. Consider a graph with two disjoint cycles of length 3. Maximum matching in bipartite double cover is 6 so half of this number still overestimates the size of original maximum matching which is 2. To make sure I didn't get something wrong, I set up a minesweeper grid which represents this situation and both solutions gave wrong answers. I've tried my best to construct cases which would break incorrect greedy matchings but I've never thought of this. I'm sorry that I couldn't catch this during the contest. I was monitoring the solutions but it's hard to figure out how some solutions work - especially when you don't understand their general approach.

@tomaz_adm: Appreciate the

coders1122 @ 14 Jun 2011 04:19 PM
@tomaz_adm: Appreciate the effort. Thank you for clarifying the nature of approach. Once again, beautiful problem. :-)

@tomaz_adm: Thanks for your

mkagenius @ 14 Jun 2011 04:51 PM
@tomaz_adm: Thanks for your time. Did you put that extra testcase on the site.(It would be nice to have complete testcase :) )

About matching algo - what I

EgorK @ 14 Jun 2011 05:54 PM
About matching algo - what I did is actually incorrect - suppouse graph that consists of 2 3-cycles. My algo will return 3 and correct answer is 2. But many authors forget to include tests on which this algo will fail

@tomaz_adm: i understand the

suh_ash2008 @ 14 Jun 2011 06:04 PM
@tomaz_adm: i understand the mistake. thanks for pointing it out.

Isn't RG_01 solvable in

Amit Karmakar @ 14 Jun 2011 06:53 PM
Isn't RG_01 solvable in O(|V|2) using adjacency matrix representation of the graph? If yes, why wasn't it the intended solution?

I think Amit is right here,

gultus @ 15 Jun 2011 04:12 AM
I think Amit is right here, though it really doesn't make much of a difference as O((V^2)*alpha(V)) is practically O(V^2). I did try an adjacency matrix representation and my non O(V^2) soln (http://www.codechef.com/viewsolution/561308) passed the judge so I didn't push for a stricter solution.

@flying_ant: Good idea!

balajiganapath @ 16 Jun 2011 07:14 PM
@flying_ant: Good idea!

Hi, May I know what is wrong

simpleton @ 19 Jun 2011 10:08 AM
Hi, May I know what is wrong with my RESTOCK? I have been debugging for days, but I still cannot find my bug. Thanks! My latest submission has submission ID 576974: http://www.codechef.com/viewsolution/576974

Hi admin, Actually, I

simpleton @ 19 Jun 2011 10:25 AM
Hi admin, Actually, I managed to solve the problem. However, I think this really weird bug that has been bugging me. This is what happened. In this accepted code (submission ID: 576985, url: http://www.codechef.com/viewsolution/576985), I did my dp from the original (1,1) to (R,C). I made everything 1-indexed, so the original changed from (0,0) to (1,1). When I wrote this, I got AC. However, if you look at this wrong submission (submission ID: 576984, url: http://www.codechef.com/viewsolution/576984), you will notice that I did not change anything other than make my dp work from (R,C) to (1,1). However, this time I get wrong answer. May I know if it is possible for me to know which is the testcase that gave me WA for the 2nd implementation? Thanks in advance!

Your wrong solution solves a

tomaz_adm @ 19 Jun 2011 05:43 PM
Your wrong solution solves a problem where distance from delivery point (R,C) increases with every pass. But that is not equivalent to decreasing the distance to storage (1,1).

Wow, that's a sneaky bug :S.

simpleton @ 19 Jun 2011 09:25 PM
Wow, that's a sneaky bug :S. Thanks!
CodeChef is a non-commercial competitive programming community
  • About CodeChef
  • About Directi
  • CEO's Corner
  • C-Programming
  • Programming Languages
  • Contact Us
© 2009 Directi Group. All Rights Reserved. CodeChef uses SPOJ © by Sphere Research Labs
In order to report copyright violations of any kind, send in an email to copyright@codechef.com
CodeChef a product of Directi
The time now is:
CodeChef - A Platform for Aspiring Programmers

CodeChef was created as a platform to help programmers make it big in the world of algorithms, computer programming and programming contests. At CodeChef we work hard to revive the geek in you by hosting a programming contest at the start of the month and another smaller programming challenge in the middle of the month. We also aim to have training sessions and discussions related to algorithms, binary search, technicalities like array size and the likes. Apart from providing a platform for programming competitions, CodeChef also has various algorithm tutorials and forum discussions to help those who are new to the world of computer programming.

Practice Section - A Place to hone your 'Computer Programming Skills'

Try your hand at one of our many practice problems and submit your solution in a language of your choice. Our programming contest judge accepts solutions in over 35+ programming languages. Preparing for coding contests were never this much fun! Receive points, and move up through the CodeChef ranks. Use our practice section to better prepare yourself for the multiple programming challenges that take place through-out the month on CodeChef.

Compete - Monthly Programming Contests and Cook-offs

Here is where you can show off your computer programming skills. Take part in our 10 day long monthly coding contest and the shorter format Cook-off coding contest. Put yourself up for recognition and win great prizes. Our programming contests have prizes worth up to Rs.20,000 and $700lots more CodeChef goodies up for grabs.

Discuss

Are you new to computer programming? Do you need help with algorithms? Then be a part of CodeChef's Forums and interact with all our programmers - they love helping out other programmers and sharing their ideas. Have discussions around binary search, array size, branch-and-bound, Dijkstra's algorithm, Encryption algorithm and more by visiting the CodeChef Forums and Wiki section.

CodeChef Community

As part of our Educational initiative, we give institutes the opportunity to associate with CodeChef in the form of Campus Chapters. Hosting online programming competitions is not the only feature on CodeChef. You can also host a coding contest for your institute on CodeChef, organize an algorithm event and be a guest author on our blog.

Go For Gold

The Go for Gold Initiative was launched about a year after CodeChef was incepted, to help prepare Indian students for the ACM ICPC World Finals competition. In the run up to the ACM ICPC competition, the Go for Gold initiative uses CodeChef as a platform to train students for the ACM ICPC competition via multiple warm up contests. As an added incentive the Go for Gold initiative is also offering over Rs.8 lacs to the Indian team that beats the 29th position at the ACM ICPC world finals. Find out more about the Go for Gold and the ACM ICPC competition here.

Domain Name Registration, Web hosting, and Website Design provided by BigRock.com