One Point Solution

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Tuesday, 20 March 2012

Writing SRM 538

Posted on 07:59 by Unknown
I am writing this before the match starts. For obvious reasons, I won't publish it until the end of the challenge phase. But please keep in mind I am writing this with no info on what will happen during the match.

So, last Friday after pushing for months to receive attention for my problems, I was asked if I was going to have time to problem set SRM 538. I accepted immediately, then noticed that there were four days left for it. I was focused on SRM 537 which was the next day.

I was nervous. Of course I have time to develop the problems and do all in 4 days. But the problem is that in four days there may not be enough time to have complete feedback cycles with testers.

At the end the development of the match got quite the obstacles. But we were able to come up with something that looks like a match. Hopefully it will not be tremendously hated by everyone, but I expect it to be. I am rather sure that nobody will solve either hard problem. Division 2 will be much harder than usual and division 1 much easier than usual. And division 2 prefer easy sets while division 1 prefer hard sets...

div2 300
This problem seems to me harder than usual. Nothing much to say about it. Other than I think it is cute.

div2 500, div1 250.
For a long time I had a dream of a problem that seems to have an easy solution that is almost a one liner but (unlike what became frequent) is actually wrong and you need to do a more complicated thing. But I couldn't. The closest thing I could do is this problem, which has two very easy solutions, but one is wrong and the other isn't.

I tried very, very hard to make people likely to get fooled into thinking the easy solution is correct. I really hope people fall for it. The whole objective of the problem is to punish anyone who enters an easy solution, passes and then does not bother asking himself why it works at all. The correct solution is itself very easy though, but hopefully people that rush into things are more likely to think of the wrong solution.


At first , the problem was about "Mr. K" claiming to solve the traveling salesman version of this typical Cartesian plane problem. And so the whole parity thing was about that. But misof thought adding a fake problem first was too confused. I sort of agree, so I preferred to remove the funnier story in exchange of an easier to follow problem.



div1 450
This problem is easy, but also cute, like the div2 250. Nothing much to say other than I do not really have a formal proof, but rng_58 claims to do. So, it is all good and dandy.

div2 1050 and div2 1050
I thought of this problem for months, yet I didn't really get to understand them fully until ... yesterday. These problems are evil and I doubt anyone will solve them during the match.

If I had a little more time, I would have come up with a different div1 hard, and swapped div2 hard with div1 medium.

We found so many mistakes in our solutions during development that I know for sure these problems are evil and will open the gates of hell. The Mayan 2012 apocalypse may be triggered by them.

But I did try to make the example cases as strong as possible, specially in the div2 hard.
---
End of predictions, now some comments about events during the match:

During the match
9 minutes after the start of the match. I figure out that the div1 hard statement does not explain what the B argument was. This was caused by a last minute language update of the statement that somehow missed it. Sorry.

- Many people are surprising me with a different (wrong) solution for div1 250 / div2 500 that I didn't expect.

- It is surprising to me that the tests for div1 450 were so weak some solutions that do not even do the dp and just sum the angles together are passing examples.

- Someone asked us what value of PI to use. Then I noticed div1 450 didn't have the usual note about relative and absolute error. Damn.

- 55 minutes after the start of the match, Egor makes a submission for 1050!.

- Sometime later, bmerry does the same thing!

- Later: What a humongous amount of div2 hard submissions! I am impressed.

- In the challenge phase, dolph was genre-savvy enough to blind challenge Egor right at the beginning of the phase. That was impressive.

- Many people actually got the typical issue with %2 and negative numbers, but that's very strange because I made sure to include a example case that detected that bug. Apparently, it was possible to make the bug with some slight changes from what I tested and pass the example cases. That's too bad. I'd hate failing for this bug.
Read More
Posted in srm, topcoder | No comments

Saturday, 17 March 2012

SRM 537: oh my

Posted on 10:25 by Unknown
I am starting to write this as the intermission phase begins. I have submitted solutions for the 275 and the div1 500. I am fairly sure my div1 500 will survive (it is dynamic programming). But I'd say the probability my 275 fails is around 95%. I am currently first in my room, but all I need is somebody in my room to figure out the 250 is a good challenge mine and I will lose the money prize.

Div1 275
Awful stuff, I knew I was going to have issues with this problem the second I read it.

