812. Bits Trocados - IME-USPschultz/maratona-ufsc/treinos/2010-04-24/prova.pdf · Maratona de...
Transcript of 812. Bits Trocados - IME-USPschultz/maratona-ufsc/treinos/2010-04-24/prova.pdf · Maratona de...
SPOJ Problem Set (obi)
812. Bits Trocados
Problem code: BIT
As Ilhas Weblands formam um reino independente nos mares do Pacífico. Como é um reino recente, a
sociedade é muito influenciada pela informática. A moeda oficial é o Bit; existem notas de B$ 50,00,
B$10,00, B$5,00 e B$1,00. Voce foi contratado(a) para ajudar na programaçao dos caixas automáticos
de um grande banco das Ilhas Weblands.
Tarefa
Os caixas eletrônicos das Ilhas Weblands operam com todos os tipos de notas disponíveis, mantendo
um estoque de cédulas para cada valor (B$ 50,00, B$10,00, B$5,00 e B$1,00). Os clientes do banco
utilizam os caixas eletrônicos para efetuar retiradas de um certo número inteiro de Bits.
Sua tarefa é escrever um programa que, dado o valor de Bits desejado pelo cliente, determine o
número de cada uma das notas necessário para totalizar esse valor, de modo a minimizar a quantidade
de cédulas entregues. Por exemplo, se o cliente deseja retirar B$50,00, basta entregar uma única nota
de cinquenta Bits. Se o cliente deseja retirar B$72,00, é necessário entregar uma nota de B$50,00, duas
de B$10,00 e duas de B$1,00.
Entrada
A entrada é composta de vários conjuntos de teste. Cada conjunto de teste é composto por uma única
linha, que contém um número inteiro positivo V, que indica o valor solicitado pelo cliente. O final da
entrada é indicado por V = 0.
Saída
Para cada conjunto de teste da entrada seu programa deve produzir tres linhas na saída. A primeira
linha deve conter um identificador do conjunto de teste, no formato "Teste n", onde n é numerado
a partir de 1. Na segunda linha devem aparecer quatro inteiros I, J, K e L que representam o resultado
encontrado pelo seu programa: I indica o número de cédulas de B$50,00, J indica o número de
cédulas de B$10,00, K indica o número de cédulas de B$5,00 e L indica o número de cédulas de
B$1,00. A terceira linha deve ser deixada em branco. A grafia mostrada no Exemplo de Saída, abaixo,
deve ser seguida rigorosamente.
Exemplo
Entrada:
1
72
0
Saída:
Teste 1
1
0 0 0 1
Teste 2
1 2 0 2
Restriçoes
0 <= V <= 10000 (V = 0 apenas para indicar o fim da entrada)
Added by: Wanderley Guimaraes
Date: 2006-04-19
Time limit: 1s
Source limit:50000B
Languages: All
Resource: Olimpiada Brasileira de Informatica 2000
2
Maratona de Programacao da SBC – ACM ICPC –2006 12
Problema FCopa do Mundo
Nome do arquivo fonte: copa.c, copa.cpp, copa.java ou copa.pas
Uma Copa do Mundo de futebol de botoes esta sendo realizada com times de todo o mundo.A classificacao e baseada no numero de pontos ganhos pelos times, e a distribuicao de pontose feita da forma usual. Ou seja, quando um time ganha um jogo, ele recebe 3 pontos; se o jogotermina empatado, ambos os times recebem 1 ponto; e o perdedor nao recebe nenhum ponto.
Dada a classificacao atual dos times e o numero de times participantes na Copa do Mundo,sua tarefa e de determinar quantos jogos terminaram empatados ate o momento.
Entrada
A entrada contem varios casos de teste. A primeira linha de um caso de teste contem doisinteiros T e N , indicando respectivamente o numero de times participantes (2 ≤ T ≤ 200) eo numero de partidas jogadas (0 ≤ N ≤ 10000). Cada uma das T linhas seguintes contem onome de um time (uma cadeia de maximo 10 letras e dıgitos), seguido de um espaco em branco,seguido do numero de pontos que o time obteve ate o momento. O final da entrada e indicadopor T = 0.
A entrada deve ser lida da entrada padrao.
Saıda
Para cada um dos casos de teste seu programa deve imprimir uma unica linha contendo umnumero inteiro, representando a quantidade de jogos que terminaram empatados ate o momento.
A saıda deve ser escrita na saıda padrao.
Exemplo de entrada
3 3
Brasil 3
Australia 3
Croacia 3
3 3
Brasil 5
Japao 1
Australia 1
0 0
Saıda para o exemplo de entrada
0
2
CraneCTU Open 2005
modified by Luıs Fernando Schultz Xavier da Silveira
Statement
ACM has bought a new crane (crane – jerab) . The crane consists of n segments of various lengths, connected by flexible joints.The end of the i-th segment is joined to the beginning of the (i + 1)-th one, for 1 6 i < n. The beginning of the first segment isfixed at point with coordinates (0, 0) and its end at point with coordinates (0, w), where w is the length of the first segment. Allof the segments lie always in one plane, and the joints allow arbitrary rotation in that plane. After series of unpleasant accidents,it was decided that software that controls the crane must contain a piece of code that constantly checks the position of the endof crane, and stops the crane if a collision should happen.
Your task is to write a part of this software that determines the position of the end of the n-th segment after each command.The state of the crane is determined by the angles between consecutive segments. Initially, all of the angles are straight, i.e.,180◦. The operator issues commands that change the angle in exactly one joint.
Input
The input consists of several instances, separated by single empty lines.The first line of each instance consists of two integers 1 6 n 6 10000 and c > 0 separated by a single space – the number of
segments of the crane and the number of commands. The second line consists of n integers l1, . . . , ln(1 6 li 6 100) separated bysingle spaces. The length of the i-th segment of the crane is li. The following c lines specify the commands of the operator. Eachline describing the command consists of two integers s and a (1 6 s < n, 0 6 a 6 359) separated by a single space – the orderto change the angle between the s-th and the (s + 1)-th segment to a degrees (the angle is measured counterclockwise from thes-th to the (s + 1)-th segment).
Output
The output for each instance consists of c lines. The i-th of the lines consists of two rational numbers x and y separated by asingle space – the coordinates of the end of the n-th segment after the i-th command, rounded to two digits after the decimalpoint.
The outputs for each two consecutive instances must be separated by a single empty line.
Sample Input Sample Output2 110 51 90
3 25 5 51 2702 90
5.00 10.00
-10.00 5.00-5.00 10.00
Note
A precision error of 10−2 will be tolerated.
1
Problem E Fare and Balanced
Input: fare.in
Handling traffic congestion is a difficult challenge for young urban planners. Millions of drivers, each with
different goals and each making independent choices, combine to form a complex system with sometimes
predictable, sometimes chaotic behavior. As a devoted civil servant, you have been tasked with optimizing rush-
hour traffic over collections of roads.
All the roads lie between a residential area and a downtown business district. In the morning, each person living
in the residential area drives a route to the business district. The morning commuter traffic on any particular
road travels in only one direction, and no route has cycles (morning drivers do not backtrack).
Each road takes a certain time to drive, so some routes are faster than others. Drivers are much more likely to
choose the faster routes, leading to congestion on those roads. In order to balance the traffic as much as possible,
you are to add tolls to some roads so that the perceived “cost” of every route ends up the same. However, to
avoid annoying drivers too much, you must not levy a toll on any driver twice, no matter which route he or she
takes.
Figure 5 shows a collection of five roads that form routes from the residential area (at intersection 1) to the
downtown business district (at intersection 4). The driving cost of each road is written in large blue font. The
dotted arrows show the three possible routes from 1 to 4. Initially the costs of the routes are 10, 8 and 12. After
adding a toll of cost 2 to the road connecting 1 and 4 and a toll of cost 4 to the road connecting 3 and 4, the cost
of each route becomes 12.
Figure 5: Roads connecting residential area at intersection 1 to business district at intersection 4
You must determine which roads should have tolls and how much each toll should be so that every route from
start to finish has the same cost (driving time cost + possible toll) and no route contains more than one toll road.
Additionally, the tolls should be chosen so as to minimize the final cost. In some settings, it might be impossible
to impose tolls that satisfy the above conditions.
InputInput consists of several test cases. A test case starts with a line containing an integer N (2 N 50000), which
is the number of road intersections, and R (1 R 50000), which is the number of roads. Each of the next R
lines contains three integers xi, yi, and ci (1 xi, yi N, 1 ci 1000), indicating that morning traffic takes road i
from intersection xi to intersection yi with a base driving time cost of ci. Intersection 1 is the starting residential
area, and intersection N is the goal business district. Roads are numbered from 1 to R in the given input order.
Every intersection is part of a route from 1 to N, and there are no cycles.
The last test case is followed by a line containing two zeros.
Output For each test case, print one line containing the case number (starting with 1), the number of roads to toll (T),
and the final cost of every route. On the next T lines, print the road number i and the positive cost of the toll to
apply to that road. If there are multiple minimal cost solutions, any will do. If there are none, print
No solution. Follow the format of the sample output.
Sample Input Output for Sample Input 4 5
1 3 5
3 2 1
2 4 6
1 4 10
3 4 3
3 4
1 2 1
1 2 2
2 3 1
2 3 2
0 0
Case 1: 2 12
4 2
5 4
Case 2: No solution
Maratona de Programacao da SBC – ACM ICPC – 2009 8
Problema EDragster
Nome do arquivo fonte: dragster.c, dragster.cpp ou dragster.java
Embora nao seja uma modalidade muito popular no Brasil, as corridas de dragsters atraemmultidoes nos EUA. Os fas gostam de ver os carros velozes correndo a velocidades de ate400 km/h, mesmo que so por alguns segundos. Muitos competidores sao mecanicos amadoresque apenas incluiram foguetes e outros artefatos para criarem carros ultra velozes.
As competicoes de dragsters sao disputadas em torneios de eliminacao, onde cada disputaconsiste de dois competidores correndo lado a lado e somente um deles sendo declarado o ven-cedor (o que chegar primeiro, claro). Os vencedores sao entao rearranjados em novas partidas,ate que no final somente um competidor seja declarado o campeao.
Rubens e um piloto experiente, com carreira em diversas categorias, inclusive a Formula 1.Entretanto, apos enfrentar alguns contratempos, resolveu dedicar-se a competicoes de dragsters.Aproveitando-se da larga experiencia que ganhou durante a Formula 1, ele consegue, observandoos competidores, dizer qual a probabilidade de cada um dos competidores envolvidos ser ovencedor de uma dada disputa.
Embora Rubens seja bom piloto, nao e muito bom em matematica nem em programacao,e pediu a sua ajuda para, dadas as probabilidades calculadas por Rubens para a disputa entrecada par de pilotos, e a descricao das corridas do torneio, determinar a probabilidade que eletem de vencer o torneio.
Entrada
A entrada e composta de varios casos de teste. A primeira linha de um caso de teste conteminteiro N indicando o numero de competidores do torneio (2 ≤ N ≤ 300). Na descricao dotorneio, os competidores sao identificados por inteiros de 1 a N , e as corridas sao identificadaspor inteiros de N + 1 a 2×N − 1. Rubens e sempre identificado pelo numero 1. As N linhasseguintes descrevem a matriz M de probabilidades calculada por Rubens. A linha i contem Nnumeros reais M [i, j] separados por espacos (0 ≤ M [i, j] ≤ 1, para 1 ≤ i ≤ N e 1 ≤ j ≤ N).Cada elemento M [i, j] da matriz indica a probabilidade de o competidor i vencer o confrontocom o competidor j (0.001 ≤ M [i, j] ≤ 0.999 e M [i, j] + M [j, i] = 1 para i 6= j, e M [i, j] = 0para i = j). As probabilidades serao sempre dadas com tres casas decimais de precisao. Cadauma das N − 1 linhas seguintes contem dois inteiros A, B descrevendo uma corrida, sendoque A e B representam identificadores de competidores ou de corridas (1 ≤ A ≤ 2 × N − 1e 1 ≤ B ≤ 2 × N − 1). Note que a primeira dessas linhas descreve a corrida identificada porN +1, a segunda linha descreve a corrida identificada por N +2 e assim por diante. Quando umidentificador de corrida k aparece na entrada como A, isto significa que o competidor que venceua corrida k e quem disputara a corrida contra B. Da mesma forma, quando um identificadorde corrida k aparece na entrada como B, isto significa que o competidor que venceu a corridak e quem disputara a corrida contra A.
O final da entrada e indicado por uma linha que contem apenas um numero zero.
Os dados devem ser lidos da entrada padrao.
Saıda
Para cada caso de teste da entrada seu programa deve imprimir uma unica linha, contendo umnumero real, escrito com precisao de seis casas decimais, indicando a probabilidade de Rubens
Maratona de Programacao da SBC – ACM ICPC – 2009 9
vencer o torneio.
O resultado de seu programa deve ser escrito na saıda padrao.
Exemplo de entrada
4
0.000 0.500 0.400 0.400
0.500 0.000 0.500 0.500
0.600 0.500 0.000 0.600
0.600 0.500 0.400 0.000
1 2
3 4
5 6
5
0.000 0.500 0.600 0.600 0.001
0.500 0.000 0.500 0.500 0.500
0.400 0.500 0.000 0.500 0.500
0.400 0.500 0.500 0.000 0.500
0.999 0.500 0.500 0.500 0.000
3 8
9 6
4 5
1 2
0
Exemplo de saıda
0.200000
0.225125
ACM ICPC2007 – South American Regionals 11
Problem FFinding Seats
Source file name: find.c, find.cpp or find.java
A group of K friends is going to see a movie. However, they are too late to get good tickets,so they are looking for a good way to sit all nearby. Since they are all science students, theydecided to come up with an optimization problem instead of going on with informal argumentsto decide which tickets to buy.
The movie theater has R rows of C seats each, and they can see a map with the currentlyavailable seats marked. They decided that seating close to each other is all that matters, evenif that means seating in the front row where the screen is so big it’s impossible to see it all atonce. In order to have a formal criteria, they thought they would buy seats in order to minimizethe extension of their group.
The extension is defined as the area of the smallest rectangle with sides parallel to the seatsthat contains all bought seats. The area of a rectangle is the number of seats contained in it.They’ve taken out a laptop and pointed at you to help them find those desired seats.
Input
Each test case will consist on several lines. The first line will contain three positive integers R,C and K as explained above (1 ≤ R,C ≤ 300, 1 ≤ K ≤ R×C). The next R lines will containexactly C characters each. The j-th character of the i-th line will be ‘X’ if the j-th seat onthe i-th row is taken or ‘.’ if it is available. There will always be at least K available seats intotal.
Input is terminated with R = C = K = 0.
The input must be read from standard input.
Output
For each test case, output a single line containing the minimum extension the group can have.
The output must be written to standard output.
ACM ICPC2007 – South American Regionals 12
Sample input
3 5 5
...XX
.X.XX
XX...
5 6 6
..X.X.
.XXX..
.XX.X.
.XXX.X
.XX.XX
0 0 0
Output for the sample input
6
9
GohanTreino para a Maratona de Programacao – UFSC
Luıs Fernando Schultz Xavier da Silveira
Enunciado
Gohan e o filho de Goku e Chichi. Sendo um talentoso descendente de saiajin, Gohan nasceu com muito poder, mas so oconseguia liberar em situacoes emocionalmente fortes. Com o tempo Gohan aprendeu a controlar seu poder e virou um grandeguerreiro.
Em sua infancia, Gohan foi ao planeta Namek buscar as esferas do dragao para ressuscitar seus amigos mortos pelos saiajinsNappa e Vegeta no planeta Terra.
Em posse do radar do dragao, Gohan conseguiu plotar a posicao das 7 esferas do dragao em um plano cartesiano tendo elecomo origem.
Nesse problema, voce deve ajudar Gohan calculando a menor distancia que ele deve percorrer para juntar as 7 esferas.
Entrada
A entrada consiste de varios casos de teste. Cada caso de teste contem 7 pares de numeros inteiros xi e yi, onde xi e a abscissae yi a ordenada da i-esima esfera do dragao, 0 6 i < 7 e |xi|, |yi| 6 104.
Saıda
Para cada caso de teste, imprima o inteiro mais proximo do menor comprimento de um caminho que sai da origem e passa pelos7 pontos descritos na entrada.
Exemplo de Entrada Exemplo de Saıda0 01 12 23 34 45 56 6
8
Nota
Voce pode assumir que se x e o valor exato do menor comprimento de um caminho que coleta as esferas, entao∣∣∣∣(x− bxc)−
12
∣∣∣∣ > 10−4.
1
FreezaTreino para a Maratona de Programacao – UFSC
Luıs Fernando Schultz Xavier da Silveira
Enunciado
Freeza e um ser terrivelmente poderoso, controlador de boa parte do universo. Foi ele quem destruiu o planeta em que Gokunasceu, forcando seus pais a manda-lo para a Terra.
Freeza esta agora no planeta Namek em busca das esferas do dragao na esperanca de conseguir vida e juventude eternas.Mais especificamente, Freeza esta atacando uma vila de namekuzeijins para obter uma esfera do dragao.
Na vila existem n namekuzeijins, o i-esimo dos quais, 0 6 i < n, esta localizado na posicao (xi, yi) do plano. Uma tecnicacomum entre namekuzeijins e a fusao (por exemplo, Pıcolo se fundiu com Nail), entao pode haver mais de um namekuzeijin namesma posicao.
Freeza gostaria de usar seu ataque “dedo da morte” para exibir sua forca e se gabar (ele adora fazer isso). Com essa tecnica,Freeza dispara um raio da ponta de seus dedos que atravessa tudo o que ve pela frente. Esse raio viaja em linha reta.
Nesse problema, voce deve ajudar Freeza a matar a maior quantidade possıvel de namekuzeijins com um unico ataque.
Entrada
A entrada consiste de varios casos de teste, cada um dos quais comeca com uma linha contendo um numero inteiro n, 0 6 n 6 103,o numero de namekuzeijins na vila, e e seguido por n pares de inteiros xi e yi, |xi|, |yi| 6 109, a abscissa e a ordenada da posicaodaquele namekuzeijin.
Saıda
Para cada caso de teste, imprima a maior quantidade de namekuzeijins que pode ser eliminada com um so ataque (a quantidadede pontos em uma reta que maximiza a quantidade de pontos em cima dela).
Exemplo de Entrada Exemplo de Saıda20 01 140 01 12 21 0
23
1
Multiplication PuzzleNortheastern Europe 2001 – Far-Eastern Subregion
modified by Luıs Fernando Schultz Xavier da Silveira
Statement
The multiplication puzzle is played with a row of cards, each containing a single positive integer. During the move player takesone card out of the row and scores the number of points equal to the product of the number on the card taken and the numberson the cards on the left and on the right of it. It is not allowed to take out the first and the last card in the row. After the finalmove, only two cards are left in the row.
The goal is to take cards in such order as to minimize the total number of scored points.For example, if cards in the row contain numbers 10 1 50 20 5, player might take a card with 1, then 20 and 50, scoring
10× 1× 50 + 50× 20× 5 + 10× 50× 5 = 500 + 5000 + 2500 = 8000.
If he would take the cards in the opposite order, i.e. 50, then 20, then 1, the score would be
1× 50× 20 + 1× 20× 5 + 10× 1× 5 = 1000 + 100 + 50 = 1150.
Input
The input contains several test cases. Each test case contains a number n (3 6 n 6 100) and n integers in the range from 1 to100.
Output
For each test case, output a single integer on a line by itself – the minimal score.
Sample Input Sample Output610 1 50 50 20 5
3650
1
Old MagicianGoogle Code Jam 2008 – Practice Contest – Problem A
modified by Luıs Fernando Schultz Xavier da Silveira
Statement
A magician does the following magic trick. He puts W white balls and B black balls in his hat and asks someone from theaudience, say Bob, to remove pairs of balls in whatever order Bob would desire. After removing a pair of balls, Bob is asked toplace a white ball back into the hat if they are the same color. Otherwise he is asked to place a black ball into the hat.
When Bob is left with only one ball in the hat, he asks the magician what color the last ball is. Needless to say, the magiciancan’t see the order by which Bob does the replacements.
The problem is that the magician, like most magicians, is old and sometimes forgets how to do the trick. Being the kindperson you are, you are going to help the magician.
For each pair of numbers (W, B) you are asked to output one of the following:
• WHITE – if the last ball in the hat will be white for sure.
• BLACK – if the last ball in the hat will be black for sure.
• UNKNOWN – if you can’t be sure of the last ball’s color.
Input
The first line of the input file contains the number of cases, N . N test cases follow.Each case contains W and B (0 6 W, B 6 109) on a line separated by a space.
Output
For each input case, you should output:
Case #X: Y
where X is the number of the test case and Y is either WHITE, BLACK or UNKNOWN as explained above.
Sample Input Sample Output23 13 6
Case #1: BLACKCase #2: WHITE
1