One Point Solution

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

Monday, 10 September 2012

Codeforces #137 (div2) C. Reducing Fractions - update

Posted on 10:53 by Unknown

I intended to return to participating in Codeforces. Today there was a division 2 match which would be good to restart engines. It didn't go so well at first, with site issues at the announced start time. Then they delayed the start of the match by 15 minutes. I had to wait more time.

Eventually I started by solving problem C. Things were going great until I tried to submit. But I could not. At first I thought it was a bug that I had in the past in division 2 matches - That "unofficial" coders were not able to submit due to a bug. But it turns out that I was just not registered. Which is strange, as I remember that around 1 hour before the contest I clicked register and had to login. And then I remember the register button not appearing anymore, so I thought I registered... Oh well.

C. Reducing Fractions

Link to problem statement

Ok, so, let us reduce a fraction. Unfortunately the numerator is expressed as a product of up to 105 numbers each from 1 to 107 and the denominator as well. The result must be printed using the same format.

Of course we cannot just multiply and then reduce. But either way, each number in the product is either going to be a prime number smaller than 107 or a composite composed of prime numbers less than 107. We could actually just keep two arrays. Each counting the number of times a prime factor appears in total in the numerator and the denominator. After getting these arrays, we can do the reduction easily: For example, let us say we have 20*6 as numerator and 2*7 as denominator. Then we have that 2 appears 3 times in total in the numerator (20 has 2, 6 has 1) and once in the denominator. Simply subtract the minimum count for each prime factor - Thus we have that in the reduced fraction, 2 will appear once in the numerator and 0 times in the denominator.

Some analysis. Each number from 1 to 107 has at most log(X) prime factors. So in total the subtraction part will take O(n * log(X)) for X <= 107. The real complication comes when extracting the prime factors of each number.

I am not sure if the usual O(sqrt(X)) algorithm to extract prime factors would be fast enough, 105*sqrt(107) might be too much for 2 seconds. But in fact, we can make an algorithm that is quite fast at extracting all prime factors of a lot of numbers with a fixed bound. The trick is to use a modified version of the Sieve of Eratosthenes, that instead of only marking if a number is prime or not, marks the number's first prime factor (for a prime number, the result is itself). By precalculating each number's first prime factor you can then use an iterative algorithm to extract all the prime factors of a number in O(log(X)) time (exactly the number of prime factors).

The second issue is, once you have the reduced counts of each prime factor, how to rebuild the two lists of integers in the original format. My intuition tells me that just multiplying each available factor from smallest to largest until the limit of 10/ is reached for an element (and then skip to the next) should be fast enough. Assuming that the original input was also in this format.

old wrong code was here

It seemed like a good problem. Approachable but not without tricks you had to do and suspense (still not sure it is guaranteed to always follow the required conditions for the output.

After figuring out I was not registered, I stopped caring for the match. Perhaps will try to make a virtual context for it, simulating the time I spent in this problem (I finished coding and testing it at 12:11).

Update: I tried it in practice and I failed test 42. Most likely because of an assert related to the limit on the number of integers in the output. Such a high test number tells me this was not even in the sample tests, yet it changes the problem as it means it is not trivial to correctly build the results.

But instantly after, it occurred to me that there is a simple idea for an algorithm that would be guaranteed to follow the conditions. Simply, iterate through each element of a, and for each of its prime factors, subtract it from the number of times that factor should appear, if the current count is 0, remove the factor from the element. Do the same with b.

int n, m; 
int a[100000];
int b[100000];

const int MAX = 10000000;
int firstFactor[MAX+1];

int countA[MAX+1];
int countB[MAX+1];


void addCounts(int x, int * counts)
{
// How to extract prime factors from a number x.
// counts[] stores the number of times each prime factor appears.
while(x != 1) {
int p = firstFactor[x];
// just divide
while (x % p == 0) {
x /= p;
counts[p]++;
}
//the new value of x is not a multiple of p, and thus will have a
// different value for firstFactor[x] - the next prime factor...
}
}

// Rebuild the set of integers for the output.
// counts[] stores the number of times each prime factor should appear.
void buildIt(int* counts, int* res, int & t)
{
for (int i=0; i<t; i++) {
int x = res[i];
while (x > 1) {
int p = firstFactor[x];
x /= p;
if ( counts[p] > 0) {
counts[p]--;
} else { //remove it
res[i] /= p;
}
}
}
}
void solve()
{
memset(countA, 0, sizeof(countA));
memset(countB, 0, sizeof(countB));
for (int i=0; i<n; i++) {
addCounts(a[i], countA);
}
for (int j=0; j<m; j++) {
addCounts(b[j], countB);
}
for (int i=2; i<=MAX; i++) {
int s = std::min(countA[i], countB[i]);
countA[i] -= s;
countB[i] -= s;
}
buildIt(countA, a, n);
buildIt(countB, b, m);

}

inline void init()
{
//Modified sieve of Erathostenes:
//firstFactor[x] will tell us the first prime factor of x.
memset(firstFactor, 0, sizeof(firstFactor));
for (int i=2; i<=MAX; i++) {
if (firstFactor[i] == 0) {
// prime
firstFactor[i] = i;
for (int j=i+i; j <= MAX; j += i) {
if (firstFactor[j] == 0) {
firstFactor[j] = i;
}
}
}
}
}
Read More
Posted in codeforces, explanation, ouch | 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
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