Anyway, note that eventually the distance between every two reachable numbers will be gcd(A,B). And that's really all I could get. I tried to do something that does simulations and does tons of hacks. Let's see if it works.

Div1 500
This was nice. You have some numbers. And there are K random steps. With 0.5 probability, the numbers are permuted using a permutation array. With 0.5, the numbers in each index are xor-ed against numbers with the same index in another array. Return the expected value for the first element after the K moves.

The constraint for K is at most 50, the limit on the number of ducks and the xor values (the elements of the array) is at most 10^9

There is a difference between quickly starting to code the solution and spending a lot of time wondering what to do. Permutation and Xor each can be seen as applying to only a single bit positions on all the numbers. Now, something funny about expected value. The expected value of the number in element 0 can be seen as (Expected value of the first bit) + 2 * (Expected value of the second bit) + .... etc. This is because the expected value is a linear application.

So, if you change the problem to finding the expected value of each of the (At most 30) bits of element 0. It becomes all about finding the probability that it will be 1. To find the probability that the x-th bit of element 0 will be 1, you can do a dynamic programming based on the following recurrence: F(v, bit, pos, K): The probability that the pos-th element will have a bit v (1 or 1) in the bit-th bit after K moves.

struct KingXMagicSpells 
{

double dp[2][30][50][51];
bool seen[2][30][50][51];
vector<int> ducks;
vector<int> spellOne;
// probability to get a bit in this position after K moves
double rec(int v, int bit, int pos, int K)
{
double & res = dp[v][bit][pos][K];
if (! seen[v][bit][pos][K]) {
seen[v][bit][pos][K] = true;
res = 0;
if (K == 0) {
// no moves
if ( v == ( (ducks[pos] >> bit) & 1 ) ) {
res = 1.0;
} else {
res = 0.0;
}
} else {
// one move...
// was there a permutation?
res = 0.5 * rec(v, bit, prev[pos], K-1);
// was there a xor?
res += 0.5 * rec(v ^ ( (spellOne[pos] >> bit) & 1 ), bit, pos, K-1);
}
}
return res;
}

int prev[50];
int n;

double expectedNumber(vector <int> ducks, vector <int> spellOne, vector <int> spellTwo, int K)
{
this->ducks = ducks;
this->spellOne = spellOne;
n = ducks.size();
for (int i=0; i<ducks.size(); i++) {
prev[ spellTwo[i] ] = i;
}
memset(seen, 0, sizeof(seen));
double res = 0;
for (int i=0; i<30; i++) {
res += ( (1<<i) * rec(1,i,0, K) );
}

return res;
}
};



Outcome
I finished typing this when the challenge phase ended. It seems 275 was not as much of a challenge fest as I thought. Even if I fail 275, I will be first place, and I am very sure that I will pass 500, unless I do something very lame somewhere that causes it to have random bugs.
Read More
Posted in explanation, srm, topcoder | No comments

Friday, 16 March 2012

Codeforces round #112

Posted on 10:13 by Unknown
It is 17 minutes before the end of the contest, I am giving up on E and D.

Problem A link
There are at most 200 points. You can actually do a O(n*n) search, for each point, iterate through all the other points and if the other point is a left,down,up or right neighbor, set a switch so you know that such a kind of neighbor was found.

int n; 
int x[1000];
int y[1000];


int solve()
{
int c = 0;
for (int i=0; i<n; i++) {
bool up = false;
bool down = false;
bool right = false;
bool left = false;

for (int j=0; j<n; j++) {
right |= ( y[i]==y[j] && x[i]<x[j] );
left |= ( y[i]==y[j] && x[i]>x[j] );
down |= ( x[i]==x[j] && y[i]<y[j] );
up |= ( x[i]==x[j] && y[i]>y[j] );
}
if ( up && down && right && left ) {
c++;
}

}
return c;
}


Problem B link
Imagine the largest case, n=10^9, k=10. Then if you use something as large as v=10000000000, it will finish in one move. So that is a value of v that can work as an upper bound. It is a large bound, but what you can do is do a binary search. If it is not possible for a v, it will not be possible for a smaller v. And if it is possible for a large v, it should be possible for any larger v.

Testing each value in the binary search takes logarithmic time in base k. Thankfully, problemsetter was not evil to allow k=1 :)

