One Point Solution

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg
Showing posts with label algorithm. Show all posts
Showing posts with label algorithm. Show all posts

Saturday, 30 March 2013

SRM 574 editorial supposedly ready

Posted on 19:34 by Unknown

The editorial for SRM 574 is in a state that can be published. https://apps.topcoder.com/wiki/display/tc/SRM+574.

I would love to say that the huge delay was because I took too long to solve div1 hard quickly (as it usually happens). But this time I had bigger issues, while I actually sort of understood all the problems in the match rather quickly (thanks to help from admins in div1 hard). My on-going recovery from health issues made me take much longer than I planned/expected. Sorry for that, but I am feeling better now.

I think the div1 1050 explanation is terrible. Maybe I will improve it.

It was a fun problem set.

Read More
Posted in algorithm, editorial, srm, topcoder | No comments

Friday, 7 September 2012

SRM 555: 5555555555555555555555

Posted on 17:39 by Unknown

Yeah, I posted it in the TCO blog: http://community.topcoder.com/tco12/srm-555/. Let me talk of what was going on to me:

Waking up at 6:30

I had it all planned up, and set things up to wake up at 6:30, so I could register (Really did not expect it to get any close to the registrants limit).

Unfortunately, I spent just about the whole period from 05:00 to 06:00 waking up to the same lame dream: that I missed the SRM. Only to find out that it was 5:00 and was way early. Arrg, I think it happened at least three times.

Div1 255

Meh, it seems that my brain was not awake when I first tried to solve this problem. At first I thought it was about splitting in multiples of 5 instead of powers of 5. My first code even had funny tricks to avoid considering a single "0" as a number that begins with leading zeros... The whole plan was to simply get the results modulo 5 when translating bits to integer. It was so clever...

But it failed examples. So, it needed powers of five... I had to fix stuff, but had some lame bugs and it delayed me. At the end , 215 points. Is way too slow. My only hope was the div1 555...

Div1 555

I actually saw the correct solution (although overcomplicated by dp for the sub-problem instead of even more binomials.) instantly. Of course, after coding everything here were bugs and bugs. I reached a state in which I was passing all examples but the second-last and third-last. Which was very puzzling, because the example that was seemingly the most complicated (last one) was correct. Surely, with 32 minutes left, I would eventually find the mistake, right? ... right?

I tried many things. I noticed the main difference between the examples I was passing and those I was not was that they were the only cases in which Rcount != Ccount, so I was trying to find any bugs related to it. Then I tried other things, and many others. But I effectively had 31 minutes with the same wrong code and no idea what to do. I even doubted the approach, but it really seemed right.

During the challenge phase, I checked out the other solutions and they were using the same logic. After some time off I opened it in the practice room, and could finally see the mistake right away. It is such a stupid mistake that it makes the drop to 18XX rating even more sad. You can see the code I had during the contest. The bug is with subProblem(er/2, Rcount) (and its column analogous), it should be: subProblem(er/2, H), of course, because the first expression makes no sense. I think I quickly replaced a different bug with Rcount and Ccount without putting a lot of thought and then completely missed it. I did not notice that it was also a main trait of the test cases I was failing, that W!=Rcount and H!=Ccount.

Anyway, this whole thing of SRMs made with mixed problem setters that turn out to have very easy div1 250 and div1 500 that everyone solves except for me that take too long or have bugs is really getting old. It is a perfect rating killing storm.

Codes!

div 2 easy, is really easy:

int theMax(vector <string> board) 
{
int h = board.size(), w = board[0].size();
int res = 0;
// pick a row
for (int i=0; i<h; i++) {
// pick a column
for (int j=0; j<w; j++) {
int ones = 0;
// count the ones
for (int a=0; a<h; a++) {
for (int b=0; b<w; b++) {
// the xor operation ^, is great to simlate toggling...
int o = ( (board[a][b]=='1') ^ (a==i) ^ (b==j) );
ones += o;
}
}
res = std::max(res, ones);
}
}
return res;
}

div2 medium / div1 easy: The lack of a c++ library function to convert a integer to binary is really lame.

int getmin(string s) 
{
int n = s.size();
int dp[n+1];
dp[0] = 0;
int INF = 100;

// make the powers of 5:
long long p = 1;
string pow5[100];
int q = 1;
pow5[0] = bit(p); // the bit(x) function returns x in binary.
while (p <= (1LL<<62) / 5) {
p *= 5;
pow5[q] = bit(p);
q++;
}

// dp part:
for (int t=1; t<=n; t++) {
dp[t] = INF;
for (int i=0; i<q; i++) {
// does it end with the i-th power of 5?
int len = pow5[i].size();
if ( (t - len >= 0) && ( s.substr(t-len, len) == pow5[i] ) ) {
//Yes. Yes, it does.
dp[t] = std::min(dp[t], dp[t - len] + 1);
}
}
}
return ( (dp[n] >= INF) ? (-1) : dp[n] );
}

