Está en la página 1de 14

ADA Tarea 4 2024-1

ADA - Análisis y Diseño de Algoritmos, 2024-1


Tarea 4: Semanas 8 y 9
Para entregar el domingo 14 de abril de 2024
Problemas conceptuales a las 23:59 por BrightSpace
Problemas prácticos a las 23:59 en la arena de programación

Tanto los ejercicios como los problemas deben ser resueltos, pero únicamente las soluciones de los problemas deben
ser entregadas. La intención de los ejercicios es entrenarlo para que domine el material del curso; a pesar de que no
debe entregar soluciones a los ejercicios, usted es responsable del material cubierto en ellos.

Instrucciones para la entrega


Para esta tarea y todas las tareas futuras, la entrega de soluciones es individual. Por favor escriba claramente su nombre,
código de estudiante y sección en cada hoja impresa entregada o en cada archivo de código (a modo de comentario).
Adicionalmente, agregue la información de fecha y nombres de compañeros con los que colaboró; igualmente cite
cualquier fuente de información que utilizó.

¿Cómo describir un algoritmo?


En algunos ejercicios y problemas se pide “dar un algoritmo” para resolver un problema. Una solución debe tomar
la forma de un pequeño ensayo (es decir, un par de párrafos). En particular, una solución debe resumir en un párrafo
el problema y cuáles son los resultados de la solución. Además, se deben incluir párrafos con la siguiente informa-
ción:
• una descripción del algoritmo en castellano y, si es útil, pseudo-código;
• por lo menos un diagrama o ejemplo que muestre cómo funciona el algoritmo;
• una demostración de la corrección del algoritmo; y
• un análisis de la complejidad temporal del algoritmo.
Recuerde que su objetivo es comunicar claramente un algoritmo. Las soluciones algorítmicas correctas y descritas
claramente recibirán alta calificación; soluciones complejas, obtusas o mal presentadas recibirán baja calificación.

1
ADA Tarea 4 2024-1

Problemas conceptuales
1. Ejercicio 4-17: Interval Scheduling Problem (Kleinberg & Tardos, página 197).

Problemas prácticos
Hay ocho problemas prácticos cuyos enunciados aparecen a partir de la siguiente página. Los problemas A, C, D y E
son obligatorios, mientras que los demás son opcionales y podrán ser resueltos para obtener puntos de bono.

2
ADA Tarea 3 2024-1

A - Calculus Simplified
Source file name: calculus.py
Time limit: x seconds

We define an expression as below:

⟨expression⟩ := ⟨number⟩ | ⟨expression⟩ + ⟨expression⟩ | ⟨expression⟩ − ⟨expression⟩ | (⟨expression⟩)

where ⟨number⟩ is defined to be an integer.


In this problem you are given an expression with all its numbers replaced with character ’x’. Then you are given a set of
numbers that were actually in the expression. We know that numbers were placed in the expression in such a way that
the expression evaluates to maximum possible value among all other placements. Write a program that calculates this
maximum value.

Input
In the first line there is an integer T (T ≤ 100), the number of tests. Each test begins with the expression itself. Next line is
an integer N, the number of numbers in the expression. In the final line of each test there are N integers ai (∥ai ∥ ≤ 3000).
Each of these numbers should be used in the expression exactly once. It is guaranteed that the expression can be parsed by
the definition in the problem statement and its length will not exceed 105 . There are no whitespaces in the expression and
all numbers are replaced with a single ’x’. The number of ’x’s in the expression is N.

The input must be read from standard input.

Output
For each test output the maximum possible value of the expression in a single line.

The output must be written to standard output.

Sample Input Sample Output

3 2
x 2
1 1
2
x-x
2
-1 1
(x)+(x)-(x)
3
1 1 1

3
ADA Tarea 3 2024-1

B - Fair Division
Source file name: division.py
Time limit: x seconds

