task stringlengths 0 154k | __index_level_0__ int64 0 39.2k |
|---|---|
IOI07 Flood (FLOOD)
English
Vietnamese
In 1964 a catastrophic flood struck the city of Zagreb. Many buildings were completely destroyed when the water struck their walls. In this task, you are given a simplified model of the city before the flood and you should determine which of the walls are left intact after the flood.
The model consists of N points in the coordinate plane and W walls. Each wall connects a pair of points and does not go through any other points. The model has the following additional properties:
No two walls intersect or overlap, but they may touch at endpoints;
Each wall is parallel to either the horizontal or the vertical coordinate axis.
Initially, the entire coordinate plane is dry. At time zero, water instantly floods the exterior (the space not bounded by walls). After exactly one hour, every wall with water on one side and air on the other breaks under the pressure of water. Water then floods the new area not bounded by any standing walls. Now, there may be new walls having water on one side and air on the other.
After another hour, these walls also break down and water floods further. This procedure repeats until water has flooded the entire area.
An example of the process is shown in the following figure.
The state at time zero. Shaded cells represent the flooded area, while white cells represent dry area (air). The state after one hour. The state after two hours. Water has flooded the entire area and the 4 remaining walls cannot be broken down.
TASK
Write a program that, given the coordinates of the N points, and the descriptions of W walls connecting these points, determines which of the walls are left standing after the flood.
INPUT
The first line of input contains an integer N (2 ≤ N ≤ 100 000), the number of points in the plane.
Each of the following N lines contains two integers X and Y (both between 0 and 1 000 000, inclusive), the coordinates of one point. The points are numbered 1 to N in the order in which they are given. No two points will be located at the same coordinates.
The following line contains an integer W (1 ≤ W ≤ 2N), the number of walls.
Each of the following W lines contains two different integers A and B (1 ≤ A ≤ N, 1 ≤ B ≤ N), meaning that, before the flood, there was a wall connecting points A and B. The walls are numbered 1 to W in the order in which they are given.
OUTPUT
The first line of output should contain a single integer K, the number of walls left standing after the flood. The following K lines should contain the indices of the walls that are still standing, one wall per line. The indices may be output in any order.
GRADING
In test cases worth a total of 40 points, all coordinates will be at most 500.
In those same cases, and cases worth another 15 points, the number of points will be at most 500.
EXAMPLE
input
15
1 1
8 1
4 2
7 2
2 3
4 3
6 3
2 5
4 5
6 5
4 6
7 6
1 8
4 8
8 8
17
1 2
2 15
15 14
14 13
13 1
14 11
11 12
12 4
4 3
3 6
6 5
5 8
8 9
9 11
9 10
10 7
7 6
output
4
6
15
16
17 | 34,800 |
IOI06 The Valley of Mexico (MEXICO)
English
Vietnamese
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.
INPUT
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.
Sample input
7
9
1 4
5 1
1 7
5 6
2 3
3 4
2 6
4 6
6 7
OUTPUT
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.
Sample output
2
3
4
1
7
6
5
GRADING
For a set of test cases worth a total of 40 points, each test case will meet the following requirements:
3 ≤ c ≤ 20 | 34,801 |
IOI06 Pyramid (MPYRAMID)
English
Vietnamese
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.
INPUT
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.
Sample input
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
OUTPUT
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.
Sample output
4 1
6 2
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 | 34,802 |
IOI05 Birthday (PBIR)
English
Vietnamese
It is Byteman’s birthday today. There are n children at his birthday party (including Byteman). The children are
numbered from 1 to n. Byteman’s parents have prepared a big round table and they have placed n chairs around the table.
When the children arrive, they take seats. The child number 1 takes one of the seats. Then the child number 2 takes the
seat on the left. Then the child number 3 takes the next seat on the left, and so on. Finally the child number n takes the
last free seat, between the children number 1 and n-1 .
Byteman’s parents know the children very well and they know that some of the children will be noisy, if they sit too close
to each other. Therefore the parents are going to reseat the children in a specific order. Such an order can be described by
a permutation p
1
,p
2
, . . . ,p
n
(p
1
,p
2
, . . . ,p
n
are distinct integers from 1 to n) — child p
1
should sit between p
n
and p
2
, child p
i
(for i = 2 ,3 , . . . ,n-1 ) should sit between p
i-1
and p
i+1
, and child p
n
should sit between p
n-1
and p
1
. Please note, that
child p
1
can sit on the left or on the right from child p
n
.
To seat all the children in the given order, the parents must move each child around the table to the left or to the right
some number of seats. For each child, they must decide how the child will move — that is, they must choose a direction of
movement (left or right) and distance (number of seats). On the given signal, all the children stand up at once, move to
the proper places and sit down.
The reseating procedure throws the birthday party into a mess. The mess is equal to the largest distance any child
moves. The children can be reseated in many ways. The parents choose one with minimum mess. Help them to find such
a way to reseat the children.
Task
Your task is to write a program that:
reads from the standard input the number of the children and the permutation describing the desired order of the
children,
determines the minimum possible mess,
writes the result to the standard output.
Input
The first line of standard input contains one integer n (1 ≤ n ≤ 1 000 000 ). The second line contains n integers
p
1
,p
2
, . . . ,p
n
, separated by single spaces. Numbers p
1
,p
2
, . . . ,p
n
form a permutation of the set {1 ,2 , . . . ,n} describing
the desired order of the children. Additionally, in 50% of the test cases, n will not exceed 1 000.
Output
The first and the only line of standard output should contain one integer: the minimum possible mess.
Example
For the input data:
6
3 4 5 1 2 6
the correct result is:
2
The left figure shows the initial arrangement of the children. The middle figure shows the result of the following reseating:
children number 1 and 2 move one place, children number 3 and 5 move two places, and children number 4 and 6 do not
change places. The conditions of arrangement are fulfilled, since 3 sits between 6 and 4, 4 sits between 3 and 5, 5 sits
between 4 and 1, 1 sits between 5 and 2, 2 sits between 1 and 6, and 6 sits between 2 and 3. There exists another possible
final arrangement of children, depicted in the right figure. In both cases no child moves more than two seats. | 34,803 |
IOI05 Rivers (RIVERS)
English
Vietnamese
Nearly all of the Kingdom of Byteland is covered by forests and rivers. Small rivers meet to form bigger rivers, which
also meet and, in the end, all the rivers flow together into one big river. The big river meets the sea near Bytetown.
There are n lumberjacks’ villages in Byteland, each placed near a river. Currently, there is a big sawmill in Bytetown
that processes all trees cut in the Kingdom. The trees float from the villages down the rivers to the sawmill in Bytetown.
The king of Byteland decided to build k additional sawmills in villages to reduce the cost of transporting the trees downriver.
After building the sawmills, the trees need not float to Bytetown, but can be processed in the first sawmill they encounter
downriver. Obviously, the trees cut near a village with a sawmill need not be transported by river. It should be noted
that the rivers in Byteland do not fork. Therefore, for each village, there is a unique way downriver from the village to
Bytetown.
The king’s accountants calculated how many trees are cut by each village per year. You must decide where to build the
sawmills to minimize the total cost of transporting the trees per year. River transportation costs one cent per kilometre,
per tree.
Task
Write a program that:
reads from the standard input the number of villages, the number of additional sawmills to be built, the number of
trees cut near each village, and descriptions of the rivers,
calculates the minimal cost of river transportation after building additional sawmills,
writes the result to the standard output.
Input
The first line of input contains two integers: n — the number of villages other than Bytetown (2 ≤ n ≤ 100 ), and k — the
number of additional sawmills to be built (1 ≤ k ≤ 50 and k ≤ n). The villages are numbered 1 ,2 , . . . ,n, while Bytetown
has number 0.
Each of the following n lines contains three integers, separated by single spaces. Line i+1 contains:
w
i
— the number of trees cut near village i per year (0 ≤ w
i
≤ 10 000 ),
v
i
— the first village (or Bytetown) downriver from village i (0 ≤ v
i
≤ n),
d
i
— the distance (in kilometres) by river from village i to vi (1 ≤ d
i
≤ 10 000 ).
It is guaranteed that the total cost of floating all the trees to the sawmill in Bytetown in one year does not exceed
2 000 000 000 cents.
In 50% of test cases n will not exceed 20.
Output
The first and only line of the output should contain one integer: the minimal cost of river transportation (in cents).
Example
For the input data:
4 2
1 0 1
1 1 10
10 2 5
1 2 3
the correct result is:
4
The above picture illustrates the example input data. Village numbers are given inside circles. Numbers below the circles
represents the number of trees cut near villages. Numbers above the arrows represent rivers’ lengths.
The sawmills should be built in villages 2 and 3. | 34,804 |
BOI 97 - Factorial (BOIFAC)
For a positive integer number N, find all positive integer numbers X (if any such number exists) with the property that the number 1*2*3*...*X has exactly N decimal digits. Assume that N is at most 150,000.
Input
A single line which contains a positive integer number denoting the number N.
Output
The first line should contain the string "NO", if such a number does not exist. Otherwise, the first line should contain a positive integer denoting how many X numbers exist. Then print all the X numbers, one number per line.
Example
Input:
5
Output:
1
8 | 34,805 |
BOI 97 - Task Execution (BOI97TE)
Assume that we have a number of tasks that must be executed. However, the tasks are not independent to each other. We say that task 2 depends on task 1, if the execution of task2 can start after the completion of task 1. However, we may find tasks that at any given time can be executed in parallel, saving time. Given a number of tasks and their dependencies, determine the shortest time that all tasks can be executed in a computer with an infinite number of processors. Then, you are requested to determine the minimum number of processors in order to execute the tasks in the (previously found) shortest time. Each task takes 1 time unit of execution. The tasks are represented by positive integers from 1 to N (N<=200).
Input
The first line contains a positive integer number N denoting the number of tasks to be executed in the computer, and another positive integer number M, denoting the number of dependencies. The next M lines until the end of the input file, contain the dependencies between the tasks. For example, when the input line, which corresponds to a dependency, contains the string "2 3", this means that in order to start the execution of task 3, task 2 must be completed first. Data is always correct and there is always a solution.
Output
Output will consist only one line, which contains two positive integer numbers, separated by space character. The first number T denotes the minimum number of time units that we need in order to execute all tasks, assuming an infinite number of processors. The second number denotes the minimum number of processors we can use in order to execute the tasks in T time units.
Example
Input:
6 6
1 4
2 5
3 6
4 6
4 5
5 6
Output:
4 2 | 34,806 |
BOI 97 - Street Network (BOI97SN)
The street network of a city is composed of streets and nodes. In a node, two or more streets can meet. All streets are one-way streets. Note also that, two nodes can be connected directly by more than one street, and one node can have a street that loops back to itself. Write a computer program in order to address the following issues:
1. Is it possible to start from at least one node A and visit ALL streets exactly once ?
2. How many nodes can serve as starting points in order to satisfy the property of the previous case ?
3. For each node X, how many paths of length S exist starting from X and ending to X, where any street or node can be visited more than once ?
Input
In the first line in the input is a positive integer number N (N<=50), denoting the number of nodes in the city street network. The second line contains a positive integer number S (S<=3) denoting the path length. The next N lines contain the network description in matrix form. More precisely, the element in row I and column J is the number of streets from node I to node J.
Output
The first line contains the string "YES" if you can start from a node, travel through all streets exactly once, and arrive either at the starting point, or at another node. Otherwise, the string "NO" should appear in the output. If the answer is "YES", the next line of the output file should contain a positive integer number denoting how many nodes can serve as starting points. Finally, the last line of the output file should contain N positive integers (separated by a space) that show for each node how many different paths with length S exist such that each path leads from the node back to itself. These numbers should be sorted in increasing order.
Example
Input 1:
3
2
1 1 0
1 1 1
0 1 1
Output:
YES
3
2 2 3
Input 2:
3
2
1 1 0
1 1 2
0 0 1
Output:
NO
1 2 2 | 34,807 |
First Number (MDIGITS2)
English
Vietnamese
A sequence of digits is obtained by writing down decimal representations of all integers starting with 1
and continuing up to a certain number N consecutively like this:
12345678910111213141516171819202122 ...
etc.
Write a program that will compute the position of the first occurrence of the decimal representation
of number N in the sequence.
Input
The first and only line of the input contains the integer N, 1 ≤ N ≤ 100,000.
Output
The first and only line of output should contain the position of the first occurrence of the decimal
representation of number N in the sequence.
Sample
input
15
output
20
input
34
output
3
input
142
output
73 | 34,808 |
The God-land (HCN3D)
English
Tiếng Việt
How great is our God! To show the respect for God, Bethlehem people decide to build a large area for memorial called "The God-land". There's a story that God used to visit N areas which is rectangles having edges paralell to the axises, described by the co-ordinate of a pair of opposite vertices: X
i1
, Y
i1
, X
i2
, Y
i2
(any two of them may have no common point, one common vertex or one common edge at most); on which of them there is a kind of grass called C
i
. People there want to build the God-land which is also a rectangle having edges parallel to the axises, putting on area(s) mentioned above, having a same kind of grass and
having the maximum area
! Help them to find the God-land before this Christmas!
Input
- The first line contains N.
- Next N line(s), each line contains X
i1
, Y
i1
, X
i2
, Y
i2
and C
i
describing the i
th
area to which God used to visit.
Output
- The maximum area found.
Sample
Input:
5
1 1 3 3 1
3 1 5 3 1
1 4 3 6 1
3 4 5 6 1
0 3 6 4 2
Output:
8
Input:
5
5 5 6 6 22
3 4 6 5 22
6 3 7 6 22
5 6 8 7 22
4 5 5 8 22
Output:
9
Limitations
- N ≤ 2500.
- 0 ≤ X
i1
, Y
i1
, X
i2
, Y
i2
≤ 10
9
.
- 1 ≤ C
i
≤ 100.
Sorry for my bad English!^_^ Please comment for a better translation ;) | 34,809 |
Homeless Jozo (HOMELESS)
English
Vietnamese
Homeless Jozo bought a monthly railway ticket so he could sleep in worm wagons and dream of a
better life.
You are given a list of all stations and railways that connect them and their length (times it takes train to
travel between to given stations). Railways are two-way and traveling in both ways last the same.
You are also given a list of all trains and the times of their departures and stations they are passing
throw. Train stops at each station that it is passing throw.
At the beginning (in 1st
second) Jozo is on the station number 1 and he has to return at that same
station between T1 and T2 second. If there are two trains in the same time at the same station, he can
jump from one train to another without losing time.
You have to write a program that will choose a route such that Jozo can drive around and spend
minimum total amount of time at the stations.
Input
First row of input file contains integers N, P, V, T1 i T2, 2 ≤ N ≤ 1000, 1 ≤ V ≤ 1000,
1 ≤ T1 ≤ T2 ≤ 50,000. N is number of stations, P is number of railways, V is number of trains, T1 and
T2 are times explained in problem statement.
Each of next P rows contains data about one railway. It contains three integers S1, S2 and T. It means
that journey from S1 to S2 (and vice versa) lasts T seconds, 1 ≤ T ≤ 600.
Each of next V rows contains data about one train. First number in that row is T0, time of departure
from first station, second number is NS, 1 ≤ NS ≤ 1000, number of stations on train’s route (including
starting and finishing station), next NS numbers are consecutively stations train passes through. Train
goes from first to the last station where all passengers leave the train and train stays at the finishing
station.
All numbers in the same row are separated by exactly one space character.
Output
First and only row of output file must contain time asked for in problem statement.
Sample
jozo.in
4 4 3 30 35
1 2 5
2 3 2
2 4 7
3 4 3
2 4 1 2 4 3
14 4 3 4 2 3
28 3 3 2 1
jozo.out
6
jozo.in
4 6 5 80 100
4 2 6
2 1 16
1 3 17
1 4 19
4 3 9
3 2 10
25 3 1 3 2
25 3 1 2 4
4 4 1 2 3 4
52 4 4 2 1 4
64 4 2 3 4 1
jozo.out
22
jozo.in
4 6 7 80 100
4 1 8
1 3 7
3 2 15
1 2 2
2 4 1
4 3 3
50 7 2 4 1 2 4 1 3
25 10 4 3 1 2 4 3 1 2 4 1
6 6 2 1 3 4 2 1
11 5 4 2 3 1 4
52 6 1 2 4 3 2 1
23 5 3 2 4 1 2
21 5 4 2 1 3 2
jozo.out
23 | 34,810 |
Highway Advertising (HWAYADS)
English
Tiếng Việt
After several years of preparing, Vietnam has been chosen to organize the IOI2023, it's such a big even with Vietnamese fans of informatics! The host country wants to invite all guests to visit N famous places (numbered 0..N-1). Of course the journey will start from the capital Hanoi (numbered 0). And after many years of developing, the travel system has been so modern that it needs only exactly N-1 highways for guests to travel to all N places from the capital. It's not only that but Ministry of Culture and Information also has an idea to paint some slogans on the highways to advertise Vietnam and the IOI competition. KTuan wants to watch the competition so he came back to Vietnam early. On the days in Hanoi, KTuan met AnhDQ (an old friend) by chance. Hearing that exciting idea, KTuan has a slogan in his mind and wants to ask AnhDQ:
how many times it appears on the way from Hanoi to the places?
. Please help AnhDQ answer KTuan's question!
Input
- The first line contains N.
- N-1 following lines, each line contains two number u, v and the string S, showing a highway from u to v, on which is painted the string S directed u->v.
- The last line contains KTuan's slogan.
Output
- The answer of AnhDQ.
Example
Input:
11
0 2 Welcom
0 7 VietN
2 8 nauTK
7 3 am
7 9 nauTK
2 5 eKTuan
5 4 IOIKTuanIO
7 1 IOI
5 6 IOI23
4 10 I2023
KTuanIOI
Output:
3
*** Explaination:
On the way 0-2-5-6: Welcome
KTuanIOI
23
On the way 0-2-5-4-10: Welcome
KTuanIOIKTuanIOI
2023
Limitations
- N ≤ 17032.
- The length of the strings ≤ 1000.
- The length of KTuan's slogan ≤ 70.
Sorry for my bad English!^_^ Please comment for a better translation ;) | 34,811 |
Masking Tape (MASKTAPE)
English
Tiếng Việt
You are a publicity agent of the JCIOI. You are ordered to make a signboard to publicize the IOI. The signboard made by painting a rectangle plywood board. The plywood board is bound with some rectangle masking tapes is in advance. So, You decide that you paint each region which is bounded by the masking tapes with different colors.
For example, five colors are necessary and enough to paint the plywood of Fig 5-1.
Write a program which, given a situation of a plywood, determine the minimum number of colors to be able to paint the input plywood with. Here, it is impossible that the entire surface of the plywood is covered by masking tapes, and every side of masking tapes is parallel to one of a side of the plywood.
Input
- The first line contains two integers separated by a single space that represent the size of the given plywood, the width w and the height h.
- The second line contains the number n of the masking tape on the plywood.
- The (2 + i)
th
line (1 ≤ i ≤ n) contains four integers x
1
, y
1
, x
2
, y
2
(0 ≤ x
1
< x
2
≤ w,0 ≤ y
1
< y
2
≤ h) separated by single spaces. (x
1
, y
1
) and (x
2
, y
2
) represent the coordinates of the bottom left corner and the top right corner, respectively, of the i
th
masking tape on the plywood.
Note that the coordinates of the bottom left corner of the plywood is (0, 0) and the coordinates of the top right corner of it is (w, h).
Output
- The output file should contain a single integer, which is the minimum number of colors to be able to paint the input plywood with.
Sample
Input:
15 6
10
1 4 5 6
2 1 4 5
1 0 5 1
6 1 7 5
7 5 9 6
7 0 9 2
9 1 10 5
11 0 14 1
12 1 13 5
11 5 14 6
Output:
5
Limitations
- 1 ≤ n ≤ 1000.
- 1 ≤ w, h ≤ 10
6
.
30% of the mark is given for test cases with w ≤ 100, h ≤ 100, n ≤ 100. | 34,812 |
KOKOS (MKOKOS)
English
Vietnamese
A set of N words is given with the length of each word being exactly 2K characters.
A directed graph with each vertex containing a single letter is called a "kokos" if, for each word in the set, there exists a directed path in the graph such that the labels on the vertices along that path form the word. Additionally, for all vertices on that path the following conditions have to be satisfied:
· the in-degree of the first vertex is 0
· the in-degrees of the next K-1 vertices is 1
· the out-degrees of the next K-1 vertices is 1
· the out-degree of the last vertex is 0
In other words, paths can fork only on the first K letters, and they can meet only on the last K letters. For the given set of the words, we say that the "kokos" is minimal if the total number of vertices is as small as possible.
Write a program that will find the number of vertices in a minimal kokos.
An example of a minimal kokos (the set of the words is from the third example):
It may seem that we can compact the graph like this:
However, this graph is not a kokos because paths meet on the 4th letter (D), and they fork on the 6th letter (E).
Input
The first line of input contains two integers N and K, 1 ≤ N ≤ 10 000, 1 ≤ K ≤ 100.
Each of the following N lines contains one word from the set. All letters will be uppercase letters of the English alphabet ('A'-'Z').
Output
The first and only line of output should contain the number of vertices in a minimal kokos.
Sample
input
2 4
ABCDEFGH
EFGHIJKL
output
16
input
4 3
XXZZXX
XXYYZZ
AABBCZ
ABCZZZ
output
18
input
4 4
ABCDEFGH
ACBDEFGH
ABDCFEHG
EFEFFEGH
output
23 | 34,813 |
A Marble Game (MARBLE)
English
Vietnamese
ktuan usually plays a marble game in a square table of NxN cells. The game proceeds as the following:
Initially, ktuan puts K obstacles into K cells of the table.
After that, ktuan makes Q turns. At the i
th
turn, ktuan flicks D
i
marbles from the outside of the board into one of the 4 sides of the board. The size of each marble fits perfectly into one cell. The marble goes through the cells in the same row/column until it goes out of the board or it meets an obstacle or another marble. If there is an obstacle or another marble at the first position then the marble will not be placed on the board.
After each turn, ktuan records the total number of cells that the marbles in that turn passing through.
Write a program that simulates the game and for each turn, print the total number of cells that the marbles in that turn passing through.
Input
The first line contains three integers N, K, Q.
Each line in the next K lines contains a pair (u, v) representing the coordinates (row, column) of an obstacle.
Each line in the next Q lines contains 4 values c, D, u, v. The character c could be 'L', 'R', 'T', or 'B' depending on whether the marbles go from the left, right, top, or bottom of the board. (u, v) represents the initial coordinates of the marbles and it should be a boundary cell (corresponding to c). D is the number of marbles in the current turn.
Output
For each turn, print the total number of cells that the marbles passing through.
Example
Input
5 1 3
3 3
L 2 3 1
T 1 1 1
B 5 5 5
Output
3
2
25
Output details
The first marble of the first turn will go through the two cells (3, 1) and (3, 2) before facing an obstacle at (3, 3).
The next marble of the first turn will go through the cell (3, 1) before facing another marble at (3, 2). Thus, the total number of cells passed through is 3.
The first marble of the second turn will pass through the two cells (1, 1) and (2, 1) before facing a marble at the cell (3, 1).
Each marble of the last turn will go out of the board as it doesn't tough obstacle or another marble. Thus, each marble will pass through 5 cells.
Constraints
N ≤ 50000, K ≤ 10, Q ≤ 100000
In 1/3 of the test cases, N and Q do not exceed 1000. | 34,814 |
Quadratics (BRHQUADR)
Butch needs help with checking his math homework. He is studying quadratic equations, which are in the form
y = ax
2
+bx+c
He wants to give you a, b, c, and x (1 ≤ a, b, c, x ≤ 10), and asks you to find y.
Input
Line 1: Three space-separated integers, a, b, and c.
Line 2: A single integer, x.
Output
Line 1: A single integer, y
Example
Input:
2 5 3
-4
Output:
15 | 34,815 |
Stacks of Bricks (SBRICKS)
Problem statement
You are given a sequence of
n
(
n
< 100) integers. Each number denotes the height of a stack of bricks. If we put the stacks in a line as in the illustration below, we would see stacks of uneven heights. Suppose a “move” is made by picking up one brick from one stack and putting it on another, compute the minimum number of moves to rearrange the bricks such that all stacks have the same height.
Read the input from standard input. The first line of the input is the integer
n
, followed by
n
lines of integers denoting the height of the
n
stacks. The total number of bricks will be divisible by the number of stacks. Thus, it is always possible to rearrange the bricks such that all stacks have the same height. Your output to standard output should consist of exactly one integer denoting the minimum number of moves.
Sample input
6
5
2
4
1
7
5
Sample output
5 | 34,816 |
Stacks of Bricks 2 (SBRICKS2)
Summary
This is similar to “Stacks of Bricks” except that for each move you are only allowed to move a brick to a stack on its immediate left or right.
Problem statement
You are given a sequence of
n
(
n
< 100) integers. Each number denotes the height of a stack of bricks. If we put the stacks in a line as in the illustration below, we would see stacks of uneven heights. Suppose a “move” is made by picking up one brick from one stack and putting it on
stack to its immediate left or right
, compute the minimum number of moves to rearrange the bricks such that all stacks have the same height.
Read the input from standard input. The first line of the input is the integer
n
, followed by
n
lines of integers denoting the height of the
n
stacks. The total number of bricks will be divisible by the number of stacks. Thus, it is always possible to rearrange the bricks such that all stacks have the same height. Your output to standard output should consist of exactly one integer denoting the minimum number of moves.
Sample input
6
5
2
4
1
7
5
Sample output
8 | 34,817 |
Accelerated Reading (BRHAR)
Oh no, Butch still needs to finish his AR book! (Yes, upperclassmen, laugh at him.) He procrastinated so much, in fact, that he's not sure if he'll finish in time for the end of the day. He'd calculate it himself, but if he can, he'll probably need every minute he can get. Assuming Butch reads P (0 ≤ P ≤ 100) pages per minute, has L (0 ≤ L ≤ 1000) pages left, and has M (0 ≤ M ≤ 30) minutes to finish, please help us to determine if Butch can finish.
Input
Line 1: 3 space-separated integers, P, L, and M.
Output
Line 1: 'yes' if he can finish, or 'no' if he can't.
Example
Input:
2 30 10
Output:
no | 34,818 |
Physics Grade (BRHPHYS)
Butch is afraid that he didn't do so well on his last Physics test. (Isn't it good enough that a bulldog can add and subtract numbers? Why does Mrs. Parker ask him to add and subtract vectors as well?)
He would like to know what letter grade he has right now, but he is too depressed about the test to do it himself.
Given N (0 < N ≤ 10) grades, each with a possible amount of points, Pi (0 ≤ Pi ≤ 200) and a score Si (0 ≤ Si ≤ Pi), find out what grade he would have if Ms. Parker truncates. The grading scale is as follows:
90 - 100 = A
80 - 89 = B
70 - 79 = C
60 - 69 = D
0 - 59 = F (Heaven forbid!)
(Note that the total points will always be more than 0)
Input
Line 1: A single integer, N
Lines 2..N+1: Two space separated integers, Pi and Si
Output
Line 1: A single upper-case character representing the grade he got.
Example
Input:
3
100 89
75 75
100 72
Output:
B | 34,819 |
Words (BRHWURD)
Butch has a favorite word W (1 ≤ length ≤ 10), and a bucket of letters. He has L (1 ≤ L ≤ 26) different letters, and Ci (1 ≤ Ci ≤ 5) of each.
He wants you to count how many ways he can make this word with the buckets.
If Butch tells you that he has a certain amount of a letter, he won't list the letter again.
The number of ways would be how many of letter 1 times how many of letter 2 times how many of letter 3...
Remember that if a letter isn't listed, then he has 0 of those letters in his bucket.
Input
Line 1: A single integer, L
Line 2: A line of text (not necessarily a real word), between 1 and 10 letters long, all lowercase.
Lines 3..L+2: A lowercase letter, and Ci, space separated.
Output
Line 1: A single integer, the number of ways he can make the word.
Example
Input:
6
dog
a 4
d 3
g 5
l 2
o 3
m 4
Output:
45 | 34,820 |
Chain Mail (BRHMAIL)
Butch is fascinated by how fast chain emails have the possibility to spread. (In case you are completely out-dated, a chain email is an email that one person send to all of his/her friends, who each then send to all of their friends, etc...)
He wants to find out how many times a certain letter will be received. Assume that no person will "receive" it more than once (though we all know how that goes).
For the sake of this investigation, Butch has conveniently named N (1 ≤ N ≤ 10) different people with the numbers 1..N. Each of these N people have Fi (0 ≤ F < N) friends within the group.
Note that if person A is friends with person B, that means that person B is friends with person A. This is guaranteed to be explicitly stated in the data. Also, note that no person will ever be friends with themself (poor lonely people...).
Assuming person 1 starts the chain (count that person 1 received it), determine how many people will receive this letter.
Input
Line 1: A single integer, N
Lines 2..N+1: One integer Fi, then Fi integers (each such that 1 ≤ Fij ≤ N), all space-separated, naming each of person i's friends.
Output
Line 1: A single integer, the number of people who receive it. Be sure not to count a single person twice!
Example
Input:
5
1 2
2 1 3
1 2
1 5
1 4
Output:
3
Output Explanation
Person 1 sends it to 2; 2 sends it to 3 only. Note that 4 and 5 never receive the mail, so the answer is 3: persons 1, 2, and 3 received it. | 34,821 |
Musical Frequencies (BRHMUSIC)
Butch is learning about the frequencies of musical notes, and he wants you to help him check whether he's calculated them correctly.
A formula you can use to calculate frequences is
f = 440 * 2
N/12
Where N is the number of half-steps away from A4. (Note that if N is negative, that means it's half-steps to the left.)
In case you aren't familiar with a piano, here's a sample:
http://www.balaams-ass.com/octave01.jpg
A half-step is the next note over; either a sharp (black note--denoted by the # symbol), if that note has one, or just the next note.
Butch would like to give you a note, and have you calculate that note's frequency. Butch will only input sharps or regular notes (so no flats, for those musically talented competitors). The lowest note will be C0, and the highest will be D#8.
For an extra challenge
: Use a function to generically find the distance between any two notes--not just A4. This may be used to break ties.
Input
Line 1: String representing the note
Output
Line 1: The frequency, TO 6 DECIMAL PLACES.
Example
Input:
C#5
Output:
554.365261
Butch is learning about the frequencies of musical notes, and he wants you to help him check whether he's calculated them correctly.
A formula you can use to calculate frequences is
f = 440 * (2)^(N/12)
Where N is the number of half-steps away from A4. (Note that if N is negative, that means it's half-steps to the left.)
In case you aren't familiar with a piano, here's a sample:
http://www.balaams-ass.com/octave01.jpg
A half-step is the next note over; either a sharp (black note--denoted by the # symbol), if that note has one, or just the next note.
Butch would like to give you a note, and have you calculate that note's frequency. Butch will only input sharps or regular notes (so no flats, for those musically talented competitors). The lowest note will be C0, and the highest will be D#8.
For an extra challenge: Use a function to generically find the distance between any two notes--not just A4. | 34,822 |
Suffix Array (SARRAY)
Given a string of length at most 100,000 consist of alphabets and numbers. Output the suffix array of the string.
A
suffix array
is an array of integers giving the starting positions (0-based) of suffixes of a string in lexicographical order. Consider a string "abracadabra0AbRa4Cad14abra". The size of the suffix array is equal to the length of the string. Below is the list of 26 suffixes of the string along with its starting position sorted in lexicographical order:
POS SUFFIX
11 0AbRa4Cad14abra
20 14abra
16 4Cad14abra
21 4abra
12 AbRa4Cad14abra
17 Cad14abra
14 Ra4Cad14abra
25 a
10 a0AbRa4Cad14abra
15 a4Cad14abra
22 abra
7 abra0AbRa4Cad14abra
0 abracadabra0AbRa4Cad14abra
3 acadabra0AbRa4Cad14abra
18 ad14abra
5 adabra0AbRa4Cad14abra
13 bRa4Cad14abra
23 bra
8 bra0AbRa4Cad14abra
1 bracadabra0AbRa4Cad14abra
4 cadabra0AbRa4Cad14abra
19 d14abra
6 dabra0AbRa4Cad14abra
24 ra
9 ra0AbRa4Cad14abra
2 racadabra0AbRa4Cad14abra
Note
: this is a partial score problem.
O(n
2
log(n)) is expected to score about 20-30. (Naive sorting all suffixes)
O(n log
2
(n)) is expected to score about 40. (OK for most programming contest problems)
O(n log n) is expected to score about 60-70. (Use counting sort for small alphabet size)
O(n) without tweaks is expected to score about 80-90.
O(n) with tweaks is expected to score 100. (This is meant for fun only :)
Input
A single line containing the string.
Output
The suffix array of the string.
Example
Input:
abracadabra0AbRa4Cad14abra
Output:
11
20
16
21
12
17
14
25
10
15
22
7
0
3
18
5
13
23
8
1
4
19
6
24
9
2 | 34,823 |
Đế chế (VNEMPIRE)
English
Vietnamese
An empire is building a network for its own planets. The empire consists of N planets, represented as points in the 3D space. The cost of connecting planet A and planet B is min{ |xA - xB|, |yA - yB|, |zA - zB| } with (xA, yA, zA), (xB, yB, zB) are coordinates of planet A, B in space. The empire is planning to build N - 1 connection and the requirement is that all planets are connected with each other and the cost is minimized.
Input
Number of planets N (N < 100001).
Next N lines, one line represents one coordiate of a planet.
Output
Only the minimum cost.
Example
Input
5
11 -15 -15
14 -5 -15
-1 -1 -5
10 -4 -1
19 -4 19
Output
4 | 34,824 |
Trò chơi (VNINGAME)
English
Vietnamese
Johny and Margaret are playing “pebbles”. Initially there is a certain number of pebbles on a table, grouped in n piles. The piles are next to each other, forming a single row. The arrangement of stones satisfies an additional property that each pile consists of at least as many pebbles as the one to the left (with the obvious exception of the leftmost pile). The players alternately remove any number of pebbles from a single pile of their choice. They have to take care, though, not to make any pile smaller than the one left to it. In other words, the piles have to satisfy the initial property after the move as well. When one of the players cannot makeamove (i.e. before his move there are no more pebbles on thetable), he loses. Johny always starts, to compensate for Margaret ’s mastery in this game.
In fact Margaret is so good that she always makes the best move, and wins the game whenever she has a chance. Therefore Johny asks your help — he would like to know if he stands a chance of beating Margaret with aparticular initial arrangement. Write a programme that determines answers to Johny ’s inquiries.
Input
In the first line of the standard input there is a single integer u (0 < u < 11) denoting the number of initial pebble arrangements to analyse. The following 2u lines contain descriptions of these arrangements; each one takes exactly two lines. The first line of each description contains a single integer n, 0 < n < 1001 — the number of piles.
The second line of description holds n non-negative integers ai separated by single spaces and denoting the numbers of pebbles in successivepiles, left to right. These numbers satisfy the following inequality a1 <= a2 <= ... <= an. The total number of pebbles in any arrangement does not exceed 10000.
Output
Precisely u lines should be printed out on the standard output. The i-th of these lines (for 1 <= i <= u) should hold the word TAK (yes in Polish),if Johny can win starting with the i-th initial arrangement given in the input, or the word NIE (no in Polish), if Johny is bound to lose that game, assuming optimal play of Margaret.
Example
Input
2
2
2 2
3
1 2 4
Output
NIE
TAK | 34,825 |
Robot quét vôi (NKROBOT)
Có 9 căn phòng (đánh số từ 1 đến 9) đã được quét vôi với màu trắng, xanh hoặc vàng. Có 9 robot (đánh số từ 1 đến 9) phụ trách việc quét vôi. Mỗi robot chỉ quét một số phòng nhất định. Việc quét vôi được thực hiện nhờ một chương trình cài sẵn theo qui tắc:
Nếu phòng đang có màu trắng thì quét màu xanh
Nếu phòng đang có màu xanh thì quét màu vàng
Nếu phòng đang có màu vàng thì quét màu trắng
Cần phải gọi lần lượt một số các robot ra quét vôi (mỗi lần một robot, một robot có thể gọi nhiều lần và có thể có robot không được gọi. Robot được gọi sẽ quét vôi tất cả các phòng mà nó phụ trách) để cuối cùng các phòng đều có màu trắng.
Yêu cầu:
Hãy tìm một phương án như vậy sao cho số lần gọi robot là ít nhất. Giả thiết rằng lượng vôi cho mỗi lượt quét đối với các phòng là như nhau.
Input
9 dòng đầu: dòng thứ i mô tả một danh sách các phòng do robot i phụ trách việc quét vôi. Mỗi dòng là một chuỗi các chữ số từ 1..9 biểu diễn các số hiệu của các phòng, các chữ số viết sát nhau.
Dòng cuối mô tả mầu vôi ban đầu của các phòng. Dòng gồm 9 ký tự viết sát nhau gồm toàn các chữ cái T (trắng), X (xanh), V(vàng) biểu diễn mầu ban đầu của 9 căn phòng theo trật tự số hiệu của chúng.
Output
gồm một dòng
Nếu không có phương án thì in ra số 0
Trái lại thì in ra dãy thứ tự các robot được gọi (số hiệu các robot được viết sát nhau)
Example
Input:
159
123
357
147
5
369
456
789
258
XVXVXVTXT
Output:
2455688 | 34,826 |
The World Final Hosting (WFHOST)
The ACM-ICPC world final hosting
There are
n
major cities in the world. These cities are labeled from 0 to
n
, which in order to form a convex polygon on a single plane (see the figure below). Each year, the ACM-ICPC Committee has to select one city from these cities to host the ACM-ICPC world final. The selection process is described as follows:
At the first phase, they create a shortlist. In order to do so, with a starting city
s
and a selection step
d
, they put all the cities with label
s
+
i
*
d
into the shortlist for all
i
such that 0<=
i
and
s
+
i
*
d
<
n
.
At the second phase, one city will be selected from the shortlist to organize the ACM-ICPC world final. At that year, they might choose the city which is the most to the North (maximal
y
coordinate), to the South (minimum
y
coordinate), to the East (maximum
x
coordinate) or to the West X (minimum
x
coordinate). It is assumed that there are no two cities having the same
x
, or
y
coordinate.
There is a cost associated with each city to organize the ACM-ICPC world final. It is assumed that this cost does not change over years. Your task is to compute the total cost the ACM-ICPC Committee has to pay to organize the ACM-ICPC world finals for a given number of years.
Input
The input consists of several data sets. The first line of the input file contains the number of data sets which is a positive integer and is not bigger than 20. The following lines describe the data sets.
For each data set, the first line contains the integer number
n
(1<=
n
<=100000). Each line of the next
n
lines describes one city, which contains three integer numbers
x
,
y
, and
c
separated by space. The pair (
x
,
y
) is a 2-D coordinate specifying the location of the city (- 200000<=
x
,
y
<=200000).
c
is the associated cost to organize the ACM-ICPC world final in that city (1<=
c
<=1000). The next line contains an integer number
m
, which is the number of years the ACM-ICPC Committee want to compute the cost to organize the ACM-ICPC world finals (1<=
m
<=10000). Each line of the next
m
lines contains three integer numbers
s
,
d
(0<=
s
<
n
;1<=
d
), and
p
separated by space. The value of
p
can be
0
,
1
,
2
or
3
for selecting the city most to the North, the South, the East or the West respectively.
Output
For each data set, write in one line the total cost for the ACM-ICPC Committee to organize the ACMICPC world finals.
Sample Input
2
4
-1 1 2
0 4 3
5 3 2
1 -1 2
2
0 1 0
0 2 1
3
0 0 2
1 1 3
2 10 2
2
1 1 1
0 2 0
Sample Output
5
5 | 34,827 |
SCRAMBLE1 (SCRAMBLE)
MOCK PE 2010
Question 2
(This question has been adapted from a CS1010e tutorial)
A word is scrambled if, given a word, the first and last letters of the word remain unchanged while the rest of the letters may have their places interchanged.
In this question, we adopt cyclic-scrambling where each letter (except for the first and last) is shifted one place to the right with wrap-around. For example, the word “programming” when cycled once will produce “pnrogrammig”. Notice the letter “n” wraps-around to the second position. When cycled another time the word produced is “pinrogrammg”. Note that the first and last characters always maintain their place.
Write a program that takes in the number of cycles, n, followed by a sentence. The program then proceeds to cyclic-scramble each word in the sentence n times.
You may assume that the length of each word is strictly below 20 characters, and the length of each sentence (aka input) is strictly below 200 characters.
Your program should contain a function ‘cycle’ that takes in arguments of two character strings str1, str2 and an integer value n that performs cycling for n times on str1 with the resulting word stored in str2.
void cycle(char str1[], char str2[], int n);
============================================
Sample 1 (Italicised words are the input, bolded words are the output):
1
According to a research at Cambridge University it does not matter in what order the letters in a word are the only important thing is that the first and last letter be in the right place
Anccordig to a rcesearh at Cgambride Utniversiy it deos not meattr in waht oerdr the lrettes in a wrod are the olny inmportat tnhig is taht the fsirt and lsat leettr be in the rhigt pclae
============================================
Sample Input 2 (italicised words are the input, bolded words are the output):
3
According to a research at Cambridge University it does not matter in what order the letters in a word are the only important thing is that the first and last letter be in the right place
Adinccorg to a rarceseh at Cidgambre Usitnivery it deos not mttear in waht order the lterets in a wrod are the olny itanmport thing is taht the first and lsat ltteer be in the right place
============================================ | 34,828 |
Borrowing money (DUGOVI)
In a little town called Križ live N people. Each of them has borrowed some money from exactly one other inhabitant. Now the time has come to pay back all the debts, but the problem is that everybody has spent all of their money!
The major of Križ has decided to solve this problem. The town will give money to a few people so that they can pay back their debts. When some people get their money back, a chain reaction is started . for example: person A gets money from the city. Person A uses that money to pay the debt toward person B. Person B then uses that money to pay the debt towards person C etc. If person B didn’t have enough money to pay back the debt, they wait until they get enough. If they have more than enough money, person B will keep what is left after payback. Another example: if two people live in Križ, and they owe $100 to each other, the town will give $100 to one of them so they can pay back the debt to the other one.
Your task is to calculate the minimum total amount of money the town has to give to some subset of the inhabitants so that after the payback protocol described above all debts are payed.
INPUT
First line of input contains one integer N (2 ≤ N ≤ 200 000), number of inhabitants of Križ. They are numbered from 1 to N.
The following N lines contain two integers, separated by space. In i.th of those lines, first number . Ai represents the id of the person i.th person owes money to (1 ≤ Ai ≤ N, Ai ≠ i), and second Bi represents the ammount of the debt in $ (1 ≤ Bi ≤ 10 000).
OUTPUT
First and only line of output should contain one integer . the minimum total ammount of money town has to give to its inhabitants so all debts are returned.
SAMPLE TESTS
input
4
2 100
1 100
4 70
3 70
output
170
input
3
2 120
3 50
2 80
output
150
input
5
3 30
3 20
4 100
5 40
3 60
output
11 | 34,829 |
Insulation (INSULENG)
Give N bricks and a sequence a
1
...a
n
as the insulation of them. If we arrange the bricks in that order into a wall then the insulation of the wall is a
1
+ a
2
+ ... + a
N
+ max(0, a
2
- a
1
) + max(0, a
3
- a
2
) + ... + max(0, a
N
- a
N
- 1). Your task is to arrange the bricks so that the insulation of the wall is maximum.
Input
The first line is N (1 <= N <= 10
5
).
In each of the next N lines, the i
th
line is a
i-1
Output
The maximum insulation of the wall.
Example
Input:
4
5
4
1
7
Output:
24 | 34,830 |
Artistic Samhita (SAMDRAW)
Type a program to draw the following image
____ _ _ _ _ _
/ ___| __ _ _ __ ___ | |__ (_) |_ __ _ / / |
\___ \ / _` | '_ ` _ \| '_ \| | __|/ _` | | | |
___) | (_| | | | | | | | | | | |_| (_| | | | |
|____/ \__,_|_| |_| |_|_| |_|_|\__|\__,_| |_|_|
Note: Points will be based on source code length. | 34,831 |
Brainfuck Geek!!! (Bonus Question) (BGEEK)
Write the following words in brainfuck programming language
"GEEK-O-CODE" (Quotes not included)
Note: Points awarded will be based on your sourcecode length | 34,832 |
DIEULINH (NTKM)
Minh has n piles of pebbles. The i-th pile has a[i] pebbles. The cost to merge 2 piles is the total of pebbles in this 2 piles. Calculate the cost to merge all these piles so that the cost is lowest.
Input
_ The first line is number N.
_ Next are n integers which is the number of pebbles in N piles.
Output
Result: write down the lowest cost
Example
Input:
5
4 1 2 7 5
Output:
41
n < 1000, a[i] < 1000000000
Note: sorry about my english ^^ | 34,833 |
REGIONS (REGIONS)
The United Nations Regional Development Agency (UNRDA) has a very well defined organizational structure. It employs a total of
people, each of them coming from one of
geographically distinct regions of the world. The employees are numbered from
to
inclusive in order of seniority, with employee number
, the Chair, being the most senior. The regions are numbered from
to
inclusive in no particular order. Every employee except for the Chair has a single supervisor. A supervisor is always more senior than the employees he or she supervises.
We say that an employee
is a manager of employee
if and only if
is
's supervisor or
is a manager of
's supervisor. Thus, for example, the Chair is a manager of every other employee. Also, clearly no two employees can be each other's managers.
Unfortunately, the United Nations Bureau of Investigations (UNBI) recently received a number of complaints that the UNRDA has an imbalanced organizational structure that favors some regions of the world more than others. In order to investigate the accusations, the UNBI would like to build a computer system that would be given the supervision structure of the UNRDA and would then be able to answer queries of the form: given two different regions
and
, how many pairs of employees
and
exist in the agency, such that employee
comes from region
, employee
comes from region
, and
is a manager of
. Every query has two parameters: the regios
and
; and its result is a single integer: the number of different pairs
and
that satisfy the above-mentioned conditions.
Task
Write a program that, given the home regions of all of the agency's employees, as well as data on who is supervised by whom, answers queries as described above.
Constraints
- the number of employees
- the number of regions
- the number of queries your program will have to answer
- the home region of employee
(for
)
- the supervisor of employee
(for
)
- the regions inquired about in a given query
Input
Your program must read from standard input the following data:
The first line contains the integers
,
and
, in order, separated by single spaces.
The next
lines describe the
employees of the agency in order of seniority. The
th of these
lines describes employee number
. The first of these lines (i.e., the one describing the Chair) contains a single integer: the home region
of the Chair. Each of the other
lines contains two integers separated by a single space: employee
's supervisor
, and employee
's home region
.
queries follow. Each query is presented on a single line of standard input and consists of two different integers separated by a single space: the two regions
and
.
Output
lines should be printed to the standard output, containing answers to subsequent queries. The response to each query must be a single line on standard output containing a single integer: the number of pairs of UNRDA employees
and
, such that
's home region is
,
's home region is
and
is a manager of
.
Note:
The test data will be such that the correct answer to any query given on standard input will always be less than
.
Grading
For a number of tests, worth a total of 30 points,
will not exceed 500.
For a number of tests, worth a total of 55 points, no region will have more than 500 employees.
The tests where both of the above conditions hold are worth 15 points.
The tests where at least one of the two conditions holds are worth 70 points.
Example
For the input data:
6 3 4
1
1 2
1 3
2 3
2 3
5 1
1 2
1 3
2 3
3 1
the correct result is:
1
3
2
1 | 34,834 |
The Journey of the Ant (ANTJOUR)
The Journey of the Ant
Time Limit 1 second/test case
Description
You will be given two positive integers m and n. Consider all latice points (the points with integral coordinates) inside (including the edges) a rectangle formed by connecting points (0, 0), (n, 0), (n, m), and (0, m). There's a wad of sugar on each of those (m+1)(n+1) points. A lost ant begins his journey to get back home from point (0, 0). He is an ant, and ants love sugar very much, so he decides to take some of the wads home. Because of some unexplainable reason, if he was on (a, b), then he can
only
move to
(a+1, b), (a+1, b+1),
or
(a, b-1)
. Of course the ant is not allowed to get out of the rectangle (or he will get lost, again). He knows that his house is at the other end of the rectangle i.e. (n, m). For example, let n = 3 and m = 2. There are 5 different ways for the ant to get home
Now your task is to find the number of ways for the ant to get home. Since the value can be very large, so output its remainder when divided by 1000000009 (10
9
+ 9).
Input Format
n and m in a single line, separated by a single space.
Output Format
A line contains the number of such ways.
Input Sample 1
3 2
Output Sample 1
5
Input Sample 2
10 8
Output Sample 2
176
Note
For 26.67% test cases: 1 ≤ n, m ≤ 1000.
For 40% test cases: 1000 ≤ max(n,m); 1 ≤ n, m ≤ 1000000; and n×m ≤ 1000000.
For other 33.33% test cases: 1 ≤ m ≤ 25 and 1000000 < n ≤ 1000000000000000000. | 34,835 |
MMO85 (MMO85)
This is one of the hardest problems of Moskow Mathematical Olympiad 1985
Prove that if n is a natural number equal or greater than 3, then there exist two
odd
natural numbers x and y such that 2
n
= 7x
2
+y
2
.
Create a program to find the value of x and y for a given n.
Input
A line contains a natural number n (3 ≤ n ≤ 62)
Output
A single line contains x and y, separated by a single space. Write any pair of x and y if you find more than one answer.
Example
Input:
3
Output:
1 1 | 34,836 |
Closest Pair Problem (CPP)
Given n points on the plane, each represented by (x, y) coordinates, find a pair of points with
the smallest distance between them.
Given n points on the plane, each represented by (x, y) coordinates, find a pair of points with the smallest distance between them.
Input
The first line of input will contain the number of points,
n (2 <= n <= 30,000)
. Each of the next
n
lines will contain two integers
x
and
y (-1,000,000 <= x, y <= 1,000,000)
. The ith line contains the coordinates for the ith point.
Output
Print to the ouput a single floating point number
d
, denoting the distance between the closest pair of points.
d
should contain exactly 6 digits after the decimal.
Example
Input:
5
0 0
-4 1
-7 -2
4 5
1 1
Output:
1.414214 | 34,837 |
Most Reliable Path (MRPATH)
A communication network is represented as a cycle-free, not necessarily simple, weighted, directed graph. The weight,
r(e)
, of an edge
e
is a real number in the interval
[0, 1]
representing the reliability of the communication channel represented by the edge. The reliability of a communication channel is interpreted as the probability that the channel will not fail. We assume that all probabilities are independent. There could be more than one channel between the same two nodes, in the same direction. Give an efficient algorithm to find the most reliable path from a given source node to a given destination node. What is the worst-case time complexity of your algorithm?
Input
The first line of input will contain the number of nodes in the network
N
and the number of edges in the network
E
(2 <= N, E <= 30,000)
.
The second line of input will contain
s
and
d
, the source and the destination.
Each of the next
E
lines will contain
a
,
b
,
c
(1 <= a, b <= N, 0 <= c <= 1)
, indicating that there is a directed edge from node
a
to node
b
with reliability
c
.
Output
Print to the ouput a single floating point number
r
, denoting the reliability of the best path from
s
to
d
.
r
should contain exactly 6 digits after the decimal point.
Example
Input:
4 6
1 4
1 2 0.75
1 2 0.5
2 3 1
2 4 0.75
1 3 1.0
3 4 0.25
Output:
0.562500 | 34,838 |
PLACE (PLACE)
Mirko loves cars and he finally managed to start his own car factory! Factory has N employees, each of them has exactly one superior (except Mirko - he is by default everybody's superior). Mirko is denoted by number 1, and the rest of the employees with numbers 2 to N.
Every employee can raise or lower the wages of all of his subordinates (both direct subordinates and those lower in the hieararchy tree). Mirko‟s role is to prevent abuse of such power, so from time to time he wants to know wage of a particular employee.
He is asking you to write a program which will help him monitor wage changes, given a sequence of commands described in the input section.
Remark: at any time, all of the wages will be positive integers and will fit in standard 32-bit integer type (int in C/C++, longint in Pascal).
Input
First line of input contains two space-separated positive integers N (1 ≤ N ≤ 500 000), number of employees, and M (1 ≤ M ≤ 500 000), number of wage changes and wage queries.
Next N lines contain the information about employees 1, 2, ..., N (respectively): starting wage and the identifier of his direct supervisor. Remark: Mirko has no supervisor, so his line will contain only his starting wage.
Next M lines contain one of the following:
1.
p A X
- employee A increases (or decreases in case of a negative X) wage of all his subordinates by the amount X (-10 000 ≤ X ≤ 10 000);
2.
u A
- Mirko wants to know the wage of employee A.
Output
Output should contain one line for each '2' query in the input - the current wage of the given employee.
Example
Input:
6 7
5
4 1
3 2
7 3
2 3
3 5
p 3 2
p 2 4
u 3
u 6
p 5 -2
u 6
u 1
Output:
7
9
7
5 | 34,839 |
TRAKA (TRAKA)
As mentioned before, there are N workers in Mirko's factory. They are manufacturing cars on a conveyor belt, in a pipeline fashion.
Workers are denoted by numbers 1 – leftmost, to N - rightmost. Each of the workers does his specific job and requires certain amount of time to complete it.
Production of a single car starts with worker #1 (Mirko). After he had finished with his part of the job, worker #2 takes over, after him #3... When worker #N finishes with his part, the car is finished.
Mirko and his workers have to produce M cars and they must produce them in order 1 to M.
For every worker i we know T[i] - time required for him to do his part of the job.
For every car j we know factor of assembly complexity F[j].
Time in minutes for worker i to finish his part of he job on the car j is computed as a product T[i]*F[j].
After some worker has finished working on a car, he has to give it to the next worker instantly, without any delay (weird company policy).
For that reason, the worker receiving the car has to be free (he must not be working on some other car). In order to fulfill this condition, Mirko has to choose a good timing to start building a new car. To be efficient, he’ll wait minimum number of minutes until he is certain that all of the conditions described are met.
Write a program which will, given worker times and factors of complexity for each car, compute total time required for producing all of the cars.
Input
First line of input contains space-separated positive integers N (1 ≤ N ≤ 100 000), number of workers, and M (1 ≤ M ≤ 100 000), number of cars.
i-th of the following N lines contains worker time T[i] for the worker i.
j-th of the following M lines contains factor of complexity F[j] for the car j.
These conditions hold: 1 ≤ T[i] ≤ 10 000, 1 ≤ F[j] ≤ 10 000.
Output
First and only line of output has to contain required number of minutes.
In test cases worth 40% of total points, N and M will be at most 1000.
Input:
3 3
2
1
1
2
1
1
Output:
11
Sample description:
After four minutes, first worker finishes working on the first car. He might start working on the second car immediately, but that would violate a condition that cars have to be passed to next workers as soon as they' re done (after seven minutes second worker would finish working on his part of second car, but the third worker would not be free to take over as he would still be working on the first car). That is the reason production of the second car is started after five minutes. Production of the third car starts after seven minutes. First car is finished after eight, second after nine and third after eleven seconds. Total time is then 11. | 34,840 |
Palindrome or not (PALINCOD)
A
palindrome
is a word, phrase, number, or other sequence of units that can be read the same way in either direction, with general allowances for adjustments to punctuatiom and word dividers
for eg., HELLOLLEH is a Palindrome string,
and 123456789 is not a Palindrome number.
Input
t - number of testcases [ t < 1000 ].
On each of the next t lines given string.
Output
For each next t lines output the dataset number as a decimal integer (start counting at one), a space and "YES" if the given input is palindrome, or "NO" if the input is not.
Example
Input:
2
HELloolLEH
ILOVEyou
Output:
1 "YES"
2 "NO"
CHAALLENGE:- minimum size of the code | 34,841 |
Redoks (REDOKS)
Luka is not paying attention in class again, while the teacher is explaining redox reactions. Instead of paying attention, he is playing with analog dials.
An analog dial is a small device which always shows one digit between 0 and 9. It also contains a small button which increases the number by 1 (unless it is 9, in which case it is changed to 0).
Luka has N such dials on his desk, numbered 1 to N left to right, and two sheets of paper for him to write on.
Luka's game starts with him setting the dials in some starting configuration, which he then writes onto the first sheet. Luka then does the following M times:
Choose two integers A and B (1 ≤ A ≤ B ≤ N) and write them down on the first sheet.
Calculate the sum of numbers on dials numbered between A and B (inclusive), and write the sum down on the second sheet.
Press the button once on all dials numbered between A and B.
Just as he had finished his game, the teacher noticed him, and took away all his dials and the
second
sheet of paper.
Given the contents of the first sheet, help him calculate the numbers on the second sheet.
Input
The first line contains two integers N and M (1 ≤ N ≤ 250000, 1 ≤ M ≤ 100000).
The second line contains the initial configuration of the dials, N decimal digits with no spaces. The first digit is the number initially on dial 1, the second digit the number on dial 2 and so on.
Each of the following M lines contains two integers A and B (1 ≤ A ≤ B ≤ N).
Output
Output M lines, the sums calculated by Luka, in order in which he calculated them.
Scoring
In 30% of all test cases, the numbers N and M will be less than 1000.
Sample #1
Input:
4 3
1234
1 4
1 4
1 4
Output:
10
14
18
Sample #2
Input:
4 4
1234
1 1
1 2
1 3
1 4
Output:
1
4
9
16
Sample #3
Input:
7 5
9081337
1 3
3 7
1 3
3 7
1 3
Output:
17
23
1
19
5 | 34,842 |
Find our next planet! (RPL_T1)
Andreina the hobbit, a famous scientist from Rainbowland is trying to make communication with other planets through a very rare object, Andreina receives the signal by her headphones connected to the object, if she hears at least N signals on an interval of K
consecutive
minutes (each minute the object makes a turn and points out to another direction in the space slightly different from the last one) then she could have find another living planet.
Sometimes the signal can be weak, sometimes the signal can be strong, and sometimes the signal can be static (this will be represented by a negative integer). they will variate every minute, as the object points to another direction slightly different from the last one.
Your task is simple, given the N signals Andreina needs to discover and the maximum interval of K minutes to do it, output if she found or not a planet.
INPUT:
The first line of the test data will start with an integer T representing the T test cases, then, T cases will follow, each of the cases starts with three integers N, K and C denoting the number of signals to find a planet, the maximum minutes that Andreina can use to find the planet and C signals test that were evaluated.
OUTPUT:
You must output the string “Scenario #i: “, where i is the test case you are evaluating, followed by the string “We are not alone” if Andreina finds another planet, otherwise print “Rainbowland is our home”
SAMPLE DATA:
INPUT
OUTPUT
3
6 2 6
1 2 3 1 2 3
6 3 6
1 2 3 3 2 1
3 2 6
1 1 1 2 1 1
Scenario #1: Rainbowland is our home
Scenario #2: We are not alone
Scenario #3: We are not alone
CONSTRAINTS:
1 <= T <= 10
Small input (30%):
1 <= C <= 1000
1 <= K <= C
-1000 <= N <= 1000
-1000 <= Ni <= 1000
Large input (70%):
1 <= C <= 10^6
1 <= K <= C
-10^9 <= N <= 10^9
-10^9 <= Ni <= 10^9 | 34,843 |
Take & Run (RPL_T2)
Take & Run is an important game of the Rainbowland Olympiads, consists in a large rectangle, in each grid of the rectangle there is a single natural number, every athlete takes their position and then the referee announces a random number (that is written on some grid of the large rectangle), all the athletes must search the number and when some of them find it, the athlete must return at full speed to the line to win.
Marge is questioning this game, she says that a pattern can be discovered as all the numbers are sorted along the rectangle grids, Marge wants to win the Olympiads, and the help of third persons is allowed in Rainbowland, she requests your help and she will give you all the numbers written on the grid of the rectangle, it is known that the number at [0,0] < [0,1] < … < [0,M] < [1,M] < … < [N,M]. Where the left number stands for the rows and the right one for the columns (the format is [R,C]).
INPUT:
The first line of the test data will start with an integer T representing the T test cases, then, an integer N and M will come, then, NxM numbers will follow, meaning that in the next N lines there will be M numbers representing the number located on the grid, after that, Q requests will come, each requests consist on a natural number P that exists somewhere over the rectangle.
OUTPUT:
You must output the string “Scenario #i:“, where i is the test case you are evaluating, a blank line, and then, the position [R,C] where the natural number given in the request is located.
Print a blank line between test cases
SAMPLE DATA:
INPUT
OUTPUT
2
3 3
1 2 3
4 5 6
7 8 9
2
5
4
3 4
298 388 641 642
643 644 645 646
777 888 998 999
2
999
644
Scenario #1:
2 2
2 1
Scenario #2:
3 4
2 2
CONSTRAINTS:
1 <= T <= 10
Small input (30%):
1 <= {N,M} <= 100
1 <= Number on the grid <= 10^9
1 <= Q <= 100
Large input (70%):
101 <= {N,M} <= 2000
1 <= Number on the grid <= 10^9
1 <= Q <= 10000
It is guaranteed that every number on the grid will be different from each other. | 34,844 |
Graphic Sequence (GRSEQ)
Given an integer sequence
d
= (
d
1
, . . . ,
d
n
) determine if
there exists a graph
G
with permutation of
d
as its sequence of degrees.
Input
The input consists of a sequence of lines.
In the first line you are given
t
<100 - the number of sequences to analyze.
The description of each of the sequences consists of two lines:
in the first line you are given one number
n
<=100000 (the length of the sequence) and in the second line you are given
n
nonnegative integers
(the sequence elements, all of these numbers are smaller than 100000).
Output
For each of the sequences print in a separate line one of the two words: POSSIBLE if such a graph might exists and IMPOSSIBLE in the opposite case.
Example
Input:
4
3
1 2 2
4
3 2 3 2
5
2 2 4 2 2
4
0 0 0 0
Output:
IMPOSSIBLE
POSSIBLE
POSSIBLE
POSSIBLE
Input data sizes
t maxn l
1 10 0.4s
2 100 0.4s
3 1000 0.4s
4 10000 0.4s
5 100000 0.4s
t - testcase number
maxn - the maximum length of the sequence
l - time limit
Hints
Using the Erdős–Gallai Theorem you will be able to implement a linear time algorithm.
You could try also
Social Network Existence
- very similar problem with smaller inputs. | 34,845 |
Cipher (OPC2408B)
Because having a problem statement is too mainstream...:P
Hint: Observe the sample input and output
Input
Contains few test cases with each test case containing a string in a seperate line.String will consist of lowercase alphabets. ('a'-'z') only and strlen(string) <=500
For taking input read till EOF.
An example of how to read strings till EOF:
while(gets(string))
{
/*process string*/
}
Score is the length of your code. (Smaller the code length,better the score)
Output
For each test case output a single string containing the answer
Example
Input:
lolo
whoami
Output:
oror
oror
zkrdpl | 34,846 |
Tropical Garden (IOI11GRD)
Botanist Somhed regularly takes groups of students to one of Thailand's largest tropical gardens. The landscape of this garden is composed of N fountains (numbered 0, 1, …, N-1) and M trails. Each trail connects a different pair of distinct fountains, and can be traveled in either direction. There is at least one trail leaving each fountain. These trails feature beautiful botanical collections that Somhed would like to see. Each group can start their trip at any fountain.
Somhed loves beautiful tropical plants. Therefore, from any fountain he and his students will take the most beautiful trail leaving that fountain, unless it is the most recent trail taken and there is an alternative. In that case, they will take the second most beautiful trail instead. Of course, if there is no alternative, they will walk back, using the same trail for the second time. Note that since Somhed is a professional botanist, no two trails are considered equally beautiful for him.
His students are not very interested in the plants. However, they would love to have lunch at a premium restaurant located beside fountain number P. Somhed knows that his students will become hungry after taking exactly K trails, where K could be different for each group of students. Somhed wonders how many different routes he could choose for each group, given that:
each group can start at any fountain;
the successive trails must be chosen in the way described above; and
each group must finish at fountain number P after traversing exactly K trails
Note that they may pass fountain number P earlier on their route, although they still need to finish their route at fountain number P.
Your task
Given the information on the fountains and the trails, you have to find the answers for Q groups of students; that is, Q values of K.
Write a procedure count_routes(N,M,P,R,Q,G) that takes the following parameters:
N – the number of fountains. The fountains are numbered 0 through N-1.
M– the number of trails. The trails are numbered 0 through M-1. The trails will be given in decreasing order of beauty: for 0 ≤ i < M-1, trail i is more beautiful than trail i+1.
P – the fountain at which the premium restaurant is located
R – a two-dimensional array representing the trails. For 0 ≤ i < M, trail i connects the fountains R[i][0] and R[i][1]. Recall that each trail joins a pair of distinct fountains, and no two trails join the same pair of fountains.
Q – the number of groups of students.
G – a one-dimensional array of integers containing the values of K. For 0 ≤ i < Q, G[i] is the number of trails K that the i-th group will take.
For 0 ≤ i < Q, your procedure must find the number of possible routes with exactly G[i] trails that group i could possibly take to reach fountain P. For each group i, your procedure should call the procedure answer(X) to report that the number of routes is X. The answers must be given in the same order as the groups. If there are no valid routes, your procedure must call answer(0).
Example 1
Consider the case shown in Figure 1, where N=6, M=6, P=0, Q=1, G[0]=3, and
R =
1 2
0 1
0 3
3 4
4 5
1 5
Note that trails are listed in decreasing order of beauty. That is, trail 0 is the most beautiful one, trail 1 is the second most beautiful one, and so on.
There are only two possible valid routes that follow 3 trails:
1 → 2 → 1 → 0,
5 → 4 → 3 → 0.
The first route starts at fountain 1. The most beautiful trail from here leads to fountain 2. At fountain 2, the group has no choice, they must return using the same trail. Back at fountain 1, the group will now avoid trail 0 and choose trail 1 instead. This trail does indeed bring them to the fountain P=0.
Thus, the procedure should call answer(2). | 34,847 |
PiggybankRI (WARAKOM)
Ramy, a college tutor interested in algorithms decided to help out his students in problem solving by giving them an easy problem to solve to practice for their algorithms exam. Below is the description of the problem that Ramy is facing.
Ramy has a piggy bank with a certain capacity m and containing an amount q. He is going to use it for saving money and paying his debts for n days. Each day he can either add an amount to it or remove the same amount from it. Mr ramy can not exceed the maximum capacity of his piggy bank and neither can he withraw an amount that is not there. He is now wondering what is the maximum amount he can have in his piggy bank after n days. Can you help Ramy with his problem???
You will be given a list of the amounts he can add or withdraw and you are required to tell him the maximum amount he can have . If it's not possible for him to do the operations tell him that.
Input
The first line will start with a number t, the number of test cases (t <= 10).
Each test case will consist of 2 lines. The first line contain n, q, m (as explained in the problem) n <= 50,
0 <= q < m <= 1000.
The next line contains n space separated values ai 0 < i <= n, 0<= ai <= m.
Please note that in the test files there are no empty lines like the ones shown below.
Output
For each test case print 1 number in a separate line which is the maximum amount Mr. Ramy can have in his piggy bank after n days or -1 if he can't do it.
Please note that you should output the results without any empty lines, unlike the format given in the output. No seperate empty lines should be present in your output.
Example
Input:
2
3 5 10
5 3 7
4 8 20
15 2 9 10
Output:
10
-1 | 34,848 |
Assassin Creed (ASSASSIN)
Ezio needs to kill
N
targets located in
N
different cities. The cities are connected by some one way roads. As time is short, Ezio can send a massage along with the map to the assassin's bureau to send some assassins who will start visiting cities and killing the targets. An assassin can start from any city, he may visit any city multiple times even the cities that are already visited by other assassins. Now Ezio wants to find the minimum number of assassins needed to kill all the targets.
Input
Input starts with an integer
T (
≤ 70)
, denoting the number of test cases.
Each case starts with a blank line. Next line contains two integers
N (1 ≤ N ≤ 1000)
and
M (0 ≤ M ≤ 10000)
, where
N
denotes the number of cities and
M
denotes the number of one way roads. Each of the next
M
lines contains two integers
u v (1 ≤ u, v ≤ N, u ≠ v)
meaning that there is a road from
u
to
v
. Assume that there can be at most one road from a city
u
to
v
.
Output
For each case, print the case number and the minimum number of assassins needed to kill all targets.
Sample Input
Output for Sample Input
3
5 4
1 2
1 3
4 1
5 1
7 0
8 8
1 2
2 3
3 4
4 1
1 6
6 7
7 8
8 6
Case 1: 2
Case 2: 7
Case 3: 2
Note
Dataset is huge, use faster I/O methods. | 34,849 |
Ray Gun (RAYGUN)
You are in an
m x n
grid. You are standing in position
(0, 0)
and in each of the other lattice points (points with integer co-ordinates) an enemy is waiting. Now you have a ray gun that can fire up to infinity and no obstacle can stop it. Your target is to kill all the enemies. You have to find the minimum number of times you have to fire to kill all of them. For a
4 x 4
grid you have to fire
13
times. See the picture below:
Input
Input starts with an integer
T (
≤ 100)
, denoting the number of test cases.
Each case contains two integers
m, n (0 ≤ m, n ≤ 10
9
)
and at least one of them will be less than or equal to
10
6
.
Output
For each case, print the case number and the minimum number of times you have to fire to kill all the enemies.
Sample Input
Output for Sample Input
2
4 4
10 10
Case 1: 13
Case 2: 65 | 34,850 |
Space Beacon (SPBEACON)
In order to discover all the planets of the solar system, we want to develop techniques to travel safely through an asteroid belt between Mars and Jupiter.
We plan to drop automatic-signaling devices into large asteroids of the belt, which will act as space beacons to guide the ships.
They will assist autopilots to track the location of the ships to adjust the orbit. Each signal sent by each beacon contains a sequence of pulses, and is characterized by a sequence T :
T = t
1
, t
2
,..., t
k
,(3 ≤ k ≤ 18)
Where t
i
is the duration of i -th pulse (t
i
is integer and is in the range of
1..9
).
In order to simplify the technical checking process and to increase the signal recognition ability, the sequence T of each beacon is designed with the following criteria:
With
1 < i < k
, either:
t
i-1
< t
i
, t
i
> t
i+1
for i mod 2 = 0
t
i-1
> t
i
, t
i
< t
i+1
for i mod 2 = 1
or
t
i-1
> t
i
, t
i
< t
i+1
for i mod 2 = 0
t
i-1
< t
i
, t
i
> t
i+1
for i mod 2 = 1
All possible T sequences are sorted in lexicographic order and labeled by consecutive integers starting with 1. The label of the sequence T of each beacon is used as the identifier of the beacon.
Given the sequence T of a beacon, your task is to write a program to find the identifier of that beacon.
Input
The input file consists of several data sets. The first line of the input file contains the number of data sets which is a positive integer and is not bigger than 20.
The following lines describe the data sets.
For each data set, there is only one single line containing k integers t
1
, t
2
,..., t
k
separated by space describing the T sequence of a beacon.
Output
For each test case, write in one line the ID of the beacon with the given T sequence.
Sample Input
Output for Sample Input
2
1 2 1 2
1 2 1 2 1 2
2
4 | 34,851 |
Gray Code (GRAYCODE)
Denis, Vanya and Fedya gathered at their first team training. Fedya told them that he knew the algorithm for constructing a Gray code.
1. Create a 2-bit list: {0, 1}.
2. Reflect this list and concatenate it with the original list: {0, 1, 1, 0}.
3. Prefix old entries with 0, and prefix new entries with 1: {00, 01, 11, 10}.
4. Repeat steps 2 and 3 until the length of all elements is equal to n.
The number n is a length of a Gray code. For example, the code of length 3 is: {000, 001, 011, 010, 110, 111, 101, 100}.
Denis ran the Fedya's algorithm and obtained a binary number x at position k (positions are numbered starting from zero). Vanya wrote down the numbers k and x in binary system. This story happened many years ago and now you hold the paper sheet with these numbers in your hands. Unfortunately, some digits are unreadable now. Could you determine the values of these digits using the readable digits?
Input
There are several test cases, one per line. Each test case consists of 2 string:
The first one is number k written in the binary system. Unreadable digits are denoted with symbol "?".
The second one is number x in the same format.
The lengths of these numbers are equal and don't exceed 10
5
. The numbers may contain leading zeroes.
Output
For each test case, output the result in one line as follow:
If there is a unique way to restore the numbers k and x, output them, replacing the symbols "?" with "0" or "1".
If there are multiple ways to restore them, output "Ambiguity".
If Denis or Vanya certainly made a mistake in these numbers, output "Impossible".
Sample Input
Output for Sample Input
0?1 0?0
?00 ??0
100 100
011 010
Ambiguity
Impossible | 34,852 |
INFORMACIJE (INFORMAC)
Mirko was bored, so he took a piece of paper and wrote down a sequence
A
of length
N
, which contains each positive integer between
1
and
N
, inclusive,
exactly once
. After that, he took another piece of paper and wrote down
M
descriptions of the sequence
A
.
Each description has one of the following formats:
1 x y v –
the largest number in positions between
x
and
y
(inclusive) equals
v
2 x y v –
the smallest number in positions between
x
and
y
(inclusive) equals
v
Then Slavko came, saw, and stole the first paper. Mirko is desperate and has asked you to find some sequence matching the descriptions, not necessarily equal to the original sequence.
INPUT:
The first line of input contains two positive integers,
N
(1 ≤
N
≤ 200), the length of the sequence, and
M
(0 ≤
M
≤ 40 000), the number of descriptions.
Each of the following
M
lines contains a description as described above.
OUTPUT:
The first and only line of output must contain a sequence of
N
space-separated positive integers (matching the descriptions and containing all positive integers from
1
to
N
), or -1 if no such sequence exists.
SAMPLE TESTS:
Input
Output
3 2
1 1 1 1
2 2 2 2
1 2 3
4 2
1 1 1 1
2 3 4 1
-1
5 2
1 2 3 3
2 4 5 4
1 2 3 4 5 | 34,853 |
Spy Office (RIOI_3_3)
Tyrion Lannister is very smart man, and he knows importance of being informed, especially when you are important man behind the throne. So Tyrion placed one spy in every major city of Seven Kingdoms.
But long before there internet existed, information was carried by foot, so it was very important to organise your spies correctly.
Seven Kingdoms can be imagined as straight road with N cities on it. Cities are numbered from 1 to N inclusive. Tyrion is located in city 1. We know distance between 2 neighbouring cities, and it is given in array D. Distance between city i and i+1 is D[i] kilometers.
After spy in city i hears something important he starts preparing for departure. He needs exactly T[i] days to prepare. After that he starts traveling to city 1 with constant speed V[i] kilometers per day. After he enters some city in between, he can either tell his news to spy located in that city, after which that spy repeats same steps, or he can continue traveling.
Tyrion needs to know what is smallest amount of time needed for each spy to reach King's Landing (city 1 where Iron Throne is located).
Tyrion Lannister is very smart man, and he knows importance of being informed, especially when you are important man behind the Iron Throne. So Tyrion placed one spy in every major city of Seven Kingdoms.
But long before internet existed, information was carried by foot, so it was very important to organise your spies optimally.
Seven Kingdoms can be imagined as straight road with
N
cities on it. Cities are numbered from
1
to
N
inclusive, with cities
i
and
i+1
being neighbouring. Tyrion is located in city numbered
1
, called King's Landing. We know distance between two neighbouring cities, and it is given in array
D
. Distance between city
i
and
i+1
is
D[i]
kilometers.
After spy in city
i
hears something important he starts preparing for departure. He needs exactly
T[i]
days to prepare. After that he starts traveling to King's Landing with constant speed
V[i]
kilometers per day. Spies never travel away from King's landing, that is, at every point in time, they try to reduce their distance to King's Landing. After he enters some city in between, he can either tell his news to spy located in that city, after which that spy repeats same steps, or he can continue traveling without telling anything to that spy.
Tyrion needs to know what is smallest amount of time needed for information from every city to reach King's Landing (city 1 where Iron Throne is located).
N <= 100000 ( in 60% of tests N <= 1000 )
0 < D[i], T[i], V[i] <= 100
Input
In first line of the input, there is integer
N
(number of cities). Second line consists of
N-1
integers describing array
D
. N-1 lines follow each containing
T[i]
and
V[i].
Output
Output N-1 numbers, smallest number of days for each city. Also note, that solutions are in fact decimal numbers, but you just output integers.
Example
Input:
7
2 9 7 2 2 10
6 6
9 2
9 10
2 3
1 1
6 6
Output:
6
14
11
9
12
11
Note : Actual results are decimal numbers, like shown below. But to avoid precision errors, output rounded numbers with 0 decimal places.
Use printf("%.0lf") formatting to output your results
6.33333
14.50000
10.80000
8.66667
11.66667
11.33333 | 34,854 |
Cheaters (RIOI_3_4)
Mirko and Slakvo are known to play some games from time to time.
N numbers appear on the screen in one minute intervals. A[1] will appear in first minute, and A[N] will appear in N-th minute. Screen has capacity of K numbers, that means that in each point in time, on the screen can be at most K numbers. After new number appears, number that appeared K minutes ago, if such exists, disappears.
Aim of the game is to tell minimal absolute difference 2 distinct numbers on the screen in every minute. Slavko is very good at this game, can you help Mirko and tell him optimal results
Mirko and Slavko are known to play some games from time to time.
N
numbers appear on the screen in one minute intervals.
A[1]
will appear in first minute, and
A[N]
will appear in
N
-th minute. Screen has capacity of
K
numbers, that means that in each point in time, on the screen can be
at most K
numbers. After new number appears, number that appeared
K
minutes ago, if such exists, disappears.
Aim of the game is to tell minimal absolute difference 2 distinct numbers on the screen in every minute. Slavko is very good at this game, help Mirko and tell him optimal results.
2 <= N <= 100 000
2 <= K <= 100 000
1 <= A[i] <= 100 000
Input
In the first line there are two numbers N and K, in the next line there are N integers describing array A.
Output
Output N-1 number, optimal result in each minute of the game.
Example
Input:
6 4
6 2 4 1 10 9
Output:
4 2 1 1 1
Explanation :
1st minute, on screen {6}
2nd minute, on screen {6, 2}, |6-2| = 4
3rd minute, on screen {6, 2, 4}, |6-4| = |4-2| = 2
4th minute, on screen {6, 2, 4, 1}, |2-1| = 1
5th minute, on screen {2, 4, 1, 10}, |2-1| = 1
6th minute, on screen {4, 1, 10, 9}, |10-9| = 1 | 34,855 |
Making the Grade (NOINCDEC)
A straight dirt road connects two fields on FJ's farm, but it changes elevation more than FJ would like. His cows do not mind climbing up or down a single slope, but they are not fond of an alternating succession of hills and valleys. FJ would like to add and remove dirt from the road so that it becomes one monotonic slope (either sloping up or down).
You are given
N
integers
A
1
, ... ,
A
N
(1 ≤
N
≤ 2,000) describing the elevation (0 ≤
A
i
≤ 1,000,000,000) at each of
N
equally-spaced positions along the road, starting at the first field and ending at the other. FJ would like to adjust these elevations to a new sequence
B
1
, . ... ,
B
N
that is either nonincreasing or nondecreasing. Since it costs the same amount of money to add or remove dirt at any position along the road, the total cost of modifying the road is
|
A
1
-
B
1
| + |
A
2
-
B
2
| + ... + |
A
N
-
B
N
|
Please compute the minimum cost of grading his road so it becomes a continuous slope. FJ happily informs you that signed 32-bit integers can certainly be used to compute the answer.
Input
* Line 1: A single integer:
N
* Lines 2..
N
+1: Line
i
+1 contains a single integer elevation:
A
i
Output
* Line 1: A single integer that is the minimum cost for FJ to grade his dirt road so it becomes nonincreasing or nondecreasing in elevation.
Sample Input
7
1
3
2
4
5
3
9
Sample Output
3 | 34,856 |
Sum of Median (MEDSUM)
You are given
n
increasing sequences A
1
, A
2
, A
3
, ... , A
n
. Each sequence have
L
values of integers.
Merge A
i
and A
j
obtained A
ij
have 2L values and A
ij
is increasing sequence. Median values of A
ij
is L-th value of A
ij
.
Example:
L = 5.
Ai = (1 3 4 5 6); Aj = (0 1 5 6 7).
Aij = (0 1 1 3 4 5 5 6 6 7).
Median value of Aij is 4.
Input
- The first line of input contains n, L (2 <= n <= 200; 1 <= L <= 20000).
- In the next n lines, the i-th line contains L integers of
<= 10
9
Ai.
Output
- Sum of all median value in module 10
9
.
Example
Input:
3 6
1 2 3 4 5 6
3 4 5 6 7 8
0 0 1 1 2 2
Output:
8 | 34,857 |
Kart (V_AYP1_A)
Pepe is a famous karting racer, but he forgot to tell his brother, Yonkleiderson, the number of his car so that could register in the competition, if Yonkleiderson fails to register his brother in the competition, his brother will be automatically disqualified. In a desperate moment, Yonkleiderson remembered that the number of the racer's car is given according to the starting position in the race, and he knows the position (i,j) where his brother's car is, the problem, then, is pretty simple, given N and M, that would be the size in a matrix and two values i,j that are the position at the matrix, Pepe wish to know what value could be in that position if the matrix is filled row by row starting from 1 until N*M.
Example
N= 3, M=4
1 2 3 4
5 6 7 8
9 10 11 12
i=0 , j=3 the number is 4
i=2 , j=2 the number is 11
i=1, j=0 the number is 5
Input details:
Four integers N,M,I,J representing the size of the matrix and the indexes i,j to search the car
Output details:
The number of the car as previously described in the statement.
INPUT
OUTPUT
3 4 0 3
4
Constraints
0 < N,M < 10000
0 <= i < N
0 <= j < M | 34,858 |
Knight Circuit (V_AYP1_B)
Luis is a great chess player and as such, he likes to test any kind of game that he imagines with the chess pieces, he just created a game pretty interesting consisting in the moves of a knight over all the possible cell whenever he can in a matrix sized board WxH, being in the position (x,y) of the matrix, the knight can move to (x+2,y+1), (x+1,y+2), (x-2,y+1), (x+2,y-1), (x-1,y+2), (x-1,y-2), (x-2,y-1), (x+1,y-2).
The knight can start from any cell in the matrix WxH, the knight may never leave the matrix and it can step an arbitrarily number of times the same cell visited, however, you shouldn't count the repeated step.
Input details:
T as an integer representing the number of cases, then, in the next T lines, two integers W and H representing the width and the height of the matrix.
Output details:
A single number representing the number of cells visited by the knight in the matrix.
INPUT
OUTPUT
3
1 1
15 2
100 100
1
8
10000
Constraints:
1 <= W <= 100,000
1 <= H <= 100,000 | 34,859 |
Iridium (V_AYP1_C)
A group of programmers from Iridium develops a multiplatform communications equipment that will connect various offices of the Company for which they work. They want to calculate the time (in ms) that a packet of information will need to travel from origin to destiny through their network, given the size in Bytes of the packet and the means through which it will travel.
The network that interconnects the company is comprised of three different technologies. The first is optic fiber (propagation speed: 0.0769 ms/m), Satellite link (0.033 ms/m) and copper wire (0.0109 ms/m). These values were estimated from the specifications of the hardware that comprises this system and are considered correct. To represent each kind of connection a character will be used: Fiber optic (F), Satellite (S) and Copper wire (T). The bandwidths of the links vary through the system. It is necessary to calculate the time 1 bit will need for it to be transmitted through the links to its destiny.
After calculating the propagation time of 1 bit, according to the data introduced by the user of each link, it will be necessary to calculate the propagation time of all the packet. As it is well known 1 Byte = 8 bits, giving us the option of transforming the packet size given in Bytes to bits and multiplying the propagation time by that amount of bits.
The program must be able to calculate several times, as the studies for the system may be many.
Input details:
The first line of each test case will contain an integer K, which will represent the size in bytes of each packet that will be sent through the link. An undetermined amount of lines will follow, each containing a single string (no spaces), formed by a character C and the distance D in meters of that link. Stopping the input of such lines when C acquires the value ‘*’. The program ends when K=0.
Output details:
For each test case the output will be the time in ms (milliseconds) taken for the transmission of each packet.
INPUT
OUTPUT
100
F30
S10
T5
*
0
2153.2
Constraints:
0≤ K<100000000
C = {‘F’, ‘S’, ‘T’, ‘*’}
0<D<100000000 | 34,860 |
Time (V_AYP1_D)
Heidi has a discrete analog clock in the shape of a circle, as the one in the figure. Two hands rotate around the center of the circle, indicating hours and minutes. The clock has 60 marks placed around its perimeter, with the distance between consecutive marks being constant.
The minute hand moves from its current mark to the next exactly once every minute. The hour hand moves from its current mark to the next exactly once every 12 minutes, so it advances five marks each hour.
We consider that both hands move discretely and instantly, which means they are always positioned exactly over one of the marks and never in between marks.
At midnight both hands reach simultaneously the top mark, which indicates zero hours and zero minutes. After exactly 12 hours or 720 minutes, both hands reach the same position again, and this process is repeated over and over again. Note that when the minute hand moves, the hour hand may not move; however, when the hour hand moves, the minute hand also moves.
Heidi likes geometry, and she likes to measure the minimum angle between the two hands of the clock at different times of the day. She has been writing some measures down, but after several years and a long list, she noticed that some angles were repeated while some others never appeared. For instance, Heidi's list indicates that both at three o'clock and at nine o'clock the minimum angle between the two hands is 90 degrees, while an angle of 65 degrees does not appear in the list. Heidi decided to check, for any integer number A between 0 and 180, if there exists at least one time of the day such that the minimum angle between the two hands of the clock is exactly A degrees.
Help her with a program that answers this question.
Input details:
An integer T representing the test cases, then, T lines will follow. Each test case is described using one line. The line contains an integer A representing the angle to be checked
.
Output details:
For each test case output a line containing a character. If there exists at least one time of the day such that the minimum angle between the two hands of the clock is exactly A degrees, then write the uppercase letter
‘Y’. Otherwise write the uppercase letter ‘N’.
INPUT
OUTPUT
7
90
65
66
67
128
0
180
Y
N
Y
N
N
Y
Y
Warning: There are no blank lines between numbers nor in the input or output.
Constraints:
0<=
A
<=180 | 34,861 |
Secret (V_AYP1_E)
Petra Pobre wishes to open a secret room in her school, but the security system consists in a puzzle that is formed by a matrix of size NxM, then, for each column you will have N numbers in any order, to solve the puzzle, you must observe a particular number K that can be found besides the matrix size, to open the door, Petra needs to shout the minimum moves that she needs to make so that every observed number K found in every column is aligned at the first row.
Every column in the matrix can be moved up or down, by instance.
N=4 M=3 K=2;
1 2 3
3 1 2
2 8 4
3 3 5
In the first column the number K moves two units up, in the second column the number is in position and in the last column it goes one unit up, therefore, the result is 3.
Input details:
There are three integers to read; N,M and K, everyone corresponding to the number of columns and rows in the matrix with the number to move, the next N lines will contain M integers separated by a single space representing the number in a position of the matrix (i,j)
Output details:
You should print the minimum moves so that the condition described previously is satisfied.
INPUT
OUTPUT
4 3 2
1 2 3
3 1 2
2 8 4
3 3 5
3
Constraints:
0 < N,M < 1500
0 < K < 2000 | 34,862 |
A little help for Yon (V_AYP1_F)
Yonkleiderson
is
a
very
lazy
student
which
really
dislikes
carrying
his
own
books.
He
often
asks
his
friends
for
help,
they
carry
a
certain
book,
a
certain
distance
for
a
Price.
Yonkleiderson
must
take
N
books
and
for
each
book
the
position
and
cost
per
meter
will
be
given.
He
needs
to
calculate
how
much
it
will
cost
him
to
take
the
books
from
one
place
to
the
other
with
Yonaiker´s
help.
Although
he
can
only
use
Yonaiker´s
help
once.
Yonkleiderson
has
a
limited
amount
of
money
and
he
is
not
always
able
to
pay
Yonaiker
to
take
all
his
books.
Yonkleiderson
must
calculate
what
is
the
greatest
amount
of
books
Yonaiker
can
carry.
Yonaiker
once
he
picks
up
a
book
will
carry
it
together
with
the
rest
he
picks
up
along
the
way,
until
the
final
destination
where
he
will
leave
all
the
books.
Input details:
The
first
line
will
contain
two
integers
N
and
V,
N
represents
the
number
of
books
to
be
picked
up,
V
is
the
amount
of
money
Yonkleiderson
has.
N
lines
will
follow
each
with
two
integers
B
and
C
where
B
represents
the
position
of
the
books
and
C
the
cost
per
meter
of
each
book.
Example
;
N=4
V=20
20
2
22
5
30
8
32
1
For
this
test
case
the
result
is
1.
Only
one
book
can
be
taken
by
Yonaiker.
The
book
in
position
20
cost
until
position
22
is
4:
(22-20)*2=
2*2=4.
If
you
want
help
with
the
first
until
the
third
book
we
must
remember
that
the
second
book
will
also
be
taken:
((30-20)*2)
+((30-22)*5)
=
20
+
40
=
60.
The
cost
of
taking
the
first
book
to
the
end:
((32-20)*2)+
((32-22)*5)
+
((32-30)*8)
=
24+50+16=90
In
the
same
way
we
start
calculating
from
the
second
book,
second
to
third:
(30-22)*5=8*5=40,
second
to
fourth:
((32-22)*5)+((32-30)*8)=
50+16=66
Third
to
fourth:
(32-30)*8=
16
We
can
observe
the
value
of
V
is
only
20
as
such
we
can
only
pay
Yonaiker
for
help
in
taking
the
first
book
to
the
second
or
the
book
before
last
to
the
last.
Output details:
The
output
will
consist
of
an
integer
which
will
show
the
maximum
amount
of
books
with
which
Yonaiker
can
help
Yonkleiderson.
INPUT
OUTPUT
4 20
20 2
22 5
30 8
32 1
1
Constraints:
0 < N < 100
0 < V < 5000000
0 < B < 300
0 < C < 20 | 34,863 |
Very Triangular (V_AYP2_A)
Español
At school, Panchito´s teacher has asked them to make a simple game that given the length of the sides of a triangle, it can classify them as Isosceles, Scalene or Equilateral.
Help:
•
Isósceles
: two sides of the same length.
•
Scalene:
all sides have different lengths.
•
Equilateral:
all sides are equal.
Input Details:
You should read three integers
X, Y, Z
be three lengths in the plane.
Output Details:
Only to print that kind of triangle is isosceles, scalene, or equilateral.
INPUT
OUTPUT
2 2 2
90 54 90
23 100 12
Equilateral
Isosceles
Scalene
Constraints:
0 <= X <= 10000000
0 <= Y <= 10000000
0 <= Z <= 10000000 | 34,864 |
Sub-matrix Average (V_AYP2_B)
Español
Dickie is learning the utilities of a matrix in the school, then the professor asked him to find the maximum submatrix in a matrix given, so that the average is maximum, we define the average in a submatrix as the sum between all the elements on the submatrix divided by the number of cells evaluating, so for example.
3 2 3
4
9 8
1
8 9
The example matrix has 4 submatrix, these are { {0,0,1,1}. {0,1,1,2}, {1,0,2,1}, {1,1,2,2} } (The values given are the pair (row,column) for the leftmost top corner and the rightmost bottom corner), of course, the maximum average obtainable in this example is the last one, giving ( (9+8+9+8) / 4 → 34 / 4 → ) 8.50
For simplicity, we ask you to print the result with two decimal places, i.e. instead of printing 8.5 you should print 8.50, if there is any result with more than two, round it up, i.e. if the result is 8.66666... you should print 8.67.
Input details
:
You must read two integers N and M, representing, respectively, the matrix N and the submatrix M to take, after that, N lines with N integers separated by a space will come, each representing the position in the matrix.
Output details
:
You should print the maximum average obtainable having in count that you should
always
form a submatrix of MxM in the bigger matrix N.
INPUT
OUTPUT
3 2
1 5 3
9 9 8
7 8 9
8.50
Constraints
:
1 <= N <= 20
1 <= M <= N | 34,865 |
Magic (V_AYP2_C)
Español
A group of numbers which have the same value when added by row, column and diagonal are known as magic groups. These groups are known to have the same amount of rows and columns. For example:
|16|3 |2 |13|
|5 |10|11|8 |
|9 |6 |7 |12|
|4 |15|14|1 |
In this magic group the magical sum is 34 in rows, columns and diagonals. If the sum of one or two of the diagonals don ́t match with the magical sum this group is considered semi-magical.
Following a much known practice, divide and conquer, we have developed a program that verifies that the columns sum match, you will only have to verify the rows and both main diagonals sums match.
Input details:
The first line will contain an integer N indicating the size of the group. N lines follow with N integers each having the numbers of the group. Groups will continue being read until N=0.
Output details:
The output line will indicate if the group (square) is magical (M), semi-magical(SM) or not magical (NM).
INPUT
OUTPUT
3
1 2 3
2 3 1
3 1 2
4
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
0
SM
M
Constraints:
1 <= N <= 50 | 34,866 |
Military (V_AYP2_D)
Español
A military column of N soldiers, is training and marching, numbered as follows, when six soldiers:
6
5
4
3
2
1
When an officer calls formation, they must act quickly to complete formation in K columns indicated to them, for example if the officer indicates do training in 2 columns, would be as follows:
3 6
2 5
1 4
In the example above, soldier 5 when called to formation, would be in row 2 and column 2. Obviously the military must be very disciplined and always form in an orderly fashion, the first soldiers will always be in the first column, then next in the second column and so on until column K is completed as ordered by the commanding official.
Input details:
The first line will contain 2 integers, N,K, Followed by a X number of soldier. N will
always be exactly divisible by K.
Output details:
The row and column in which the soldier who was called to formation is in.
INPUT
OUTPUT
15 3
8
3 2
Constraints:
0<N<=1000000
0<K<=N
0<X<=N | 34,867 |
Lazy Decision (V_AYP2_E)
Español
Samuel is a pretty intelligent Young man. He recently completed high school and thanks to his high IQ he was given the opportunity of choosing which University he wanted to continue his education in. Although he is very smart, he is extremely lazy.
His primary concern is not how good the university is but how close it is to his home as he really hates getting up early. Write a program that helps Samuel in this decision as it is a loss of his precious time to think about this issue.
Input details:
The first line of the input will have an integer T with the number of test cases, each case will have an integer N indicating the number of universities that Samuel can choose. These universities will be ordered from best to worse (first in the list is the best, last in the list will be the worse).The next line will contain 2 coordinates, (Px,Py) indicating the position of Samuel ́s house. N lines will follow each containing 2 numbers Xi,Yi that represent the location (coordinates) of university i.
Output details:
The output will contain three numbers X,Y,Z. X and Y represent the coordinates of the closest university to Samuel ́s house, Z will represent the minimum distance to the university. In case 2 universities have the same distance to Samuel ́s house, he will choose the best between them. Consider that in Samuel ́s city the only way to move about is horizontally and vertically, there are no shortcuts as taking diagonals.
INPUT
OUTPUT
1
2
0 0
1 1
2 2
1 1 2
Constraints:
0<T<10000
0<N<10000
0<xi<1000000
0<yi<1000000 | 34,868 |
Mirrors (V_AYP2_F)
Español
Dickie likes to play with mirrors on Sundays, and, as he gets bored very fast he decided to use a flash light in a room full of mirrors to see what happens, he saw a lot of lights crossing over the room but he doesn't know why its happening, he wants to know what kind of wicked reflection law is happening here and that's why he called you, given the size of the matrix of mirrors, the position of the flashlight and the direction, you should be able to determine where the light intersects, you may know that:
All the mirrors are located on the walls of the matrix
The direction will change according to the collision of mirrors, that is, if the direction is, by example, south-west and collides to the western wall, the light will change its direction to south-east by logic, the same happens with the light when collides to the northern, southern and eastern wall.
Input details:
You will read four integers H,W,I,J, corresponding, respectively, to the dimension of the matrix (HxW) and the initial position of the flashlight (I,J), after that, read a string S, the string S could contain one of these possibilities, south-west, south-east, north-east, north-west, you can safely assume that there will not be errors when giving the string.
Output details:
Output a pair of numbers (R,S), corresponding to the intersecting point of two light rays.
INPUT
OUTPUT
5 6 1 3 south-east
0 0
Explanation:
Beginning on (1,3) to the south-east, the light collides to (3,5), then, goes to the south-west when it collides in the southern wall (4,4), then it changes the direction to the north-west and then collides at point (0,0), when colliding this point, the light will return by the same place it came, so the intersection is immediate and you should print 0,0
Hint, answers for the other directions are:
south-west: 4 0
north-east: 1 3
north-west: 1 3
Constraints;
1 <= H,W <= 1000
0 <= I < H
0 <= J < W
S = { “south-east”, “south-west”, “north-east”, “north-west” } | 34,869 |
Game of Life (GMLIFE)
Alice and Bob are playing a game of life, Alice is representing the evil character, and Bob is representing the good character; the game requires the evil to make a ritual in order to rule the world; Bob, being the good character, he tries to stop Alice from making this ritual.
The ritual consists of m gears that can rotate in only one direction, that is clockwise direction; each gear has a pointer pointing to one of its holes; the i
th
gear contains n
i
holes; in order to make the ritual, all the gears must be on their starting position. The configuration of the gears was ready to make the ritual, but unfortunately for Alice, Bob rotated the gears by some number of pushes, precisely he pushed the i
th
gear by a
i
holes, then he changed the system of the gears, and made it with one global control for all the gears, so that the only move Alice can make is to push all the gears at the same time by one hole for each gear. Since it will take too much time to complete the ritual, Alice thought of bringing some workers to finish the task for her as soon as possible, given that they all do the same amount of work. Alice wants to know in how many ways can she do this.
It's guaranteed that the minimum positive number of moves Alice can make, so it can restore the gears from the current configuration to Bob's configuration again, will not exceed 10
14
; and it is also guaranteed that Bob's configuration isn't the original configuration.
Sample input 1, the first gear rotated clockwise by 2 pushes, and the second gear rotated clockwise by 5 pushes.
Input
For each input file, the first line contains a single integer m (1 <= m <= 10
3
), the number of gears, and each of the next m lines contains two integers, the i
th
line contain the two integers a
i
and n
i
space separated (0 <= a
i
< n
i
< 10
14
).
Output
For each test case, output a line containing a single integer, the number of ways to get an amount of workers, such that each does the same amount of work so they can solve the ritual.
Example
Input:
2
2 3
5 7
Output:
5
Input:
2
2 6
3 4
Output:
0
In the first case, the ritual can be completed after 16 pushes, so Alice can bring 1, 2, 4, 8, or 16 workers. In the second case, the ritual cannot be completed. | 34,870 |
Roses (V_CIIC_A)
Adriana discovered that she had a secret admirer one night, when coming home from work.
She found a note that said:
“See, roses. Roses for you.
The greatest number of each column you shall seek,
the number of the row you shall write down,
and with ASCII my name you’ll discover.”
After reading the note she saw a rectangle of 26 rows and several columns, each cell had several roses. As a proud computer scientist she is, she understood that she needed to find the row of each column that has the greatest number of roses. This way the number of the row would tell her the letter (one of the 26 letters of the alphabet, A-Z), thus uncovering the name of her admirer.
Note: If for some reason two cells within the same column have the same amount of roses, the cell with the lowest i (0 <= i <= 26) will be selected.
Input details:
The first line will contain an integer M which will represent the number of columns of the rectangle (obviously the length of her secret admirer’s name). The next 26 lines correspond to Xij values that correspond to the amount of roses in each cell.
Output details:
The output will contain one line which will be the name of Adriana’s secret admirer.
INPUT
OUTPUT
6
79 185 83 93 62 84
48 31 26 62 6 36
68 1 77 14 67 9
20 39 1 52 48 95
65 44 15 61 172 97
46 72 21 43 68 20
84
11 32 92 33 49
52 78 53 23 7 69
92 72 80 175 90 10
13 35 92 44 6 56
9 66 49 19 94 87
22 9 38 18 79 97
62 68 58 48 12 45
90 58 72 40 98 40
15 0 96 39 88 28
9 80 29 12 97 91
23 37 50 9 68 32
96 9 4 95 16 119
89 1 57 12 64 74
18 25 9 48 9 34
26 31 80 60 79 80
2 70 191 62 72 44
63 80 28 53 15 90
178 35 69 22 41 24
83 18 40 20 15 47
34 72 8 3 27 61
XAVIER
Constraints:
0 < M ≤ 100
0 ≤ X
ij
≤ 90000 | 34,871 |
Mirrors Revisited (V_CIIC_B)
Dickie is playing with mirrors again, but now, he brought some friends to the mirror room, to make every friend different, Dickie gave them a flashlight to each friend with a unique color (red, blue, yellow and green), Dickie has the white flashlight and they started playing, after having fun for hours, they all thought the same idea, they want to unite the beams of light for each flashlight as long as they can, of course, they cannot stand at the same place and point to the same mirror, so each friend must be in a different square from any other, he can choose to point his flashlight to any of the 4 diagonals (south-west, south-east, north-west, north-east). Your task is to find the number of beams that intersect any other in the room, as it is the speed of light, the time is irrelevant and the direction that each friend has to point to make it.
There are certain rules, by instance, if a friend or Dickie choose to stay in a borderline ( [0,X] [X,0], [0,M], [N,0] ) he cannot point his flashlight to the direction corresponding to the collide. That is, if Dickie or some friend is in position (1,0), representing the row 1 column 0, he cannot point the flashlight to north-east nor north-west, equivalent things happen for each scenario.
We say that a light intersect any other if and only if the square (I,J) has received more than one flash beams. That is, a single flash beam doesn't count as an intersection.
If the same result comes from different settings directions, you should print the one immediately smallest lexicographically, by instance,
if friend 1 points the flashlight to south-west and friend 2 points the flashlight to north-east and make it to 10 intersections, but the same happens if friend 1 points the flashlight no north-east and friend 2 points the flashlight to north-east, choose the second option as “north-east” is lexicographically smallest than south-west.
If friend 1 from scenario 1 and friend 1 from scenario 2 shares the same direction, you should keep until you find the best answer.
You may use string comparison to find the answer (string A<string B)
For simplicity, we are only interested on the light beam until it reaches one of the visited points, when crashing to a diagonal, it is safe to say that it will stop immediately.
The figure above shows the maximum path (6 square intersection) between two flashlights
INPUT DETAILS:
Each input file starts with three integers N,M,F, denoting respectively the size (NxM) of the matrix and the number of flashlights given. After that, F lines will come each denoting the position of every friend in the matrix
OUTPUT DETAILS:
Print in a single line the sum of intersections of flash beams in the room, then, print F lines in the format “S. |DIRECTION|” where S denotes the number of the friend you are showing, followed by a period '.' and a space, then print the direction that the friend holds to make the beam (north-west, north-east, south-east, south-west are accepted as a valid direction).
INPUT
OUTPUT
4 5 3
1 1
1 2
2 2
6
1. north-east
2. north-east
3. south-east
INPUT2
OUTPUT2
4 5 2
2 4
0 0
5
1. north-west
2. south-east
CONSTRAINTS
:
1 <= N,M <= 200
1 <= F <= 5 | 34,872 |
Loading (V_CIIC_C)
Dickie is downloading some files, his internet connection may be slow as it may be fast, however, he has waited for too long over now and he wants to play as he downloads the files, the 'game' he formulated goes like this.
You are filling a string of length S with the following expression language, the characters will contain one of these, S={0-9,%,-,|}
Now, each character of the string S is a block of file, now, if this block of file is completely filled, you must print a 'pipe' character ('|'), if its not, you must print a dash ('-'), however, if it corresponds to the middle three positions of the string, you must print ([0-9][0-9]%), this corresponds directly to the percentage already downloaded.
Your task is to print the string described above and the time left to download the file entirely, if, for any reason, the time given exceeds the total downloaded file, you should print 'Download is complete'.
INPUT DETAILS:
You are given an integer T, representing the number of test cases, then T lines will follow with four integers each, P, S, F, A, these represents, respectively, the time that already has been downloaded, the number of characters that must be contained in the string S, the size of the files (in megabytes) and the download velocity of the internet connection (given in kilobytes per second). Beware that only the size of the files and the download velocity can be given in floating points.
OUTPUT DETAILS:
For each output you must print the string S as described above, followed by a space and the string “Time left:“, followed by a space and a number H that will be the hours left of the files to download, followed by the string “hs”, followed by a space and then a number M representing the number of minutes, followed by a single character 'm', then a final space and a number C that contains the number of seconds left to download the file.
INPUT
OUTPUT
4
0 10 100 10
60 20 360 60
900 24 167 52.70
2 10 10 5000
----00%---- Time left: 2hs 46m 40s
---------01%--------- Time left: 1hs 39m 0s
||||||-----28%----------- Time left: 0hs 37m 48s
Download is complete
CONSTRAINTS:
0 <= P <= 10^8
5 <= S <= 2T {T € N}
1 <= F <= 1000
10^-2 <= A <= 1000000 | 34,873 |
Cards (V_CIIC_D)
Beto is playing cards with Xavier, Dickie and Charlie, Luis, as usual, is the dealer, then, he deals M cards to each player, then, he puts N cards flipped up on the table and S cards flipped up below the other ones, now, each player can play as many cards they have in their hands as long as the kind of the card is shown in the S cards flipped up, at the same time, the kind chosen must appear in at least one of the kinds shown in the first N cards flipped up.
The player must choose only one kind of his all hand and play it along, the game continues as this, The player puts his card on the table, and then he sums to his/her count i*j where i is the number of the placed card (starting from 1) and j is the number of the card (from 1 to 9), you are ask to maximize the sum of the result and show the kind that must be played to achieve this score, in case of tie, break the tie by choosing the lexicographically smallest kind.
INPUT DETAILS:
The input starts with three integers N,M,S, each of one denoting, respectively, the length of a string S1, the cards in the hand of Beto and the length of a string S2. Then, M lines will follow, each of one will denote the description of the cards in the hand of Beto, every line will contain two characters X and Y, the first one will denote the value of the card (from 1 to 9) and the second character will contain the kind of the card (from A to Z).
OUTPUT DETAILS:
You must print a character and an integer, the character must be the best kind for the selected combination and the integer must be the best selected combo of the cards. The character and the integer must be separated by a single space.
INPUT
OUTPUT
4 5 2
DCHS
9H
3C
4S
1D
3S
HS
S 11
CONSTRAINTS:
1 <= N <= 26
1 <= M <= 10000
1 <= S <= N | 34,874 |
Storm (V_CIIC_E)
Its widely known that the fibonacci sequence is associated to natural phenomenoms, in the case of atmospherics and great storms, within its patterns there are fibonacci numbers.
As we should know, the fibonacci sequence starts in 0 and 1, these numbers belong to the X
0
y X
1
being X
2
The sum of the two previous numbers, we are considering that F(0) = 1 and F(1) = 2, that is:
1 2 3 5 8 13 21 ...
We are developing a new method of storm detection according to studies applying the fibonacci sequence, if there is data in the storm of at least K fibonacci consecutive numbers we consider the storm of grade K.
We need that, given the set of numbers in a storm and any K, you must affirm or deny if such storm is at least grade K
INPUT DETAILS
The first line contains two integers N and M that denotes the dimension of the matrix, followed by the data of storm given in N lines with M numbers in each line, separated by a space, then, the number K that it's the grade to evaluate.
OUTPUT DETAILS
You must print “YES” if the grade of storm is at least K, print “NO” otherwise.
INPUT
OUTPUT
3 4 2
1 5 4 8
9 2 7 3
5 4 1 6
YES
CONSTRAINTS
0 < K ≤ 40
0 < N,M ≤ 1000 | 34,875 |
Spam (V_CIIC_F)
Facebook is getting tired of spammers, as such, they plan to go hard on the spammers, that's why they called you, they would like a program that controls this kind of situation, facebook receives the information as follows:
NAME: COMMENT
Where the NAME string is, it's going to be replaced by a string, belonging to the person who wrote the comment, note that the name can be a string of more than a single word, after that, a colon will continue followed by a single space, when the word COMMENT is, it's gonna be the comment of the person, a person can comment as many times they like if he/she uses as much stars at the end as comment they possess. By instance
Dickie: THIS*
Dickie: IS**
Dickie: SPARTA***
Else it will be counted as a spammer.
Given N comments on a topic found on facebook, please determine if the people it's a spammer or not.
INPUT DETAILS:
An integer N denoting the numbers of comment, then N lines with a string S.
OUTPUT DETAILS:
Print a list of K people, the K people implied on the status, you must print a string P where P represents the person you are telling (you must print it in order of appearance), followed by a space and then a string 'YES' or 'NO' if the person is a spammer or not.
INPUT
OUTPUT
10
Victoria: STOP SPAMMING ME
Rudolph: Why?
Orianna: Don't you like it!?
Victoria: No! Drop death!
Victoria: Dead*
Maurice: Hahaha she doesn't know how to spek
Maurice: speak
Orianna: IGRJAIGRJAI
Orianna: GRJAIGJAIA
Orianna: :D
Victoria NO
Rudolph NO
Orianna YES
Maurice YES
CONSTRAINTS:
1 <= N <= 1000
1 <= |S| <= 10000 | 34,876 |
Davy Jones’s Organ (MFNNM)
Two melodies don’t go out of Davy Jones’s head. One of them or another sometimes emerge in his mind. To get rid of annoying melodies, Davy Jones decided to play them on his organ. At first, he wants consequently perform first and second melodies. And then Davy Jones is going to play the same notes as the first time but in the reverse order.
If the first and second compositions sound exactly the same, then, according to Davy Jones's idea, the melodies will no longer vary by his subconscious and finally will leave him alone.
Jones recorded the notes of both songs. He was sure in the song’s duration, but not really in which place every song begins. But it is not important, because they play cyclically in his mind and you can choose any place as a start in each of them.
Input
In the first line of the input you are given a string of length
n
— sequence of notes of the first melody. In the second line there is a string of length
m
— sequence of notes of the second melody (1 ≤
m
<
n
≤ 5.10
4
,
m
≤
n
). Each note is represented by lowercase Latin letter. Order of notes in the melody corresponds to their order in its playback accurate within start of the melody.
Output
If it is impossible to play compositions conceived by Davy Jones's way, output “No”. Otherwise, in the first line write “Yes” and in the second — a pair of integers — numbers of notes in the first and second tunes respectively, which you should choose as a start. Numbering of notes corresponds to a record of melodies in the input and starts from one. If there are several possible solutions choose the one with the smallest possible tune index from the first note. If there are still many solutions print any.
Example
Input:
cdedab
bac
Output:
Yes
5 3
Input:
aaaa
bbb
Output:
No | 34,877 |
Scavenger Hunt (SHUNT)
You are playing a scavenger hunt game organized by your school.
Assume the school is an infinite 2D field. The rules of the game are quite simple: There are
n
people from the organization, numbered from
1
to
n
. Person
i
is located at position
(x
i
, y
i
)
. All you have to do is go to
(x
i
, y
i
)
and let the
i-
th person see you, for all
1 ≤ i ≤ n
. You can run from a position
(x
a
, y
a
)
to a position
(x
b
, y
b
)
in
dist((x
a
,y
a
),(x
b
,y
b
))
seconds, where
dist(P,Q)
is the euclidian distance between points
P
and
Q
.
Initially, you are at the same position of person
1
, who already saw you. Also, initially you only know the position of person
1
. To find out the position of some other person, you need to ask someone. Every person knows the position of all the others. However, if you ask person
i
where person
j
is, it will take him
W
i,j
seconds to answer. Your task is to find a sequence of questions and runnings that let you finish the game quickly. This is a partial problem - you do not need to find an optimal solution, but your score will be proportional to the solution you find.
Input/Output
This is an iterative problem. Your program will "talk" to the judge directly via the standard input and output.
There are no more than 20 test cases. For each test case, the judge will start by printing
START n
x
1
y
1
W
1,1
W
1,2
...
W
1,n
W
2,1
W
2,2
...
W
2,n
...
W
n,1
W
n,2
...
W
n,n
(Assume
2≤n≤40
and
0≤ x
i
,y
i
,W
i,j
≤
10
4
).
After reading that, your program should print commands. A command must be one of these:
ASK i
ask the person that saw you last where the person
i
is. The judge will reply by printing
ANSWER x
i
y
i
.
You'll get "Runtime Error" if
(1
≤
i
≤
n)
doesn't hold.
GO i
go to the position of the person
i
and let him see you. The judge will reply by printing
MOVED
. You'll get "Runtime Error" if
(1
≤
i
≤
n)
doesn't hold or if you don't know the position of the person
i
yet.
FINISH
finish the game. The judge will reply by printing
OK length
, where
length
is the total time spent by you in the game of the test case in seconds, with exactly 3 fractional digits (this is just a "bonus"; your program should be able to calculate
length
by itself). You'll get "Wrong Answer" if
you haven't been to everyone's position at least once.
You'll get "Runtime error" if your program prints something different from the commands described above.
Imediatally after printing
OK length
, the judge will start another test case by printing
START ...
. If there are no more test cases, the judge will print
END
instead. In this case, your program should terminate.
Please notice that you are allowed to ask more than one question or to not ask any questions at all to a person.
Attention:
the program should clear the output buffer after printing each line. It can be done using fflush(stdout) command or by setting the proper type of buffering at the beginning of the execution - setlinebuf(stdout).
Also, while reading data from the judge in C/C++ using scanf, avoid hardcoding the commands you known you'll receive. For instance, prefer to use scanf("%s %d",start_string,&n) instead of scanf("START %d",&n).
Score
For each test case,
p
i
=
min(1.0, length/greedy)
, where
length
is the total time spent by you, and
greedy
is the length obtained by a program that prints ASK 2 GO 2 ASK 3 GO 3 ... ASK n GO n FINISH.
Your final score will be equal to
ceil
[ (
∑(p
i
*n
i
)/∑n
i
)*100 ], where
n
i
is the value of
n
in the
i-
th test case. The
lower
your score is, the
better
you're ranked.
Exemple
This is an exemple of the executation of a program that obtains
greedy
as the total spend time (and thus gets the score 100):
Judge:
START 3
0 0
1 2 3
4 5 6
7 8 9
Program:
ASK 2
Judge:
ANSWER 2 2
Program:
GO 2
Judge:
MOVED
Program:
ASK 3
Judge:
ANSWER 1 1
Program:
GO 3
Judge:
MOVED
Program:
FINISH
Judge:
OK 12.243
END
Program:
<terminates> | 34,878 |
Yet another range difference query! (TREAP)
Given an empty set S, you have to apply Q operations on this set while keeping the set sorted in increasing order and elements have indices 0 <= i < size(S)
The operations are insert, delete, find min difference in a given range, find max difference in a given range.
Input
I k
Insert k into S, if k is not in S
D k
Delete k from S, if k is in S
N i j
Print min{abs(S[x] - S[y]) | i <= x, y <= j} or -1 if the range has 1 element
X i j
Print max{abs(S[x] - S[y]) | i <= x, y <= j} or -1 if the range has 1 element
I k : Insert k into S, if k is not in S
D k : Delete k from S, if k is in S
N i j : Print min{abs(S[x] - S[y]) | i <= x, y <= j} or -1 if the range has 1 element
X i j : Print max{abs(S[x] - S[y]) | i <= x, y <= j} or -1 if the range has 1 element
limits: 0 < Q <= 200000 , 0 <= k <= 10^9 , 0 <= i,j < size(S)
Output
For each N and X operations, print an integer per line as described above.
Example
Input:
11
I 1
I 12
I 4
I 8
N 0 3
X 0 3
N 1 3
X 0 2
D 4
N 0 1
X 1 2
Output:
3
11
4
7
7
4 | 34,879 |
Rice Hub - IOI (RACEHUB)
In the countryside, you can find a long straight road known as the Rice Way. Along this road
there are R rice fields. Each field is located at an integer coordinate between 1 and L, inclusive.
The rice fields will be presented in non-decreasing order of their coordinates. Formally, for
0 ≤ i < R, rice field i is at coordinate X[i]. You may assume that 1 ≤ X[0] ≤ ... ≤ X[R-1] ≤ L.
Please note that multiple rice fields may share the same coordinate.
We plan to construct a single rice hub as a common place to store as much of the harvest as possible. As with the rice fields, the hub has to be at an integer coordinate between 1 and L, inclusive.
The rice hub can be at any location, including one that already contains one or more rice fields.
Each rice field produces exactly 1 truckload of rice every harvest season. To transport the rice to
the hub, the city has to hire a truck driver. The driver charges 1 Baht to transport a truckload of
rice per unit of distance towards the hub. In other words, the cost of transporting rice from a
given field to the rice hub is numerically equal to the difference between their coordinates.
Unfortunately, our budget for this season is tight: we may only spend at most B Baht on transportation. Your task is to help us strategically place the hub to gather as much rice as possible.
In the countryside, you can find a long straight road known as the Rice Way. Along this road
there are R rice fields. Each field is located at an integer coordinate between 1 and L, inclusive.
The rice fields will be presented in non-decreasing order of their coordinates. Formally, for
0 ≤ i < R, rice field i is at coordinate X[i]. You may assume that 1 ≤ X[0] ≤ ... ≤ X[R-1] ≤ L.
Please note that multiple rice fields may share the same coordinate.
We plan to construct a single rice hub as a common place to store as much of the harvest as possible. As with the rice fields, the hub has to be at an integer coordinate between 1 and L, inclusive.
The rice hub can be at any location, including one that already contains one or more rice fields.
Each rice field produces exactly 1 truckload of rice every harvest season. To transport the rice to
the hub, the city has to hire a truck driver. The driver charges 1 Baht to transport a truckload of
rice per unit of distance towards the hub. In other words, the cost of transporting rice from a
given field to the rice hub is numerically equal to the difference between their coordinates.
Unfortunately, our budget for this season is tight: we may only spend at most B Baht on transportation. Your task is to help us strategically place the hub to gather as much rice as possible.
Task
Given integers R, L and B ( 1 ≤ R ≤ 100 000, 1 ≤ L ≤ 1 000 000 000 , 1 ≤ B ≤ 2 000 000 000 000 000 ) and an array X containing R positive integers:
• R – the number of rice fields. The fields are numbered 0 through R-1.
• L – the maximum coordinate.
• X – a one-dimensional array of integers sorted from smallest to largest.
For each 0 ≤ i < R, field i is located at X[i].
• B – the budget.
You must find an optimal location of the hub and return the maximum number of
truckloads of rice that can be transported to the hub within the budget.
Note that the total cost of transporting the rice can be very large. The budget is given as a 64-bit
integer, and we recommend that you use 64-bit integers in your computation. In C/C++, use the
type long long; in Pascal, use the type Int64.
Example
Input:
5 20 6
1
2
10
12
14
Output:
3 | 34,880 |
Yet another strings problem !! (SKIPLIST)
Given a string S and integer N, your task is to compute the substring of length N that is repeated most in the string.
If two substrings of length N have the same occurrence count in S, return the smallest lexicographically.
Input
The first line contains the number of test cases T. T <= 10.
The following T lines hold the test cases, each line consisting of integer N followed by string S. N and S are space separated. N <= 100, |S| <= 100000 .
Output
Print T lines, each containing the substring of length N that is most frequent. If two substrings have the same occurrence count, print the smallest lexicographically.
Example
Input:
2
2 efababefef
1 aabebb
Output:
ef
b | 34,881 |
Scrivener - IOI 2012 (SCRIVIOI)
Crayfish scrivener
Some people say that Leonardo was a great admirer of Johannes Gutenberg, the German blacksmith who invented movable-type printing, and that he paid homage by designing a machine called the crayfish scrivener — il gambero scrivano — a very simple typing device. It is somehow similar to a simple modern typewriter and accepts only two commands: one to type the next character and one to undo the most recent commands. The notable feature of the crayfish scrivener is that the undo command is extremely powerful: an undo is also considered to be a command itself,
and can be undone.
Statement
Your task is to realize a software version of the crayfish scrivener: it starts with an integer representing the number of queries and accepts a sequence of commands entered by the user, and queries for specific positions of the current version of the text, as follows.
T L — append to the end of the text a single lowercase letter L chosen from
a, …, z.
U C — undo the the last C commands, for a positive integer C.
P X — return the letter at position X in the current text, for a non-negative index X. The first letter in the text has index 0. (This query is not a command and thus is ignored by the undo command.)
It is guaranteed that C in query 'U' will not exceed the number of previously received commands, and that X in query 'P' will be less than the current text length ( the number of letter in the current text ).
As for query 'U', it undoes the previous C commands in reverse order: if the command to be undone is T L, then it removes L from the end of the current text; if the command to be undone is U X for some value X, it re-does the previous X commands in their original order.
Example
Input
Output
10
a
T c
c
T z
T u
T a
T i
T h
T f
T z
P 3
P 0 | 34,882 |
Swap (Original) (TOKI1493)
NyanCoder have a new hobby, that hobby is playing with string and He love sorted string. NyanCoder want to make two strings
a
and
b
, both string have equal length
N
. At that both string, NyanCoder want to swap some element (or none) on string
a
with element on string
b
that located at same position. More specifically, NyanCoder may choose integer i, and then swap a[i] with b[i].
NyanCoder want when he finished playing, both new string have non-decreasing element (e.g. "aabbb", "cccdee" but not "bbaa" or "ebd"). Help NyanCoder to count number of possible initial string
a
and
b
with length
N
that meet the condition that NyanCoder want.
Input
First line there is an integer
T
denoting number of test cases, then
T
test cases follow.
For each test case, there is two integers
N
and
M
, separated by a space where
N
denoting length of both string, and alphabet that can be used on that both string is
M
first letters (lower case) on latin alphabet ('a','b','c', and so on). For example, if
M
=3, all character on both string is formed with only first 3 lower case letters ('a','b', and 'c').
Output
For each test case, output an integer which is the number of possible initial string
a
and
b
with length
N
and meet all condition that have described before. Since that answer can be too large, take modulo 10
9
+7
Example
Input:
1
2 2
Output:
11
Explanation
When
N
=2 and
M
=2, all pair of initial sring that meet the condition is:
"aa", "aa"
"aa", "ab"
"aa", "bb"
"ab", "aa"
"ab", "ab"
"ab", "bb"
"bb", "aa"
"bb", "ab"
"bb", "bb"
"ba", "ab"
"ab", "ba"
Subtask
Subtask 1 (10 points): 1<=
N
<=5, 1<=
M
<=26
Subtask 2 (20 points): 1<=
N
<=10, 1<=
M
<=26
Subtask 3 (30 points): 1<=
N
<=40, 1<=
M
<=26
Subtask 4 (40 points): 1<=
N
<=1000, 1<=
M
<=26
To get AC on this problem you need to solve at least one test data (min possible points on rank table for this problem is 10).
Other Info
This is a copy of
TOKI
problem, with some small changes to become suitable with SPOJ server and judge:
Language, because SPOJ is International Online Judge, so I must translate the problem statement and other to English before publishing it.
I/O format, because SPOJ server is busy (too many submission per minute), to make it stable then I should make number of input data as small as possible, so my solution is to put multiple test case in one file.
Test Case, because I don't know official test case used on this problem, I build my own test case. All possible case that meet the constraints will appear once on each test data.
Problem setter who created this problem is
Risan Petrus
. I only copy his
problem that used on TOKI open contest june 2013 to SPOJ because for me this problem is very interesting. I like it, and I want every user on SPOJ can enjoy his
problem too.
See also:
Another problem added by Tjandra Satria Gunawan | 34,883 |
good string (GOODS)
The definition of beauty quotes sequence:
Empty string is a series of beautiful quotes.
If X is a series of beautiful quotes, then [X], (X), {X} is also a beautiful array brackets.
If X, Y ranges are 2 beautiful quotation marks, the sequence XY is also beautiful.
Example: () [() ()] is a row of beautiful quotes. {[)} Is not beautiful array brackets.
Given a string S contains only the brackets. When writing out the characters from position to position i of the string S j (1 <= i <= j <= Length (S)) we obtain the sequence S (i, j). An S (i, j) is the better of the string S if S (i, j) is a series of beautiful quotes. Request the number of good properties of S.
The definition of beauty quotes sequence:
Empty string is a series of beautiful quotes.
If X is a series of beautiful quotes, then [X], (X), {X} is also a beautiful array brackets.
If X, Y ranges are 2 beautiful quotation marks, the sequence XY is also beautiful.
Example: () [() ()] is a row of beautiful quotes. {[)} Is not beautiful array brackets.
Given a string S contains only the brackets. When writing out the characters from position to position i of the string S j (1 <= i <= j <= Length (S)) we obtain the sequence S (i, j). An S (i, j) is good substring of string S if S (i, j) is a series of beautiful quotes. Request the number of good substring of S.
Input
A single line: string S.
The first 10 trials, the length of S is less than 101.
The next 10 trials, the length of S is less than 10001.
10 final test, the length of S is less than 1000001.
Output
A single integer: Number of possible substring of S.
Example
Input:
(){](({}))[]
Output:
6 | 34,884 |
Smugglers (SMUGGLER)
Byteotia is famous for its rich deposits of gold. Therefore, for many years there flourished the sale of that metal to a neighbouring kingdom, Bitland. Unfortunately, the growing deficit of the national budget forced the king of Bitland to introduce heavy tariffs on metals and minerals. Traders crossing the border have to pay customs duty of 50% of the value of the transported load. Byteotian merchants are threatened with bankruptcy. Fortunately, Byteotian alchemists have developed ways to transform some metals into other. The merchants' idea is to use the alchemists' know-how to transform gold into some cheap metal, and next, after crossing the border and paying little tariff, to transform it back into gold. Unfortunately, the alchemists can not transform any metal into arbitrarily chosen other one. Therefore, it may happen that the process of obtaining a given metal from gold must be a chain of transformations that produces a different metal on each stage. The alchemists demand stiff fees for their services. They have fixed a price for transforming 1 kg of a metal
A
into a metal
B
for each transformation they are able to conduct. The traders ponder on what form gold should be transported across the border and what sequence of alchemical processes should be applied to achieve the highest income.
Task
Help to cure Byteotian economy! Write a program which:
Reads a table of prices for all metals and prices for transformations offered by the alchemists.
Determines such a sequence of metals
m
1
,
m
1
, ...,
m
k
that:
m
1
=
m
k
is gold,
for each
i
=2, 3, ...,
k
the alchemists are able to obtain metal
m
i
from metal
m
i
-1
, and
the cost of performing the whole sequence of alchemical processes for 1 kg of gold, augmented by the duty paid on the border (50% of the price of 1 kg of the cheapest metal from
m
i
, for
i
= 1, 2, ...,
k
) is the smallest possible.
We assume that during the alchemical processes the weight of metals does not alter.
Writes out the cost of performing the determined sequence of alchemical processes augmented by the duty paid on the border.
Input
In the first line of the standard input there is one positive integer
n
denoting the number of different metals, 1 <=
n
<= 5000. In the (
k
+1)-st line, for 1 <=
k
<=
n
, there is a non-negative even integer
p
k
: the price of 1 kg of the
k
-th metal, 0 <=
p
k
<= 10
9
. We assume that gold has the number 1. In the (
n
+2)-nd line there is one non-negative integer
m
equal to the number of transformation processes the alchemists are able to conduct, 0 <=
m
<= 100000. In each of the following
m
lines there are three positive integers, separated by single spaces, describing consecutive transformation processes. A triple of numbers
a
,
b
,
c
denotes that the alchemists are able to obtain the
b
-th metal from the
a
-th metal, and they demand
c
bytealers for transforming 1 kg of material, 1 <=
a
,
b
<= n, 0 <=
c
<= 10000. An ordered pair of numbers
a
and
b
may appear at most once in the data.
Output
Your program should write to the standard output. In the first line there should be one integer - the cost of performing the alchemical processes determined by your program augmented by the duty paid on the border.
Example
For the following input data:
4
200
100
40
2
6
1 2 10
1 3 5
2 1 25
3 2 10
3 4 5
4 1 50
the correct answer is in the following output:
60 | 34,885 |
Big number only (PBIGNUM)
We call:
F1(x,y) is x*y.
F2(x,y) is x/y if x/y is an integer, else it is 1.
F3(x,y) is the max number k that x/k,y/k are integer.
F4(x,y) is the min number k that more than 0 and k/x,k/y are integer.
For S is an array of integer. First, all of them are one. We have Q query that one forms of:
1 x y k: Change a[x] become Fk(a[x],y).
2 x y k: Change a[x] become Fk(a[x],a[y]).
3 x y: Let 4 number: F1(a[x],a[y]); F2(a[x],a[y]); F3(a[x],a[y]); F4(a[x],a[y]).
Input:
The first line: Two integer,n is the size of S and number Q.
One of Q line next is a query.
Output:
Many line, one of them is result of a query that type 3.
Example:
Input:
2 4
1 2 100 1
3 1 2
1 2 1000 2
3 1 2
Output:
100 1 1 100
1 1 1 1
Note:
0<n,Q<10001;
In the query of type 1: 0<x<n+1; 0<k<5; 0<y<10001.
In the query of type 2: 0<x,y<n+1; 0<k<5.
In the query of type 3: 0<x,y<n+1. | 34,886 |
AlienGift (AGIFT)
In a gift box, we have a springs that stiffness from L to H, and 4 gift that is numbered 1,2,3,4. Each gift is value. A key is a string that have 4 characters of {0,1}. When you use a key, you’ll have some gift that have character 1 in string in number gift. Example: With key 0110, you’ll have gift 2 and gift 3.
In courtyard we have N gift box that is numbered from 1 to n. When you are in gift box i, you’ll use a key to collect gift, that the key have no character 1 next to character 1, and have no character 1 match about last key you use. And then, you use springs to fly to other gift box. If you use springs with stiffness k, you are going to flying to gift box i+k, or you go out courtyard if i+k>n.
You are in gift box 1, and you fly until go out courtyard. You collect gift and not empty. You’ll have total gift value. Let the maximum value you can collect.
Input:
The first line is a integer: N.
In n line next, each line is 6 integers: L,H and value about 4 gift.
Output:
Let the number is maximum value you can collect. (have no other characters).
Example:
Input:
6
1 1 3 2 -4 5
1 2 2 -3 1 3
2 2 1 1 -1 -1
1 3 -10 10 30 33
1 1 2 3 -5 4
1 100 2 2 2 2
Output:
67
Note:
0<N<100001.
0<L≤H<1000000001.
Value of gift is a integer that the absolute not more than 1000000000.
50% test n<1001. | 34,887 |
Alien Virut (AVIRUT)
We have a matrix, size n*m. The point in line i and column j is point (i,j).
Now, we pour water in point (x,y) at seconds 0.
If at seconds k, point (i,j) have water, we say point (i,j) is degree k. And water'll pour to point (x-1,y),(x+1,y),(x,y-1),(x,y+1) at seconds k+1 if they are having no water. But if c[i,j]=w, point (i,j) never have water, and haven't degree of course.
In point (i,j) (degree k) have some virut dying. But if have water, they live again. And they'll attack some point that degree ≥ k-b[i,j] and degree ≤ k; and total virut in them augment a[i,j].
Finally, if total virut in point (i,j)>c[i,j], house in this point will be infection.
Input
The first line is 5 integer: n,m,x,y,w.
In n group line next, group line i is m line, line j in m line is 3 integer: a[i,j],b[i,j],c[i,j].
Output
n Line. Line i is a integer: The number of house in line i that is infection.
Example
Input:
3 3 1 2 5
1 1 20
1 3 40
1 1 5
2 0 29
1 1 1
2 2 2
2 3 5
1 4 4
1 5 50
Output:
0
2
1
Note:
0<n,m<501. 0<a[i,j]<1001. 0≤b[i,j]≤m*n. 0<c[i,j]≤1000000000.
50% test: 0<n,m<101. | 34,888 |
Liga (SKLIGA)
While the players are resting between sets, the station puts on tedious commercials. Zvonko fires up
the teletext feature on his TV set and is reviewing the latest scores and standings in the football league.
Always sharp, he has come up with a new mathematical game.
The standings table contains five statistics for each team: the total number of games played, how many
of those games the team won, drew and lost, and points earned. A team earns 3 points for every win
and 1 point for every draw.
Zvonko noticed that the values of some fields can be determined from the others.
Write a program that takes in a table in which the values of some fields are unknown, and fills in the
missing fields.
The data for different teams is not related. For example, it is possible that the table says all teams have
won all their games (although that is not possible in a real league).
Each team will have played at most 100 games (even though that can be one of the missing fields).
While the players are resting between sets, the station puts on tedious commercials. Zvonko fires up
the teletext feature on his TV set and is reviewing the latest scores and standings in the football league.
Always sharp, he has come up with a new mathematical game.
The standings table contains five statistics for each team: the total number of games played, how many
of those games the team won, drew and lost, and points earned. A team earns 3 points for every win
and 1 point for every draw.
Zvonko noticed that the values of some fields can be determined from the others.
Write a program that takes in a table in which the values of some fields are unknown, and fills in the
missing fields.
The data for different teams is not related. For example, it is possible that the table says all teams have
won all their games (although that is not possible in a real league).
Each team will have played at most 100 games (even though that can be one of the missing fields).
Input
The first line contains an integer N (1 ≤ N ≤ 1000), the number of teams in the league.
Each of the following N lines contains the 5 fields for one team separated by single spaces, containing
the 5 pieces of data as described in the problem statement. Each field contains an integer (at least 0), or
the character '?' (question mark) if the value is not known.
The input will be consistent and there will be a unique way to determine the values of the missing
fields.
Output
Output the table with the missing fields filled in.
Note: For each test case, your program will receive a score linearly proportional to the number of
correctly solved teams, rounded down. If your program exceeds the time limit or another error occurs,
the score for that test case will be 0.
Example
Input:
5
27 21 3 3 66
27 18 6 3 ?
? 15 5 7 50
? 14 7 5 ?
? 14 ? 8 47
Output:
27 21 3 3 66
27 18 6 3 60
27 15 5 7 50
26 14 7 5 49
27 14 5 8 47 | 34,889 |
dvaput (SKDVA)
Ivana won the bet (Zvonko hadn't foreseen this and suspects that it is due to outside interference) and
now Zvonko is waiting for her at the movies. While he is waiting, he is observing messages on a screen
above him.
As Ivana is running late, Zvonko has been looking at the screen for a while and noticed that some
messages appeared on the screen more than once. Naturally, he's been writing down all messages on a
piece of paper. He wants to know the length of the longest string that appeared at least twice (appears
in two different positions on the paper).
Ivana won the bet (Zvonko hadn't foreseen this and suspects that it is due to outside interference) and
now Zvonko is waiting for her at the movies. While he is waiting, he is observing messages on a screen
above him.
As Ivana is running late, Zvonko has been looking at the screen for a while and noticed that some
messages appeared on the screen more than once. Naturally, he's been writing down all messages on a
piece of paper. He wants to know the length of the longest string that appeared at least twice (appears
in two different positions on the paper).
Input
The first line of input contains an integer L (1 ≤ L ≤ 200 000), the length of the string Zvonko wrote
down.
The second line contains a string of L lowercase letter of the English alphabet.
Output
Output the length of the longest string that appears twice on a single line. If there is no such string,
output zero.
Example
Input:
18
trutrutiktiktappop
Output:
4 | 34,890 |
Ivana (SKIVA)
Even though she saw Zvonko steal Mirko's microprocessor in the second task, Mirko's sister Ivana did
not tell Mirko because she likes Zvonko. She suggested to him that they go see a movie together so that
she would "forget" about the incident.
Zvonko does not care much for girls because they take away precious time he usually spends practicing
his math-fu. He suggested that the two of them play a game and, if Ivana wins, they will go see a movie
together. Ivana agreed, being good at jump rope and she sometimes even kicks a football around with
her two brothers.
Zvonko laid N positive integers in a circle on the floor and explained the rules:
• The first player takes any number.
• The second player takes either of the two numbers adjacent to the one the first player took.
• The next player takes a number adjacent to any of the numbers taken so far, and so on until
they run out of numbers. The player to take more odd numbers (not divisible by 2) wins.
Zvonko plays optimally; he always looks for a strategy that leads to certain victory or a draw. Zvonko
does not know how well Ivana plays. Being a true cavalier, he let Ivana have the first move.
But Ivana only cares about sitting next to Zvonko in front of the big screen so she seeks help playing.
Write a program that finds how many different first moves Ivana can make, so that she has a chance of
winning afterwards.
Even though she saw Zvonko steal Mirko's microprocessor in the second task, Mirko's sister Ivana did
not tell Mirko because she likes Zvonko. She suggested to him that they go see a movie together so that
she would "forget" about the incident.
Zvonko does not care much for girls because they take away precious time he usually spends practicing
his math-fu. He suggested that the two of them play a game and, if Ivana wins, they will go see a movie
together. Ivana agreed, being good at jump rope and she sometimes even kicks a football around with
her two brothers.
Zvonko laid N positive integers in a circle on the floor and explained the rules:
• The first player takes any number.
• The second player takes either of the two numbers adjacent to the one the first player took.
• The next player takes a number adjacent to any of the numbers taken so far, and so on until
they run out of numbers. The player to take more odd numbers (not divisible by 2) wins.
Zvonko plays optimally; he always looks for a strategy that leads to certain victory or a draw. Zvonko
does not know how well Ivana plays. Being a true cavalier, he let Ivana have the first move.
But Ivana only cares about sitting next to Zvonko in front of the big screen so she seeks help playing.
Write a program that finds how many different first moves Ivana can make, so that she has a chance of
winning afterwards.
Input
The first line of input contains an integer N (1 ≤ N ≤ 100), how many numbers there are in the circle.
The second line contains N integers separated by single spaces. All numbers will be between 1 and
1000 (inclusive). No two numbers will be the same.
Output
Output the desired number on a single line.
Example
Input:
8
4 10 5 2 9 8 1 7
Output:
5 | 34,891 |
Policija (SKPOLICE)
To help capture criminals on the run, the police are introducing a new computer system. The area
covered by the police contains N cities and E bidirectional roads connecting them. The cities are
labelled 1 to N.
The police often want to catch criminals trying to get from one city to another. Inspectors, looking at a
map, try to determine where to set up barricades and roadblocks. The new computer system should
answer the following two types of queries:
1. Consider two cities A and B, and a road connecting cities G1
and G2
. Can the criminals get
from city A to city B if that one road is blocked and the criminals can't use it?
2. Consider three cities A, B and C. Can the criminals get from city A to city B if the entire city
C is cut off and the criminals can't enter that city?
Write a program that implements the described system
To help capture criminals on the run, the police are introducing a new computer system. The area covered by the police contains N cities and E bidirectional roads connecting them. The cities are labelled 1 to N. The police often want to catch criminals trying to get from one city to another. Inspectors, looking at a map, try to determine where to set up barricades and roadblocks. The new computer system should answer the following two types of queries:
1. Consider two cities A and B, and a road connecting cities G1 and G2. Can the criminals get from city A to city B if that one road is blocked and the criminals can't use it?
2. Consider three cities A, B and C. Can the criminals get from city A to city B if the entire city C is cut off and the criminals can't enter that city?
Write a program that implements the described system
Input
The first line contains two integers N and E (2 ≤ N ≤ 100 000, 1 ≤ E ≤ 500 000), the number of cities and roads. Each of the following E lines contains two distinct integers between 1 and N – the labels of two cities connected by a road. There will be at most one road between any pair of cities. The following line contains the integer Q (1 ≤ Q ≤ 300 000), the number of queries the system is being tested on. Each of the following Q lines contains either four or five integers. The first of these integers is the type of the query – 1 or 2.
If the query is of type 1, then the same line contains four more integers A, B, G1 and G2 as described earlier. A and B will be different. G1 and G2 will represent an existing road.
If the query is of type 2, then the same line contains three more integers A, B and C. A, B and C will be distinct integers.
The test data will be such that it is initially possible to get from each city to every other city.
Output
Output the answers to all Q queries, one per line. The answer to a query can be "yes" or "no".
Example
Input:
13 15
1 2
2 3
3 5
2 4
4 6
2 6
1 4
1 7
7 8
7 9
7 10
8 11
8 12
9 12
12 13
5
1 5 13 1 2
1 6 2 1 4
1 13 6 7 8
2 13 6 7
2 13 6 8
Output:
yes
yes
yes
no
yes | 34,892 |
Avogadro (SKAVO)
Luka is slacking again during chemistry class, while the teacher is explaining Avogadro's law.
Luka first drew a table consisting of 3 rows and N columns. Then he wrote the numbers 1 to N into
the first row in arbitrary order, each number appearing exactly once. In the other two rows he also
wrote integers between 1 and N, but didn't care how many times a number appeared.
Luka can now delete any set of columns from the table. After doing so, he sorts the numbers in each
row in ascending order.
He wants to obtain a table in which all three rows are identical after sorting. Write a program that
determines the smallest number of columns he must delete.
Luka is slacking again during chemistry class, while the teacher is explaining Avogadro's law.
Luka first drew a table consisting of 3 rows and N columns. Then he wrote the numbers 1 to N into
the first row in arbitrary order, each number appearing exactly once. In the other two rows he also
wrote integers between 1 and N, but didn't care how many times a number appeared.
Luka can now delete any set of columns from the table. After doing so, he sorts the numbers in each
row in ascending order.
He wants to obtain a table in which all three rows are identical after sorting. Write a program that
determines the smallest number of columns he must delete.
Input
The first line of input contains the integer N (1 ≤ N ≤ 100 000), the number of columns in the table.
The following three lines contain N integers each, separated by single spaces. The numbers will be
between 1 and N, and there will be no duplicates in the first row.
Output
Output the smallest number of columns Luka must delete.
Example
Input:
7
5 4 3 2 1 6 7
5 5 1 1 3 4 7
3 7 1 4 5 6 2
Output:
4 | 34,893 |
Rice Cracker (SKRICE)
Since its foundation, IOI Confectionery has been making rice crackers in a traditional style, where one
side of crackers is char-grilled for a certain period of time, then they are turned, and the other side is
char-grilled for a certain period of time. Though they keep the tradition. they now use an automated
grilling machine to make crackers. Inside this machine, crackers are arranged in a grid with R rows and
C columns (1 ≤ R ≤ 10, 1 ≤ C ≤ 10000). The machine is usually operated automatically, and all the
crackers are turned at the same time when one side is grilled for the right amount of time.
One day they were right in the middle of the grilling process and about to turn the crackers when
an earthquake occurred and some of the crackers were turned inadvertently. Fortunately, the charcoals
were in a good state. They switched the machine to the manual operation at once to turn only the
crackers that were not already turned; otherwise one side of the crackers will be grilled for too long and
they cannot be shipped as products. This machine is capable of turning one or more rows at the same
time or one or more columns at the same time, but not capable of turning just one cracker.
If they spend too much time to turn the crackers, the crackers will be burned too much and not
suitable for shipping. They decided to first turn some rows and then turn some columns so that they
would maximize the number of ready-to-ship crackers, or the crackers both of whose sides would be
suitably grilled without overgrilling one side. They can choose not to turn any rows, and they can also
choose not to turn any columns. Write a program which computes the maximum number of ready-to-
ship crackers.
Input
Line 1 of the input file contains two space-separated integers R and C (1 ≤ R ≤ 10, 1 ≤ C ≤ 10000).
The following R lines specify the state of crackers just after the earthquake. Line i + 1 (1 ≤ i ≤ R)
contains C space-separated integers ai,1 , ai,2 , . . . , ai,C , where ai, j specifies the state of the cracker at
row i, column j. It is not yet turned if ai, j is 1, and it is already turned if ai, j is 0.
Output
Each output file to submit consists of one line, and the line contains the maximum number of ready-to-
ship crackers.
Example
Input:
2 5
0 1 0 1 0
1 0 0 0 1
Output:
9 | 34,894 |
Cruise (SKCRUISE)
Task
JOI country consists of n islands which are numbered from 1 to n. The country is now developping the
ship network between these islands.
You are working at a ticket center of these ships. Many people thinks of making a trip to another
island as cheep as possible. They write the islands of departure and destinations of their trip in the
order forms and send them to you.
Your task is answering to the query from the clients, by calculating the lowest possible cost to reach
their destination from their departure island by using the ships. In some case that the trip by the ships is
impossible, you must tell it to your client. Moreover, in this country, many ship lines are beginning one
after another, and you are passed on the information about new ships at any time. So you must check
the latest information carefully to answer to your clients.
You are given a list of the order forms from clients and information of new ships, sorted by time.
Write a program that calculates the answer to your clients.
Input
The format of each input file is as follows.
Line 1 consists of 2 space-separated integers: the number n (1
n
100) of islands, and the
number k (1 k 5000) of following lines in the input (input consists of k + 1 lines).
Line i + 1 (1 i k) consists of 3 or 4 space-separated integers:
• If the first number is 0, the line represents a order form. The line consists of 3 integers 0, a, b
(1 a n, 1 b n, a b). This means that a client has sent the order form of a trip from
island a to island b.
• If the first number is 1, the line represents a new ship. The line consists of 4 integers 1, c, d, e
(1 c n, 1 d n, c d, 1 e 1000000). This means that a new ship line connecting
island c and d has begun, and the fare of c to d and d to c are both e. For the queries in the rest
of the input, this ship also must be taken in consideration.
In the beginning, no ship is running. In the input, the number of lines representing information
of new ship is not more than 1000. There may be two or more ships between the same pair of
islands.
Output
The format of each output file to submit is as follows. The file consists of m lines. Line i (1 i m)
should contain one integer representing the answer to i-th order form. This means, if the trip in i-th
order form is possible by some ships, write the minimum possible value of total fare, and other wise,
write -1.
Example
Input:
5 16
1 1 2 343750
1 1 3 3343
1 1 4 347392
1 1 5 5497
1 2 3 123394
1 2 4 545492
1 2 5 458
1 3 4 343983
1 3 5 843468
1 4 5 15934
0 2 1
0 4 1
0 3 2
0 4 2
0 4 3
0 5 3
Output:
5955
21431
9298
16392
24774
8840 | 34,895 |
Average (AVERAGE)
Description
Given a list of numbers, compute the median and the mean.
Median - When the list is sorted, the median is the middle number. If the length of the list is even, the median is halfway between the two middle numbers.
Mean - The arithmetic mean is the sum divided by the length of the list.
Input
The first line is the
N
, the length of the list of numbers (
1 <= N <= 100
).
The next
N
lines are integers between 1 and 1000 inclusive.
Output
On the first line, print the median. On the second line, print the mean.
Your answer must be accurate within three decimal places.
Input
Input
5
1
2
3
4
5
4
3
11
4
3
Output
Output
3
3
3.5
5.25 | 34,896 |
Money, Money, Money (MONEYS)
Description
Given a whole number of US dollars, what combination of $1, $5, $20, and $100 bills sum to that amount?
Choose the combination that minimizes the total number of bills.
For example, $10 may be composed of
ten $1 bills
one $5 and five $1 bills
two $5 bills
The fewest bills are the two $5 bills.
Input
An integer number of dollars, from 0 to 1200 inclusive.
Output
The numbers of bills, in the following order: $100, $20, $5, and $1. Separate the numbers by whitespace.
Input
Input
10
334
Output
Output
0 0 2 0
3 1 2 4 | 34,897 |
Comments (COMMENTS)
Description
Everyone knows that lots and lots of comments make for great code.
Well...actually that's not true.
In any case, we are going to count comments in programs written in a new language: C' (pronounced C prime).
In this language, comments take two forms.
Type-1: Beginning with two slashes (//), and ending with a new line, or end-of-file.
Type-2: Beginning with a slash and asterisk (/*), and ending with an asterisk and a slash (*/).
Comments are found by starting at the beginning of the program and moving forward. An opening comment token can be anywhere except inside another comment. Once a comment begins, it is terminated only by the ending sequence for that same type.
For instance,
//* */ hello
is a single type-1 comment, since it began with // and it can only end with a new line or end-of-file.
Likewise,
/** a
// b
*/ c
is a single type-2 comment, since it began with /* and can only end with */.
Given source code, how many comments of each type are present?
Input
Source code consisting of at most 5000 characters. The code will be legal according to the rules earlier (i.e. it will not have unclosed comments).
Output
The number of type-1 comments and the number of type-2 comments. Separate these answers by whitespace.
Input
//* */ hello
Output
1 0
Input
/**
* @return whether program halts
*/
int doesItHalt(void (*program)()) {
return 1; //remember: big picture perspective
}
Output
1 1
Input
int f(int a, int *b) {
char *t = "//yeah, this isn't C";
return a /*b */*//*c
;
}
Output
2 1 | 34,898 |
Starcraft (MINERALS)
Description
In Starcraft, the Terran race has a unit called the T-280 SCV.
Among other things, the SCV can collect minerals. For simplicity, assume that each SCV collects 1 mineral per second. Minerals are discrete (they cannot be divided), so only once after a full second is the mineral collected.
A Command Center takes 17 seconds and consumes 50 minerals to produce one SCV. It can build only one SCV at a time.
Suppose a player is alone on a map, and starts with no minerals, a single Command Center, and a given number of SCVs. If the player does nothing but collect minerals and produce SCVs as as fast as possible, how long would it take to collect all available minerals on the map?
For example, if a player started with one SCV (and one Command Center) and 71 minerals were available, it would take 69 seconds to collect all of them.
Time
SCV
Minerals
Minerals collected so far
0
1
0
0
...
49
1
49
49
50
1
0
50
...
66
1
16
66
67
2
17
67
68
2
19
69
69
2
21
71
Intially, the rate of mineral gathering is 1 per second. At 50 seconds, the Command Center starts building a second SCV, which finishes at 67 seconds. Thus, at 67 seconds, the total rate of mineral gathering becomes 2 per second.
Input
The first line is the number of starting SCVs, from 1 to 50 inclusive.
The second line is the total number of available minerals, from 1 to 10000 inclusive.
Output
The number of seconds required to collect the minerals. Round up to the nearest second.
Input
Input
1
71
1
10000
Output
Output
69
658 | 34,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.