div2 hard: This guy was completely not standard and not easy (at least not for me.) I think I needed a lot of thought to reach the good method to do a dp program. Like I said in the TCO blog, it is all about what starting point you use for the analysis. I was trying bottom-up dp instead of top-down and it was a true nightmare. (For me, this is the hardest div2 hard in a while).

const int MOD = 555555555; 
typedef long long int64;
#define long int64
long dp[555][554][2][2];
struct MuddyRoad2
{
int theCount(int N, int muddyCount)
{
memset(dp, 0, sizeof(dp) );
dp[0][0][1][1] = 1;
dp[0][0][0][0] = 1;

//dp[i][m][p1][p2] returns the total number of ways
// to set muddy segments if:
// * We have already assigned segments higher than i
// * p1 is the parity of the number of paths for i+1
// * p2 is the parity of the number of paths for i+2
// * There are m muddy roads left to mark.
//
for (int i=1; i<=N-1; i++) {
for (int p1 = 0; p1 < 2; p1++) {
for (int p2 = 0; p2 < 2; p2++) {
for (int m=0; m<=muddyCount; m++) {
long & res = dp[i][m][p1][p2];
// do nothing
res = dp[i-1][m][ (p1 ^ p2) ][p1];
// place a 0
if ( (m > 0) && (i < N-1) ) {
res += dp[i-1][m-1][0][p1];
res %= MOD;
}
}
}
}

}
// this way p1^p2 = 1 for i=N-1 :)
return dp[N-1][muddyCount][0][1];
}
};
#undef long

Div1 medium: This dreaded problem was easy but that's not a good thing when you do it wrong for a lame reason and everyone else solves it.

 
long C[3200][3200];
int count(int H, int W, int Rcount, int Ccount, int S)
{
long res = 0;
memset(C, 0, sizeof(C));
// Pascal's triangle is a combinatorics problem coder's best friend
for (int i=0; i<=3199; i++) {
C[i][0] = 1;
for (int j=1; j<=i; j++) {
C[i][j] = (C[i-1][j-1] + C[i-1][j]) % MOD;
}
}
for (int r = (Rcount % 2); r <= Rcount && r <= H; r += 2) {
for (int c = (Ccount % 2); c <= Ccount && c <= W; c += 2) {
int tem = (H - r) * c + (W - c) * r;
if (tem == S) {
cout << r << ", "<<c<<endl;
int er = (Rcount - r)/2; //extra
int ec = (Ccount - c)/2;
long prod = 1;
prod = (prod * C[H][r]) % MOD;
prod = (prod * C[W][c]) % MOD;
prod = (prod * C[H-1 + er][H-1]) % MOD;
prod = (prod * C[W-1 + ec][W-1]) % MOD;
res += prod;
}
}
}
return (int)(res % MOD);
}
Read More
Posted in algorithm, badday, srm, topcoder | No comments

Sunday, 2 September 2012

SRM 554

Posted on 19:09 by Unknown

I posted something about SRM 554 TCO blog. Extra comments:

I had quite a silly luck this time. I do not why, but I took very long in the 250 points one. Probably because I went from the general case to the specific case instead of the opposite. So I was just about to solve the problem finding the union of three arithmetic sequences, until I started doing an extra analysis to notice that many of the intersections are not possible.

Pretty code for that problem:

int find(int redCount, int redHeight, int blueCount, int blueHeight) 
{
return
+ min(redCount, blueCount)
+ 1 + min(redCount-1, blueCount)
+ 1 + min(redCount, blueCount-1)
- (redHeight == blueHeight) * (min(redCount, blueCount) );
}

For div1 500, I messed up even more spectacularly. I reached the conclusion of the condition that was necessary to reach the optimal result (but I did not think to prove that it is also sufficient, knowing that it was also sufficient would have saved me a lot of problems). The problem is that after that, I used a dynamic programming approach. I took some time to code it, until I found that I was failing the last example (Which does not make sense, because the condition IS necessary). I did a quick fix by adding a dimension to the dp. The quick fix was not necessary, but it passed the examples so I submitted the problem.

Then I noticed that I had too many dimensions and my approach could be too slow (It was n6 in theory, but maybe it runs faster). I tried some random test cases, until I found one that was not timing out, but instead breaking an assertion I added while debugging the first bug. It turns out that I was sorting an array after I make the copy that was in use by the dynamic programing algorithm. So, I fixed that bug, which fixed the assertion, but now, as I suspected, was timing out. I figured that maybe that lame bug was the one that caused my initial solution to fail. There was only 1 minute left. Somehow, I managed to get rid of the extra dimension in the dp, pass examples and re-submit before the end of the coding phase.

