olimpíadas internacionais de informática (ioi’2006)³rio de actividades ioi 2006... · cada ano...

37
Associação para a Promoção e Desenvolvimento da Sociedade da Informação Olimpíadas Internacionais de Informática (IOI’2006) Relatório de Actividades Novembro 2006 Patrocínio Principal Patrocínio

Upload: vuhanh

Post on 20-Jan-2019

214 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

Associação para a Promoção e Desenvolvimento da Sociedade da Informação

Olimpíadas Internacionais de Informática (IOI’2006)

Relatório de Actividades

Novembro 2006

Patrocínio Principal Patrocínio

Page 2: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

Olimpíadas Internacionais de Informática (IOI’2006)

Relatório de Actividades Pág. 2

ÍNDICE

1. Introdução .........................................................................................................................3 2. Conclusões .......................................................................................................................4

ANEXOS...............................................................................................................................5 Anexo I - Sítio na Internet ( http://www.ioi2006.org/ )...................................................6 Anexo II - Problemas da prova de selecção no final do estágio ...................................8 Anexo III - Classificações da prova de selecção no final do estágio............................15 Anexo IV - Problemas das duas provas nas IOI...........................................................17 Anexo V - Resultados..................................................................................................30 Anexo VI - Fotografias dos concorrentes e professores...............................................36

Page 3: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

Olimpíadas Internacionais de Informática (IOI’2006)

Relatório de Actividades Pág. 3

1. Introdução As Olimpíadas Internacionais de Informática, IOI – International Olympiad in Informatics – http://olympiads.win.tue.nl/ioi, são uma das seis olimpíadas de ciência, destinadas estudantes do ensino secundário de todo o mundo. As outras são as Olimpíadas da Matemática, da Física, da Química, da Biologia e da Astronomia. O objectivo principal das Olimpíadas Internacionais de Informática é estimular o interesse dos jovens pela informática e pelas tecnologias da informação. Os vencedores das IOI em cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas mundiais no domínio da Informática. Este ano, a Olimpíada Internacional de Informática realizou-se em Mérida, estado de Yucatán, no México, http://www.ioi2006.org/, entre 13 e 20 de Agosto, e Portugal foi um dos países participantes, entre mais de 80, com uma delegação formada por quatro estudantes e dois professores. Portugal tem estado presente regularmente nas IOI desde 1992. A APDSI, desde o ano passado, continua a conduziu a participação portuguesa. Portugal foi o país organizador da edição de 1998, que teve lugar em Setúbal e que trouxe até ao nosso país, no ano da Expo em Lisboa, mais de 300 estudantes de todo o mundo e seus acompanhantes. A equipa portuguesa para o concurso no México foi formada pelos estudantes André Pinto, André Santos, Miguel Araújo e Rui Barbosa. Estes quatro concorrentes foram seleccionados no final de um estágio de preparação que decorreu entre 26 e 30 de Julho nas instalações do Departamento de Ciência de Computadores da Faculdade de Ciências da Universidade do Porto e no qual participaram os oito primeiros classificados das Olimpíadas Nacionais de Informática (ONI) deste ano. Dos quatro seleccionados, dois, o André Santos e o Miguel Araújo, são do Colégio Internato dos Carvalhos, de Vila Nova de Gaia, o André Pinto é da Escola Secundária/3 da Senhora da Hora, de Matosinhos e o Rui Barbosa é da Escola Secundária Carlos Amarante, de Braga. Integraram a delegação portuguesa os professores Pedro Guerreiro e Pedro Ribeiro, da Universidade Nova de Lisboa e da Universidade do Porto, respectivamente. Estes dois professores foram os responsáveis técnicos e científicos pelas ONI e por todo o processo de selecção e treino dos concorrentes para as IOI.

Page 4: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

Olimpíadas Internacionais de Informática (IOI’2006)

Relatório de Actividades Pág. 4

2. Conclusões Nos anos anteriores, os quatro melhores classificados nas Olimpíadas Nacionais de Informática eram seleccionados automaticamente para constituir a equipa portuguesa concorrente às Olimpíadas Internacionais. Desde o ano passado, decidimos proceder de maneira diferente, convidando para um estágio de formação os oito melhores e escolhendo a equipa só no final do estágio, por meio de um concurso realizado em moldes semelhantes aos das Olimpíadas Internacionais. O objectivo desta medida era evitar que os concorrentes, seleccionados com muita antecedência, descurassem a sua preparação, e incrementar o empenho de todos no estágio. No final do estágio, os quatro escolhidos, curiosamente, foram os quatro mais bem classificados nas Olimpíadas Nacionais. O estágio realizou-se nas instalações do Departamento de Ciência de Computadores da Faculdade de Ciências da Universidade do Porto, de 26 a 30 de Julho, isto é, duas semanas antes da prova internacional. Foi coordenado pelo Prof. Pedro Guerreiro e pelo Dr. Pedro Ribeiro, e contou com a colaboração do senhor Pedro Pereira, aluno da licenciatura em Ciências da Computação da Universidade do Porto, antigo concorrente às Olimpíadas Internacionais. Durante o estágio, os alunos concorrentes aprenderam as principais técnicas de programação necessárias para resolver os problemas que costumam sair neste tipo de concursos. Verificámos, após a prova no México, que o conteúdo do estágio estava muito bem adequado ao que realmente saiu, ainda que, infelizmente, os alunos não tivessem sido capazes de pôr em prática os ensinamentos recebidos. Os problemas usados na prova de selecção realizada no final do estágio estão em anexo, assim como a classificação. Os quatro alunos seleccionados – André Pinto, André Santos, Miguel Araújo e Rui Barbosa – viajaram para o México, acompanhados pelo Prof. Pedro Guerreiro, team leader, e pelo Dr. Pedro Ribeiro, deputy leader. Nas Olimpíadas Internacionais de Informática, o concurso é constituído por duas provas, cada uma de cinco horas, em cada uma das quais são apresentados três problemas de programação que se encontram em anexo. Apesar de bem preparados, os nossos concorrentes fraquejaram, e não resolveram devidamente problemas que normalmente estariam ao seu alcance. Por isso, a classificação final foi modesta, muito abaixo das nossas legítimas expectativas. De acordo com as regras da Olimpíadas Internacionais, os concorrentes na primeira metade da classificação recebem uma medalha. Há medalhas de ouro, prata e bronze, distribuídas na proporção 1:2:3. Em anexo está a lista dos 144 medalhados, entre os quais não se encontra nenhum dos concorrentes portugueses. A classificação dos concorrentes não medalhados não é publicada, apenas é divulgada a pontuação de todos eles. O sítio Web das Olimpíadas Internacionais de Informática, 2006, cujo endereço é http://www.ioi2006.org/, contém mais informações sobre o evento, cuja página de entrada incluímos em anexo. As fotografias dos concorrentes e dos professores, extraídas do sítio da delegação portuguesa, estão também em anexo.

Page 5: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

Olimpíadas Internacionais de Informática (IOI’2006)

Relatório de Actividades Pág. 5

ANEXOS

Page 6: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

Olimpíadas Internacionais de Informática (IOI’2006)

Relatório de Actividades Pág. 6

Anexo I - Sítio na Internet ( http://www.ioi2006.org/ )

Page 7: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas
Page 8: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

Olimpíadas Internacionais de Informática (IOI’2006)

Relatório de Actividades Pág. 8

Anexo II - Problemas da prova de selecção no final do estágio

Page 9: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

O Cartaz do Google file:///P:/APDSI%20-%20PA/Olimp%EDadas%20Inform%E1tica/O...

1 of 2 12-12-2006 16:25

Problema A - O Cartaz do GoogleA foto aqui ao lado mostra o cartaz que há tempos a Googlecolocou numa concorrida auto-estrada, nos Estados Unidos.Quem descobrisse o primeiro número primo com 10algarismos na dízima infinita do número e, base doslogaritmos naturais, deveria escrever num "bráuser" essenúmero, seguido de ".com" e iria parar a um sítio com maisinstruções. Eventualmente, acabaria por ser convidado parauma entrevista, e, quem sabe, ganharia um belo emprego.

Não vão eles, na Google, arranjar outra charada do mesmo género, o melhor é treinarmo-nos nestaproblemática dos números primos que aparecem em dízimas infinitas.

Concretamente, neste exercício, é-nos dada uma cadeia de algarismos, muito comprida, e queremoscontar o número de ocorrências de números primos com x algarismos (para um x dado) nessa cadeia. Porexemplo, se a cadeia for "1297521973" e x valer 2, temos 5 ocorrências: 29, 97, 19, 97 (de novo) e 73.

O Problema

Dada uma cadeia de algarismos s e um número x, calcular o número de ocorrências de números primosformados por x algarismos consecutivos em s.

Input

Na primeira linha vem o número inteiro x, o comprimento em algarismos decimais dos números primosem que estamos interessados, 1 <= x <= 7. Seguem-se uma ou mais linhas não vazias (em númeroindeterminado) totalmente formadas por algarismos. Cada linha tem no máximo 100 algarismos. A cadeias na qual queremos procurar os números primos é a que resulta da concatenação da sucessivas linhas. Ocomprimento máximo de s é 10000000.

Output

O output tem uma linha, na qual aparece um número: o número de ocorrências de números primosformados por x algarismos consecutivos na cadeia s.

Exemplo de Input 1367485085739031663904

Exemplo de Output 12

Exemplo de Input 22129752

Page 10: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

O Cartaz do Google file:///P:/APDSI%20-%20PA/Olimp%EDadas%20Inform%E1tica/O...

2 of 2 12-12-2006 16:25

1973

Exemplo de Output 25

Selecção dos Concorrentes PortuguesesOlimpíadas Internacionais de Informática 2006

(30 de Julho de 2006)

Page 11: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

Magia com Espadas file:///P:/APDSI%20-%20PA/Olimp%EDadas%20Inform%E1tica/O...

1 of 2 12-12-2006 16:26

Problema B - Magia com EspadasUma bela mulher entra para dentro de uma misteriosa caixa. A caixa édepois completamente perfurada por espadas, introduzidas de um lado aooutro da caixa nas mais variadas direcções. O público agonia-se... Asespadas são retiradas uma a uma e a caixa aberta. Maravilhosamente, amulher está completamente intacta e sobreviveu! O público aplaude entãoruidosamente. Haverá truque de magia de palco mais conhecido que este?

Nunca te perguntaste como este truque é realizado? A ilusão dos mágicosestá sempre bem guardada, mas um teu amigo pensa que já percebeu tudoe decidiu ele próprio tentar realizar o truque. Segundo ele, o segredo éconseguir ter uma assistente suficientemente pequena e flexível, para quedepois de entrar na caixa possa dobrar-se e colocar-se de tal modo quefica numa posição onde não é tocada por nenhuma espada.

Claro que é muito importante a maneira como se coloca as espadas, pois se por um lado o público tem deficar com a sensação que toda a caixa está perfurada, por outro lado tem de haver espaço suficiente nacaixa para que a assistente não corra perigo de vida.

Sabendo dos teus conhecimentos de programação, o teu amigo decidiu pedir-te uma ajuda! O que eleprecisa é de saber qual a maior área onde o assistente se pode colocar em segurança, tendo em conta umadada maneira de perfurar a caixa com espadas.

As espadas apenas podem ser introduzidas horizontalmente pelos lados, percorrendo toda a largura dacaixa ou, perpendicularmente à maneira atrás descrita, percorrendo a caixa em todo o seu comprimento.Podem também ser introduzidas verticalmente, de cima para baixo, percorrendo toda a altura da caixa.Em qualquer dos casos atrás descrito, a espada vai sempre de uma ponta à outra da caixa, para que opúblico possa ver as duas "pontas" da espada.

Para te facilitar a vida, o teu amigo deixa-te pensar na caixa como um rectângulo plano, a duasdimensões, com um determinado comprimento e largura, embora na realidade, a caixa tenha trêsdimensões. E o espaço a ocupar pela assistente tem de ser rectangular. Cada espada tem uma largura deuma unidade. Podes imaginar a caixa como um quadriculado, onde cada espada introduzidahorizontalmente ocupa uma linha ou coluna, e cada espada vertical ocupa apenas uma quadrícula. Afigura seguinte exemplifica isto graficamente.

O Problema

Page 12: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

Magia com Espadas file:///P:/APDSI%20-%20PA/Olimp%EDadas%20Inform%E1tica/O...

2 of 2 12-12-2006 16:26

Dadas as dimensões da caixa e a maneira de introduzir as espadas, a tua tarefa é escrever um programaque calcule a maior área rectangular possível onde a assistente pode estar em segurança sem ser tocadapor nenhuma espada.

Input

Na primeira linha do input estão dois inteiros L e C separados por um espaço, indicando respectivamenteo número de linhas e o número de colunas da caixa a considerar (1 <= L,C <= 300).

Segue-se uma linha contendo unicamente E, indicando o número de espadas a introduzir na caixa (0 <= E<= 200).

Depois temos exactamente E linhas contendo cada uma a descrição de uma espada. Cada descrição vemnum dos seguintes formatos:

HL NUM_LINHA, indicando uma espada a ser introduzida horizontalmente de lado, na linha indicadapor NUM_LINHA, ao longo de toda a largura da caixa;HT NUM_COLUNA, indicando uma espada a ser introduzida horizontalmente de lado pelo "topo", nacoluna indicada por NUM_COLUNA, ao longo de toda comprimento da caixa;V NUM_LINHA NUM_COLUNA, indicando uma espada a ser introduzida verticalmente, na linha e colunaindicadas;

Output

O output deve vir numa única linha, contendo o valor da maior área rectangular da caixa que não temespadas. É garantido que existe sempre pelo menos uma quadrícula dentro da caixa sem espadas.

Exemplo de Input6 43HL 4V 6 1HT 2V 5 4

Exemplo de Output6

Selecção dos Concorrentes PortuguesesOlimpíadas Internacionais de Informática 2006

(30 de Julho de 2006)

Page 13: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

Ronda Nocturna file:///P:/APDSI%20-%20PA/Olimp%EDadas%20Inform%E1tica/O...

1 of 2 12-12-2006 16:27

Problema C - Ronda NocturnaClancy Wiggum é o chefe da polícia de Springfield. Como qualquerpolícia que se preze, gosta muito de passar a vida comer donuts(passatempo também partilhado por Homer Simpson, diga-se). Oproblema é que tanto tempo passado nos vícios gastronómicosdeixou-o um pouco "pesadote" e com pouca mobilidade. Ainda porcima ele é extremamente preguiçoso.

Clancy tem diariamente a tarefa de fazer uma ronda nocturna porvários locais de Springfield. Começa na esquadra, passa por todos oslocais desejados pelo menos uma vez, e volta novamente à esquadra.Obviamente, quer mexer-se o menos possível nessa tarefa e por issoquer saber qual o caminho que minimiza o tempo dispendido. Será quepodes ajudá-lo?

O mapa de Springfield é-te dado neste problema como uma matriz.Certas posições da matriz estão indicadas como obstáculos e não épossível passar por elas. Em cada posição, o nosso polícia pode efectuar quatro tipos de movimentos:norte, sul, este e oeste (desde que a quadrícula para onde se desloca esteja livre, claro). A mudança deuma quadricula para outra custa uma unidade.

O Problema

Dado uma mapa de Springfield com o local da esquadra de polícia e dos locais a visitar, tens de calcular ocomprimento do menor caminho que começa na esquadra, passa por todos os locais a visitar pelo menosuma vez, e termina novamente na esquadra. É garantido que é sempre possível arranjar pelo menos umcaminho nas condições descritas.

Input

Na primeira linha vêm dois inteiros N e M (3<=N,M<=300), o número de linhas e o número de colunasdo mapa, respectivamente.

As próximas N linhas descrevem o mapa. Cada linha é composta por M caracteres (que podem ser '#', '.','V' ou 'S'). '#' representa um obstáculo, '.' uma quadrícula livre, 'V' representa um local a visitar e 'S' olocal da esquadra.

Existe exactamente um 'S' no input e até 10 'V''s, podendo não existir nenhum.

O mapa está sempre rodeado de '#' nos seus limites.

Output

Deve ser impressa uma única linha com o tamanho do menor caminho que começa na posição indicadapor 'S', passa por todas as casas 'V' e regressa a 'S'.

Exemplo de Input10 10###########.V......#

Page 14: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

Ronda Nocturna file:///P:/APDSI%20-%20PA/Olimp%EDadas%20Inform%E1tica/O...

2 of 2 12-12-2006 16:27

#.###.##.##..V#..#.##......#.##..#.###V##....#...##....#S..##..#.#...###########

Exemplo de Output36

Selecção dos Concorrentes PortuguesesOlimpíadas Internacionais de Informática 2006

(30 de Julho de 2006)

Page 15: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

Olimpíadas Internacionais de Informática (IOI’2006)

Relatório de Actividades Pág. 15

Anexo III - Classificações da prova de selecção no final do estágio

Page 16: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

Olimpíadas Internacionais de Informática (IOI’2006)

Relatório de Actividades Pág. 16

Page 17: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

Olimpíadas Internacionais de Informática (IOI’2006)

Relatório de Actividades Pág. 17

Anexo IV - Problemas das duas provas nas IOI

Page 18: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

Writing Official version IOI’06 English Day 1 – Task 1 Version 1.3

Number of pages 1 IOI’06 Page 1

DECIPHERING THE MAYAN WRITING Deciphering the Mayan writing has proven to be a harder task than anticipated by the early investigations. After almost two hundred years, very little of it was actually understood. It has been only in the last three decades that real advances have been made. Mayan writing is based on small drawings known as glyphs which represent sounds. Mayan words are normally written as glyphs put together at various positions. One of several problems in deciphering Mayan writing arises in the order of reading. When placing several glyphs in order to form a word, Mayan writers sometimes decided the position based more on their own esthetic views than on any particular rule. This leads to the fact that, even though the sound for many glyphs is known, sometimes archaeologists are not sure how to pronounce a written word. The archaeologists are looking for a special word W. They know the glyphs for it, but they don’t know all the possible ways of arranging them. Since they knew you were coming to IOI’06, they have asked for your help. They will provide you with the g glyphs from W and a sequence S of all the glyphs (in the order they appear) in the carvings they are studying. Help them by counting the number of possible appearances of the word W. TASK Write a program that, given the glyphs for W and the sequence S of glyphs in the carvings, counts the number of possible appearances of W in S; that is, every sequence of consecutive g glyphs in S that is a permutation of the glyphs in W. CONSTRAINTS 1 ≤ g ≤ 3 000 the number of glyphs in W g ≤ |S| ≤ 3 000 000 where |S| is the number of glyphs in the sequence S INPUT Your program must read the following data from the file writing.in writing.in DESCRIPTION 4 11 cAda AbrAcadAbRa

LINE 1: Contains 2 space-separated integers that represent g and |S|. LINE 2: Contains g consecutive characters that represent the glyphs

in W. Valid characters are ‘a’-‘z’ and ‘A’-‘Z’; uppercase and lowercase characters are considered different.

LINE 3: Contains |S| consecutive characters that represent the glyphs in the carvings. Valid characters are ‘a’-‘z’ and ‘A’-‘Z’; uppercase and lowercase characters are considered different.

OUTPUT Your program must write the following data to the file writing.out writing.out DESCRIPTION 2 LINE 1: Must contain the count of possible appearances of W in S. GRADING For a set of test cases worth a total of 50 points, each test run will meet the requirement that g ≤ 10.

IMPORTANT NOTE FOR PASCAL PROGRAMMERS By default in FreePascal, a variable of type string has a size limit of 255 characters. If you want to use strings longer than that, you should add the directive {$H+} to your code just below the program ...; line.

Page 19: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

Pyramid Official version IOI’06 English Day 1 – Task 2 Version 1.2

Number of pages 1 IOI’06 Page 1

PYRAMID After winning a great battle, King Jaguar wants to build a pyramid that will serve both as a monument to remember his victory and as a tomb for the brave soldiers that died in battle. The pyramid will be built in the battlefield and will have a rectangular base of a columns by b rows. Inside it, at ground level, is a smaller, rectangular chamber of c columns by d rows that will contain the corpses and weapons of the fallen soldiers.

The King’s architects have surveyed the battlefield as an m columns by n rows grid and have measured the elevation of each square as an integer.

Both the pyramid and the chamber are to be built covering complete squares of the grid and with their sides parallel to those of the battlefield. The elevation of the squares of the internal chamber must remain unchanged but the remaining terrain of the base of pyramid will be leveled by moving sand from higher squares to lower ones. The final elevation of the base will be the average elevation of all the squares of the base (excluding those of the chamber). The architects are free to locate the internal chamber anywhere within the pyramid as long as they leave a wall at least one square thick surrounding the chamber.

Help the architects pick the best place to locate the pyramid and the internal chamber so that the final elevation of the base is the maximum possible for the sizes given. The figure shows an example of the battlefield; the number in each square represents the elevation of the terrain in that particular position of the field. The gray squares represent the base of the pyramid while the surrounded white squares represent the chamber. This figure illustrates an optimal placement.

TASK Write a program that, given the dimensions of the field, the pyramid, and the chamber along with the elevation of every square in the field, locates both the pyramid in the field and the chamber inside the pyramid so that the elevation of the base is the maximum possible. CONSTRAINTS 3 ≤ m ≤ 1000 3 ≤ n ≤ 1000 3 ≤ a ≤ m 3 ≤ b ≤ n 1 ≤ c ≤ a – 2 1 ≤ d ≤ b – 2 All elevations are integers in the range from 1 to 100.

Page 20: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

Pyramid Official version IOI’06 English Day 1 – Task 2 Version 1.2

Number of pages 2 IOI’06 Page 2

INPUT Your program must read the following data from the file the pyramid.in pyramid.in DESCRIPTION 8 5 5 3 2 1 1 5 10 3 7 1 2 5 6 12 4 4 3 3 1 5 2 4 3 1 6 6 19 8 1 1 1 3 4 2 4 5 6 6 3 3 3 2 2 2

LINE 1: Contains six space-separated integers, respectively: m, n, a, b, c, and d.

NEXT n LINES: Each line contains m space-separated integers that represent the elevations of one row of the grid. The first of these lines represents the top row (row 1) of the grid, and the last line represents the bottom row (row n). The m integers in each line represent the elevations of squares of that row starting from column 1.

OUTPUT Your program must write the following data to the file the pyramid.out pyramid.out DESCRIPTION 4 1 6 2

LINE 1: Must contain 2 space-separated integers that represent the upper-left corner of the base of the pyramid, the first number being the column and the second the row.

LINE 2: Must contain 2 space-separated integers that represent the upper-left corner of the chamber inside the pyramid, the first number being the column and the second the row.

NOTE: If there are multiple optimal placements, then any one of them you output will be considered correct. GRADING For a number of test cases worth a total of 30 points, every test run will meet the following requirements: 3 ≤ m ≤ 10 3 ≤ n ≤ 10

Page 21: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

Forbidden Official version IOI’06 English Day 1 – Task 3 Version 1.2

Number of pages 1 IOI’06 Page 1

FORBIDDEN SUBGRAPH Two undirected graphs G and H are said to be isomorphic if:

• they have the same number of vertices and • a one-to-one correspondence exists between their vertices so that, for any two distinct

vertices of G, there exists an edge between them if and only if there exists an edge between their corresponding vertices in H.

For example, the next two graphs are isomorphic, even though they look different here:

A possible one-to-one correspondence showing that these two graphs are isomorphic is given by {a-1, b-6, c-8, d-3, g-5, h-2, i-4, j-7}, but others exist too.

A subgraph of a graph G is a graph whose sets of vertices and edges are subsets of those in G. Note that G is a subgraph of itself. The following example shows a graph and one of its subgraphs:

We say that a graph G contains another graph H if there is at least one subgraph H’ of G which is isomorphic to H. The following figure shows a graph G that contains the graph H.

TASK

Given two undirected graphs G and H, produce a subgraph G’ of G such that: • the number of vertices in G and G’ is the same and • H is not contained in G’.

Naturally, there may be many subgraphs G’ with the above properties. Produce one of those subgraphs with as many edges as possible.

Page 22: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

Forbidden Official version IOI’06 English Day 1 – Task 3 Version 1.2

Number of pages 2 IOI’06 Page 2

BASE ALGORITHM Perhaps the most basic strategy to approach this problem is to consider the edges of G in the order that they are represented in the input file, then attempting to add them one by one to G’, verifying at each step whether H is contained in G’ or not. The correct implementation of this greedy algorithm will earn some points, but much better strategies exist. CONSTRAINTS 3 ≤ m ≤ 4 The number of vertices of H. 3 ≤ n ≤ 1000 The number of vertices of G. INPUT You will be given 10 files forbidden1.in to forbidden10.in each with the following data: forbiddenK.in DESCRIPTION 3 5 0 1 0 1 0 1 0 1 0 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0

LINE 1: Contains two space-separated integers, respectively: m and n.

NEXT m LINES: Each line contains m space-separated integers and represents one vertex of H in the order 1, ..., m. The i-th element of the j-th line in this section is equal to 1 if vertices i and j are joined by an edge in H and is equal to 0 otherwise.

NEXT n LINES: Each line contains n space-separated integers and represents one vertex of G in the order 1, ..., n. The i-th element of the j-th line in this section is equal to 1 if vertices i and j are joined by an edge in G and is equal to 0 otherwise.

Observe that, except for line 1, the above input represents the adjacency matrices of H and G. OUTPUT You must provide 10 files, one for each of the inputs. Each file must contain the following data: forbiddenK.out DESCRIPTION #FILE forbidden K 5 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

LINE 1: The file header. The file header must contain #FILE forbidden K

where K is a number between 1 and 10 that corresponds to the input file solved.

LINE 2: Contains one integer: n. NEXT n LINES: Each line contains n space-separated integers and

represents one vertex of G’ in the order 1, ..., n. The i-th element of the j-th line in this section is equal to 1 if vertices i and j are joined by an edge in G’, and is 0 otherwise.

Observe that, except for lines 1 and 2, the above output represents the adjacency matrix of G’. Note that there are many possible outputs, and that the above output is correct but not optimal. GRADING Your score will depend on the number of edges in the G’ you output. Your score will be determined in the following way: you will receive a non-zero score for each output file only if it meets the task specification. If it does, your score will be calculated as follows. Let Ey be the number of edges in your output, let Eb be the number of edges in G’ as computed by the BASE ALGORITHM, and let Em be the maximum number of edges in the output of any of the contestants submissions. Your score for the case will be:

• 30 Ey / Eb if Ey ≤ Eb, or • 30 + 70(Ey - Eb)/ (Em - Eb) if Ey > Eb.

Page 23: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

Mexico Official version IOI’06 English Day 2 – Task 1 Version 1.1

Number of pages 1 IOI’06 Page 1

THE VALLEY OF MEXICO

Mexico City is built in a beautiful valley known as the Valley of Mexico which, years ago, was mostly a lake. Around the year 1300, Aztec religious leaders decreed that the lake’s center be filled in order to build the capital of their empire. Today, the lake is completely covered. Before the Aztecs arrived, c cities were located around the lake on its shores. Some of these cities established commercial agreements. Goods were traded, using boats, between cities that had a commercial agreement. It was possible to connect any two cities by a line segment through the lake. Eventually, the kings of the cities decided to organize this commerce. They designed a commerce route that connected every city around the lake. The route met the following requirements:

• It could start in any of the cities, visited each of the cities around the lake, and finally ended in another city different from the starting city.

• The route visited each city exactly once. • Every pair of consecutively visited cities in the route had a commercial agreement. • Every pair of consecutively visited cities in the route was connected by a line segment. • To avoid crashes between boats, the route never crossed itself.

The figure shows the lake and the cities around it. The lines (both thick and thin) represent commercial agreements between cities. The thick lines represent a commerce route starting in city 2 and ending in city 5. This route never crosses itself. It would not be legal, for example, to construct a route that went from 2 to 6 to 5 to 1, since the route would cross itself. Cities in the lake are numbered from 1 through c moving in clockwise direction.

TASK Write a program that, given both the count c of cities and a list of the commercial agreements between them, constructs a commerce route that meets the above requirements. CONSTRAINTS 3 ≤ c ≤ 1000 Number of cities around the lake.

Page 24: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

Mexico Official version IOI’06 English Day 2 – Task 1 Version 1.1

Number of pages 2 IOI’06 Page 2

INPUT Your program must read the following data from the file mexico.in mexico.in DESCRIPTION 7 9 1 4 5 1 1 7 5 6 2 3 3 4 2 6 4 6 6 7

LINE 1: Contains integer c LINE 2: Contains an integer n that represents the number of

commercial agreements NEXT n LINES: Each line represents a unique commercial

agreement. Every line contains two space-separated integers that represent the two cities involved in the agreement.

OUTPUT Your program must output the following data to the file mexico.out mexico.out DESCRIPTION 2 3 4 1 7 6 5

If it’s possible to construct the commerce route, write c lines, each with an integer that represents the order in which the cities are visited in the commerce route. If it’s not possible to construct a commerce route that meets all the requirements, output a single line containing the number -1.

NOTE: If there is more than one commerce route that meets the requirements, any of them you output will be considered correct. GRADING For a set of test cases worth a total of 40 points, each test case will meet the following requirements: 3 ≤ c ≤ 20

Page 25: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

Points Official version IOI’06 English Day 2 – Task 2 Version 1.2

Number of pages 1 IOI’06 Page 1

JOINING POINTS

“Joining points” is a single-player game. To play it, choose two integers greater than two and call them g and r. Then draw four points at the vertices of a square making the top two points green and the bottom two points red. Draw green points and red points inside the square taking care that no three points, including the four initial ones, are in the same line. Continue until the total number of green points equals g and the total number of red points equals r. After the board is drawn, start joining points. Any two points can be joined by a line segment as long as:

• The two points to be joined are of the same color, and • The line segment joining the points does not intersect any other previously drawn line

segment (other than at the endpoints). Two points u and v are said to be in the same component if it is possible to traverse from point u to point v using the line segments already drawn. You win the game if you get all the green points in one component using exactly g-1 line segments, and all the red points in another component using exactly r-1 line segments. It can be proven that if the points are drawn as described above, then there is always a way to win the game. You will be given a square board of size s with g green and r red points whose coordinates are represented by integer pairs (xi, yi). Green points are numbered from 1 to g with the top-left point at (0,s) being 1, the top-right at (s,s) being 2, and interior points ranging from 3 to g in arbitrary order. Red points are numbered from 1 to r with the bottom-left point at (0,0) being 1, the bottom-right at (s,0) being 2, and interior points ranging from 3 to r in arbitrary order.

The figure shows a sample game all the green points are joined into one component and all the red points are joined into another component. You can see that no three points are in the same line, and that no two line segments intersect each other except at their endpoints.

TASK Write a program that, given the coordinates of the g green points and the coordinates of the r red points, decides how to draw g - 1 green line segments and r - 1 red line segments so that all of the green points are in the same component, all of the red points are in another component, and no two line segments intersect each other. CONSTRAINTS 3 ≤ g ≤ 50 000 Number of green points. 3 ≤ r ≤ 50 000 Number of red points. 0 < s ≤ 200 000 000

Page 26: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

Points Official version IOI’06 English Day 2 – Task 2 Version 1.2

Number of pages 2 IOI’06 Page 2

INPUT Your program must read the following data from the file points.in points.in DESCRIPTION 6 0 1000 1000 1000 203 601 449 212 620 837 708 537 8 0 0 1000 0 185 300 314 888 416 458 614 622 683 95 838 400

LINE 1: Contains the integer g. NEXT g LINES: Each line contains two space-separated integers that

represent the coordinates xi and yi of each of the g green points, starting from 1 to g.

LINE g+2: Contains integer r. NEXT r LINES: Each line contains two space-separated integers that

represent the coordinates xi and yi of each of the r red points, starting from 1 to r.

OUTPUT Your program must write the following data to the file points.out points.out DESCRIPTION 1 3 g 3 1 r 3 5 r 4 6 r 6 5 r 4 6 g 1 2 g 1 2 r 5 2 g 2 6 g 7 8 r 8 2 r

Your output file must contain (g – 1) + (r – 1) lines, one for every line segment drawn to join points. Each line must contain three space-separated entities: two integers and a character.The two integers represent the numbers of two points joined by that line segment. The character must be a g if the points are green and an r if the joined points are red. The order in which you list the line segments does not matter; neither does the order of the endpoints of each line segment.

GRADING For a set of test cases worth a total of 35 points, every test run will meet the following requirements: 3 ≤ g ≤ 20 3 ≤ r ≤ 20

Page 27: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

Blackbox Official version IOI’06 English Day 2 – Task 3 Version 1.6

Number of pages 1 IOI’06 Page 1

A BLACK BOX GAME The Black Box Game is played with a square-shaped black box lying flat on a table. Each of its four sides has n holes (for a total of 4n holes) into which a ball can be thrown. A thrown ball will eventually exit from one of the 4n holes, potentially the same hole into which it was thrown. The black box’s internals can be envisioned as an n x n grid. The holes in the sides are the starts and ends of rows and columns. Each of the box’s squares is either empty or occupied by a deflector. A deflector is a piece of hardware that changes the direction of the ball by 90 degrees. Consider this example of a 5x5 box.

A ball thrown into the box follows a straight line until it either hits a deflector or exits the box. When a ball hits a deflector, the ball changes direction and the deflector toggles its position (by “toggle” we mean rotate 90 degrees). The examples below show the action of a deflector.

a) A ball is thrown through a hole; it hits a deflector and changes direction. b) After the first ball was thrown, the deflector has toggled its position. A new ball is thrown into

