-1

For a problem

https://codeforces.com/problemset/problem/760/B

when i submitted solution having declaration inside int main() it shows TLE, but when declaration is above int main(), it's accepted in c++.

So my question is does global declaration affects the compilation speed significantly or i am missing something?

Here is the accepted one :

#include<bits/stdc++.h>
using namespace std;
int n,k,m,a=1,c=1;

int main()
{
    cin>>n>>m>>k;

    m -= n;
    while (m>0){

        if (k+a<=n) c++;
        if (k-a>=1) c++;
        m -=c;
        a++;
    }
    cout<<a;
    return 0;
}

here is TLE one :

#include<bits/stdc++.h>
using namespace std;

int main()
{
int n,k,m,a=1,c=1;

    cin>>n>>m>>k;

    m -= n;
    while (m>0){

        if (k+a<=n) c++;
        if (k-a>=1) c++;
        m -=c;
        a++;
    }
    cout<<a;
    return 0;
}
cigien
  • 50,328
  • 7
  • 37
  • 78
gaurav
  • 336
  • 2
  • 12
  • 4
    You worry about the effects that a global variable might have on compilation time, but [include the whole standard library, when you would only need `iostream`](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) :D – churill May 23 '20 at 06:09
  • 3
    TLE is for execution. The compilation speed is not relevant. What optimizations is this program being run with? – cigien May 23 '20 at 06:12
  • @cigien I believe that online judge uses GCC with -O2. – BessieTheCookie May 23 '20 at 06:18
  • It's probably because having the local variables in this case just happens to affect the way the compiler optimize your code and makes it a little slower. There shouldn't be any significant difference in general though. – BessieTheCookie May 23 '20 at 06:25
  • Uugh... yep, sure are.... Missed that... Then I guess the answer would be ... 40 years ago (with C) declaring variables as global made sense because stack space was limited -- now it is simply an anachronism you may find referenced in some very very old documentation. – David C. Rankin May 23 '20 at 06:28
  • Avoid that bits include please – Michael Chourdakis May 23 '20 at 07:33

1 Answers1

2

There should be no difference. If your sample size is small (you submitted both solutions once or twice), perhaps you were on the border of Time Limit Exceeded vs not, and just got lucky sometimes.

John Zwinck
  • 207,363
  • 31
  • 261
  • 371