Challenge phase was more about feeling very nervous. I felt the approach was right, but overcomplicated , so there was plenty of room for failure. At the end I passed. (yay)

Here is pretty code for it:

vector<int> find(vector<int> heights) 
{
int n = heights.size();
vector<int> res(n, 0), used(n, false);
used[0] = true;
//res[0] = 0 is always possible.
// Yes, it is always possible to choose any arbitrary first element and still
// follow the condition (non-increasing and then non-decreasing)
//
for (int i=1; i<n; i++) {
for (int j=n-1; j>=0; j--) {
if (! used[j]) {
if (heights[j] <= heights[ res[i-1] ] ) {
//this is always fine.
// If an element j exists such that:
// heights[j] < heights[res[i-1])
//
// It means that the next case was never reached. Thus it is
// still possible to do it.
//
// if heights[j] = heights[res[i-1]], then it can count as
// either of the cases and also fine.
res[i] = j;
} else {
// If the new element is greater, then it must forcefully be
// equal to the minimum of the remaining elements so that the
// rest of the elements are placed in non-decreasing order.
bool can = true;
for (int k=0; k<n; k++) {
can &= (used[k] || (heights[k] >= heights[j]) );
}
if (can) {
res[i] = j;
}
}
}
}
used[res[i]] = true;
}
return res;
}

As you can see, Figuring out (and proving) that the condition is not only necessary but also sufficient allows a VERY simple approach.

Div2 1000 was cute. Here is code for it too:

const int MOD = 1234567891; 
#define for_each(q, s) for(typeof(s.begin()) q=s.begin(); q!=s.end(); q++)
struct TheBrickTowerHardDivTwo
{
int pow5[5];
int mem[8][48][5*5*5*5];

// I encode each state as a single number in base 5.
// (I added a fifth color that is a wildcard. So that the top-most row
// in a dp can add any colors without decreasing K).
//
// The transition array saves all the possible transitions from a state
// of colors to another AND the value we have to decrease from K.
// It is sorted non-decreasingly by the value to decrease from K, so that
// we can stop when K would get less than 0.
vector<pair<int,int> > transition[5*5*5*5];


int rec(int K, int H, int state)
{
int &res = mem[K][H][state];
if (res == -1) {
if (H==0) {
res = 1; //empty
} else {
long long tem = 0;
// Iterate through the list of transitions, try the transition
for_each(q, transition[state]) {
int nk = K - q->first;
if (nk >= 0) {
tem += rec(nk, H-1, q->second);
} else {
break;
}
}
res = (int)( tem % MOD);
}
}
return res;
}

int find(int C, int K, int H)
{
pow5[0] = 1;
for (int i=1; i<=4; i++) {
pow5[i] = 5*pow5[i-1];
}
memset(mem, -1, sizeof(mem));

// make the transitions
for (int state=0; state<pow5[4]; state++) {
for (int newstate=0; newstate < pow5[4]; newstate++) {
bool valid = true;
int krem = 0;
for (int i=0; i<4; i++) {
int x = (newstate / pow5[i])%5;
// use only C colors...
valid &= ( x < C);
// sharing face with the above brick
if ( (state/pow5[i]) % 5 == x) {
krem++;
}
// We represent the colors in this way.
// [0][1]
// [3][2]
// This means that a cube is adjacent to the next and previouis
// index. Which translates to us needing to check index (i+1)%4
int y = (newstate / pow5[ (i+1) % 4 ]) % 5;
if (y == x) {
krem ++;
}
}
if (valid && (krem <= K) ) {
transition[state].push_back( make_pair(krem, newstate) );
}
}
sort(transition[state].begin(), transition[state].end());
}
long long res = 0;
for (int i=1; i<=H; i++) {
res += rec(K, i, pow5[4] - 1 );
}
return (int)(res % MOD);
}
};

Read More
Posted in algorithm, srm, topcoder | No comments

Thursday, 23 August 2012

SRM 553

Posted on 08:34 by Unknown

I posted stuff to the TCO blog: http://community.topcoder.com/tco12/happened-in-srm-553/

More things to say:

  • I did not really want div1 250 to be so tricky. In fact, the second-last example is supposed to detect overflow. Apparently, it only detects overflow in the specific solution I was trying, a different kind of overflow was not detectable, sorry.
  • I was expecting this to be an awful problem set (Except for div1 hard). But it seems reception was mostly positive. Ok...
  • I was very happily writing that TCO blog post, then I noticed that the handle tag script I wrote was failing. I then remembered that profile pages were updated... Lucky me it actually did not take me a lot of time to update my script. If you used it, you can get the update from its post.

Nice codes for the problems:

