I need help. I can't figure out why my program works differently in main function and in any other function, lets say solve() function. I want to solve this problem http://codeforces.com/contest/768/problem/B?locale=en. I have written the code and it works fine, but gets time limit in the server. My code is like this and it works fine when I compile it:
#include<iostream>
#include<windows.h>
#include<math.h>
#include<algorithm>
#include<map>
#include<list>
#include<iterator>
using namespace std;
main()
{
list < int > li;
list < int >::iterator i;
list < int >::iterator end = li.begin();
int n, l, r, buffer, ans = 0;
cin >> n >> l >> r;
li.push_back(n);
for(i=li.begin(); i!=li.end(); i++)
{
while(*i>1)
{
buffer = *i;
i = li.erase(i);
li.insert(i, buffer/2);
li.insert(i, buffer%2);
li.insert(i, buffer/2);
}
}
advance(end, r+1);
i = li.begin();
for(advance(i, l-1); i!=end; i++)
ans += *i;
cout << ans << endl;
return 0;
}
When I rewrited the code like this, it stopps working properly, so I think the time limit is because of this:
#include<iostream>
#include<windows.h>
#include<math.h>
#include<algorithm>
#include<map>
#include<list>
#include<iterator>
using namespace std;
int solve()
{
list < int > li;
list < int >::iterator i;
list < int >::iterator end = li.begin();
int n, l, r, buffer, ans = 0;
cin >> n >> l >> r;
li.push_back(n);
for(i=li.begin(); i!=li.end(); i++)
{
while(*i>1)
{
buffer = *i;
i = li.erase(i);
li.insert(i, buffer/2);
li.insert(i, buffer%2);
li.insert(i, buffer/2);
}
}
advance(end, r+1);
i = li.begin();
for(advance(i, l-1); i!=end; i++)
ans += *i;
cout << ans << endl;
}
main()
{
ios_base::sync_with_stdio(false);
solve();
return 0;
}
Anybody knows why?