bool possible(long n, int k, long v) 
{
long done = 0;
long div = 1;
while (n > done) {
long todo = v / div;
if (todo == 0) {
break;
}
done += todo;
div *= k;
}
return (done >= n);
}

long solve(int n, int k)
{
long hi = 10000000000ll;
long lo = 0;

while (lo + 1 < hi ) {
long ha = (hi + lo) / 2;

if (possible( n, k, ha ) ) {
hi = ha;
} else {
lo = ha;
}
}
return hi;

}



Problem C link
Ok, with such large constraints we want a linear algorithm.

What about k=2, and a string like "00101001" ? Consider the definition of a important fragment: A fragment that begins and ends with 1 and contains exactly k 1s. In the example, there are two important fragments: --101--- and ----1001 Each of these two places has a number of adjacent 0s to the right and left sides (possibly zero). Now the key is to notice that the number of substrings that contain each of these important fragments is equal to (number of left zeros + 1) * (number of right zeros + 1). In other words, for fragment 101, surrounded by 00 to the left and 00 to the right, there are 9 substrings: 00101, 001010, 0010100, 0101, 01010, 010100, 101, 1010 and 10100. For fragment "1001", there are 2: "01001", "1001".

The problem becomes to find these fragments and count the side zeros in O(n). It is not actually so difficult. Let onepos be an array that contains the positions of 1 characters in the string. Then you can find that each fragment that begins at onepos[i] will finish at some onepos[i + k - 1]. Then you can use onepos[i-1] to count the zeros in the left side (consider the corner case when i=0, though) and a similar idea for the right zeros.

Catch: k can be 0. Then you have to count the number of substrings containing only 0 characters. Too bad I didn't see this during the match and had to resubmit.

To deal with this special case, use the onepos array once again, but this time to find all the maximal fragments that contain only zeros. From the sizes of each of these fragments, you can find the number of substrings inside it.

int k; 
string s;

long solve()
{
vector<long> onepos;
for (int i=0; i<s.size(); i++) {
if (s[i] == '1') {
onepos.push_back(i);
}
}
long res = 0;
if (k == 0) {
for (int i=0; i <= onepos.size(); i++) {
long a = ( (i==onepos.size()) ? s.size(): onepos[i] );
long b = ( (i==0) ? -1: onepos[i-1] );
long leftZeros = a - b - 1;
// number of substrings inside this fragment that contains leftZeros zeros
res += ( leftZeros * (leftZeros + 1) ) / 2;
}
} else {
for (int i=0; i + k - 1 < onepos.size(); i++) {
int j = i + k - 1;
long leftZeros = onepos[i] - ( (i==0) ? -1 : onepos[i-1] ) - 1;
long rightZeros = ( (j==onepos.size()-1) ? s.size() : onepos[j+1] ) - onepos[j] - 1;
// number of ways to add zeros to the important fragment.
res += ( leftZeros + 1) * (rightZeros + 1);
}
}


return res;
}


D and E
I avoided D, it seemed that if I found a solution it would take long to code it. Note that the input is a tree (connected, with n-1 vertices) and the single vertex with more than 2 edges can easily be the root you pick. There are never more than 1 path connecting two vertices, so you are only interested in confirming if there is a path or not.

E seemed more interesting so I focused on it. With no success yet. Tried stuff with tries, but everything seems too slow. Might post an update later.
Read More
Posted in codeforces, explanation | No comments

Tuesday, 13 March 2012

Language features: Rants and wishes

Posted on 20:06 by Unknown
Every time the google code jam approaches I ponder the idea of making a preprocessor of sorts to be able to "use my own language" in the qualification rounds. But then I notice that there is little time left. Either way, these are things I really wish I could use during contests, without losing the good powerful things such as the STL that c++ has, of course.

Loops in general blow
For loops are such basic construction blocks that you always use yet in c++ and many other languages they are so messed up and limited...

Look at this:
for(int i=0; i<4; i++) {
}


What is wrong with that? You may ask. Well, note how you type the variable i three times. Were the guys at the C council of standards really unable to ponder about "once and only once"? I am just saying... making funny bugs and wasting at least 3 seconds finding out you mistyped one of the three instances of the variable and put j instead of i gets very old.