Div2 250

A good balance is to iterate for the number of platypuses (or platypy, platypeople? whatever).

int minimumAnimals(int webbedFeet, int duckBills, int beaverTails) 
{
for (int p=0; p<=duckBills && p<=beaverTails; p++) {
int d = duckBills - p; //number of ducks
int b = beaverTails - p; //number of beavers
// verify
if (p*4 + d*2 + b*4 == webbedFeet) {
return p+d+b;
}
}
// this is not reached, but in the judge solution I use it to verify
// that the test case passes constraints...
return -1;
}

It needs at most 500 iterations. Crude bruteforce shall work too, unless you do a good work in making it very unoptimized.

This also works:

return webbedFeet / 2 - beaverTails;

Why does it work? Well, try simplifying the equations derived from the first code and you shall see, eventually.

Div2 500 / Div1 250

Again, I really like Petr's solution. rng_58 was the first to try something like that. This is a very concise version:

const int INF = 2000000000; 
int simulate(vector<int> program, int x)
{
// x determines what integer to replace -1 with.
stack<int> S;
// this way return S.top() will always return something
S.push(0);
for (int i=0; i<program.size(); i++) {
int p = ( (program[i]==-1) ? x : program[i] );
if (p == 0) {
if (S.size() > 1) {
int a = S.top(); S.pop();
int b = S.top(); S.pop();
// INF prevents overflow (I just dislike
// typing long long that much)
S.push( (a > INF - b)? INF : (a+b) );
} //Else there is nothing to do.
} else {
S.push(p);
}
}
return S.top();
}
int findMissing(vector <int> program, int wantedResult)
{
if (simulate(program, 0) == wantedResult) {
// If 0 works, it is the result.
return 0;
}
int a = simulate(program, 1);
int x = wantedResult - a + 1;
int b = simulate(program, 2);
// The equation is : a - 1 + x = wantedResult

// If they are equal the result is constant and cannot
// be changed. If x <= 0, then there is no valid result
// (Using x = 0 is not possible, because 0 has a special meaning)
return ( (a == b) || (x <= 0) )? -1 : x;
}

Div2 1000:

It is a polynomial time dp. O(n4)

#define for_each(q, s) for(typeof(s.begin()) q=s.begin(); q!=s.end(); q++) 
struct SafeRemoval
{
vector<int> modsum[4];
int finish;

int dp[51][51][51][51];

// modsum[i][x] returns the sum of the x largest numbers that are = i modulo 4
int rec(int n0, int n1, int n2, int n3)
{
int & res = dp[n0][n1][n2][n3];
if (res == -1) {
res = 0;

int total = modsum[0][n0] + modsum[1][n1]
+ modsum[2][n2] + modsum[3][n3];

// The finishing state is when there are (finish) numbers left.
// ( finish = n - k )
if (finish == n0 + n1 + n2 + n3) {
//base case:
res = total;
} else {
// remove a number that is: 0 mod 4
if ( (n0 > 0) && (total % 4 != 0) ) {
res = std::max(res, rec(n0-1, n1, n2, n3) );
}
// remove a number that is: 1 mod 4
if ( (n1 > 0) && (total % 4 != 1) ) {
res = std::max(res, rec(n0, n1-1, n2, n3) );
}
// remove a number that is: 2 mod 4
if ( (n2 > 0) && (total % 4 != 2) ) {
res = std::max(res, rec(n0, n1, n2-1, n3) );
}
// remove a number that is: 3 mod 4
if ( (n3 > 0) && (total % 4 != 3) ) {
res = std::max(res, rec(n0, n1, n2, n3-1) );
}

}
}
return res;
}

int removeThem(vector <int> seq, int k)
{
finish = seq.size() - k;
// sort in reverse!
sort(seq.rbegin(), seq.rend());
for (int i=0; i<4; i++) {
modsum[i].push_back(0);
}
// Make the sums:
for_each(q, seq) {
modsum[*q % 4].push_back(*q + *modsum[*q % 4].rbegin() );
}
memset(dp, -1, sizeof(dp));

// We initially have all the numbers:
int res = rec( modsum[0].size()-1, modsum[1].size()-1,
modsum[2].size()-1, modsum[3].size()-1);

// 0 is a good invalid value. It is impossible for a valid result
// to be 0, because k is strictly less than n.
return ( (res==0) ? -1 : res );
}
};

The first version of the problem had n<=30 and the modulo was not fixed to 4. It was a variable m that could be at most 10. The idea is the same, but encoding the dp state is not as easy. Just use a map or hash table to use whole vector as key.

Div1 500

This problem is very evil implemenation-wise. I cannot provide less messy code than what you can already see submitted. Sorry.

Read More
Posted in algorithm, srm, topcoder | No comments
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