the same hole, hits the deflector and is deflected in a direction opposite to that of the first ball. c) The deflector toggles every time it is hit.

Whenever a deflector is hit, it makes a beep. The number of times the ball was deflected can be deduced by counting the beeps. It can be proved that the ball always exits the box. The box has a button that resets it to its original state and another button that toggles all of its deflectors. TASK You will be provided with an interface to 15 black boxes via a library of Pascal or C/C++ functions. You must determine the internals of each one of them as best as possible and submit a file describing each. You will also be provided with a method to define your own black boxes for testing. CONSTRAINTS 1 ≤ n ≤ 30 OUTPUT You must submit a file containing the following data for each one of the 15 black-boxes blackboxK.out DESCRIPTION #FILE blackbox K ..... .../. .\... .../. .?.?.

LINE 1: The file header. The file header must contain #FILE blackbox K

where K (range 1..15) corresponds to the box being solved. n LINES: Each line describes a row of the box, starting from the topmost row

to the bottom row. Each line must contain exactly n characters; each character corresponds to a column (running from left to right).

• ‘.’ means that the square is empty. • ‘/’ means the square contains a deflector with initial position ‘/’ • ‘\’ means the square contains a deflector with initial position ‘\’ • ‘?’ means that you were unable to determine the initial contents of