It is not just the possibility of bugs or having to type things multiple times. I sometimes wish the language didn't expect me to code something as common as a walk from 0 to 6 having to do so many manual things like the comparison function and the increments... I once dreamed of something like this:

for( 0 <= i < 4) {}


Imagine that, it is clearly saying that you will repeat the operations for numbers from 0 to 3. You can control bounds being exclusive or not. And it is very expressive. Of course, it is not perfect and I am not saying it is. But I actually implemented this in a custom language I wrote for Warcraft 3 map making. And it was so cute... Anyway, serious languages have solutions of their own, like python's range() function. A lot of these solutions are better than what C, C++ and Java offer in this regards.

The other day, I pondered about loops that need you to iterate through pairs or tuples of many variables. Imagine you could just do this, in a single loop.

for (1 <= a < b < c < n) {


Sounds fun.

Solution?
- Switch to python , some other language? Not very viable in most contests. And well, I do like C++ better than other languages overall. I really like the STL during contests, so this is not so easy.
- MACROS. This is what a lot of C++ coders in high positions do. They for example have a FOR(v,n) macro that implements for (int v=0; v<n; v++). This fixes the issue with having to type the same variable thrice but it introduces the issue of using macros and making your code look uglier.
- Give up and live with it.

Lack of a for each construct
I covered this before when I explained why I use the for_each #define. It is still quite lame to have to use a #define for this.

Just something, I just found out c++11 kind of implements this. http://en.wikipedia.org/wiki/C%2B%2B11#Range-based_for-loop

Lack of var
Something c++11 (or c++0x) does well is add the auto keyword. It will work like this:
map< pair<int,int>, string > thesupermap 
auto q = thesupermap.begin();
//get it? This is the equivalent of the good oldie
// map<pair<int,int>, string>::iterator q = thesupermap.begin()



This should be of great value to anyone who has attempted to use the STL and has not gone insane in the process.

But there is a problem. Why call it auto? I wish it was named var, like in some other language. It seems they just wanted to recycle a keyword instead of adding a new one.

The lack of this feature really hurts. The good news is that it is probably already possible to use it in the google code jam, shall you get a compiler that supports the new c++ specification. The bad thing is that it is less likely in topcoder. Which uses a C++ compiler from the stone age and is likely to ever update the language versions.

Solution?
- Use c++11, if possible.
- Use a #define. Like in the case of for_each, the typeof() macro can help. The problem is that the syntax of declaring a variable will look like this: var(q, s); instead of auto q = s;
- Live with it.
- Lobby g++ to implement c++11 fully, then lobby topcoder to use the new g++ version.

I miss <?, >?, <?= and >?=
These are operators that do operations so basic that it is hard to believe that after gcc invented them, they decided to deprecate them instead of lobby the c++0x council to make them global standards.

Explanation : (5 <? 3) returns 3. That's right, it gets the minimum of two numbers. >? the maximum and, even nicer: x <?= 5 is the same as x = min(x, 5).

Something good about the old g++ version in TopCoder is that this obscure feature is still supported. The bad thing is that it is not a standard, and later compilers removed the features. So I had to stop using it.

There was so much potential in this. Surely, it causes confusion, but that is only because it is a rare feature. I am sure that if *= was not a standard everybody would get very confused about finding code that says x *= 4.

I would have made them better though. Let them do what std::min and std::max do. So, for example, imagine you could do this:

string s[5] = {"aab", "bbc", "xxx", "h", "lxa" }; 
string lex = s[1];
for (1 <= i < 5) {
lex <?= s[i];
}


To find the lexicographically smallest of 5 strings...

Solution?
- Use old g++ versions. Good luck with that. Codeforces does not support this. And in recent ubuntu versions, for example, gcc 4.0 is not in the repositories.
- Live with it.

Native bignum support
Easy, I wish you could just do (big x = "3483389483893382929284349493839338") and then use x in all sort of operations.

Solution?
- Switch to another language. But not Java because their bignum support does not do this. A lot of languages can do this, some without even asking... (Which is not a good thing, if instead of overflow your program suddenly gets magnitudes slower)
- Really, if you can use non-standard libraries just get gmp and do a typedef.
- If you can't use libraries, well... live with it.

I really wish c++11 implemented this, but it won't. Surely you can code your own big nums, but not so much, and in fact there is such a plethora of optimizations and aspects that it is better to use a well-tested wheel rather than make your own. Plus bignums in contests are the archetypical Fake difficulty stunt.


.begin(), .end() ad nauseum
Speaking of using the STL and going insane in the process. If there is something that is really broken about it, is that you have to do (v.begin(), v.end()) so many times... Once again, this is an explicit attack against "once and only once".

Solution?
- Live with it.
- Coders tend to make an ALL(v) #define that translates to v.begin(), v.end(). Once again, it fixes one problem and introduces another.

Stupid !@#~% long long
I hate having to type long twice. I really do. Specially because there is a pointless "long" type that does the same as "int". c++11 does nothing to fix this.

I have resorted to using a define in my code that fixes this, and once again introduces tons of other issues.
Read More
Posted in implementation, languages, rant | No comments

Google code jam registration - Just note something about privacy

Posted on 12:26 by Unknown
By now you should all know that GCJ registration has begun. Which is great and I have already register.

But wait a second, the codejam is perhaps the google site that has the most private information about me. Will it be able to exchange this information with other services as the new privacy rules from google allow.

Good news everyone! It will!

From https://code.google.com/codejam/terms_content.html

Contestants also understand this data may be used by Google in order to verify a contestant's identity, postal address and telephone number in the event a contestant qualifies for a prize, and if agreed to by contestant, for recruiting purposes. Contestants have the right to access, review, rectify or cancel any personal data held by Google in connection with the Contest by writing to Google at the address listed below. If a contestant does not provide the data required at registration, that contestant's entry will be ineligible. Otherwise, all personal information that is collected from the contestant is subject to Google's Privacy Policy, located at http://www.google.com/privacypolicy.html.
Read More
Posted in google, googlecodejam | No comments

Sunday, 11 March 2012

Codeforces: VK Cup round 1: Problem C: Abracadabra

Posted on 19:57 by Unknown
This problem haunted me all day and I kept solving it inside my head without really wanting to. At the end, the solution I thought of all day was sort of incomplete, but a little dirty trick can make it pass. Later I saw some other codes and finally noticed the hard reality...

The divide and conquer
First of all, let us say that we care about the string present after a number of steps equal to step (30 for the string we want to solve). We can tell the size of the string (t = 2^step - 1). We can know the position of them middle character m = t/2 + 1. Please note that due to how the string is constructed, the middle character is unique - this character does not appear in any other position of the string at this number of steps.

In fact, that's really all we need to know how to use divide and conquer in this problem. Let us say that the result greatest common substring contains this middle character, then it is forcefully the overlap between the two intervals. If the best substring is not the overlap between the two intervals, then it won't contain the middle character.

In fact, we can split each of the intervals into two maximal parts (possibly empty) that do not contain the middle character. And each of these four parts will match an interval in the string for step # (step - 1). (The positions of the intervals that appear after the middle, shall get the middle position subtracted).

The result is thus one of five possibilities: It can be the overlap of the two intervals. Or it can be the largest substring (same sub-problem) between one of the four possible pairs between strings that come from the first interval and strings that come from the second.

This solution as is has a lot of branching. Worst case may call the divide and conquer recurrence 4^30 times.

Dirty tricks
First of all, we will handle trivial cases such as when one of the intervals is empty. The result is obviously always 0 in those cases.

But there are ways to optimize that original 4^30 idea. What I did was to make sure that it is 2^30, avoiding to branch the recurrence more than two times per instance, this requires some tricks like not doing the split when both intervals begin at the first position or end at the last (It can be proven the overlap is the best result in this case). Even at 2^30, it is too slow, the second dirty trick was to do an array mem[80][80][80][80], and if both extremes are less than 80, memoize the results of the recurrence. This will make the number of calls from 2^30 to 2^30 / (80^4) + 80^4. This is enough to solve the problem.

The better solution
A smarter solution involves noticing, what if one interval is completely inside the other? In this case, the overlap is 100% surely the best answer (And it is actually equal to the size of the smallest string). It is easy to know that this will give a correct answer. It is slightly more complicated to notice that this little optimization will make the algorithm run very fast. In fact, the maximum number of branches is 2, so the result is O(step). Really.

As a slight proof, let us think of a pair of intervals such that one is not a subset of the other.

1) If neither interval touches the middle letter, the only pair that is not trivial (does not have an empty string) will be one that matches the two intervals again but in the previous step. No branching.
2) If both intervals touch the middle letter, there will be branching. Yes. But 2 of the pairs of intervals generated will be cases in which one interval is a subset of the other. So the case will branch 2 times, and both times the case will an interval that begins at position 1 with another interval that ends at position t.
3) Handling Case 2 will either result in a sub-problem in which one interval is a subset or the other, or in Case 2 again. Try it.

