I'm trying to solve this problem of SPOJ: http://br.spoj.com/problems/GENERAL/
My solution works in Ideone (http://ideone.com/Xj2B9Y), but when I put the same solution in SPOJ, it reports that TLE - Time Limit Exceeded.
I have searched in the Internet to find a solution to improve my code. I replaced the "Scanner" by "BufferedReader", but I keep getting the message TLE.
Please could someone tell me where I am going wrong?
public static void main(String[] args) throws java.lang.Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
//Scanner scan = new Scanner(System.in);
int instancias = Integer.parseInt(br.readLine());
int count = 0;
while(instancias != 0)
{
count = 0;
boolean possible = true;
boolean impossible = false;
st = new StringTokenizer(br.readLine());
int numSoldados = Integer.parseInt(st.nextToken());
int distancia = Integer.parseInt(st.nextToken());
int[] listaSoldados = new int[numSoldados];
st = new StringTokenizer(br.readLine());
for (int i = 0; i < numSoldados; i++)
{
listaSoldados[i] = Integer.parseInt(st.nextToken());
}
while(possible)
{
possible = false;
for (int i = 0; i < numSoldados; i++)
{
if(numSoldados - (i + distancia) >= 1)
{
int alturaPS = listaSoldados[i];
int alturaSS = listaSoldados[i + distancia];
if(alturaPS > alturaSS)
{
listaSoldados[i] = alturaSS;
listaSoldados[i + distancia] = alturaPS;
count = count + 1;
possible = true;
}
}
else
{
if(!possible)
{
for (int j = 0; j < numSoldados - 1; j++)
{
if(listaSoldados[j] > listaSoldados[j+1])
{
impossible = true;
break;
}
}
break;
}
break;
}
}
}
if(impossible)
System.out.println("impossivel");
else
System.out.println(count);
instancias--;
}
}