It’s your friend’s birthday, and you and some other people decided to buy him a copy of StarCraft II, because who wouldn’t
want to have that?
You agreed to divide the costs as fairly as possible. Since some of you have more money available than others, you also
agreed that nobody has to pay more than he can afford. Every contribution will be a multiple of 1 cent, i.e., nobody can pay
fractions of a cent.
Everybody writes down the maximum amount he is able to contribute. Taking into account these maximum amounts from
everybody, you share the cost of the present as fairly as possible. That means, you minimize the largest distance of the
1
contributions to -th of the total cost. In case of a tie, minimize the second largest distance, and so on. Since the smallest
n
unit of contribution is 1 cent, there might be more than one possible division of the cost. In that case, persons with a higher
maximum amount pay more. If there is still ambiguity, those who come first in the list pay more.
Since you bought the present, it is your task to figure out how much everybody has to pay (including you).

Input
On the first line a positive integer: the number of test cases, at most 100. After that per test case:
• One line with two integers p and n: the price of the present in cents (1 ≤ p ≤ 1000000) and the number of people
(2 ≤ n ≤ 100) who contribute to the present (including you).
• One line with n integers ai (1 ≤ ai ≤ 1000000), where ai is the maximum amount, in cents, that the i-th person on the
list is able to contribute.

The input must be read from standard input.

Output
Per test case:
• One line with n integers: the amounts each person has to contribute according to the scheme. If the total cost cannot
be divided according to the above rules, the line must contain ’IMPOSSIBLE’ instead.

The output must be written to standard output.

Sample Input Sample Output

3 6 6 4 4
20 4 IMPOSSIBLE
10 10 4 4 8 7 8 7 4
7 3
1 1 4
30/4 = 7.5 34 5
9 8 9 9 4
23/3 =7

16/2 = 8

4
ADA Tarea 3 2024-1

C - Tian Ji - The Horse Racing


Source file name: racing.py
Time limit: x seconds

Here is a famous story in Chinese history.


That was about 2300 years ago. General Tian Ji was a high official in the country Qi. He likes to play horse
racing with the king and others.
Both of Tian and the king have three horses in different classes, namely, regular, plus, and super. The rule
is to have three rounds in a match; each of the horses must be used in one round. The winner of a single round
takes two hundred silver dollars from the loser.
Being the most powerful man in the country, the king has so nice horses that in each class his horse is
better than Tian’s. As a result, each time the king takes six hundred silver dollars from Tian.
Tian Ji was not happy about that, until he met Sun Bin, one of the most famous generals in Chinese history.
Using a little trick due to Sun, Tian Ji brought home two hundred silver dollars and such a grace in the next
match.
It was a rather simple trick. Using his regular class horse race against the super class from the king, they
will certainly lose that round. But then his plus beat the king’s regular, and his super beat the king’s plus. What
a simple trick. And how do you think of Tian Ji, the high ranked official in China?

Were Tian Ji lives in nowadays, he will certainly laugh at himself. Even more, were he sitting in the ACM contest right now,
he may discover that the horse racing problem can be simply viewed as finding the maximum matching in a bipartite graph.
Draw Tian’s horses on one side, and the king’s horses on the other. Whenever one of Tian’s horses can beat one from the
king, we draw an edge between them, meaning we wish to establish this pair. Then, the problem of winning as many rounds
as possible is just to find the maximum matching in this graph. If there are ties, the problem becomes more complicated, he
needs to assign weights 0, 1, or -1 to all the possible edges, and find a maximum weighted perfect matching . . .
However, the horse racing problem is a very special case of bipartite matching. The graph is decided by the speed of
the horses — a vertex of higher speed always beat a vertex of lower speed. In this case, the weighted bipartite matching
algorithm is a too advanced tool to deal with the problem.
In this problem, you are asked to write a program to solve this special case of matching problem

Input
The input consists of up to 50 test cases. Each case starts with a positive integer n (n ≤ 1000) on the first line, which is the
number of horses on each side. The next n integers on the second line are the speeds of Tian’s horses. Then the next n
integers on the third line are the speeds of the king’s horses.
The input ends with a line that has a single ’0’ after the last test case.

The input must be read from standard input.

Output
For each input case, output a line containing a single number, which is the maximum money Tian Ji will get, in silver
dollars.

5
ADA Tarea 3 2024-1

The output must be written to standard output.

Sample Input Sample Output

3 200
92 83 71 0
95 87 74 0
2
20 20
20 20
2
20 19
22 18
0

6
ADA Tarea 3 2024-1

D - Slim Span
Source file name: span.py
Time limit: x seconds

