hxano's blog

By hxano, history, 3 weeks ago, In English

Today I tried to solve 1932F - Feed Cats, and finally got Accepted, though not after some hard debugging. You can give a try at the problem first before reading this.

Here is my original submission with WA on test 3 268592520 and here is my AC submission 268597071.

My thought process went like this:

  • I thought of a segment tree with sweepline style solution

  • Though using segment tree with n=10^6 is very risky (high constant time)

  • So I went ahead and compress the coordinates of the start point and end point of each segment.

  • Query an addition at the compressed start point and a removal at the (compressed end point) +1.

This is WRONG, however. Since there is a chance of nothing happening at the compressed end point and something else happening at the (compressed end point) +1 that might influence the answer, this can give a wrong result. The really important part is the compressed (end point +1) where the removal ACTUALLY happens, which I failed to realise for 90 minutes.

Did I learn my lesson? Yes. Did you waste your time reading something you already know/ don't need to know yet? I hope not. Either way, perhaps I will leave this blog here as a cautionary tale for myself, to better tackle future problems I will have to solve.

Full text and comments »

  • Vote: I like it
  • +18
  • Vote: I do not like it

By hxano, history, 5 months ago, In English

The problem goes as follows:

You are given an array a of N non-negative integers, indexed from 1 to N. Define prev(x) such that prev(x) is the largest integer that satifies both following conditions: prev(x) < x, and a[prev(x)] < x. Print prev(i) for each i from 1 to N.

This is a basic problem that can be solved using stacks. However, I've seen an interesting implementation that avoids data structures altogether. Here's the main code for it:

cin>>n;
for (int i=1; i<=n; ++i) cin>>a[i];
a[0]=-inf;
for (int i=1; i<=n; ++i){
    int p=i-1;
    while (a[p]>=a[i]) p=sol[p];
    sol[i]=p;
}
for (int i=1; i<=n; ++i) cout<<sol[i]<<" "; cout<<"\n";
return 0;

It seems to me that this runs in O(n) on average, but I cannot find its worst-case complexity. I suspect it to be O(n^2) but have had no luck proving it so far (I once used this implementation in a practice problem and got TLEed). Any help would be greatly appreciated. Thanks!

Full text and comments »

  • Vote: I like it
  • +8
  • Vote: I do not like it