that square

Deflectors

Hole

Page 28: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

Blackbox Official version IOI’06 English Day 2 – Task 3 Version 1.6

Number of pages 2 IOI’06 Page 2

LIBRARY You are given a library that provides the following functions

FUNCTION Description PASCAL function Initialize(box: integer): integer; C/C++ int Initialize(int box);

Initializes the library, must be called once at the start of your program. It returns n, the number of holes on each side of the box. The parameter box must contain an integer between 1 and 15 indicating the box you want to use or 0 if you want to use a box created by you.

PASCAL function throwBall(holeIn, sideIn: integer; var holeOut, sideOut: integer): longint; C int throwBall(int holeIn, int sideIn, int *holeOut, int *sideOut); C++ int throwBall(int holeIn, int sideIn, int &holeOut, int &sideOut);

Throws a ball into the box through hole number holeIn in side sideIn, sides are numbered as 1 – Top, 2 – Right, 3 – Bottom and 4 – Left. Holes are numbered from left to right and from top to bottom starting from number 1 in each side. In holeOut and sideOut you’ll receive the hole and side number where the ball exits the box. The function throwBall returns the number of beeps caused by the ball hitting a deflector.

PASCAL procedure ResetBox; C/C++ void ResetBox();

Resets every deflector in the box to its initial position.

PASCAL procedure ToggleDeflectors; C/C++ void ToggleDeflectors();

Toggles every deflector in the box.

PASCAL procedure Finalize; C/C++ void Finalize();

Gracefully ends the interaction with the box. It should be called at the end of your program.

To be able to use the library in your program do as follows:

• FreePascal: In the task directory you will find the files pbblib.o and pbblib.ppu to be able to use them include the following statement.

uses pbblib; The file pblackbox.pas gives an example of how to use the library.

• C: In the task directory you will find the files cbblib.o and cbblib.h, to be able to use them include the following statement in your code.

#include “cbblib.h” The file cblackbox.c gives an example of how to use the library. In order to compile your

code you will need to use the following command gcc –o yourprogram cbblib.o yourprogram.c

• C++: In the task directory you will find the files cppbblib.o and cppbblib.h, to be able to use them include the following statement in your code.

#include “cppbblib.h” The file cppblackbox.cpp gives an example of how to use the library. In order to compile

your code you will need to use the following command g++ –o yourprogram cppbblib.o yourprogram.cpp

NOTE: At any given time only one program using the library can be running.

Page 29: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

Blackbox Official version IOI’06 English Day 2 – Task 3 Version 1.6

Number of pages 3 IOI’06 Page 3

SAMPLE INTERACTION A sample interaction for the box in the previous figure could be: FUNCTION CALL VALUE RETURNED BY FUNCTION Initialize(0); Assuming that the box used is the one in the previous

figure. Returns 5 indicating that n = 5 PASCAL throwBall(3,4,holeOut,sideOut); C throwBall(3,4,&holeOut,&sideOut); C++ throwBall(3,4,holeOut,sideOut);

A ball is thrown into hole number 3 (third from the top) on the left side. Returns 1, indicating that the ball hit 1 deflector. When the function returns, holeOut will equal 2 and sideOut will equal 3 indicating that the ball exited through hole 2 (second from the left) of the bottom side of the box.

EXPERIMENTATION If you pass an integer value of 0 to the function Initialize, the library will read the box internals from the file blackbox.in. In this way you can experiment with the library. The format for the file blackbox.in is described below. blackbox.in DESCRIPTION 5 3 2 3 \ 4 2 / 4 4 /

LINE 1: Contains n, the number of holes on each side. LINE 2: Contains an integer d that indicates the number of deflectors

in the box. NEXT d LINES: There must be one line for every deflector in the box.

Each line contains two space-separated integers that represent the column and the row of the deflector respectively, and a character separated with a space from the second integer that can be either ‘/’ or ‘\’ that represents the original position of the deflector.

NOTE; The example blackbox.in describes the black box shown in the figure at the top of page 1. ERROR MESSAGES In the case of any anomalies the library will output an error message to the standard error. The possible error message that you can get and their meanings are shown in the table below. ERROR MESSAGE MEANING ERR 1 More than one app Only one application at a time can interact with the black boxes,

please restart all applications and start only one at a time ERR 2 Invalid box The box number you input is not in the range from 0 to 15 ERR 3 Invalid deflector The file blackbox.in has a deflector in an invalid position ERR 4 Invalid symbol The file blackbox.in has an invalid symbol ERR 5 Invalid size The size of the black box in blackbox.in is invalid. ERR 6 Invalid input hole Either the side or the input hole that you entered are invalid ERR 7 ALARM Please call the technical staff GRADING For each box you must submit a text file that describes the internals of the black box as best as possible. For each box:

• If your submission has a ‘.’, ‘/’ or ‘\’ character in an incorrect position, you’ll get zero points for that box.

• Let Bm be the maximum number of discovered positions among all of the correct submissions, and let By be the number of discovered positions in your submission, then percentage of your score for that box will be

100 By / Bm NOTE: The official solution for this task can programmatically discover 100% of the initial contents of any of the boxes in a time less than 8 minutes.

Page 30: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

Olimpíadas Internacionais de Informática (IOI’2006)

Relatório de Actividades Pág. 30

Anexo V - Resultados

Page 31: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas
Page 32: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas
Page 33: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas
Page 34: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas
Page 35: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas
Page 36: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

Olimpíadas Internacionais de Informática (IOI’2006)

Relatório de Actividades Pág. 36

Anexo VI - Fotografias dos concorrentes e professores

Page 37: Olimpíadas Internacionais de Informática (IOI’2006)³rio de actividades ioi 2006... · cada ano são estudantes excepcionais e pertencem ao grupo dos melhores jovens cientistas

Olimpíadas Internacionais de Informática (IOI’2006)

Relatório de Actividades Pág. 37