Please can anybody tell me why the judge accepts the first one but doesn't accept the second one and gives a time-limit exceeded error. While on my computer with MSVC++ compiler it's exactly the opposite; the first one runs fine while in the second case time is exceeded because the loop doesn't exit with start and end are zero.
[cpp]
int main(int argc, char* argv[])
{
long nStart, nEnd, nMax;
RedNum[1]=1;
while(cin>>nStart>>nEnd)
{
if(nStart<nEnd)
nMax = MaxCycle(nStart, nEnd);
else
nMax = MaxCycle(nEnd, nStart);
cout << nStart << ' ' << nEnd << ' ' << nMax << endl;
}
return 0;
}
[/cpp]
[cpp]
#include <iostream.h>
#define SIZE 1000000
unsigned short MaxCycle(unsigned long Start, unsigned long End);
unsigned short ReduceAlgo(unsigned long n);
unsigned short ReduceAlgo2(unsigned long n);
unsigned short RedNum[SIZE + 1] = {0};
int main(int argc, char* argv[])
{
long nStart, nEnd, nMax;
RedNum[1]=1;
scanf("%d %d", &nStart, &nEnd);
while(nStart!=0 && nEnd!=0)
{
if(nStart<nEnd)
nMax = MaxCycle(nStart, nEnd);
else
nMax = MaxCycle(nEnd, nStart);
printf("%d %d %d\n", nStart, nEnd, nMax);
scanf("%d %d", &nStart, &nEnd);
}
return 0;
}
unsigned short MaxCycle(unsigned long Start, unsigned long End)
{
unsigned short nMax=1, nCur;
for(;Start<=End; Start++)
{
nCur = ReduceAlgo(Start);
if(nCur > nMax)
nMax = nCur;
}
return nMax;
}
/* Recursive */
unsigned short ReduceAlgo(unsigned long n)
{
if(n==1)
return 1;
if(n<SIZE)
{
if(RedNum[n])
return RedNum[n];
if(n%2)
RedNum[n] = ReduceAlgo(3*n + 1) + 1;
else
RedNum[n] = ReduceAlgo(n/2) + 1;
return RedNum[n];
}
else
{
if(n%2)
return ReduceAlgo2(3*n + 1) + 1;
else
return ReduceAlgo2(n/2) + 1;
}
}
/* iterative */
unsigned short ReduceAlgo2(unsigned long n)
{
short ctr=1;
while(n != 1)
{
if(n<SIZE && RedNum[n])
return RedNum[n] + ctr - 1;
if(n%2)
n = 3*n + 1;
else
n = n/2;
ctr++;
}
return ctr;
}[/cpp]

[/cpp]