When the algorithm is correct, but still TL

  • Tutorial
Many are surprised, but how do different people solve problems in such a way that they are taken instantly or almost instantly ? The answer is simple: they make a lot of interesting experiments, optimize the code, and sometimes come up with funny results. Here I will bring a few of mine.

Reading integers

1. Accepted in 0.193
std::ios_base::sync_with_stdio(0);
//...
std::cin >> a[i];
2. Accepted in 0.187
scanf("%d", &a[i]);
3. Accepted in 0.109
int nextInt() {
    int res = 0,c = getchar();
    while(c < '0' || c > '9') c = getchar();
    while(c >= '0' && c <= '9') {
        res = res * 10 + c - '0';
        c = getchar();
    }
    return res;
}
//...
a[i] = nextInt();
4. Accepted in 0.098
a[i] = 00;
c = getchar();
while(c < '0' || c > '9') c = getchar();
while(c >= '0' && c <= '9') {
    a[i] = a[i] * 10 + c - '0';
    c = getchar();
}

The most interesting is the sharp difference between the second and third paragraph. The third and fourth are also interesting: after all, in the last there is a multiple access to the array element, which in theory requires more time than calling the function once.

Array Access

1. Time Limit Exceeded (test 9)
for(int i = 0; i < n; i ++) {
    //Много операций с array[i]
}
2. Accepted
for(int i = 0; i < n; i ++) {
    double x = array[i];
    //Много операций с x
}
Perhaps these observations can help someone. Let’s say, they helped me :)

Also popular now: