TLE when while(tc- -) is used
When I submitted my solutions(mostly containing while loops) to some problems I am getting TLE. Whenever I replaced those while loops with the equivalent for loop, my code gets executed successfully and gets an AC.
Here is my code snippet which gets either TLE or some type of Runtime error, when while loops are used.
#include using namespace std;
int main()
{
#ifndef ONLINE_JUDGE
freopen(“input.txt”, “r”, stdin);
freopen(“output.txt”, “w”, stdout);
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int tc, n, laddus, rank, severity;
cin >> tc;
string origin, s;
while(tc-- )
{
laddus = 0;
cin >> n >> origin;
while(n-- )
{
cin >> s;
if (s == “CONTEST_WON”) {
cin >> rank;
if (rank <= 20) laddus += 300 + (20 - rank);
else laddus+= 300;
}
else if (s == “TOP_CONTRIBUTOR”) laddus += 300;
else if (s == “BUG_FOUND”) {
cin >> severity;
laddus += severity;
}
else if (s == “CONTEST_HOSTED”) laddus += 50;
}
if (origin == “INDIAN”) cout << laddus / 200 << “\n”;
else if (origin == “NON_INDIAN”) cout << laddus / 400 << “\n”;
}
}
And here is my code snippet when I replaced the while loops with the equivalent for loops and got AC:
#include using namespace std;
int main()
{
#ifndef ONLINE_JUDGE
freopen(“input.txt”, “r”, stdin);
freopen(“output.txt”, “w”, stdout);
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int tc, n, laddus, rank, severity;
cin >> tc;
string origin, s;
for (int i = 0; i < tc; i++)
{
laddus = 0;
cin >> n >> origin;
for (int j = 0; j < n; j++)
{
cin >> s;
if (s == “CONTEST_WON”) {
cin >> rank;
laddus += 300;
if (rank <= 20) laddus += 20 - rank;
}
else if (s == “TOP_CONTRIBUTOR”) laddus += 300;
else if (s == “BUG_FOUND”) {
cin >> severity;
laddus += severity;
}
else if (s == “CONTEST_HOSTED”) laddus += 50;
}
if (origin == “INDIAN”) cout << laddus / 200 << “\n”;
else if (origin == “NON_INDIAN”) cout << laddus / 400 << “\n”;
}
}
I want to add that, it is happening with not only this code, but I had the same issue when solving other problems with while and got TLE.
I am wondering why it is happening like this. I don't why this happens or is there any mistake in my code. I would like to know why this happens. Thanks in advance!