int solve(int l1, int r1, int l2, int r2, int step=30) 
{
if (l1 > r1) {
return 0;
}
if (l2 > r2) {
return 0;
}
//overlap
int ovl = max(l1, l2);
int ovr = min(r1, r2);
int overlap = ( (ovr >= ovl)? (ovr - ovl + 1) : 0 );

int t = (1<<step) - 1;

int m = t/2 + 1; //the middle

// should we continue in depth? (Is the result not necessarily the overlap?)
if ( (l1 <= l2 && r1 >= r2) || (l2 <= l1 && r2 >= r1)) { //one is a subset of the other
return overlap;
}
// split each interval in two halves that don't touch the middle.
int l[4] = { min(l1, m) , max(m+1, l1) - m, min(l2, m) , max(m+1, l2) - m};
int r[4] = { min(r1, m-1), max(m, r1) - m, min(r2, m-1), max(m, r2) - m};
int res = overlap;
// try each pair of interval.
for (int i=0; i<2; i++) {
for (int j=2; j<4; j++) {
res = max(res, solve(l[i],r[i], l[j], r[j], step-1) );
}
}
return res;

}
Read More
Posted in codeforces, vkcup | No comments

Codeforces: VK Cup round 1 (update 1)

Posted on 10:14 by Unknown
After learning that people that are not in the cup can participate in a rated version of the contest. I really went through a lot of inconvenience to be able to participate in this round.

