== Got TLE on OJ? Here is the solution! ==

时间:2023-03-09 00:28:26
== Got TLE on OJ? Here is the solution! ==

As a solo warrior in OJ, I spent about nearly 50% of my time on tackling TLE - that is innumerous hours. I almost lost my courage to OJ.But thanks to this post: http://www.spoj.com/forum/viewtopic.php?f=3&t=7968. I didn't use all of the hints, but getchar_unlocked works like charms.

As advised, cin\cout is too slow. For example, my Dijkstra using cin\cout took 25+ seconds, but after using the below code piece to get ints:

#define gc getchar_unlocked
int read_int()
{
char c = gc();
while(c<'' || c>'') c = gc();
int ret = ;
while(c>='' && c<='') {
ret = * ret + c - ;
c = gc();
}
return ret;
}
void print_fast(char *p)
{
fwrite_unlocked(p, , strlen(p), stdout);
}

The same code ran only 11.34 seconds. Please note that, _unlocked API are not available on every platform - never mind, SPOJ has it.

And by the way, std::sync_with_stdio(false) gave segment error. I don't know why.