why does my algorithm only work for the first values of n? (ACM problem baggage 2014)

0

The problem is simple, order 2n (3 ≤ n ≤ 100) pairs of letters BABABABA by moving blocks of letters (you always have to move a pair of continuous letters to two continuous empty spaces) to arrive at an expected result AAAA .. ..ABBBBB ... BBBB showing the least amount of movements to be made

I have managed to identify a pattern for n ≤ 7

1- Mark the position of the first empty block (-1 and 0)

2- Mark the last pair AB as an empty position and move it towards the previous empty block (with the condition that B is not forming a pair with another B)

3- Mark the first BA block found after position 1 and move it to the previous empty block.

Repeat 2 and 3 until the condition of 2

is not met
  

Example of my algorithm for n = 7:

     

.. BABABABABAB AB To move the last AB (position 12 to -1):

     

ABBA BA BABABAB..A move the first BA (position 3 to 12):

     

ABBA..BAB AB ABBA move the last pair AB before a pair already done   (position 8 to 3)

     

ABBAAB BA B .. ABBAA move the first BA after position 1   (position 5 to 8) and order the AABB pairs formed

     

ABBAAB..BBAABBAA

     

A..AABBBBBAABBAA

     

AAAAABBBBB..BBAA

     

AAAAABBBBBBB..AA

     

AAAAAAABBBBBBB ..

I include my algorithm for the first part of the order:

    public void emparejarAAyBB(int pos){ // pos = posicion a remplazar
    System.out.println("PAREJA AB");
    int bloqueAux = tomarUltimoAB();
    moverBloque(bloqueAux,pos); // el bloque que fue movido se elimina por lo que se guarda en una variable auxiliar
    System.out.println("PAREJA BA");
    int bloqueAux2 = tomarPrimerBA();
    moverBloque(bloqueAux2,bloqueAux);
    if(tomarUltimoAB()!=-1){        // si hay otro bloque AB que cumpla los requisitos se repite el ciclo
        emparejarAAyBB(aux2);
    }
    ordenarParejas(aux2);
}

This pattern is only valid for n ≤ 7, it is not valid for other values larger than n, so it does not solve my problem. I've thought about doing it by brute force or recursively resounding a n > 7 from a n minor but the truth I have been stuck in this.

    
asked by Cristian Figueroa 04.11.2018 в 21:59
source

0 answers