After I solved problem B (albeit with an overflow bug), I was not able to submit. Some time later codeforces announced the unofficial match won't be rated because unofficials weren't able to submit. At then I stopped trying. Around some time later I check back codeforces and it seems that submission is possible again. So I tried to submit B, failed, fixed and then suddenly I had only less than an hour left... I wish things went differently, I got problem D solved, kind of.

Problem B linky
Only Karts that have stools will be discounted. Now note that once you put a stool in the kart, then you would like to avoid to place any element with smaller cost. Placing elements with larger cost will not change the discount (but it might make you miss the opportunity to receive a discount on that same item in another kart). So, once you place a stool, you really should avoid placing any other item altogether. In cases where there are more karts than stools, there will be plenty of karts to place the elements you do not want to place in karts that already have stools. In the other case, where the number of stools is less than or equal to the number of karts, then there is no need to place those unwanted elements in more than one kart with a stool. Doing this will make you unable to get the discount for that stool, and in fact will make you get a discount for the least expensive item overall.

The best discount you can get will get from stools. If there are less discountable karts than stools, it is better to pick the largest stools to place into each of those karts. Thus the logic goes as follows:

- If there are less stools than karts: Pick a kart for each stools. Distribute the remaining items in the stool-less karts (make sure to place at least one item in each, but the actual distribution does not matter).
- Else, you will need to forcefully place the minimum price kart and a stool in one kart. Place the best (k-1) stools in the other karts and any other element in the kart that has the least expensive element.

Problem A linky
At first I thought you would need fancy std::sets, but since x and y are always the same for all soldiers, it gets a little simple.

Assume that you have the soldiers and vests sorted non-decreasingly.

Now, let us say you are picking the i-th soldier in such order. Since we have already made decisions for all the soldiers with a smaller a_i, then we can get rid of all vests that are smaller than a_i - x. The smallest vest greater than or equal to a_i-x will remain, note that if this vest is less than or equal to a_i+y, you can match it to the soldier, and in fact, you must match it to the soldier. Else it will be impossible to match the vest, but it might be possible to match it with a soldier with a higher preference.

Problem C linky
Seemed interesting, but submission counts suggested D was easier, and they both have the same score, so I skipped to D.

Problem D linky