Given an undirected weighted graph G, you should find one of spanning trees specified as follows.
The graph G is an ordered pair (V, E), where V is a set of vertices {v1 , v2 , . . . , vn } and E is a set of undirected edges
{e1 , e2 , . . . , em }. Each edge e ∈ E has its weight w(e).

Figure 1: A graph G and the weights of the edges

A spanning tree T is a tree (a connected subgraph without cycles) which connects all the n vertices with n − 1 edges. The
slimness of a spanning tree T is defined as the difference between the largest weight and the smallest weight among the
n − 1 edges of T .
For example, a graph G in Figure 1(a) has four vertices {v1 , v2 , v3 , v4 } and five undirected edges {e1 , e2 , e3 , e4 , e5 }. The
weights of the edges are w(e1 ) = 3, w(e2 ) = 5, w(e3 ) = 6, w(e4 ) = 6, w(e5 ) = 7 as shown in Figure 1(b).

Figure 2: Examples of the spanning trees of G

There are several spanning trees for G. Four of them are depicted in Figure 2(a)(d). The spanning tree T a in Figure 2(a) has
three edges whose weights are 3, 6 and 7. The largest weight is 7 and the smallest weight is 3 so that the slimness of the tree
Ta is 4. The slimnesses of spanning trees T b , T c and T d shown in Figure 2(b), (c) and (d) are 3, 2 and 1, respectively. You
can easily see the slimness of any other spanning tree is greater than or equal to 1, thus the spanning tree T d in Figure 2(d)
is one of the slimmest spanning trees whose slimness is 1.
Your job is to write a program that computes the smallest slimness.

Input
The input consists of multiple datasets, followed by a line containing two zeros separated by a space. Each dataset has the
following format.
nm
a1 b1 w1

7
ADA Tarea 3 2024-1

...
am bm wm
Every input item in a dataset is a non-negative integer. Items in a line are separated by a space. n is the number of the
vertices and m the number of the edges. You can assume 2 ≤ n ≤ 100 and 0 ≤ m ≤ n(n − 1)/2. ak and bk (k = 1, . . . , m) are
positive integers less than or equal to n, which represent the two vertices vak and vbk connected by the k-th edge ek . wk is a
positive integer less than or equal to 10000, which indicates the weight of ek . You can assume that the graph G = (V, E) is
simple, that is, there are no self-loops (that connect the same vertex) nor parallel edges (that are two or more edges whose
both ends are the same two vertices).

The input must be read from standard input.

Output
For each dataset, if the graph has spanning trees, the smallest slimness among them should be printed. Otherwise, ’-1’
should be printed. An output should not contain extra characters.

The output must be written to standard output.

8
ADA Tarea 3 2024-1

Sample Input Sample Output

4 5 1
1 2 3 20
1 3 5 0
1 4 6 -1
2 4 6 -1
3 4 7 1
4 6 0
1 2 10 1686
1 3 100 50
1 4 90
2 3 20
2 4 80
3 4 40
2 1
1 2 1
3 0
3 1
1 2 1
3 3
1 2 2
2 3 5
1 3 6
5 10
1 2 110
1 3 120
1 4 130
1 5 120
2 3 110
2 4 120
2 5 130
3 4 120
3 5 110
4 5 120
5 10
1 2 9384
1 3 887
1 4 2778
1 5 6916
2 3 7794
2 4 8336
2 5 5387
3 4 493
3 5 6650
4 5 1422
5 8
1 2 1
2 3 100
3 4 100
4 5 100
1 5 50
2 5 50
3 5 50
4 1 150
0 0
9
ADA Tarea 3 2024-1

E - Extreme Terror
Source file name: terror.py
Time limit: x seconds

“Kana Shamsu” is a frightening local terror. There are N business places in his area. He (Kana Shamsu) claims extortion to
the business owners to continue their business, otherwise they will suffer. Shamsu is a dangerous man. There is a rumor that
Shamsu can kill people for money. The total business society is feeling unsafe. It comes as an unexpected disaster.
But Shamsu has his own boss too. He works under a very powerful godfather named “Vuri Kamal”. Kamal is a very busy
person, as he needs to manage lots of local terror like Shamsu. So he (Kamal) doesn’t want to know how much money
Shamsu can receive from the business owner. He claims Shamsu to give him some specific amount of money Xi for those
business places (where i = 0 to N − 1). On the other hand, business owners want to make an agreement with Shamsu for
the donation amount Yi for each business (where i = 0 to N − 1).
So it comes to a situation that, for each business place i (0 ≤ i < N) Shamsu gets Yi from the business owner and needs
to give the Kamal Xi . Meanwhile Shamsu realizes that, for some business places, his godfather Mr. Vuri Kamal claims
more than he can manage from that place. To some extent, Vuri Kamal gives Shamsu a chance to deny collecting money
from at most K places. So now Shamsu needs to find a process to maximize his profit he can gain from these N business
places.

Input
There will be T (T ≤ 100) test cases. For each test case, there will be three lines of input. In the first line you will be given
N (1 ≤ N < 106 ) and K (0 ≤ K ≤ N). The second line contains N space separated integers Xi (0 ≤ Xi < 108 ), denoting the
amount of money Vuri Kamal claims from Shamsu for each business place. The next line will contain another N space
separated integers Yi (0 ≤ Yi < 108 ) denoting Shamsu can get from the business owner.

The input must be read from standard input.

Output
In the output, you will print the maximum profit Shamsu can earn for the given input. If it is not possible to earn positive
profit (total profit ≤ 0) for a given input, you will print ’No Profit’ without the quote. For further instruction, follow the
sample input output given bellow.

The output must be written to standard output.

Sample Input Sample Output

2 Case 1: 5
5 2 Case 2: No Profit
4 5 6 7 8
5 6 7 8 9
5 0
7 6 7 8 7
4 5 6 7 8

10
ADA Tarea 3 2024-1

F - High School Assembly


Source file name: assembly.py
Time limit: x seconds

It’s Saturday morning of a new week and students of National High School have gathered on the central ground for an
assembly.
At the beginning, students from different classes stand in their own lines. Then the class teachers of each class move over
from front to back and organize the line according to the increasing order of students’ heights. They can pick a student
from any position and send him to the end of the line.
Mr. Kapono Khan is the class teacher of 7th grade. He doesn’t like this job of walking along the line back and forth. So he
wants to organize the students with minimal number of moves. As usual, you are here to help Mr. Khan. Given the heights
of each student of his class, your job is to find out minimum number of moves required to sort the students based on the
increasing order of their heights. Picking up a student from any position and sending him to the end is defined as a move
for this problem. Luckily students of his class have unique heights.

Input
There will be T test cases, (T ≤ 100).
Input for each case will start with an integer n (1 ≤ n ≤ 104 ) which represents the number of students of the class. Then an
array of n integers will follow where 1 ≤ Hi ≤ n and each height is unique.

The input must be read from standard input.

Output
For each case, print case number using the format Case x:’ (without quotes) followed by an integer showing minimum
number of moves required to sort the line in increasing order.
Explanation of Sample I/O
Case 1: move 3 to last, move 4 to last, move 5 to last.

The output must be written to standard output.

Sample Input Sample Output

2 Case 1: 3
5 Case 2: 6
5 1 3 2 4
9
4 5 1 2 6 3 8 9 7

11
ADA Tarea 3 2024-1

G - The ’Hire-a-Coder’ Business Model


Source file name: model.py
Time limit: x seconds

