/* Bianco e nero (selezioni nazionali 2002) Copyright (C) 2002 Paolo Boldi This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include #include #define MAXN 1000 /* Chiamiamo "blocco" una sequenza di perline dello stesso colore consecutive. Per esempio, se la collana è BBBNNNBNBB, ci sono 4 blocchi (il primo blocco che si incontra è NNN, seguito dal blocco B, seguito dal blocco N, seguito dal blocco BBBBB, che è a cavallo della fine. In ogni istante, col[0],...,col[N-1] contiene i colori della collana, e num[0],...,num[N-1] i numeri delle perline. */ char col[MAXN]; int N, num[MAXN]; void swapi( int *a, int *b ) { int c = *a; *a = *b; *b = c; } void swapc( char *a, char *b ) { char c = *a; *a = *b; *b = c; } int main() { FILE *r, *w; int i, j, k; r = fopen( "input.txt", "r" ); w = fopen( "output.txt", "w" ); fscanf( r, "%d ", &N ); for ( i = 0; i < N; i++ ) { fscanf( r, "%c", &col[i] ); num[i] = i+1; } fclose( r ); for ( ;; ) { /* Cerco il primo indice i dopo il quale inizia un blocco nuovo */ i = 0; while ( i < N && col[i] == col[(i+1)%N] ) i++; /* Indice non trovato: vuol dire che sono tutte dello stesso colore! */ if ( i >= N ) { fclose(w); return 0; } /* Cerco la fine del blocco (cioè l'inizio del blocco successivo) */ j = i+1; while ( j < N && col[j] == col[(j+1)%N] ) j++; /* Il seguente if non si deve verificare mai (si può sostituire con un assert) */ assert( j < N ); /* Cerco la fine del secondo blocco */ k = j+1; while ( k < N && col[k] == col[(k+1)%N] ) k++; /* Indice non trovato: vuol dire che ci sono solo due blocchi! */ if ( k >= N ) { fclose(w); return 0; } /* Inverto i blocchi */ fprintf( w, "%d %d\n", num[i+1], num[k] ); for ( j = i+1; j <= (k+i+1)/2; j++ ) { swapi( &num[j], &num[k+i+1-j] ); swapc( &col[j], &col[k+i+1-j] ); } } return 0; }