Since it is a tree, it is quite dp-friendly. Assume we have
decided an arbitrary root for the tree, and such each node is either the root or has a parent and all the other adjacent nodes are children. Let us say we constructed a table dp[x][k], which returns the number of (grand) children of x at a minimum distance equal to k. Once the tree gets an arbitrary root, it is easy to calculate this table: dp[x][0] is 1 for all nodes (the node itself is at 0 units of distance), then it is sum(dp[y][k-1]) for all y that are children of x.

Let us count all the pairs (x,y) that are K edges away and x is a (Grand) parent of y. This is precisely equal to dp[x][K].

But there is a catch, sometimes the parent node x may be just part of the K-size path between two nodes that are children of it (Do not worry about parents of x, you will consider their involvement when they themselves become x).

Well, not so hard, let starting from dp[y][a] for all children y of x, you can easily count the number of paths of length a+1 that start at x and go through the y child. You can merge all such the paths of different sizes a and b such that a+b = k. This requires some trick to make sure the algorithm is not very slow (Let sum[a] be the total sum of paths of length a, sum[a] - dp[y][a] will give the number of paths that do not go through y).

This takes you to a O(n * k) algorithm. Note that the number of edges is O(n), (in the second part whilst doing all the merges, you visit all edges O(k) times).

Edit: here is the code for problem D. I mostly finished it during the match but had the typical bug of increasing the wrong counter inside a for. Then it turns out that when practice room becomes active I actually time out in the largest case. It turns out that the constraints were too large and you couldn't use memoization in the dp part. That's kind of lame.

//================================ 
// Program:
//
int n, k;
int u[50000]; //note that I use 0-based indices instead of 1-based
int v[50000]; //because 1-indexing is crud.

int degree[50000];
vector<int> G[50000];

int parent[50000];

void dfs(int x, int p)
{
if (parent[x] == -2) {
parent[x] = p;
for (int i=0; i<degree[x]; i++) {
dfs( G[x][i] , x );
}
}
}

// dp[j][x] how many grand children does x have away of j distance units?
int dp[501][50000];

long long solve()
{
fill(degree, degree+n, 0);
for (int i=0; i<(n-1); i++) {
degree[ u[i] ]++;
degree[ v[i] ]++;
}
for (int i=0; i<n; i++) {
G[i].resize(degree[i]);
degree[i] = 0;
}
for (int i=0; i<(n-1); i++) {
G[u[i]][degree[ u[i] ]++] = v[i];
G[v[i]][degree[ v[i] ]++] = u[i];
}
fill(parent, parent+ n, -2);
dfs(0, -1);

for (int j=0; j<=k; j++) {
for (int x=0; x<n; x++) {
if (j==0) {
//Base case, when k = 0, the only "child" at a distance 0 is
// the node x itself.
dp[j][x] = 1;
} else {
dp[j][x] = 0;
// Else the sum of dp[j-1][y] for every children y of x.
for (int i=0; i<degree[x]; i++) {
int y = G[x][i];
if (y != parent[x]) {
dp[j][x] += dp[j-1][y];
}
}
}
}
}

long long res = 0;
for (int i=0; i<n; i++) {
res += dp[k][i]; //Paths that start at node #i


// Paths that go through node #i, without using the edge connecting it
// to its parent.
long long sum[k+1];
fill(sum, sum+k+1, 0);
int active = 0;
for (int j=0; j<degree[i]; j++) {
if (G[i][j] != parent[i]) {
active++;
for (int p = 0; p <= k; p++) {
sum[p] += dp[p][ G[i][j] ];
}
}
}
if (active > 0) {
long long tem = 0;
for (int j=0; j<degree[i]; j++) {
if (G[i][j] != parent[i]) {
active++;
for (int p = 1; p <= k-1; p++) {
//a: number of paths of length p that go from node i
//and use the edge towards child j.
//b: number of paths of length k-p that go from node i
//and don't use the edge that towards child j.
long long a = dp[p-1][ G[i][j] ];
long long b = sum[k - p - 1] - dp[k - p - 1][ G[i][j] ];
tem += a*b;
}
}
}
res += tem / 2;
}
}

return res;

}
Read More
Posted in codeforces, vkcup | No comments
Newer Posts Older Posts Home
Subscribe to: Posts (Atom)