As some other websites, ’Hire-a-Coder’ is a new website that works as an agent between custom software buyers and
freelance software developers. According to the ’Hire-a-Coder’ business model, a number of clients are registered in the
system. Some of them are software buyers. They post custom software projects on the site. Then the coders bid on the
projects and each of the projects is assigned to a single particular coder after the biddings and dealings. Any buyer may
have more than one open project at a time. Similarly any coder can take up more than a single project at any time. But no
coder is allowed to take multiple projects from the same buyer at a time. The site works as a medium in the total procedure.
Now, if a coder successfully completes his assigned project and the buyer accepts his work, ’Hire-a-Coder’ gets some
commission for that. But if the coder fails to complete a project or satisfy the client with his work, the company has to pay
a penalty to the buyer thus suffering a loss.
Recently it is found out that there are a number of fake coders that take up a project but never finish their work eventually
causing the company a good amount of loss. So, they need someone to advise them which of the possible project
assignments are to make and which are to avoid in order to minimize their loss.
Assume, all the registered clients of the company are denoted by a unique positive integer number between 1 and N. By the
help of a great fortune-teller, they have already tabulated the future of assigning all possible buyer-coder pairs. You can
assume that assigning any project from a particular buyer to a particular coder has the same future. In their tabulation, if a
coder fails to do a project from a buyer, a positive integer value is assigned to this particular buyer-coder pair. The value
indicates the amount of loss the company is going to suffer if they pair-up these two clients. On the other hand, in case of a
successful completion of a project from a buyer-coder pair, a negative integer value is assigned to this pair which denotes
negative loss i.e. amount of profit.
You are assured that, every single individual in the community has a communication link to all other people in this
community, not necessarily through direct acquaintance. The link may well be via one or more other people. Also note that,
if ’A’ knows ’B’ then ’B’ always knows ’A’.
There’s one more problem. You have the pairing information for all those N people but you don’t know which of them
are buyers and which of them are coders. But you know that, all the registered clients are either a buyer or a coder and
there’s no one who is a buyer and a coder simultaneously. If the data for any test case violates this assumption, print
’Invalid data, Idiot!’ and stop processing that case further.
Now, bearing all these factors in mind, you are to select a subset of the possible pairings so that if the company makes
strictly those assignments, their loss is minimum possible. Also, you have to choose the subset so that every single person
still has a direct / indirect communication link to all other people.

Input
Every test case starts with a single positive integer N (2 ≤ N ≤ 200) which is the number of registered clients. The second
line has another positive integer E (1 ≤ N ≤ 11000), the number of pairs tabulated by the fortune-teller. Each of the next E
lines contains 3 integers A, B and C which means, if the company pairs A with B, they will end up in a loss with amount C.
(1 ≤ A, B ≤ N) and −1000 ≤ C ≤ 1000).
The last test case will be followed immediately by a single line containing a ’0’. This line indicates the end of file.

The input must be read from standard input.

Output
If the there is any inconsistency in the data (as described in the statement) print ’Invalid data, Idiot!’ in a single
line. Otherwise, print the minimum possible loss the company can afford without disconnecting the social network.

The output must be written to standard output.

12
ADA Tarea 3 2024-1

Sample Input Sample Output

6 8
9 Invalid data, Idiot!
1 4 1 -7
2 4 2
3 4 3
1 5 2
2 5 3
3 5 2
1 6 3
2 6 1
3 6 2
6
10
1 2 3
1 4 1
2 4 2
3 4 3
1 5 2
2 5 3
3 5 2
1 6 3
2 6 1
3 6 2
4
4
1 3 5
1 4 -3
2 3 2
2 4 -6
0

13
ADA Tarea 3 2024-1

H - Songs
Source file name: songs.py
Time limit: x seconds

John Doe is a famous DJ and, therefore, has the problem of optimizing the placement of songs on his tapes. For a given
tape and for each song on that tape John knows the length of the song and the frequency of playing that song. His problem
is to record the songs on the tape in an order that minimizes the expected access time. If the songs are recorded in the order
S s(1) , . . . , S s(n) on the tape then the function that must be minimized is
n
X s(i)
X
f s(i) l s( j)
i=1 j=1

where f s(i) is the frequency of playing the i-th song and l is the length of the song. Can you help John?

Input
The program input is from a text file. Each data set in the file stands for a particular set of songs that must be recorded on a
tape. A data set starts with the number N (fits a 16 bit integer) of songs. Follow N the song specifications, and in the end, a
number representing the position of a song S on the optimized tape. A song specification consists of the song identifier (fits
an integer), the length of the song (fits a 16 bit integer), and the frequency of playing the song (a floating-point number).
The program prints the identifier of the song S .
White spaces can occur freely in the input. The input data are correct and terminate with an end of file.

The input must be read from standard input.

Output
For each set of data the program prints the result to the standard output from the beginning of a line.
Note: An input/output sample is in the table below. There is a single data set that contains 5 song specifications. The first
song has the identifier 1, length 10 and playing frequency 45.5 etc. The result for the data set is the identifier of the 3rd
song on the optimized tape. It is 2 for the given example.

The output must be written to standard output.

Sample Input Sample Output

5 2
1 10 45.5
2 5 20
30 20 10
400 50 35
15 17 89.9
3

14

También podría gustarte