Popular Posts

  • TopCoder SRM 557 - finally
    SRM 557 Explanation for division 1 Easy and match recap. Explanations for div2 easy and div2 medium. It feels like it has been ages since t...
  • SRM 590 recap and editorial
    Another week another Topcoder match. Not a great day. I had a bad flu and still do. Div1 500: The one with Xor Given a list of cards with nu...
  • 2010's gcj prediction about 2012, how is it going?
    In 2010 I wrote some predictions about Google Code Jam 2012. If I use gcj 2011 do the trends seem to agree? - There will be 5 advancers to ...
  • SRM 589 Editorial
    I have finished writing the editorial for TopCoder SRM 589: http://apps.topcoder.com/wiki/display/tc/SRM+589 . As you most likely noticed. L...
  • c++ and python topcoder generic testers
    A sequel to post: did I just spent all my Saturday customizing my Tester? . I have been improving the idea further. After adapting the ideas...
  • SRM 601 editorial (minus div1 hard)
    It is up: http://apps.topcoder.com/wiki/display/tc/SRM+601 This was a very dry editorial to write. All problems were mathy ad hoc or complex...
  • Glad I am not the world's best programmer
    Update : The incredibly misleading name "Facebook hacker cup" makes Bolivian newspapers fail: Facebook busca al mejor hacker del p...
  • SRM 546: relief
    I figured I should post something about this SRM. I've been very busy these weeks because the semester is ending and I tried to win a t-...
  • SRM 533: Div1 500 MagicBoard explanation
    Finally solved it. It is a nice problem that is worth explaining in a post. You have a grid/board of at most 50x50 cells. Some cells contain...
  • KawgiEdit-pfa with c++ code cleaner and Greed
    I released a new update to my unofficial version of KawigiEdit. Among other minor things, I added ahmed_aly 's unused code cleaner. He m...

Categories

  • acm
  • algorithm
  • answers
  • arenaplugin
  • badday
  • behindthescenes
  • bugs
  • c++
  • censorship
  • codechef
  • codeforces
  • contests
  • crocchamp
  • editorial
  • editorial.srm
  • embarrassing
  • explanation
  • gcj2013
  • gmp
  • goodday
  • google
  • googlecodejam
  • greed
  • groklaw
  • health
  • html
  • httpseverywhere
  • implementation
  • ipsc
  • ispc
  • java
  • kawigiedit
  • kindagoodday
  • lamebook
  • languages
  • lego
  • listedlinks
  • marathon
  • nasa
  • offtopic
  • ouch
  • postmortem
  • postportem
  • practical
  • probably_not_a_good_tip
  • problemsetting
  • programming
  • python
  • quora
  • rant
  • recap
  • slightlygoodday
  • snippet
  • srm
  • stl
  • strategy
  • swerc
  • tco
  • tco12
  • tco13
  • tco2012
  • tco2013
  • ternarysearch
  • topcoder
  • tricks
  • ubuntu
  • uva
  • vjass
  • vkcup
  • wc3
  • zinc

Blog Archive

  • ▼  2014 (1)
    • ▼  January (1)
      • Per problem memory and Time limits in Greed
  • ►  2013 (141)
    • ►  December (14)
    • ►  November (8)
    • ►  October (13)
    • ►  September (11)
    • ►  August (14)
    • ►  July (15)
    • ►  June (13)
    • ►  May (13)
    • ►  April (12)
    • ►  March (11)
    • ►  February (11)
    • ►  January (6)
  • ►  2012 (94)
    • ►  December (5)
    • ►  October (6)
    • ►  September (8)
    • ►  August (6)
    • ►  July (3)
    • ►  June (5)
    • ►  May (8)
    • ►  April (10)
    • ►  March (20)
    • ►  February (16)
    • ►  January (7)
  • ►  2011 (51)
    • ►  December (7)
    • ►  November (12)
    • ►  October (5)
    • ►  September (1)
    • ►  August (3)
    • ►  July (4)
    • ►  June (3)
    • ►  May (7)
    • ►  April (3)
    • ►  March (2)
    • ►  February (1)
    • ►  January (3)
  • ►  2010 (9)
    • ►  December (4)
    • ►  October (1)
    • ►  June (1)
    • ►  May (1)
    • ►  January (2)
  • ►  2009 (1)
    • ►  December (1)
Powered by Blogger.

About Me

Unknown
View my complete profile