id
stringlengths 6
10
| question
stringlengths 29
13k
| language
stringclasses 1
value |
|---|---|---|
seed_280
|
# Crocodile's Underground City
Archaeologist Benjamas is running for her life after investigating the mysterious Crocodile's Underground City. The city has \(N\) chambers. There are \(M\) bidirectional corridors, each connecting a different pair of distinct chambers. Running through different corridors may require different amounts of time. Only \(K\) of the \(N\) chambers are exit chambers that allow her to escape. Benjamas starts in chamber \(0\). She wants to reach an exit chamber as quickly as possible.
The Crocodile gatekeeper wants to prevent Benjamas from escaping. From his den, he controls secret doors that can block any *single* corridor. That is, whenever he blocks a new corridor, the previously blocked one has to be reopened.
Benjamas's situation can be described as follows: Each time she tries to leave a chamber, the Crocodile gatekeeper may choose to block one of the corridors adjacent to it. Benjamas then chooses and follows one of the unblocked corridors to the next chamber. Once Benjamas enters a corridor, the Crocodile gatekeeper may not block it until Benjamas reaches the other end. Once she enters the next chamber, the gatekeeper may again choose to block one of the outgoing corridors (possibly the corridor that Benjamas just followed), and so on.
She would like to have a simple escape plan in advance. More precisely, she would like to have a set of instructions that tell her what to do when she gets to a chamber. Let \(A\) be one of the chambers. If it is an exit chamber, no instructions are needed---obviously, she can escape the city. Otherwise, the instruction for chamber \(A\) should have one of the following forms:
- *\"If you ever reach chamber \(A\), take the corridor leading to chamber \(B\). However, if that corridor is blocked, then take the corridor leading to chamber \(C\).\"*
- *\"Don't bother about chamber \(A\); according to this escape plan you cannot possibly reach it.\"*
Note that in some cases (for example, if your plan directs Benjamas to run in a cycle) the gatekeeper may be able to prevent Benjamas from reaching an exit. An escape plan is *good* if Benjamas is guaranteed to reach an exit chamber after a finite amount of time, regardless of what the gatekeeper does. For a good escape plan, let \(T\) be the smallest time such that after time \(T\), Benjamas is guaranteed to reach an exit. In that case, we say that the *good escape plan takes time \(T\)*.
## Your Task
Write a procedure `travel_plan(\(N, M, R, L, K, P\))` that takes the following parameters:
- \(N\) -- the number of chambers. The chambers are numbered \(0\) through \(N-1\).
- \(M\) -- the number of corridors. The corridors are numbered \(0\) through \(M-1\).
- \(R\) -- a two-dimensional array of integers representing the corridors. For \(0 \leq i < M\), corridor \(i\) connects two distinct chambers \(R[i][0]\) and \(R[i][1]\). No two corridors join the same pair of chambers.
- \(L\) -- a one-dimensional array of integers containing the times needed to traverse the corridors. For \(0 \leq i < M\), the value \(1 \leq L[i] \leq 1,000,000,000\) is the time Benjamas needs to run through the \(i\)-th corridor.
- \(K\) -- the number of exit chambers. You may assume that \(1 \leq K < N\).
- \(P\) -- a one-dimensional array of integers with \(K\) distinct entries describing the exit chambers. For \(0 \leq i < K\), the value \(P[i]\) is the number of the \(i\)-th exit chamber. Chamber \(0\) will never be one of the exit chambers.
Your procedure must return the smallest time \(T\) for which there exists a good escape plan that takes time \(T\).
You may assume that each non-exit chamber will have at least two corridors leaving it. You may also assume that in each test case there is a good escape plan for which \(T \leq 1,000,000,000\).
## Examples
### Example 1
Consider the case shown in Figure 1, where \(N=5\), \(M=4\), \(K=3\), and
\[
R = \begin{bmatrix}
0 & 1 \\
0 & 2 \\
3 & 2 \\
2 & 4
\end{bmatrix}, \quad
L = \begin{bmatrix}
2 \\
3 \\
1 \\
4
\end{bmatrix}, \quad
P = \begin{bmatrix}
3 \\
2 \\
4
\end{bmatrix}.
\]
<center>
<image>
</center>
An optimal escape plan is the following one:
- If you ever reach chamber \(0\), take the corridor leading to chamber \(1\). However, if that corridor is blocked, then take the corridor leading to chamber \(2\).
- If you ever reach chamber \(2\), take the corridor leading to chamber \(3\). However, if that corridor is blocked, then take the corridor leading to chamber \(4\).
In the worst case, Benjamas will reach an exit chamber in \(7\) units of time. Hence, `travel_plan` should return \(7\).
### Example 2
Consider the case shown in Figure 2, where \(N=5\), \(M=7\), \(K=2\), and
\[
R = \begin{bmatrix}
0 & 2 \\
0 & 3 \\
3 & 2 \\
0 & 1 \\
0 & 4 \\
3 & 4 \\
2 & 1
\end{bmatrix}, \quad
L = \begin{bmatrix}
4 \\
3 \\
2 \\
10 \\
7 \\
9 \\
100
\end{bmatrix}, \quad
P = \begin{bmatrix}
1 \\
3
\end{bmatrix}.
\]
<center>
<image>
</center>
An optimal escape plan is:
- If you ever reach chamber \(0\), take the corridor leading to chamber \(3\). However, if that corridor is blocked, then take the corridor leading to chamber \(2\).
- If you ever reach chamber \(2\), take the corridor leading to chamber \(3\). However, if that corridor is blocked, then take the corridor leading to chamber \(1\).
- Don't bother about chamber \(4\); according to this escape plan you cannot possibly reach it.
Benjamas will reach one of the exit chambers no later than after \(14\) units of time. Therefore, `travel_plan` should return \(14\).
## Implementation Details
**Limits**
- CPU time limit: \(2\) seconds.
- Memory limit: \(256\) MB.
- **Note:** There is no explicit limit for the size of stack memory. Stack memory counts towards the total memory usage.
**Interface (API)**
- Implementation folder: `crocodile/`
- To be implemented by contestant: `crocodile.c` or `crocodile.cpp` or `crocodile.pas`
- Contestant interface: `crocodile.h` or `crocodile.pas`
**Input Format:**
- Line \(1\): \(N, M, K\).
- Lines \(2\) to \(M+1\): For \(0 \leq i < M\), line \(i+2\) contains \(R[i][0], R[i][1], L[i]\), separated by a space.
- Line \(M+2\): A list of \(K\) integers \(P[0], P[1], \dots, P[K-1]\), separated by a space.
- Line \(M+3\): The expected solution.
**Expected Output:**
- Expected output for sample grader input: `grader.expect.1, grader.expect.2, \dots`
- For this task, each one of these files should contain precisely the text `\"Correct\"`.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
- \(3 \leq N \leq 1,000\).
- \(2 \leq M \leq 100,000).
|
Python
|
seed_282
|
# DAY-2
Version D
rods
## Task Description
IOI 2002
Yong-In
Korea
# Two Rods
## PROBLEM
A rod is either a horizontal or a vertical sequence of at least 2 consecutive grid cells. Two rods, one horizontal and the other vertical, are placed on an N x N grid. In Figure-1, the two rods are shown by **X**'s. The rods may or may not be the same length; furthermore, they may share a cell. If, from a diagram such as Figure-1, it is possible to interpret a cell, e.g., (4,4), as being in just one rod or in both rods, we make the interpretation that the cell is in both. Hence, the top cell of the vertical rod is (4,4) rather than (5,4).

Initially we do not know where the two rods are, and so your task is to write a program to determine their locations. We call the horizontal rod ROD1, and the vertical rod ROD2. Each grid cell is represented by a row/column pair (r, c), and the top left corner of the grid is taken to be location (1,1). Each rod is represented as two cells, β¨ (r1, c1), (r2, c2) β©. In Figure-1 ROD1 is β¨ (4,3), (4,8) β© and ROD2 is β¨ (4,4), (9,4) β©.
This task involves the use of library functions for input, for determining the solution, and for output. The length of a side of the square grid is given by the library function `gridsize`, which your program is to call at the beginning of each test case. To locate the rods, you can only use the library function `rect(a,b,c,d)`, which examines the rectangular region [a,b] x [c,d] (shaded region in Figure-1), where a β€ b and c β€ d. [Note carefully the order of these parameters.] If at least one grid cell of either rod falls inside the query rectangle [a,b] x [c,d], `rect` returns 1; otherwise it returns 0. So in the example, `rect(3,8,3,6)` returns 1. Your task is to write a program to discover the exact location of the rods using a limited number of `rect` calls.
You produce output by calling another library function `report(r1,c1,r2,c2,p1,q1,p2,q2)` where ROD1 is β¨ (r1, c1), (r2, c2) β© and ROD2 is β¨ (p1, q1), (p2, q2) β©. Calling `report` terminates your program. Recall that ROD1 is horizontal and ROD2 is vertical, and (r1, c1) is the left end cell of the horizontal rod ROD1. Cell (p1, q1) is the top end cell of ROD2. Hence r1 = r2, c1 < c2, p1 < p2, and q1 = q2. If your `report` parameters do not meet these constraints, then you will get error messages on standard output.
## CONSTRAINTS
- You can access input only by using the library functions `gridsize` and `rect`.
- N, the maximum row (column) size of input, satisfies 5 β€ N β€ 10000.
- The number of `rect` calls should be at most 400 for every test case. If your program calls `rect` more than 400 times, this will terminate your program.
- Your program must call `rect` more than once and call `report` exactly once.
- If a `rect` call is not valid (e.g., the query range exceeds the grid space), it will terminate your program.
- Your program must not read or write any files and must not use any standard input/output.
## LIBRARY
### FreePascal Library (`prectlib.ppu, prectlib.o`)
```
function gridsize: LongInt;
function rect(a, b, c, d: LongInt): LongInt;
procedure report(r1, c1, r2, c2, p1, q1, p2, q2: LongInt);
```
Instructions: To compile your `rods.pas`, include the import statement
```
uses prectlib;
```
in the source code and compile it as
```
fpc -So -O2 -XS rods.pas
```
The program `prodstool.pas` gives an example of using this FreePascal library.
### GNU C/C++ Library (`crectlib.h, crectlib.o`)
```
int gridsize();
int rect(int a, int b, int c, int d);
void report(int r1, int c1, int r2, int c2, int p1, int q1, int p2, int q2);
```
Instructions: To compile your `rods.c`, use
```
#include \"crectlib.h\"
```
in the source code and compile it as:
```
gcc -O2 -static rods.c crectlib.o -lm
g++ -O2 -static rods.cpp crectlib.o -lm
```
The program `crodstool.c` gives an example of using this GNU C/C++ library.
### For C/C++ in the RHIDE environment
Be sure that you set the Option β Linker configuration to `crectlib.o`.
## EXPERIMENTATION
To experiment with the library, you must create a text file `rods.in`. The file must contain three lines. The first line contains one integer: N, the size of the grid. The second line contains the coordinates of ROD1, r1 c1 r2 c2, where (r1, c1) is the left end cell of ROD1. The third line contains the coordinates of ROD2, p1 q1 p2 q2, where (p1, q1) is the top end cell of ROD2.
After running your program which calls `report`, you will get the output file `rods.out`. This file contains the number of `rect` function calls and the coordinates of the ends of the rods you submitted in your call to `report`. If there are any errors or violations of the requirements during library calls, then `rods.out` will contain the corresponding error messages.
The dialogue between your program and the library is recorded in the file `rods.log`. This log file `rods.log` shows the sequence of function calls your program made in the form of
```
\"k : rect(a,b,c,d) = ans\"
```
which means k-th function call `rect(a,b,c,d)` returns `ans`.
## EXAMPLE INPUT AND OUTPUT
**Example:** `rods.in`
```
9
4 3 4 8
4 4 9 4
```
**Example:** `rods.out`
```
20
4 3 4 8
4 4 9 4
```
## SCORING
If your program violates any of the constraints (e.g., more than 400 `rect` calls), or if your program's output (the locations of the rods) is not correct, the score is 0.
If your program's output is correct, then your score depends on the number of `rect` calls for each testing data. For each test case:
- If the number of `rect` calls is at most 100, then you get 5 points.
- If your program calls `rect` 101 to 200 times, you get 3 points.
- If the number of `rect` calls is between 201 and 400, then you get 1 point.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
|
Python
|
seed_296
|
# Day 2 Task 1: Memory
## Introduction
A game called *Memory* is played using 50 cards. Each card has one of the letters from A to Y (ASCII 65 to 89) printed on the face, so that each letter appears on exactly two cards. The cards are shuffled into some random order and dealt face down on the table.
Jack plays the game by turning two cards face up so the letters are visible. For each of the 25 letters Jack gets a candy from his mother the first time he sees both copies of the letter on the two face up cards. For example, the first time Jack turns over both cards that contain the letter M, he gets a candy. Regardless of whether the letters were equal or not, Jack then turns both cards face down again. The process is repeated until Jack receives 25 candies --- one for each letter.
You are to implement a procedure `play` that plays the game. Your implementation should call the procedure `faceup(C)` which is implemented by the grader. `C` is a number between 1 and 50 denoting a particular card you wish to be turned face up. The card must not currently be face up. `faceup(C)` returns the character that is printed on the card C.
After every second call to `faceup`, the grader automatically turns both cards face down again.
Your procedure `play` may only terminate once Jack has received all 25 candies. It is allowed to make calls to `faceup(C)` even after the moment when Jack gets the last candy.
## Example
The following is one possible sequence of calls your procedure `play` could make, with explanations.
| **Call** | **Returned Value** | **Explanation** |
|--------------------|--------------------|-----------------------------------------------------------|
| `faceup(1)` | 'B' | Card 1 contains B. |
| `faceup(7)` | 'X' | Card 7 contains X. The letters are not equal. |
| *The grader automatically turns cards 1 and 7 face down.* | | |
| `faceup(7)` | 'X' | Card 7 contains X. |
| `faceup(15)` | 'O' | Card 15 contains O. The letters are not equal. |
| *The grader automatically turns cards 7 and 15 face down.* | | |
| `faceup(50)` | 'X' | Card 50 contains X. |
| `faceup(7)` | 'X' | Card 7 contains X. Jack gets his first candy. |
| *The grader automatically turns cards 50 and 7 face down.* | | |
| `faceup(7)` | 'X' | Card 7 contains X. |
| `faceup(50)` | 'X' | Card 50 contains X. Equal letters, but Jack gets no candy.|
| *The grader automatically turns cards 7 and 50 face down.* | | |
| `faceup(2)` | 'B' | Card 2 contains B. |
| ... | ... | (some function calls were omitted) |
| `faceup(1)` | 'B' | Card 1 contains B. |
| `faceup(2)` | 'B' | Card 2 contains B. Jack gets his 25th candy. |
## Implementation Details
- Implementation folder: `/home/ioi2010-contestant/memory/`
- To be implemented by contestant: `memory.c OR memory.cpp OR memory.pas`
- Contestant interface: `memory.h OR memory.pas`
- Grader interface: `grader.h OR graderlib.pas`
- Sample grader: `grader.c OR grader.cpp OR grader.pas and graderlib.pas`
- Sample grader input: `grader.in.1`
*Note*: the input file contains one line with 50 characters denoting the letters on the cards, in order, from 1 to 50.
- Expected output for sample grader input: if your implementation is correct, the output file will contain `OK n` where `n` is the number of calls to `faceup(C)`.
## Usage
- Compile and run (command line): `runc grader.c OR runc grader.cpp OR runc grader.pas`
- Compile and run (gedit plugin): `Control-R`, while editing any implementation file.
- Submit (command line): `submit grader.c OR submit grader.cpp OR submit grader.pas`
- Submit (gedit plugin): `Control-J`, while editing any implementation or grader file.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
Implement a strategy that finishes any possible game with at most 100 calls to `faceup(C)`.
|
Python
|
seed_299
|
# Day 2 Task 2: Traffic Congestion
Although Canada is a large country, many areas are uninhabited, and most of the population lives near the southern border. The Trans-Canada Highway, completed in 1962, connects the people living in this strip of land, from St. John's in the East to Victoria in the West, a distance of 7821 km.
Canadians like hockey. After a hockey game, thousands of fans get in their cars and drive home from the game, causing heavy congestion on the roads. A wealthy entrepreneur wants to buy a hockey team and build a new hockey arena. Your task is to help him select a location for the arena to minimize the traffic congestion after a hockey game.
The country is organized into cities connected by a network of roads. All roads are bidirectional, and there is exactly one *route* connecting any pair of cities. A *route* connecting the cities $c_0$ and $c_k$ is a sequence of distinct cities $c_0, \dots, c_k$ such that there is a road from $c_{i-1}$ to $c_i$ for each $i$. The new arena must be built in one of the cities, which we will call the *arena city*. After a hockey game, all of the hockey fans travel from the arena city to their home city, except those who already live in the arena city. The amount of congestion on each road is proportional to the number of hockey fans that travel along the road. You must locate the arena city such that the amount of congestion on the most congested road is as small as possible. If there are several equally good locations, you may choose any one.
You are to implement a procedure `LocateCentre(N, P, S, D)`. $N$ is a positive integer, the number of cities. The cities are numbered from $0$ to $N-1$. $P$ is an array of $N$ positive integers; for each $i$, $P[i]$ is the number of hockey fans living in the city numbered $i$. The total number of hockey fans in all the cities will be at most $2,000,000,000$. $S$ and $D$ are arrays of $N-1$ integers each, specifying the locations of roads. For each $i$, there is a road connecting the two cities whose numbers are $S[i]$ and $D[i]$. The procedure must return an integer, the number of the city that should be the arena city.
## Example
As an example, consider the network of five cities in the top diagram on the right, where cities $0$, $1$, and $2$ contain $10$ hockey fans each, and cities $3$ and $4$ contain $20$ hockey fans each. The middle diagram shows the congestions when the new arena is in city $2$, the worst congestion being $40$ on the thicker arrow. The bottom diagram shows the congestions when the new arena is in city $3$, the worst congestion being $30$ on the thicker arrow. Therefore, city $3$ would be a better location for the arena than city $2$. The data for this example are in `grader.in.3a`.

## Note
We remind contestants that with the given constraints, it is possible to submit a solution that passes Subtask $3$ and fails Subtask $2$. However, remember that your final score for the entire task is determined by **only one** of your submissions.
## Implementation Details
- Implementation folder: `/home/ioi2010-contestant/traffic/`
- To be implemented by contestant: `traffic.c` or `traffic.cpp` or `traffic.pas`
- Contestant interface: `traffic.h` or `traffic.pas`
- Grader interface: `none`
- Sample grader: `grader.c` or `grader.cpp` or `grader.pas`
- Sample grader input: `grader.in.1 grader.in.2`
**Note:** The first line of the input file contains $N$. The following $N$ lines contain $P[i]$ for $i$ between $0$ and $N-1$. The following $N-1$ lines contain pairs $S[i]$ and $D[i]$ for $i$ between $0$ and $N-2$.
- Expected output for sample grader input: `grader.expect.1 grader.expect.2` etc.
- Compile and run (command line): `runc grader.c` or `runc grader.cpp` or `runc grader.pas`
- Compile and run (gedit plugin): `Control-R`, while editing any implementation file.
- Submit (command line): `submit grader.c` or `submit grader.cpp` or `submit grader.pas`
- Submit (gedit plugin): `Control-J`, while editing any implementation or grader file.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
Make the same assumptions as in Subtask $1$, but there are at most $1,000,000$ cities.
|
Python
|
seed_300
|
# Day 2 Task 2: Traffic Congestion
Although Canada is a large country, many areas are uninhabited, and most of the population lives near the southern border. The Trans-Canada Highway, completed in 1962, connects the people living in this strip of land, from St. John's in the East to Victoria in the West, a distance of 7821 km.
Canadians like hockey. After a hockey game, thousands of fans get in their cars and drive home from the game, causing heavy congestion on the roads. A wealthy entrepreneur wants to buy a hockey team and build a new hockey arena. Your task is to help him select a location for the arena to minimize the traffic congestion after a hockey game.
The country is organized into cities connected by a network of roads. All roads are bidirectional, and there is exactly one *route* connecting any pair of cities. A *route* connecting the cities $c_0$ and $c_k$ is a sequence of distinct cities $c_0, \dots, c_k$ such that there is a road from $c_{i-1}$ to $c_i$ for each $i$. The new arena must be built in one of the cities, which we will call the *arena city*. After a hockey game, all of the hockey fans travel from the arena city to their home city, except those who already live in the arena city. The amount of congestion on each road is proportional to the number of hockey fans that travel along the road. You must locate the arena city such that the amount of congestion on the most congested road is as small as possible. If there are several equally good locations, you may choose any one.
You are to implement a procedure `LocateCentre(N, P, S, D)`. $N$ is a positive integer, the number of cities. The cities are numbered from $0$ to $N-1$. $P$ is an array of $N$ positive integers; for each $i$, $P[i]$ is the number of hockey fans living in the city numbered $i$. The total number of hockey fans in all the cities will be at most $2,000,000,000$. $S$ and $D$ are arrays of $N-1$ integers each, specifying the locations of roads. For each $i$, there is a road connecting the two cities whose numbers are $S[i]$ and $D[i]$. The procedure must return an integer, the number of the city that should be the arena city.
## Example
As an example, consider the network of five cities in the top diagram on the right, where cities $0$, $1$, and $2$ contain $10$ hockey fans each, and cities $3$ and $4$ contain $20$ hockey fans each. The middle diagram shows the congestions when the new arena is in city $2$, the worst congestion being $40$ on the thicker arrow. The bottom diagram shows the congestions when the new arena is in city $3$, the worst congestion being $30$ on the thicker arrow. Therefore, city $3$ would be a better location for the arena than city $2$. The data for this example are in `grader.in.3a`.

## Note
We remind contestants that with the given constraints, it is possible to submit a solution that passes Subtask $3$ and fails Subtask $2$. However, remember that your final score for the entire task is determined by **only one** of your submissions.
## Implementation Details
- Implementation folder: `/home/ioi2010-contestant/traffic/`
- To be implemented by contestant: `traffic.c` or `traffic.cpp` or `traffic.pas`
- Contestant interface: `traffic.h` or `traffic.pas`
- Grader interface: `none`
- Sample grader: `grader.c` or `grader.cpp` or `grader.pas`
- Sample grader input: `grader.in.1 grader.in.2`
**Note:** The first line of the input file contains $N$. The following $N$ lines contain $P[i]$ for $i$ between $0$ and $N-1$. The following $N-1$ lines contain pairs $S[i]$ and $D[i]$ for $i$ between $0$ and $N-2$.
- Expected output for sample grader input: `grader.expect.1 grader.expect.2` etc.
- Compile and run (command line): `runc grader.c` or `runc grader.cpp` or `runc grader.pas`
- Compile and run (gedit plugin): `Control-R`, while editing any implementation file.
- Submit (command line): `submit grader.c` or `submit grader.cpp` or `submit grader.pas`
- Submit (gedit plugin): `Control-J`, while editing any implementation or grader file.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
The assumptions from Subtask $1$ may no longer be true.
There are at most $1,000,000$ cities.
|
Python
|
seed_301
|
# Day 2 Task 2: Traffic Congestion
Although Canada is a large country, many areas are uninhabited, and most of the population lives near the southern border. The Trans-Canada Highway, completed in 1962, connects the people living in this strip of land, from St. John's in the East to Victoria in the West, a distance of 7821 km.
Canadians like hockey. After a hockey game, thousands of fans get in their cars and drive home from the game, causing heavy congestion on the roads. A wealthy entrepreneur wants to buy a hockey team and build a new hockey arena. Your task is to help him select a location for the arena to minimize the traffic congestion after a hockey game.
The country is organized into cities connected by a network of roads. All roads are bidirectional, and there is exactly one *route* connecting any pair of cities. A *route* connecting the cities $c_0$ and $c_k$ is a sequence of distinct cities $c_0, \dots, c_k$ such that there is a road from $c_{i-1}$ to $c_i$ for each $i$. The new arena must be built in one of the cities, which we will call the *arena city*. After a hockey game, all of the hockey fans travel from the arena city to their home city, except those who already live in the arena city. The amount of congestion on each road is proportional to the number of hockey fans that travel along the road. You must locate the arena city such that the amount of congestion on the most congested road is as small as possible. If there are several equally good locations, you may choose any one.
You are to implement a procedure `LocateCentre(N, P, S, D)`. $N$ is a positive integer, the number of cities. The cities are numbered from $0$ to $N-1$. $P$ is an array of $N$ positive integers; for each $i$, $P[i]$ is the number of hockey fans living in the city numbered $i$. The total number of hockey fans in all the cities will be at most $2,000,000,000$. $S$ and $D$ are arrays of $N-1$ integers each, specifying the locations of roads. For each $i$, there is a road connecting the two cities whose numbers are $S[i]$ and $D[i]$. The procedure must return an integer, the number of the city that should be the arena city.
## Example
As an example, consider the network of five cities in the top diagram on the right, where cities $0$, $1$, and $2$ contain $10$ hockey fans each, and cities $3$ and $4$ contain $20$ hockey fans each. The middle diagram shows the congestions when the new arena is in city $2$, the worst congestion being $40$ on the thicker arrow. The bottom diagram shows the congestions when the new arena is in city $3$, the worst congestion being $30$ on the thicker arrow. Therefore, city $3$ would be a better location for the arena than city $2$. The data for this example are in `grader.in.3a`.

## Note
We remind contestants that with the given constraints, it is possible to submit a solution that passes Subtask $3$ and fails Subtask $2$. However, remember that your final score for the entire task is determined by **only one** of your submissions.
## Implementation Details
- Implementation folder: `/home/ioi2010-contestant/traffic/`
- To be implemented by contestant: `traffic.c` or `traffic.cpp` or `traffic.pas`
- Contestant interface: `traffic.h` or `traffic.pas`
- Grader interface: `none`
- Sample grader: `grader.c` or `grader.cpp` or `grader.pas`
- Sample grader input: `grader.in.1 grader.in.2`
**Note:** The first line of the input file contains $N$. The following $N$ lines contain $P[i]$ for $i$ between $0$ and $N-1$. The following $N-1$ lines contain pairs $S[i]$ and $D[i]$ for $i$ between $0$ and $N-2$.
- Expected output for sample grader input: `grader.expect.1 grader.expect.2` etc.
- Compile and run (command line): `runc grader.c` or `runc grader.cpp` or `runc grader.pas`
- Compile and run (gedit plugin): `Control-R`, while editing any implementation file.
- Submit (command line): `submit grader.c` or `submit grader.cpp` or `submit grader.pas`
- Submit (gedit plugin): `Control-J`, while editing any implementation or grader file.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
The assumptions from Subtask $1$ may no longer be true.
There are at most $1000$ cities.
|
Python
|
seed_313
|
# Day 2 Task 4: Saveit
The Xedef Courier Company provides air package delivery among several cities. Some of these cities are **Xedef hubs** where special processing facilities are established. Each of Xedef's aircraft shuttles back and forth between one pair of cities, carrying packages in either direction as required.
To be shipped from one city to another, a package must be transported by a sequence of hops, where each hop carries the package between a pair of cities served by one of the aircraft. Furthermore, the sequence must include at least one of Xedef's hubs.
To facilitate routing, Xedef wishes to encode the length of the shortest sequence of hops from every city to every hub on the shipping label of every package. (The length of the shortest sequence leading from a hub to itself is zero.) Obviously, a compact representation of this information is required.
You are to implement two procedures, `encode(N,H,P,A,B)` and `decode(N,H)`. $N$ is the number of cities and $H$ is the number of hubs. Assume that the cities are numbered from $0$ to $N-1$, and that the hubs are the cities with numbers between $0$ and $H-1$. Further assume that $N \leq 1000$ and $H \leq 36$. $P$ is the number of pairs of cities connected by aircraft. All (unordered) pairs of cities will be distinct. $A$ and $B$ are arrays of size $P$, such that the first pair of connected cities is $(A[0], B[0])$, the second pair is $(A[1], B[1])$, and so on.
`encode` must compute a sequence of bits from which `decode` can determine the number of hops from every city to every hub. `encode` will transmit the sequence of bits to the grading server by a sequence of calls to `encode_bit(b)` where $b$ is either $0$ or $1$. `decode` will receive the sequence of bits from the grading server by making calls to `decode_bit`. The $i$-th call to `decode_bit` will return the value of $b$ from the $i$-th call to `encode_bit(b)`. Note that you must ensure that the number of times `decode_bit` will always be at most equal to the number of times `encode` previously called `encode_bit(b)`.
After decoding the numbers of hops, `decode` must call `hops(h,c,d)` for every hub $h$ and every city $c$ (including every hub, that is, also for $c=h$), giving the minimum number of hops necessary to ship a package between $h$ and $c$. That is, there must be $N * H$ calls to `hops(h,c,d)`. The order does not matter. You are guaranteed that it is always possible to ship a package between every hub and every city.
**Note:** `encode` and `decode` must communicate only through the specified interface. Shared variables, file access and network access are prohibited. In C or C++, you may declare persistent variables to be `static` to retain information for `encode` or `decode`, while preventing them from being shared. In Pascal, you may declare persistent variables in the `implementation` part of your solution files.
## Example
As an example, consider the diagram on the right. It shows five cities ($N=5$) connected by seven aircraft ($P=7$). Cities $0$, $1$ and $2$ are hubs ($H=3$). One hop is needed to ship a package between hub $0$ and city $3$, whereas $2$ hops are needed to ship a package between hub $2$ and city $3$. The data for this example are in `grader.in.1`.
The entries in the following table are all $d$-values that `decode` must deliver by calling `hops(h,c,d)`:
```
| d | City c | 0 | 1 | 2 | 3 | 4 |
|---------------|--------|---|---|---|---|---|
| Hub h = 0 | 0 | 0 | 1 | 1 | 1 | 1 |
| Hub h = 1 | 1 | 0 | 1 | 1 | 1 | 1 |
| Hub h = 2 | 1 | 1 | 0 | 2 | 2 | 2 |
```
<image>
## Implementation Details
- Implementation folder: `/home/ioi2010-contestant/saveit/`
- To be implemented by contestant:
- `encoder.c` or `encoder.cpp` or `encoder.pas`
- `decoder.c` or `decoder.cpp` or `decoder.pas`
- Contestant interface:
- `encoder.h` or `encoder.pas`
- `decoder.h` or `decoder.pas`
- Grader interface: `grader.h` or `graderlib.pas`
- Sample grader: `grader.c` or `grader.cpp` or `grader.pas and graderlib.pas`
- Sample grader input: `grader.in.1 grader.in.2 etc.`
**Expected output for sample grader input:**
- If the implementation is correct for subtask $1$, the output will contain `OK 1`
- If the implementation is correct for subtask $2$, the output will contain `OK 2`
- If the implementation is correct for subtask $3$, the output will contain `OK 3`
- If the implementation is correct for subtask $4$, the output will contain `OK 4`
**Compile and run (command line):**
- `runc grader.c` or `runc grader.cpp` or `runc grader.pas`
**Compile and run (gedit plugin):**
- `Control-R`, while editing any implementation file.
**Submit (command line):**
- `submit grader.c` or `submit grader.cpp` or `submit grader.pas`
**Submit (gedit plugin):**
- `Control-J`, while editing any implementation or grader file.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
`encode` must make no more than 360,000 calls to `encode_bit(b)`.
|
Python
|
seed_316
|
# Deciphering the Mayan Writing
Deciphering the Mayan writing has proven to be a harder task than anticipated by the early investigations. After almost two hundred years, very little of it was actually understood. It has been only in the last three decades that real advances have been made.
Mayan writing is based on small drawings known as glyphs which represent sounds. Mayan words are normally written as glyphs put together at various positions.
One of several problems in deciphering Mayan writing arises in the order of reading. When placing several glyphs in order to form a word, Mayan writers sometimes decided the position based more on their own esthetic views than on any particular rule. This leads to the fact that, even though the sound for many glyphs is known, sometimes archaeologists are not sure how to pronounce a written word.
The archaeologists are looking for a special word $W$. They know the glyphs for it, but they donβt know all the possible ways of arranging them. Since they knew you were coming to IOI'06, they have asked for your help. They will provide you with the $g$ glyphs from $W$ and a sequence $S$ of all the glyphs (in the order they appear) in the carvings they are studying. Help them by counting the number of possible appearances of the word $W$.
## Task
Write a program that, given the glyphs for $W$ and the sequence $S$ of glyphs in the carvings, counts the number of possible appearances of $W$ in $S$; that is, every sequence of consecutive $g$ glyphs in $S$ that is a permutation of the glyphs in $W$.
### Constraints
- $1 \leq g \leq 3$: the number of glyphs in $W$
- $g \leq |S| \leq 3,000,000$: where $|S|$ is the number of glyphs in the sequence $S$
### Input
Your program must read the following data from the file `writing.in`:
```
writing.in DESCRIPTION
4 11
cAda
AbrAcadAbRa
```
- **LINE 1:** Contains 2 space-separated integers that represent $g$ and $|S|$.
- **LINE 2:** Contains $g$ consecutive characters that represent the glyphs in $W$. Valid characters are `'a'-'z'` and `'A'-'Z'`; uppercase and lowercase characters are considered different.
- **LINE 3:** Contains $|S|$ consecutive characters that represent the glyphs in the carvings. Valid characters are `'a'-'z'` and `'A'-'Z'`; uppercase and lowercase characters are considered different.
### Output
Your program must write the following data to the file `writing.out`:
```
writing.out DESCRIPTION
2
```
- **LINE 1:** Must contain the count of possible appearances of $W$ in $S$.
### Important Note for Pascal Programmers
By default in FreePascal, a variable of type `string` has a size limit of 255 characters. If you want to use strings longer than that, you should add the directive `{$H+}` to your code just below the `program ...;` line.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
|
Python
|
seed_317
|
# Definition
**_Balanced number_** is the number that * **_The sum of_** all digits to the **_left of the middle_** digit(s) and the sum of all digits to the **_right of the middle_** digit(s) are **_equal_***.
____
# Task
**_Given_** a number, **_Find if it is Balanced or not_** .
____
# Warm-up (Highly recommended)
# [Playing With Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
___
# Notes
* *If* the **_number has an odd number of digits_** then **_there is only one middle digit_**, e.g. `92645` has middle digit `6`; **_otherwise_**, there are **_two middle digits_** , e.g. `1301` has middle digits `3` and `0`
* **_The middle digit(s)_** should **_not_** be considered when *determining whether a number is balanced or not*, **_e.g_** `413023` is a **_balanced number because the left sum and right sum are both_** `5`.
* **_Number_** *passed is always* **_Positive_** .
* **_Return_** *the result as* **_String_**
___
# Input >> Output Examples
```
(balanced-num 7) ==> return "Balanced"
```
## **_Explanation_**:
* **_Since_** , **_The sum of_** *all digits to the* **_left of the middle_** digit (0)
* and **_the sum of_** *all digits to the* **_right of the middle_** digit (0) are **_equal_** , **_then_** *It's* **_Balanced_**
___
```
(balanced-num 295591) ==> return "Not Balanced"
```
## **_Explanation_**:
* **_Since_** , **_The sum of_** *all digits to the* **_left of the middle_** digits (11)
* and **_the sum of_** *all digits to the* **_right of the middle_** digits (10) are **_Not equal_** , **_then_** *It's* **_Not Balanced_**
* **_Note_** : **_The middle digit(s)_** *are* **_55_** .
___
```
(balanced-num 959) ==> return "Balanced"
```
## **_Explanation_**:
* **_Since_** , **_The sum of_** *all digits to the* **_left of the middle_** digits (9)
* and **_the sum of_** *all digits to the* **_right of the middle_** digits (9) are **_equal_** , **_then_** *It's* **_Balanced_**
* **_Note_** : **_The middle digit_** *is* **_5_** .
____
```
(balanced-num 27102983) ==> return "Not Balanced"
```
## **_Explanation_**:
* **_Since_** , **_The sum of_** *all digits to the* **_left of the middle_** digits (10)
* and **_the sum of_** *all digits to the* **_right of the middle_** digits (20) are **_Not equal_** , **_then_** *It's* **_Not Balanced_**
* **_Note_** : **_The middle digit(s)_** *are* **_02_** .
___
___
___
# [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
# [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays)
# [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored)
___
## ALL translations are welcomed
## Enjoy Learning !!
# Zizou
|
Python
|
seed_319
|
# Definition
**_Extra perfect number_** *is the number that* **_first_** and **_last_** *bits* are **_set bits_**.
____
# Task
**_Given_** *a positive integer* `N` , **_Return_** the **_extra perfect numbers_** *in range from* `1` to `N` .
____
# Warm-up (Highly recommended)
# [Playing With Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
___
# Notes
* **_Number_** *passed is always* **_Positive_** .
* **_Returned array/list_** should *contain the extra perfect numbers in ascending order* **from lowest to highest**
___
# Input >> Output Examples
```
extraPerfect(3) ==> return {1,3}
```
## **_Explanation_**:
# (1)10 =(1)2
**First** and **last** bits as **_set bits_**.
# (3)10 = (11)2
**First** and **last** bits as **_set bits_**.
___
```
extraPerfect(7) ==> return {1,3,5,7}
```
## **_Explanation_**:
# (5)10 = (101)2
**First** and **last** bits as **_set bits_**.
# (7)10 = (111)2
**First** and **last** bits as **_set bits_**.
___
___
___
# [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
# [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays)
# [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored)
___
## ALL translations are welcomed
## Enjoy Learning !!
# Zizou
|
Python
|
seed_320
|
# Definition
**_Jumping number_** is the number that *All adjacent digits in it differ by 1*.
____
# Task
**_Given_** a number, **_Find if it is Jumping or not_** .
____
# Warm-up (Highly recommended)
# [Playing With Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
___
# Notes
* **_Number_** *passed is always* **_Positive_** .
* **_Return_** *the result as* **_String_** .
* **_The difference between_** *β9β and β0β* is **_not considered as 1_** .
* **_All single digit numbers_** are considered as **_Jumping numbers_**.
___
# Input >> Output Examples
```
jumpingNumber(9) ==> return "Jumping!!"
```
## **_Explanation_**:
* It's **_single-digit number_**
___
```
jumpingNumber(79) ==> return "Not!!"
```
## **_Explanation_**:
* *Adjacent digits* **_don't differ by 1_**
___
```
jumpingNumber(23) ==> return "Jumping!!"
```
## **_Explanation_**:
* *Adjacent digits* **_differ by 1_**
___
```
jumpingNumber(556847) ==> return "Not!!"
```
## **_Explanation_**:
* *Adjacent digits* **_don't differ by 1_**
___
```
jumpingNumber(4343456) ==> return "Jumping!!"
```
## **_Explanation_**:
* *Adjacent digits* **_differ by 1_**
___
```
jumpingNumber(89098) ==> return "Not!!"
```
## **_Explanation_**:
* *Adjacent digits* **_don't differ by 1_**
___
```
jumpingNumber(32) ==> return "Jumping!!"
```
## **_Explanation_**:
* *Adjacent digits* **_differ by 1_**
___
___
___
# [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
# [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays)
# [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored)
___
## ALL translations are welcomed
## Enjoy Learning !!
# Zizou
|
Python
|
seed_321
|
# Definition
**_Strong number_** is the number that *the sum of the factorial of its digits is equal to number itself*.
## **_For example_**: **_145_**, since
```
1! + 4! + 5! = 1 + 24 + 120 = 145
```
So, **_145_** is a **_Strong number_**.
____
# Task
**_Given_** a number, **_Find if it is Strong or not_**.
____
# Warm-up (Highly recommended)
# [Playing With Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
___
# Notes
* **_Number_** *passed is always* **_Positive_**.
* **_Return_** *the result as* **_String_**
___
# Input >> Output Examples
```
strong_num(1) ==> return "STRONG!!!!"
```
## **_Explanation_**:
Since , **_the sum of its digits' factorial of (1) is equal to number itself (1)_** , **_Then_** its a **_Strong_** .
____
```
strong_num(123) ==> return "Not Strong !!"
```
## **_Explanation_**:
Since **_the sum of its digits' factorial of 1! + 2! + 3! = 9 is not equal to number itself (123)_** , **_Then_** it's **_Not Strong_** .
___
```
strong_num(2) ==> return "STRONG!!!!"
```
## **_Explanation_**:
Since **_the sum of its digits' factorial of 2! = 2 is equal to number itself (2)_** , **_Then_** its a **_Strong_** .
____
```
strong_num(150) ==> return "Not Strong !!"
```
## **_Explanation_**:
Since **_the sum of its digits' factorial of 1! + 5! + 0! = 122 is not equal to number itself (150)_**, **_Then_** it's **_Not Strong_** .
___
___
___
# [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
# [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays)
# [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored)
___
## ALL translations are welcomed
## Enjoy Learning !!
# Zizou
|
Python
|
seed_322
|
# Definition
A **_Tidy number_** *is a number whose* **_digits are in non-decreasing order_**.
___
# Task
**_Given_** a number, **_Find if it is Tidy or not_** .
____
# Warm-up (Highly recommended)
# [Playing With Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
___
# Notes
* **_Number_** *passed is always* **_Positive_** .
* **_Return_** *the result as* a **_Boolean_**
~~~if:prolog
* Since prolog doesn't have booleans, return value should be 1 for (True) or 0 for (false)
~~~
___
# Input >> Output Examples
```
tidyNumber (12) ==> return (true)
```
## **_Explanation_**:
**_The number's digits_** `{ 1 , 2 }` are *in non-Decreasing Order* (i.e) *1 <= 2* .
____
```
tidyNumber (32) ==> return (false)
```
## **_Explanation_**:
**_The Number's Digits_** `{ 3, 2}` are **_not in non-Decreasing Order_** (i.e) *3 > 2* .
___
```
tidyNumber (1024) ==> return (false)
```
## **_Explanation_**:
**_The Number's Digits_** `{1 , 0, 2, 4}` are **_not in non-Decreasing Order_** as *0 <= 1* .
___
```
tidyNumber (13579) ==> return (true)
```
## **_Explanation_**:
**_The number's digits_** `{1 , 3, 5, 7, 9}` are *in non-Decreasing Order* .
____
```
tidyNumber (2335) ==> return (true)
```
## **_Explanation_**:
**_The number's digits_** `{2 , 3, 3, 5}` are *in non-Decreasing Order* , **_Note_** *3 <= 3*
___
___
___
# [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
# [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays)
# [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored)
___
## ALL translations are welcomed
## Enjoy Learning !!
# Zizou
|
Python
|
seed_325
|
# Definition
A number is a **_Special Number_** *if itβs digits only consist 0, 1, 2, 3, 4 or 5*
**_Given_** a number *determine if it special number or not* .
# Warm-up (Highly recommended)
# [Playing With Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
___
# Notes
* **_The number_** passed will be **_positive_** (N > 0) .
* All **single-digit numbers** with in the interval **_[0:5]_** are considered as **_special number_**.
___
# Input >> Output Examples
```
specialNumber(2) ==> return "Special!!"
```
## Explanation:
It's **_a single-digit number_** within the interval **_[0:5]_** .
```
specialNumber(9) ==> return "NOT!!"
```
## Explanation:
Although, it's a single-digit number but **_Outside the interval [0:5]_** .
```
specialNumber(23) ==> return "Special!!"
```
## Explanation:
All **_the number's digits_** formed from the interval **_[0:5]_** digits .
```
specialNumber(39) ==> return "NOT!!"
```
## Explanation:
Although, *there is a digit (3) Within the interval* **_But_** **_the second digit is not (Must be ALL The Number's Digits )_** .
```
specialNumber(59) ==> return "NOT!!"
```
## Explanation:
Although, *there is a digit (5) Within the interval* **_But_** **_the second digit is not (Must be ALL The Number's Digits )_** .
```
specialNumber(513) ==> return "Special!!"
```
___
```
specialNumber(709) ==> return "NOT!!"
```
___
# [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored)
### ALL translation are welcomed
## Enjoy Learning !!
# Zizou
|
Python
|
seed_327
|
# Description
Given a number `n`, you should find a set of numbers for which the sum equals `n`. This set must consist exclusively of values that are a power of `2` (eg: `2^0 => 1, 2^1 => 2, 2^2 => 4, ...`).
The function `powers` takes a single parameter, the number `n`, and should return an array of unique numbers.
## Criteria
The function will always receive a valid input: any positive integer between `1` and the max integer value for your language (eg: for JavaScript this would be `9007199254740991` otherwise known as `Number.MAX_SAFE_INTEGER`).
The function should return an array of numbers that are a **power of 2** (`2^x = y`).
Each member of the returned array should be **unique**. (eg: the valid answer for `powers(2)` is `[2]`, not `[1, 1]`)
Members should be sorted in **ascending order** (small -> large). (eg: the valid answer for `powers(6)` is `[2, 4]`, not `[4, 2]`)
|
Python
|
seed_328
|
# Description
Write a function that accepts the current position of a knight in a chess board, it returns the possible positions that it will end up after 1 move. The resulted should be sorted.
## Example
"a1" -> ["b3", "c2"]
|
Python
|
seed_330
|
# Description
Write a function that checks whether a credit card number is correct or not, using the Luhn algorithm.
The algorithm is as follows:
* From the rightmost digit, which is the check digit, moving left, double the value of every second digit; if the product of this doubling operation is greater than 9 (e.g., 8 Γ 2 = 16), then sum the digits of the products (e.g., 16: 1 + 6 = 7, 18: 1 + 8 = 9) or alternatively subtract 9 from the product (e.g., 16: 16 - 9 = 7, 18: 18 - 9 = 9).
* Take the sum of all the digits.
* If the total modulo 10 is equal to 0 (if the total ends in zero) then the number is valid according to the Luhn formula; else it is not valid.
The input is a string with the full credit card number, in groups of 4 digits separated by spaces, i.e. "1234 5678 9012 3456"
DonΒ΄t worry about wrong inputs, they will always be a string with 4 groups of 4 digits each separated by space.
# Examples
`valid_card?("5457 6238 9823 4311") # True`
`valid_card?("5457 6238 9323 4311") # False`
for reference check: https://en.wikipedia.org/wiki/Luhn_algorithm
|
Python
|
seed_331
|
# Description
You are required to implement a function `find_nth_occurrence` that returns the index of the nth occurrence of a substring within a string (considering that those substring could overlap each others). If there are less than n occurrences of the substring, return -1.
# Example
```python
string = "This is an example. Return the nth occurrence of example in this example string."
find_nth_occurrence("example", string, 1) == 11
find_nth_occurrence("example", string, 2) == 49
find_nth_occurrence("example", string, 3) == 65
find_nth_occurrence("example", string, 4) == -1
```
Multiple occurrences of a substring are allowed to overlap, e.g.
```python
find_nth_occurrence("TestTest", "TestTestTestTest", 1) == 0
find_nth_occurrence("TestTest", "TestTestTestTest", 2) == 4
find_nth_occurrence("TestTest", "TestTestTestTest", 3) == 8
find_nth_occurrence("TestTest", "TestTestTestTest", 4) == -1
```
|
Python
|
seed_332
|
# Description:
Count the number of exclamation marks and question marks, return the product.
# Examples
```
Product("") == 0
product("!") == 0
Product("!ab? ?") == 2
Product("!!") == 0
Product("!??") == 2
Product("!???") == 3
Product("!!!??") == 6
Product("!!!???") == 9
Product("!???!!") == 9
Product("!????!!!?") == 20
```
|
Python
|
seed_334
|
# Description:
Move all exclamation marks to the end of the sentence
# Examples
```
remove("Hi!") === "Hi!"
remove("Hi! Hi!") === "Hi Hi!!"
remove("Hi! Hi! Hi!") === "Hi Hi Hi!!!"
remove("Hi! !Hi Hi!") === "Hi Hi Hi!!!"
remove("Hi! Hi!! Hi!") === "Hi Hi Hi!!!!"
```
|
Python
|
seed_343
|
# Digital Circuit
There is a circuit, which consists of $N + M$ **gates** numbered from $0$ to $N + M - 1$.
Gates $0$ to $N - 1$ are **threshold gates**, whereas gates $N$ to $N + M - 1$ are **source gates**.
Each gate, except for gate $0$, is an **input** to exactly one threshold gate.
Specifically, for each $i$ such that $1 \le i \le N + M - 1$, gate $i$ is an input to gate $P[i]$, where $0 \le P[i] \le N-1$.
Importantly, we also have $P[i] \lt i$.
Moreover, we assume $P[0] = -1$.
Each threshold gate has one or more inputs.
Source gates do not have any inputs.
Each gate has a **state** which is either $0$ or $1$.
The initial states of the source gates are given by an array $A$ of $M$ integers.
That is, for each $j$ such that $0 \le j \le M - 1$, the initial state of the source gate $N + j$ is $A[j]$.
The state of each threshold gate depends on the states of its inputs and is determined as follows.
First, each threshold gate is assigned a threshold **parameter**.
The parameter assigned to a threshold gate with $c$ inputs must be an integer between $1$ and $c$ (inclusive).
Then, the state of a threshold gate with parameter $p$ is $1$, if at least $p$ of its inputs have state $1$, and $0$ otherwise.
For example, suppose there are $N = 3$ threshold gates and $M = 4$ source gates.
The inputs to gate $0$ are gates $1$ and $6$, the inputs to gate $1$ are gates $2$, $4$, and $5$, and the only input to gate $2$ is gate $3$.
This example is illustrated in the following picture.
Suppose that source gates $3$ and $5$ have state $1$, while source gates $4$ and $6$ have state $0$.
Assume we assign parameters $1$, $2$ and $2$ to threshold gates $2$, $1$ and $0$ respectively.
In this case, gate $2$ has state $1$, gate $1$ has state $1$ and gate $0$ has state $0$.
This assignment of parameter values and the states is illustrated in the following picture.
Gates whose state is $1$ are marked in black.
The states of the source gates will undergo $Q$ updates.
Each update is described by two integers $L$ and $R$ ($N \le L \le R \le N + M - 1$) and toggles the states of all source gates numbered between $L$ and $R$, inclusive.
That is, for each $i$ such that $L \le i \le R$, source gate $i$ changes its state to $1$, if its state is $0$, or to $0$, if its state is $1$.
The new state of each toggled gate remains unchanged until it is possibly toggled by one of the later updates.
Your goal is to count, after each update, how many different assignments of parameters to threshold gates result in gate $0$ having state $1$.
Two assignments are considered different if there exists at least one threshold gate that has a different value of its parameter in both assignments.
As the number of ways can be large, you should compute it modulo $1\;000\;002\;022$.
Note that in the example above, there are $6$ different assignments of parameters to threshold gates, since gates $0$, $1$ and $2$ have $2$, $3$ and $1$ inputs respectively.
In $2$ out of these $6$ assignments, gate $0$ has state $1$.
## Implementation Details
Your task is to implement two procedures.
```
void init(int N, int M, int[] P, int[] A)
```
* $N$: the number of threshold gates.
* $M$: the number of source gates.
* $P$: an array of length $N + M$ describing the inputs to the threshold gates.
* $A$: an array of length $M$ describing the initial states of the source gates.
* This procedure is called exactly once, before any calls to `count_ways`.
```
int count_ways(int L, int R)
```
* $L$, $R$: the boundaries of the range of source gates, whose states are toggled.
* This procedure should first perform the specified update, and then return the number of ways, modulo $1\;000\;002\;022$, of assigning parameters to the threshold gates, which result in gate $0$ having state $1$.
* This procedure is called exactly $Q$ times.
## Example
Consider the following sequence of calls:
```
init(3, 4, [-1, 0, 1, 2, 1, 1, 0], [1, 0, 1, 0])
```
This example is illustrated in the task description above.
```
count_ways(3, 4)
```
This toggles the states of gates $3$ and $4$, i.e. the state of gate $3$ becomes $0$, and the state of gate $4$ becomes $1$.
Two ways of assigning the parameters which result in gate $0$ having state $1$ are illustrated in the pictures below.
| Way $1$ | Way $2$ |
|:-------:|:-------:|
|
|
|
In all other assignments of parameters, gate $0$ has state $0$.
Thus, the procedure should return $2$.
```
count_ways(4, 5)
```
This toggles the states of gates $4$ and $5$.
As a result, all source gates have state $0$, and for any assignment of parameters, gate $0$ has state $0$.
Thus, the procedure should return $0$.
```
count_ways(3, 6)
```
This changes the states of all source gates to $1$.
As a result, for any assignment of parameters, gate $0$ has state $1$.
Thus, the procedure should return $6$.
## Constraints
* $1 \le N, M \le 100\,000$
* $1 \le Q \le 100\,000$
* $P[0] = -1$
* $0 \le P[i] \lt i$ and $P[i] \le N - 1$ (for each $i$ such that $1 \le i \le N + M - 1$)
* Each threshold gate has at least one input (for each $i$ such that $0 \le i \le N - 1$ there exists an index $x$ such that $i \lt x \le N + M - 1$ and $P[x] = i$).
* $0 \le A[j] \le 1$ (for each $j$ such that $0 \le j \le M - 1$)
* $N \le L \le R \le N + M - 1$
## Sample Grader
The sample grader reads the input in the following format:
* line $1$: $N \; M \; Q$
* line $2$: $P[0] \; P[1] \; \ldots \; P[N + M - 1]$
* line $3$: $A[0] \; A[1] \; \ldots \; A[M - 1]$
* line $4 + k$ ($0 \le k \le Q - 1$): $L \; R$ for update $k$
The sample grader prints your answers in the following format:
* line $1 + k$ ($0 \le k \le Q - 1$): the return value of `count_ways` for update $k$
|
Python
|
seed_344
|
# Digital Circuit
There is a circuit, which consists of $N + M$ **gates** numbered from $0$ to $N + M - 1$.
Gates $0$ to $N - 1$ are **threshold gates**, whereas gates $N$ to $N + M - 1$ are **source gates**.
Each gate, except for gate $0$, is an **input** to exactly one threshold gate.
Specifically, for each $i$ such that $1 \le i \le N + M - 1$, gate $i$ is an input to gate $P[i]$, where $0 \le P[i] \le N-1$.
Importantly, we also have $P[i] \lt i$.
Moreover, we assume $P[0] = -1$.
Each threshold gate has one or more inputs.
Source gates do not have any inputs.
Each gate has a **state** which is either $0$ or $1$.
The initial states of the source gates are given by an array $A$ of $M$ integers.
That is, for each $j$ such that $0 \le j \le M - 1$, the initial state of the source gate $N + j$ is $A[j]$.
The state of each threshold gate depends on the states of its inputs and is determined as follows.
First, each threshold gate is assigned a threshold **parameter**.
The parameter assigned to a threshold gate with $c$ inputs must be an integer between $1$ and $c$ (inclusive).
Then, the state of a threshold gate with parameter $p$ is $1$, if at least $p$ of its inputs have state $1$, and $0$ otherwise.
For example, suppose there are $N = 3$ threshold gates and $M = 4$ source gates.
The inputs to gate $0$ are gates $1$ and $6$, the inputs to gate $1$ are gates $2$, $4$, and $5$, and the only input to gate $2$ is gate $3$.
This example is illustrated in the following picture.
Suppose that source gates $3$ and $5$ have state $1$, while source gates $4$ and $6$ have state $0$.
Assume we assign parameters $1$, $2$ and $2$ to threshold gates $2$, $1$ and $0$ respectively.
In this case, gate $2$ has state $1$, gate $1$ has state $1$ and gate $0$ has state $0$.
This assignment of parameter values and the states is illustrated in the following picture.
Gates whose state is $1$ are marked in black.
The states of the source gates will undergo $Q$ updates.
Each update is described by two integers $L$ and $R$ ($N \le L \le R \le N + M - 1$) and toggles the states of all source gates numbered between $L$ and $R$, inclusive.
That is, for each $i$ such that $L \le i \le R$, source gate $i$ changes its state to $1$, if its state is $0$, or to $0$, if its state is $1$.
The new state of each toggled gate remains unchanged until it is possibly toggled by one of the later updates.
Your goal is to count, after each update, how many different assignments of parameters to threshold gates result in gate $0$ having state $1$.
Two assignments are considered different if there exists at least one threshold gate that has a different value of its parameter in both assignments.
As the number of ways can be large, you should compute it modulo $1\;000\;002\;022$.
Note that in the example above, there are $6$ different assignments of parameters to threshold gates, since gates $0$, $1$ and $2$ have $2$, $3$ and $1$ inputs respectively.
In $2$ out of these $6$ assignments, gate $0$ has state $1$.
## Implementation Details
Your task is to implement two procedures.
```
void init(int N, int M, int[] P, int[] A)
```
* $N$: the number of threshold gates.
* $M$: the number of source gates.
* $P$: an array of length $N + M$ describing the inputs to the threshold gates.
* $A$: an array of length $M$ describing the initial states of the source gates.
* This procedure is called exactly once, before any calls to `count_ways`.
```
int count_ways(int L, int R)
```
* $L$, $R$: the boundaries of the range of source gates, whose states are toggled.
* This procedure should first perform the specified update, and then return the number of ways, modulo $1\;000\;002\;022$, of assigning parameters to the threshold gates, which result in gate $0$ having state $1$.
* This procedure is called exactly $Q$ times.
## Example
Consider the following sequence of calls:
```
init(3, 4, [-1, 0, 1, 2, 1, 1, 0], [1, 0, 1, 0])
```
This example is illustrated in the task description above.
```
count_ways(3, 4)
```
This toggles the states of gates $3$ and $4$, i.e. the state of gate $3$ becomes $0$, and the state of gate $4$ becomes $1$.
Two ways of assigning the parameters which result in gate $0$ having state $1$ are illustrated in the pictures below.
| Way $1$ | Way $2$ |
|:-------:|:-------:|
|
|
|
In all other assignments of parameters, gate $0$ has state $0$.
Thus, the procedure should return $2$.
```
count_ways(4, 5)
```
This toggles the states of gates $4$ and $5$.
As a result, all source gates have state $0$, and for any assignment of parameters, gate $0$ has state $0$.
Thus, the procedure should return $0$.
```
count_ways(3, 6)
```
This changes the states of all source gates to $1$.
As a result, for any assignment of parameters, gate $0$ has state $1$.
Thus, the procedure should return $6$.
## Constraints
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
* $M = N + 1$
* $M = 2^z$ (for some positive integer $z$)
* $P[i] = \lfloor\frac{i - 1}{2}\rfloor$ (for each $i$ such that $1 \le i \le N + M - 1$)
## Sample Grader
The sample grader reads the input in the following format:
* line $1$: $N \; M \; Q$
* line $2$: $P[0] \; P[1] \; \ldots \; P[N + M - 1]$
* line $3$: $A[0] \; A[1] \; \ldots \; A[M - 1]$
* line $4 + k$ ($0 \le k \le Q - 1$): $L \; R$ for update $k$
The sample grader prints your answers in the following format:
* line $1 + k$ ($0 \le k \le Q - 1$): the return value of `count_ways` for update $k$
|
Python
|
seed_346
|
# Digital Circuit
There is a circuit, which consists of $N + M$ **gates** numbered from $0$ to $N + M - 1$.
Gates $0$ to $N - 1$ are **threshold gates**, whereas gates $N$ to $N + M - 1$ are **source gates**.
Each gate, except for gate $0$, is an **input** to exactly one threshold gate.
Specifically, for each $i$ such that $1 \le i \le N + M - 1$, gate $i$ is an input to gate $P[i]$, where $0 \le P[i] \le N-1$.
Importantly, we also have $P[i] \lt i$.
Moreover, we assume $P[0] = -1$.
Each threshold gate has one or more inputs.
Source gates do not have any inputs.
Each gate has a **state** which is either $0$ or $1$.
The initial states of the source gates are given by an array $A$ of $M$ integers.
That is, for each $j$ such that $0 \le j \le M - 1$, the initial state of the source gate $N + j$ is $A[j]$.
The state of each threshold gate depends on the states of its inputs and is determined as follows.
First, each threshold gate is assigned a threshold **parameter**.
The parameter assigned to a threshold gate with $c$ inputs must be an integer between $1$ and $c$ (inclusive).
Then, the state of a threshold gate with parameter $p$ is $1$, if at least $p$ of its inputs have state $1$, and $0$ otherwise.
For example, suppose there are $N = 3$ threshold gates and $M = 4$ source gates.
The inputs to gate $0$ are gates $1$ and $6$, the inputs to gate $1$ are gates $2$, $4$, and $5$, and the only input to gate $2$ is gate $3$.
This example is illustrated in the following picture.
Suppose that source gates $3$ and $5$ have state $1$, while source gates $4$ and $6$ have state $0$.
Assume we assign parameters $1$, $2$ and $2$ to threshold gates $2$, $1$ and $0$ respectively.
In this case, gate $2$ has state $1$, gate $1$ has state $1$ and gate $0$ has state $0$.
This assignment of parameter values and the states is illustrated in the following picture.
Gates whose state is $1$ are marked in black.
The states of the source gates will undergo $Q$ updates.
Each update is described by two integers $L$ and $R$ ($N \le L \le R \le N + M - 1$) and toggles the states of all source gates numbered between $L$ and $R$, inclusive.
That is, for each $i$ such that $L \le i \le R$, source gate $i$ changes its state to $1$, if its state is $0$, or to $0$, if its state is $1$.
The new state of each toggled gate remains unchanged until it is possibly toggled by one of the later updates.
Your goal is to count, after each update, how many different assignments of parameters to threshold gates result in gate $0$ having state $1$.
Two assignments are considered different if there exists at least one threshold gate that has a different value of its parameter in both assignments.
As the number of ways can be large, you should compute it modulo $1\;000\;002\;022$.
Note that in the example above, there are $6$ different assignments of parameters to threshold gates, since gates $0$, $1$ and $2$ have $2$, $3$ and $1$ inputs respectively.
In $2$ out of these $6$ assignments, gate $0$ has state $1$.
## Implementation Details
Your task is to implement two procedures.
```
void init(int N, int M, int[] P, int[] A)
```
* $N$: the number of threshold gates.
* $M$: the number of source gates.
* $P$: an array of length $N + M$ describing the inputs to the threshold gates.
* $A$: an array of length $M$ describing the initial states of the source gates.
* This procedure is called exactly once, before any calls to `count_ways`.
```
int count_ways(int L, int R)
```
* $L$, $R$: the boundaries of the range of source gates, whose states are toggled.
* This procedure should first perform the specified update, and then return the number of ways, modulo $1\;000\;002\;022$, of assigning parameters to the threshold gates, which result in gate $0$ having state $1$.
* This procedure is called exactly $Q$ times.
## Example
Consider the following sequence of calls:
```
init(3, 4, [-1, 0, 1, 2, 1, 1, 0], [1, 0, 1, 0])
```
This example is illustrated in the task description above.
```
count_ways(3, 4)
```
This toggles the states of gates $3$ and $4$, i.e. the state of gate $3$ becomes $0$, and the state of gate $4$ becomes $1$.
Two ways of assigning the parameters which result in gate $0$ having state $1$ are illustrated in the pictures below.
| Way $1$ | Way $2$ |
|:-------:|:-------:|
|
|
|
In all other assignments of parameters, gate $0$ has state $0$.
Thus, the procedure should return $2$.
```
count_ways(4, 5)
```
This toggles the states of gates $4$ and $5$.
As a result, all source gates have state $0$, and for any assignment of parameters, gate $0$ has state $0$.
Thus, the procedure should return $0$.
```
count_ways(3, 6)
```
This changes the states of all source gates to $1$.
As a result, for any assignment of parameters, gate $0$ has state $1$.
Thus, the procedure should return $6$.
## Constraints
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
* $N = 1$
* $M \le 1000$
* $Q \le 5$
## Sample Grader
The sample grader reads the input in the following format:
* line $1$: $N \; M \; Q$
* line $2$: $P[0] \; P[1] \; \ldots \; P[N + M - 1]$
* line $3$: $A[0] \; A[1] \; \ldots \; A[M - 1]$
* line $4 + k$ ($0 \le k \le Q - 1$): $L \; R$ for update $k$
The sample grader prints your answers in the following format:
* line $1 + k$ ($0 \le k \le Q - 1$): the return value of `count_ways` for update $k$
|
Python
|
seed_347
|
# Digital Circuit
There is a circuit, which consists of $N + M$ **gates** numbered from $0$ to $N + M - 1$.
Gates $0$ to $N - 1$ are **threshold gates**, whereas gates $N$ to $N + M - 1$ are **source gates**.
Each gate, except for gate $0$, is an **input** to exactly one threshold gate.
Specifically, for each $i$ such that $1 \le i \le N + M - 1$, gate $i$ is an input to gate $P[i]$, where $0 \le P[i] \le N-1$.
Importantly, we also have $P[i] \lt i$.
Moreover, we assume $P[0] = -1$.
Each threshold gate has one or more inputs.
Source gates do not have any inputs.
Each gate has a **state** which is either $0$ or $1$.
The initial states of the source gates are given by an array $A$ of $M$ integers.
That is, for each $j$ such that $0 \le j \le M - 1$, the initial state of the source gate $N + j$ is $A[j]$.
The state of each threshold gate depends on the states of its inputs and is determined as follows.
First, each threshold gate is assigned a threshold **parameter**.
The parameter assigned to a threshold gate with $c$ inputs must be an integer between $1$ and $c$ (inclusive).
Then, the state of a threshold gate with parameter $p$ is $1$, if at least $p$ of its inputs have state $1$, and $0$ otherwise.
For example, suppose there are $N = 3$ threshold gates and $M = 4$ source gates.
The inputs to gate $0$ are gates $1$ and $6$, the inputs to gate $1$ are gates $2$, $4$, and $5$, and the only input to gate $2$ is gate $3$.
This example is illustrated in the following picture.
Suppose that source gates $3$ and $5$ have state $1$, while source gates $4$ and $6$ have state $0$.
Assume we assign parameters $1$, $2$ and $2$ to threshold gates $2$, $1$ and $0$ respectively.
In this case, gate $2$ has state $1$, gate $1$ has state $1$ and gate $0$ has state $0$.
This assignment of parameter values and the states is illustrated in the following picture.
Gates whose state is $1$ are marked in black.
The states of the source gates will undergo $Q$ updates.
Each update is described by two integers $L$ and $R$ ($N \le L \le R \le N + M - 1$) and toggles the states of all source gates numbered between $L$ and $R$, inclusive.
That is, for each $i$ such that $L \le i \le R$, source gate $i$ changes its state to $1$, if its state is $0$, or to $0$, if its state is $1$.
The new state of each toggled gate remains unchanged until it is possibly toggled by one of the later updates.
Your goal is to count, after each update, how many different assignments of parameters to threshold gates result in gate $0$ having state $1$.
Two assignments are considered different if there exists at least one threshold gate that has a different value of its parameter in both assignments.
As the number of ways can be large, you should compute it modulo $1\;000\;002\;022$.
Note that in the example above, there are $6$ different assignments of parameters to threshold gates, since gates $0$, $1$ and $2$ have $2$, $3$ and $1$ inputs respectively.
In $2$ out of these $6$ assignments, gate $0$ has state $1$.
## Implementation Details
Your task is to implement two procedures.
```
void init(int N, int M, int[] P, int[] A)
```
* $N$: the number of threshold gates.
* $M$: the number of source gates.
* $P$: an array of length $N + M$ describing the inputs to the threshold gates.
* $A$: an array of length $M$ describing the initial states of the source gates.
* This procedure is called exactly once, before any calls to `count_ways`.
```
int count_ways(int L, int R)
```
* $L$, $R$: the boundaries of the range of source gates, whose states are toggled.
* This procedure should first perform the specified update, and then return the number of ways, modulo $1\;000\;002\;022$, of assigning parameters to the threshold gates, which result in gate $0$ having state $1$.
* This procedure is called exactly $Q$ times.
## Example
Consider the following sequence of calls:
```
init(3, 4, [-1, 0, 1, 2, 1, 1, 0], [1, 0, 1, 0])
```
This example is illustrated in the task description above.
```
count_ways(3, 4)
```
This toggles the states of gates $3$ and $4$, i.e. the state of gate $3$ becomes $0$, and the state of gate $4$ becomes $1$.
Two ways of assigning the parameters which result in gate $0$ having state $1$ are illustrated in the pictures below.
| Way $1$ | Way $2$ |
|:-------:|:-------:|
|
|
|
In all other assignments of parameters, gate $0$ has state $0$.
Thus, the procedure should return $2$.
```
count_ways(4, 5)
```
This toggles the states of gates $4$ and $5$.
As a result, all source gates have state $0$, and for any assignment of parameters, gate $0$ has state $0$.
Thus, the procedure should return $0$.
```
count_ways(3, 6)
```
This changes the states of all source gates to $1$.
As a result, for any assignment of parameters, gate $0$ has state $1$.
Thus, the procedure should return $6$.
## Constraints
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
* $N, M \le 1000$
* $Q \le 5$
## Sample Grader
The sample grader reads the input in the following format:
* line $1$: $N \; M \; Q$
* line $2$: $P[0] \; P[1] \; \ldots \; P[N + M - 1]$
* line $3$: $A[0] \; A[1] \; \ldots \; A[M - 1]$
* line $4 + k$ ($0 \le k \le Q - 1$): $L \; R$ for update $k$
The sample grader prints your answers in the following format:
* line $1 + k$ ($0 \le k \le Q - 1$): the return value of `count_ways` for update $k$
|
Python
|
seed_348
|
# Digital Circuit
There is a circuit, which consists of $N + M$ **gates** numbered from $0$ to $N + M - 1$.
Gates $0$ to $N - 1$ are **threshold gates**, whereas gates $N$ to $N + M - 1$ are **source gates**.
Each gate, except for gate $0$, is an **input** to exactly one threshold gate.
Specifically, for each $i$ such that $1 \le i \le N + M - 1$, gate $i$ is an input to gate $P[i]$, where $0 \le P[i] \le N-1$.
Importantly, we also have $P[i] \lt i$.
Moreover, we assume $P[0] = -1$.
Each threshold gate has one or more inputs.
Source gates do not have any inputs.
Each gate has a **state** which is either $0$ or $1$.
The initial states of the source gates are given by an array $A$ of $M$ integers.
That is, for each $j$ such that $0 \le j \le M - 1$, the initial state of the source gate $N + j$ is $A[j]$.
The state of each threshold gate depends on the states of its inputs and is determined as follows.
First, each threshold gate is assigned a threshold **parameter**.
The parameter assigned to a threshold gate with $c$ inputs must be an integer between $1$ and $c$ (inclusive).
Then, the state of a threshold gate with parameter $p$ is $1$, if at least $p$ of its inputs have state $1$, and $0$ otherwise.
For example, suppose there are $N = 3$ threshold gates and $M = 4$ source gates.
The inputs to gate $0$ are gates $1$ and $6$, the inputs to gate $1$ are gates $2$, $4$, and $5$, and the only input to gate $2$ is gate $3$.
This example is illustrated in the following picture.
Suppose that source gates $3$ and $5$ have state $1$, while source gates $4$ and $6$ have state $0$.
Assume we assign parameters $1$, $2$ and $2$ to threshold gates $2$, $1$ and $0$ respectively.
In this case, gate $2$ has state $1$, gate $1$ has state $1$ and gate $0$ has state $0$.
This assignment of parameter values and the states is illustrated in the following picture.
Gates whose state is $1$ are marked in black.
The states of the source gates will undergo $Q$ updates.
Each update is described by two integers $L$ and $R$ ($N \le L \le R \le N + M - 1$) and toggles the states of all source gates numbered between $L$ and $R$, inclusive.
That is, for each $i$ such that $L \le i \le R$, source gate $i$ changes its state to $1$, if its state is $0$, or to $0$, if its state is $1$.
The new state of each toggled gate remains unchanged until it is possibly toggled by one of the later updates.
Your goal is to count, after each update, how many different assignments of parameters to threshold gates result in gate $0$ having state $1$.
Two assignments are considered different if there exists at least one threshold gate that has a different value of its parameter in both assignments.
As the number of ways can be large, you should compute it modulo $1\;000\;002\;022$.
Note that in the example above, there are $6$ different assignments of parameters to threshold gates, since gates $0$, $1$ and $2$ have $2$, $3$ and $1$ inputs respectively.
In $2$ out of these $6$ assignments, gate $0$ has state $1$.
## Implementation Details
Your task is to implement two procedures.
```
void init(int N, int M, int[] P, int[] A)
```
* $N$: the number of threshold gates.
* $M$: the number of source gates.
* $P$: an array of length $N + M$ describing the inputs to the threshold gates.
* $A$: an array of length $M$ describing the initial states of the source gates.
* This procedure is called exactly once, before any calls to `count_ways`.
```
int count_ways(int L, int R)
```
* $L$, $R$: the boundaries of the range of source gates, whose states are toggled.
* This procedure should first perform the specified update, and then return the number of ways, modulo $1\;000\;002\;022$, of assigning parameters to the threshold gates, which result in gate $0$ having state $1$.
* This procedure is called exactly $Q$ times.
## Example
Consider the following sequence of calls:
```
init(3, 4, [-1, 0, 1, 2, 1, 1, 0], [1, 0, 1, 0])
```
This example is illustrated in the task description above.
```
count_ways(3, 4)
```
This toggles the states of gates $3$ and $4$, i.e. the state of gate $3$ becomes $0$, and the state of gate $4$ becomes $1$.
Two ways of assigning the parameters which result in gate $0$ having state $1$ are illustrated in the pictures below.
| Way $1$ | Way $2$ |
|:-------:|:-------:|
|
|
|
In all other assignments of parameters, gate $0$ has state $0$.
Thus, the procedure should return $2$.
```
count_ways(4, 5)
```
This toggles the states of gates $4$ and $5$.
As a result, all source gates have state $0$, and for any assignment of parameters, gate $0$ has state $0$.
Thus, the procedure should return $0$.
```
count_ways(3, 6)
```
This changes the states of all source gates to $1$.
As a result, for any assignment of parameters, gate $0$ has state $1$.
Thus, the procedure should return $6$.
## Constraints
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
* $N, M \le 1000$
* $Q \le 5$
* Each threshold gate has exactly two inputs.
## Sample Grader
The sample grader reads the input in the following format:
* line $1$: $N \; M \; Q$
* line $2$: $P[0] \; P[1] \; \ldots \; P[N + M - 1]$
* line $3$: $A[0] \; A[1] \; \ldots \; A[M - 1]$
* line $4 + k$ ($0 \le k \le Q - 1$): $L \; R$ for update $k$
The sample grader prints your answers in the following format:
* line $1 + k$ ($0 \le k \le Q - 1$): the return value of `count_ways` for update $k$
|
Python
|
seed_349
|
# Digital Circuit
There is a circuit, which consists of $N + M$ **gates** numbered from $0$ to $N + M - 1$.
Gates $0$ to $N - 1$ are **threshold gates**, whereas gates $N$ to $N + M - 1$ are **source gates**.
Each gate, except for gate $0$, is an **input** to exactly one threshold gate.
Specifically, for each $i$ such that $1 \le i \le N + M - 1$, gate $i$ is an input to gate $P[i]$, where $0 \le P[i] \le N-1$.
Importantly, we also have $P[i] \lt i$.
Moreover, we assume $P[0] = -1$.
Each threshold gate has one or more inputs.
Source gates do not have any inputs.
Each gate has a **state** which is either $0$ or $1$.
The initial states of the source gates are given by an array $A$ of $M$ integers.
That is, for each $j$ such that $0 \le j \le M - 1$, the initial state of the source gate $N + j$ is $A[j]$.
The state of each threshold gate depends on the states of its inputs and is determined as follows.
First, each threshold gate is assigned a threshold **parameter**.
The parameter assigned to a threshold gate with $c$ inputs must be an integer between $1$ and $c$ (inclusive).
Then, the state of a threshold gate with parameter $p$ is $1$, if at least $p$ of its inputs have state $1$, and $0$ otherwise.
For example, suppose there are $N = 3$ threshold gates and $M = 4$ source gates.
The inputs to gate $0$ are gates $1$ and $6$, the inputs to gate $1$ are gates $2$, $4$, and $5$, and the only input to gate $2$ is gate $3$.
This example is illustrated in the following picture.
Suppose that source gates $3$ and $5$ have state $1$, while source gates $4$ and $6$ have state $0$.
Assume we assign parameters $1$, $2$ and $2$ to threshold gates $2$, $1$ and $0$ respectively.
In this case, gate $2$ has state $1$, gate $1$ has state $1$ and gate $0$ has state $0$.
This assignment of parameter values and the states is illustrated in the following picture.
Gates whose state is $1$ are marked in black.
The states of the source gates will undergo $Q$ updates.
Each update is described by two integers $L$ and $R$ ($N \le L \le R \le N + M - 1$) and toggles the states of all source gates numbered between $L$ and $R$, inclusive.
That is, for each $i$ such that $L \le i \le R$, source gate $i$ changes its state to $1$, if its state is $0$, or to $0$, if its state is $1$.
The new state of each toggled gate remains unchanged until it is possibly toggled by one of the later updates.
Your goal is to count, after each update, how many different assignments of parameters to threshold gates result in gate $0$ having state $1$.
Two assignments are considered different if there exists at least one threshold gate that has a different value of its parameter in both assignments.
As the number of ways can be large, you should compute it modulo $1\;000\;002\;022$.
Note that in the example above, there are $6$ different assignments of parameters to threshold gates, since gates $0$, $1$ and $2$ have $2$, $3$ and $1$ inputs respectively.
In $2$ out of these $6$ assignments, gate $0$ has state $1$.
## Implementation Details
Your task is to implement two procedures.
```
void init(int N, int M, int[] P, int[] A)
```
* $N$: the number of threshold gates.
* $M$: the number of source gates.
* $P$: an array of length $N + M$ describing the inputs to the threshold gates.
* $A$: an array of length $M$ describing the initial states of the source gates.
* This procedure is called exactly once, before any calls to `count_ways`.
```
int count_ways(int L, int R)
```
* $L$, $R$: the boundaries of the range of source gates, whose states are toggled.
* This procedure should first perform the specified update, and then return the number of ways, modulo $1\;000\;002\;022$, of assigning parameters to the threshold gates, which result in gate $0$ having state $1$.
* This procedure is called exactly $Q$ times.
## Example
Consider the following sequence of calls:
```
init(3, 4, [-1, 0, 1, 2, 1, 1, 0], [1, 0, 1, 0])
```
This example is illustrated in the task description above.
```
count_ways(3, 4)
```
This toggles the states of gates $3$ and $4$, i.e. the state of gate $3$ becomes $0$, and the state of gate $4$ becomes $1$.
Two ways of assigning the parameters which result in gate $0$ having state $1$ are illustrated in the pictures below.
| Way $1$ | Way $2$ |
|:-------:|:-------:|
|
|
|
In all other assignments of parameters, gate $0$ has state $0$.
Thus, the procedure should return $2$.
```
count_ways(4, 5)
```
This toggles the states of gates $4$ and $5$.
As a result, all source gates have state $0$, and for any assignment of parameters, gate $0$ has state $0$.
Thus, the procedure should return $0$.
```
count_ways(3, 6)
```
This changes the states of all source gates to $1$.
As a result, for any assignment of parameters, gate $0$ has state $1$.
Thus, the procedure should return $6$.
## Constraints
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
* $N, M \le 5000$
## Sample Grader
The sample grader reads the input in the following format:
* line $1$: $N \; M \; Q$
* line $2$: $P[0] \; P[1] \; \ldots \; P[N + M - 1]$
* line $3$: $A[0] \; A[1] \; \ldots \; A[M - 1]$
* line $4 + k$ ($0 \le k \le Q - 1$): $L \; R$ for update $k$
The sample grader prints your answers in the following format:
* line $1 + k$ ($0 \le k \le Q - 1$): the return value of `count_ways` for update $k$
|
Python
|
seed_350
|
# Digital Circuit
There is a circuit, which consists of $N + M$ **gates** numbered from $0$ to $N + M - 1$.
Gates $0$ to $N - 1$ are **threshold gates**, whereas gates $N$ to $N + M - 1$ are **source gates**.
Each gate, except for gate $0$, is an **input** to exactly one threshold gate.
Specifically, for each $i$ such that $1 \le i \le N + M - 1$, gate $i$ is an input to gate $P[i]$, where $0 \le P[i] \le N-1$.
Importantly, we also have $P[i] \lt i$.
Moreover, we assume $P[0] = -1$.
Each threshold gate has one or more inputs.
Source gates do not have any inputs.
Each gate has a **state** which is either $0$ or $1$.
The initial states of the source gates are given by an array $A$ of $M$ integers.
That is, for each $j$ such that $0 \le j \le M - 1$, the initial state of the source gate $N + j$ is $A[j]$.
The state of each threshold gate depends on the states of its inputs and is determined as follows.
First, each threshold gate is assigned a threshold **parameter**.
The parameter assigned to a threshold gate with $c$ inputs must be an integer between $1$ and $c$ (inclusive).
Then, the state of a threshold gate with parameter $p$ is $1$, if at least $p$ of its inputs have state $1$, and $0$ otherwise.
For example, suppose there are $N = 3$ threshold gates and $M = 4$ source gates.
The inputs to gate $0$ are gates $1$ and $6$, the inputs to gate $1$ are gates $2$, $4$, and $5$, and the only input to gate $2$ is gate $3$.
This example is illustrated in the following picture.
Suppose that source gates $3$ and $5$ have state $1$, while source gates $4$ and $6$ have state $0$.
Assume we assign parameters $1$, $2$ and $2$ to threshold gates $2$, $1$ and $0$ respectively.
In this case, gate $2$ has state $1$, gate $1$ has state $1$ and gate $0$ has state $0$.
This assignment of parameter values and the states is illustrated in the following picture.
Gates whose state is $1$ are marked in black.
The states of the source gates will undergo $Q$ updates.
Each update is described by two integers $L$ and $R$ ($N \le L \le R \le N + M - 1$) and toggles the states of all source gates numbered between $L$ and $R$, inclusive.
That is, for each $i$ such that $L \le i \le R$, source gate $i$ changes its state to $1$, if its state is $0$, or to $0$, if its state is $1$.
The new state of each toggled gate remains unchanged until it is possibly toggled by one of the later updates.
Your goal is to count, after each update, how many different assignments of parameters to threshold gates result in gate $0$ having state $1$.
Two assignments are considered different if there exists at least one threshold gate that has a different value of its parameter in both assignments.
As the number of ways can be large, you should compute it modulo $1\;000\;002\;022$.
Note that in the example above, there are $6$ different assignments of parameters to threshold gates, since gates $0$, $1$ and $2$ have $2$, $3$ and $1$ inputs respectively.
In $2$ out of these $6$ assignments, gate $0$ has state $1$.
## Implementation Details
Your task is to implement two procedures.
```
void init(int N, int M, int[] P, int[] A)
```
* $N$: the number of threshold gates.
* $M$: the number of source gates.
* $P$: an array of length $N + M$ describing the inputs to the threshold gates.
* $A$: an array of length $M$ describing the initial states of the source gates.
* This procedure is called exactly once, before any calls to `count_ways`.
```
int count_ways(int L, int R)
```
* $L$, $R$: the boundaries of the range of source gates, whose states are toggled.
* This procedure should first perform the specified update, and then return the number of ways, modulo $1\;000\;002\;022$, of assigning parameters to the threshold gates, which result in gate $0$ having state $1$.
* This procedure is called exactly $Q$ times.
## Example
Consider the following sequence of calls:
```
init(3, 4, [-1, 0, 1, 2, 1, 1, 0], [1, 0, 1, 0])
```
This example is illustrated in the task description above.
```
count_ways(3, 4)
```
This toggles the states of gates $3$ and $4$, i.e. the state of gate $3$ becomes $0$, and the state of gate $4$ becomes $1$.
Two ways of assigning the parameters which result in gate $0$ having state $1$ are illustrated in the pictures below.
| Way $1$ | Way $2$ |
|:-------:|:-------:|
|
|
|
In all other assignments of parameters, gate $0$ has state $0$.
Thus, the procedure should return $2$.
```
count_ways(4, 5)
```
This toggles the states of gates $4$ and $5$.
As a result, all source gates have state $0$, and for any assignment of parameters, gate $0$ has state $0$.
Thus, the procedure should return $0$.
```
count_ways(3, 6)
```
This changes the states of all source gates to $1$.
As a result, for any assignment of parameters, gate $0$ has state $1$.
Thus, the procedure should return $6$.
## Constraints
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
* Each threshold gate has exactly two inputs.
## Sample Grader
The sample grader reads the input in the following format:
* line $1$: $N \; M \; Q$
* line $2$: $P[0] \; P[1] \; \ldots \; P[N + M - 1]$
* line $3$: $A[0] \; A[1] \; \ldots \; A[M - 1]$
* line $4 + k$ ($0 \le k \le Q - 1$): $L \; R$ for update $k$
The sample grader prints your answers in the following format:
* line $1 + k$ ($0 \le k \le Q - 1$): the return value of `count_ways` for update $k$
|
Python
|
seed_353
|
# Distributing Candies
Aunty Khong is preparing n boxes of candies for students from a nearby school. The boxes are numbered from 0 to n β 1 and are initially empty. Box i (0 β€ i β€ n β 1) has a capacity of c[i] candies.
Aunty Khong spends q days preparing the boxes. On day j (0 β€ j β€ q β 1), she performs an action specified by three integers l[j], r[j] and v[j] where 0 β€ l[j] β€ r[j] β€ n β 1 and v[j] β 0. For each box k satisfying l[j] β€ k β€ r[j]:
- If v[j] > 0, Aunty Khong adds candies to box k, one by one, until she has added exactly v[j] candies or the box becomes full. In other words, if the box had p candies before the action, it will have min(c[k], p + v[j]) candies after the action.
- If v[j] < 0, Aunty Khong removes candies from box k, one by one, until she has removed exactly βv[j] candies or the box becomes empty. In other words, if the box had p candies before the action, it will have max(0, p + v[j]) candies after the action.
Your task is to determine the number of candies in each box after the q days.
## Implementation Details
You should implement the following procedure:
```
int[] distribute_candies(int[] c, int[] l, int[] r, int[] v)
```
- c: an array of length n. For 0 β€ i β€ n β 1, c[i] denotes the capacity of box i.
- l, r and v: three arrays of length q. On day j, for 0 β€ j β€ q β 1, Aunty Khong performs an action specified by integers l[j], r[j] and v[j], as described above.
- This procedure should return an array of length n. Denote the array by s. For 0 β€ i β€ n β 1, s[i] should be the number of candies in box i after the q days.
## Examples
### Example 1
Consider the following call:
```
distribute_candies([10, 15, 13], [0, 0], [2, 1], [20, -11])
```
This means that box 0 has a capacity of 10 candies, box 1 has a capacity of 15 candies, and box 2 has a capacity of 13 candies.
At the end of day 0, box 0 has min(c[0], 0 + v[0]) = 10 candies, box 1 has min(c[1], 0 + v[0]) = 15 candies and box 2 has min(c[2], 0 + v[0]) = 13 candies.
At the end of day 1, box 0 has max(0, 10 + v[1]) = 0 candies, box 1 has max(0, 15 + v[1]) = 4 candies. Since 2 > r[1], there is no change in the number of candies in box 2. The number of candies at the end of each day are summarized below:
| Day | Box 0 | Box 1 | Box 2 |
|-----|-------|-------|-------|
| 0 | 10 | 15 | 13 |
| 1 | 0 | 4 | 13 |
As such, the procedure should return [0, 4, 13].
## Constraints
* $1 \le n \le 200\,000$
* $1 \le q \le 200\,000$
* $1 \le c[i] \le 10^9$ (for all $0 \le i \le n - 1$)
* $0 \le l[j] \le r[j] \le n - 1$ (for all $0 \le j \le q - 1$)
* $-10^9 \le v[j] \le 10^9, v[j] \neq 0$ (for all $0 \le j \le q - 1$)
## Sample Grader
The sample grader reads in the input in the following format:
- line 1: n
- line 2: c[0] c[1] β¦ c[n β 1]
- line 3: q
- line 4 + j (0 β€ j β€ q β 1): l[j] r[j] v[j]
The sample grader prints your answers in the following format:
- line 1: s[0] s[1] β¦ s[n β 1]
|
Python
|
seed_355
|
# Distributing Candies
Aunty Khong is preparing n boxes of candies for students from a nearby school. The boxes are numbered from 0 to n β 1 and are initially empty. Box i (0 β€ i β€ n β 1) has a capacity of c[i] candies.
Aunty Khong spends q days preparing the boxes. On day j (0 β€ j β€ q β 1), she performs an action specified by three integers l[j], r[j] and v[j] where 0 β€ l[j] β€ r[j] β€ n β 1 and v[j] β 0. For each box k satisfying l[j] β€ k β€ r[j]:
- If v[j] > 0, Aunty Khong adds candies to box k, one by one, until she has added exactly v[j] candies or the box becomes full. In other words, if the box had p candies before the action, it will have min(c[k], p + v[j]) candies after the action.
- If v[j] < 0, Aunty Khong removes candies from box k, one by one, until she has removed exactly βv[j] candies or the box becomes empty. In other words, if the box had p candies before the action, it will have max(0, p + v[j]) candies after the action.
Your task is to determine the number of candies in each box after the q days.
## Implementation Details
You should implement the following procedure:
```
int[] distribute_candies(int[] c, int[] l, int[] r, int[] v)
```
- c: an array of length n. For 0 β€ i β€ n β 1, c[i] denotes the capacity of box i.
- l, r and v: three arrays of length q. On day j, for 0 β€ j β€ q β 1, Aunty Khong performs an action specified by integers l[j], r[j] and v[j], as described above.
- This procedure should return an array of length n. Denote the array by s. For 0 β€ i β€ n β 1, s[i] should be the number of candies in box i after the q days.
## Examples
### Example 1
Consider the following call:
```
distribute_candies([10, 15, 13], [0, 0], [2, 1], [20, -11])
```
This means that box 0 has a capacity of 10 candies, box 1 has a capacity of 15 candies, and box 2 has a capacity of 13 candies.
At the end of day 0, box 0 has min(c[0], 0 + v[0]) = 10 candies, box 1 has min(c[1], 0 + v[0]) = 15 candies and box 2 has min(c[2], 0 + v[0]) = 13 candies.
At the end of day 1, box 0 has max(0, 10 + v[1]) = 0 candies, box 1 has max(0, 15 + v[1]) = 4 candies. Since 2 > r[1], there is no change in the number of candies in box 2. The number of candies at the end of each day are summarized below:
| Day | Box 0 | Box 1 | Box 2 |
|-----|-------|-------|-------|
| 0 | 10 | 15 | 13 |
| 1 | 0 | 4 | 13 |
As such, the procedure should return [0, 4, 13].
## Constraints
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
* $1 \le n \le 200\,000$
* $1 \le q \le 200\,000$
* $1 \le c[i] \le 10^9$ (for all $0 \le i \le n - 1$)
* $0 \le l[j] \le r[j] \le n - 1$ (for all $0 \le j \le q - 1$)
* $-10^9 \le v[j] \le 10^9, v[j] \neq 0$ (for all $0 \le j \le q - 1$)
* $l[j] = 0$ and $r[j] = n - 1$ (for all $0 \le j \le q - 1$)
## Sample Grader
The sample grader reads in the input in the following format:
- line 1: n
- line 2: c[0] c[1] β¦ c[n β 1]
- line 3: q
- line 4 + j (0 β€ j β€ q β 1): l[j] r[j] v[j]
The sample grader prints your answers in the following format:
- line 1: s[0] s[1] β¦ s[n β 1]
|
Python
|
seed_360
|
# Do you ever wish you could talk like Siegfried of KAOS ?
## YES, of course you do!
https://en.wikipedia.org/wiki/Get_Smart
# Task
Write the function ```siegfried``` to replace the letters of a given sentence.
Apply the rules using the course notes below. Each week you will learn some more rules.
Und by ze fifz vek yu vil be speakink viz un aksent lik Siegfried viz no trubl at al!
# Lessons
## Week 1
* ```ci``` -> ```si```
* ```ce``` -> ```se```
* ```c``` -> ```k``` (except ```ch``` leave alone)
## Week 2
* ```ph``` -> ```f```
## Week 3
* remove trailing ```e``` (except for all 2 and 3 letter words)
* replace double letters with single letters (e.g. ```tt``` -> ```t```)
## Week 4
* ```th``` -> ```z```
* ```wr``` -> ```r```
* ```wh``` -> ```v```
* ```w``` -> ```v```
## Week 5
* ```ou``` -> ```u```
* ```an``` -> ```un```
* ```ing``` -> ```ink``` (but only when ending words)
* ```sm``` -> ```schm``` (but only when beginning words)
# Notes
* You must retain the case of the original sentence
* Apply rules strictly in the order given above
* Rules are cummulative. So for week 3 first apply week 1 rules, then week 2 rules, then week 3 rules
|
Python
|
seed_362
|
# Don't give me five!
In this kata you get the start number and the end number of a region and should return the count of all numbers except numbers with a 5 in it. The start and the end number are both inclusive!
Examples:
```
1,9 -> 1,2,3,4,6,7,8,9 -> Result 8
4,17 -> 4,6,7,8,9,10,11,12,13,14,16,17 -> Result 12
```
The result may contain fives. ;-)
The start number will always be smaller than the end number. Both numbers can be also negative!
I'm very curious for your solutions and the way you solve it. Maybe someone of you will find an easy pure mathematics solution.
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have also created other katas. Take a look if you enjoyed this kata!
|
Python
|
seed_363
|
# Dungeons Game
Robert is designing a new computer game. The game involves one hero, n opponents and n + 1 dungeons. The opponents are numbered from 0 to n β 1 and the dungeons are numbered from 0 to n. Opponent i (0 β€ i β€ n β 1) is located in dungeon i and has strength s[i]. There is no opponent in dungeon n.
The hero starts off entering dungeon x, with strength z. Every time the hero enters any dungeon i (0 β€ i β€ n β 1), they confront opponent i, and one of the following occurs:
- If the hero's strength is greater than or equal to the opponent's strength s[i], the hero wins. This causes the hero's strength to increase by s[i] (s[i] β₯ 1). In this case the hero enters dungeon w[i] next (w[i] > i).
- Otherwise, the hero loses. This causes the hero's strength to increase by p[i] (p[i] β₯ 1). In this case the hero enters dungeon l[i] next.
Note p[i] may be less than, equal to, or greater than s[i]. Also, l[i] may be less than, equal to, or greater than i. Regardless of the outcome of the confrontation, the opponent remains in dungeon i and maintains strength s[i].
The game ends when the hero enters dungeon n. One can show that the game ends after a finite number of confrontations, regardless of the hero's starting dungeon and strength.
Robert asked you to test his game by running q simulations. For each simulation, Robert defines a starting dungeon x and starting strength z. Your task is to find out, for each simulation, the hero's strength when the game ends.
## Implementation details
You should implement the following procedures:
```
void init(int n, int[] s, int[] p, int[] w, int[] l)
```
- n: number of opponents.
- s, p, w, l: arrays of length n. For 0 β€ i β€ n β 1:
- s[i] is the strength of the opponent i. It is also the strength gained by the hero after winning against opponent i.
- p[i] is the strength gained by the hero after losing against opponent i.
- w[i] is the dungeon the hero enters after winning against opponent i.
- l[i] is the dungeon the hero enters after losing against opponent i.
- This procedure is called exactly once, before any calls to simulate (see below).
```
int64 simulate(int x, int z)
```
- x: the dungeon the hero enters first.
- z: the hero's starting strength.
- This procedure should return the hero's strength when the game ends, assuming the hero starts the game by entering dungeon x, having strength z.
- The procedure is called exactly q times.
## Example
Consider the following call:
```
init(3, [2, 6, 9], [3, 1, 2], [2, 2, 3], [1, 0, 1])
```
The diagram above illustrates this call. Each square shows a dungeon. For dungeons 0, 1 and 2, the values s[i] and p[i] are indicated inside the squares. Magenta arrows indicate where the hero moves after winning a confrontation, while black arrows indicate where the hero moves after losing.
Let's say the grader calls simulate(0, 1).
The game proceeds as follows:
| Dungeon | Hero's strength before confrontation | Result |
|---------|-------------------------------------|--------|
| 0 | 1 | Lose |
| 1 | 4 | Lose |
| 0 | 5 | Win |
| 2 | 7 | Lose |
| 1 | 9 | Win |
| 2 | 15 | Win |
| 3 | 24 | Game ends |
As such, the procedure should return 24.
Let's say the grader calls simulate(2, 3).
The game proceeds as follows:
| Dungeon | Hero's strength before confrontation | Result |
|---------|-------------------------------------|--------|
| 2 | 3 | Lose |
| 1 | 5 | Lose |
| 0 | 6 | Win |
| 2 | 8 | Lose |
| 1 | 10 | Win |
| 2 | 16 | Win |
| 3 | 25 | Game ends |
As such, the procedure should return 25.
## Constraints
* $1 \le n \le 400\,000$
* $1 \le q \le 50\,000$
* $1 \le s[i], p[i] \le 10^7$ (for all $0 \le i \le n β 1$)
* $0 \le l[i], w[i] \le n$ (for all $0 \le i \le n β 1$)
* $w[i] > i$ (for all $0 \le i \le n β 1$)
* $0 \le x \le n β 1$
* $1 \le z \le 10^7$
## Sample grader
The sample grader reads the input in the following format:
- line 1: n q
- line 2: s[0] s[1] β¦ s[n β 1]
- line 3: p[0] p[1] β¦ p[n β 1]
- line 4: w[0] w[1] β¦ w[n β 1]
- line 5: l[0] l[1] β¦ l[n β 1]
- line 6 + i (0 β€ i β€ q β 1): x z for the i-th call to simulate.
The sample grader prints your answers in the following format:
- line 1 + i (0 β€ i β€ q β 1): the return value of the i-th call to simulate.
|
Python
|
seed_366
|
# Dungeons Game
Robert is designing a new computer game. The game involves one hero, n opponents and n + 1 dungeons. The opponents are numbered from 0 to n β 1 and the dungeons are numbered from 0 to n. Opponent i (0 β€ i β€ n β 1) is located in dungeon i and has strength s[i]. There is no opponent in dungeon n.
The hero starts off entering dungeon x, with strength z. Every time the hero enters any dungeon i (0 β€ i β€ n β 1), they confront opponent i, and one of the following occurs:
- If the hero's strength is greater than or equal to the opponent's strength s[i], the hero wins. This causes the hero's strength to increase by s[i] (s[i] β₯ 1). In this case the hero enters dungeon w[i] next (w[i] > i).
- Otherwise, the hero loses. This causes the hero's strength to increase by p[i] (p[i] β₯ 1). In this case the hero enters dungeon l[i] next.
Note p[i] may be less than, equal to, or greater than s[i]. Also, l[i] may be less than, equal to, or greater than i. Regardless of the outcome of the confrontation, the opponent remains in dungeon i and maintains strength s[i].
The game ends when the hero enters dungeon n. One can show that the game ends after a finite number of confrontations, regardless of the hero's starting dungeon and strength.
Robert asked you to test his game by running q simulations. For each simulation, Robert defines a starting dungeon x and starting strength z. Your task is to find out, for each simulation, the hero's strength when the game ends.
## Implementation details
You should implement the following procedures:
```
void init(int n, int[] s, int[] p, int[] w, int[] l)
```
- n: number of opponents.
- s, p, w, l: arrays of length n. For 0 β€ i β€ n β 1:
- s[i] is the strength of the opponent i. It is also the strength gained by the hero after winning against opponent i.
- p[i] is the strength gained by the hero after losing against opponent i.
- w[i] is the dungeon the hero enters after winning against opponent i.
- l[i] is the dungeon the hero enters after losing against opponent i.
- This procedure is called exactly once, before any calls to simulate (see below).
```
int64 simulate(int x, int z)
```
- x: the dungeon the hero enters first.
- z: the hero's starting strength.
- This procedure should return the hero's strength when the game ends, assuming the hero starts the game by entering dungeon x, having strength z.
- The procedure is called exactly q times.
## Example
Consider the following call:
```
init(3, [2, 6, 9], [3, 1, 2], [2, 2, 3], [1, 0, 1])
```
The diagram above illustrates this call. Each square shows a dungeon. For dungeons 0, 1 and 2, the values s[i] and p[i] are indicated inside the squares. Magenta arrows indicate where the hero moves after winning a confrontation, while black arrows indicate where the hero moves after losing.
Let's say the grader calls simulate(0, 1).
The game proceeds as follows:
| Dungeon | Hero's strength before confrontation | Result |
|---------|-------------------------------------|--------|
| 0 | 1 | Lose |
| 1 | 4 | Lose |
| 0 | 5 | Win |
| 2 | 7 | Lose |
| 1 | 9 | Win |
| 2 | 15 | Win |
| 3 | 24 | Game ends |
As such, the procedure should return 24.
Let's say the grader calls simulate(2, 3).
The game proceeds as follows:
| Dungeon | Hero's strength before confrontation | Result |
|---------|-------------------------------------|--------|
| 2 | 3 | Lose |
| 1 | 5 | Lose |
| 0 | 6 | Win |
| 2 | 8 | Lose |
| 1 | 10 | Win |
| 2 | 16 | Win |
| 3 | 25 | Game ends |
As such, the procedure should return 25.
## Constraints
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
* $1 \le n \le 50\,000$
* $1 \le q \le 50\,000$
* $1 \le s[i], p[i] \le 10^7$ (for all $0 \le i \le n β 1$)
* $0 \le l[i], w[i] \le n$ (for all $0 \le i \le n β 1$)
* $w[i] > i$ (for all $0 \le i \le n β 1$)
* $0 \le x \le n β 1$
* $1 \le z \le 10^7$
## Sample grader
The sample grader reads the input in the following format:
- line 1: n q
- line 2: s[0] s[1] β¦ s[n β 1]
- line 3: p[0] p[1] β¦ p[n β 1]
- line 4: w[0] w[1] β¦ w[n β 1]
- line 5: l[0] l[1] β¦ l[n β 1]
- line 6 + i (0 β€ i β€ q β 1): x z for the i-th call to simulate.
The sample grader prints your answers in the following format:
- line 1 + i (0 β€ i β€ q β 1): the return value of the i-th call to simulate.
|
Python
|
seed_367
|
# Dungeons Game
Robert is designing a new computer game. The game involves one hero, n opponents and n + 1 dungeons. The opponents are numbered from 0 to n β 1 and the dungeons are numbered from 0 to n. Opponent i (0 β€ i β€ n β 1) is located in dungeon i and has strength s[i]. There is no opponent in dungeon n.
The hero starts off entering dungeon x, with strength z. Every time the hero enters any dungeon i (0 β€ i β€ n β 1), they confront opponent i, and one of the following occurs:
- If the hero's strength is greater than or equal to the opponent's strength s[i], the hero wins. This causes the hero's strength to increase by s[i] (s[i] β₯ 1). In this case the hero enters dungeon w[i] next (w[i] > i).
- Otherwise, the hero loses. This causes the hero's strength to increase by p[i] (p[i] β₯ 1). In this case the hero enters dungeon l[i] next.
Note p[i] may be less than, equal to, or greater than s[i]. Also, l[i] may be less than, equal to, or greater than i. Regardless of the outcome of the confrontation, the opponent remains in dungeon i and maintains strength s[i].
The game ends when the hero enters dungeon n. One can show that the game ends after a finite number of confrontations, regardless of the hero's starting dungeon and strength.
Robert asked you to test his game by running q simulations. For each simulation, Robert defines a starting dungeon x and starting strength z. Your task is to find out, for each simulation, the hero's strength when the game ends.
## Implementation details
You should implement the following procedures:
```
void init(int n, int[] s, int[] p, int[] w, int[] l)
```
- n: number of opponents.
- s, p, w, l: arrays of length n. For 0 β€ i β€ n β 1:
- s[i] is the strength of the opponent i. It is also the strength gained by the hero after winning against opponent i.
- p[i] is the strength gained by the hero after losing against opponent i.
- w[i] is the dungeon the hero enters after winning against opponent i.
- l[i] is the dungeon the hero enters after losing against opponent i.
- This procedure is called exactly once, before any calls to simulate (see below).
```
int64 simulate(int x, int z)
```
- x: the dungeon the hero enters first.
- z: the hero's starting strength.
- This procedure should return the hero's strength when the game ends, assuming the hero starts the game by entering dungeon x, having strength z.
- The procedure is called exactly q times.
## Example
Consider the following call:
```
init(3, [2, 6, 9], [3, 1, 2], [2, 2, 3], [1, 0, 1])
```
The diagram above illustrates this call. Each square shows a dungeon. For dungeons 0, 1 and 2, the values s[i] and p[i] are indicated inside the squares. Magenta arrows indicate where the hero moves after winning a confrontation, while black arrows indicate where the hero moves after losing.
Let's say the grader calls simulate(0, 1).
The game proceeds as follows:
| Dungeon | Hero's strength before confrontation | Result |
|---------|-------------------------------------|--------|
| 0 | 1 | Lose |
| 1 | 4 | Lose |
| 0 | 5 | Win |
| 2 | 7 | Lose |
| 1 | 9 | Win |
| 2 | 15 | Win |
| 3 | 24 | Game ends |
As such, the procedure should return 24.
Let's say the grader calls simulate(2, 3).
The game proceeds as follows:
| Dungeon | Hero's strength before confrontation | Result |
|---------|-------------------------------------|--------|
| 2 | 3 | Lose |
| 1 | 5 | Lose |
| 0 | 6 | Win |
| 2 | 8 | Lose |
| 1 | 10 | Win |
| 2 | 16 | Win |
| 3 | 25 | Game ends |
As such, the procedure should return 25.
## Constraints
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
* $1 \le n \le 50\,000$
* $1 \le q \le 50\,000$
* $1 \le s[i], p[i] \le 10^7$ (for all $0 \le i \le n β 1$)
* All opponents have the same strength, in other words, $s[i] = s[j]$ for all $0 \le i, j \le n β 1$.
* $0 \le l[i], w[i] \le n$ (for all $0 \le i \le n β 1$)
* $w[i] > i$ (for all $0 \le i \le n β 1$)
* $0 \le x \le n β 1$
* $1 \le z \le 10^7$
## Sample grader
The sample grader reads the input in the following format:
- line 1: n q
- line 2: s[0] s[1] β¦ s[n β 1]
- line 3: p[0] p[1] β¦ p[n β 1]
- line 4: w[0] w[1] β¦ w[n β 1]
- line 5: l[0] l[1] β¦ l[n β 1]
- line 6 + i (0 β€ i β€ q β 1): x z for the i-th call to simulate.
The sample grader prints your answers in the following format:
- line 1 + i (0 β€ i β€ q β 1): the return value of the i-th call to simulate.
|
Python
|
seed_368
|
# Dungeons Game
Robert is designing a new computer game. The game involves one hero, n opponents and n + 1 dungeons. The opponents are numbered from 0 to n β 1 and the dungeons are numbered from 0 to n. Opponent i (0 β€ i β€ n β 1) is located in dungeon i and has strength s[i]. There is no opponent in dungeon n.
The hero starts off entering dungeon x, with strength z. Every time the hero enters any dungeon i (0 β€ i β€ n β 1), they confront opponent i, and one of the following occurs:
- If the hero's strength is greater than or equal to the opponent's strength s[i], the hero wins. This causes the hero's strength to increase by s[i] (s[i] β₯ 1). In this case the hero enters dungeon w[i] next (w[i] > i).
- Otherwise, the hero loses. This causes the hero's strength to increase by p[i] (p[i] β₯ 1). In this case the hero enters dungeon l[i] next.
Note p[i] may be less than, equal to, or greater than s[i]. Also, l[i] may be less than, equal to, or greater than i. Regardless of the outcome of the confrontation, the opponent remains in dungeon i and maintains strength s[i].
The game ends when the hero enters dungeon n. One can show that the game ends after a finite number of confrontations, regardless of the hero's starting dungeon and strength.
Robert asked you to test his game by running q simulations. For each simulation, Robert defines a starting dungeon x and starting strength z. Your task is to find out, for each simulation, the hero's strength when the game ends.
## Implementation details
You should implement the following procedures:
```
void init(int n, int[] s, int[] p, int[] w, int[] l)
```
- n: number of opponents.
- s, p, w, l: arrays of length n. For 0 β€ i β€ n β 1:
- s[i] is the strength of the opponent i. It is also the strength gained by the hero after winning against opponent i.
- p[i] is the strength gained by the hero after losing against opponent i.
- w[i] is the dungeon the hero enters after winning against opponent i.
- l[i] is the dungeon the hero enters after losing against opponent i.
- This procedure is called exactly once, before any calls to simulate (see below).
```
int64 simulate(int x, int z)
```
- x: the dungeon the hero enters first.
- z: the hero's starting strength.
- This procedure should return the hero's strength when the game ends, assuming the hero starts the game by entering dungeon x, having strength z.
- The procedure is called exactly q times.
## Example
Consider the following call:
```
init(3, [2, 6, 9], [3, 1, 2], [2, 2, 3], [1, 0, 1])
```
The diagram above illustrates this call. Each square shows a dungeon. For dungeons 0, 1 and 2, the values s[i] and p[i] are indicated inside the squares. Magenta arrows indicate where the hero moves after winning a confrontation, while black arrows indicate where the hero moves after losing.
Let's say the grader calls simulate(0, 1).
The game proceeds as follows:
| Dungeon | Hero's strength before confrontation | Result |
|---------|-------------------------------------|--------|
| 0 | 1 | Lose |
| 1 | 4 | Lose |
| 0 | 5 | Win |
| 2 | 7 | Lose |
| 1 | 9 | Win |
| 2 | 15 | Win |
| 3 | 24 | Game ends |
As such, the procedure should return 24.
Let's say the grader calls simulate(2, 3).
The game proceeds as follows:
| Dungeon | Hero's strength before confrontation | Result |
|---------|-------------------------------------|--------|
| 2 | 3 | Lose |
| 1 | 5 | Lose |
| 0 | 6 | Win |
| 2 | 8 | Lose |
| 1 | 10 | Win |
| 2 | 16 | Win |
| 3 | 25 | Game ends |
As such, the procedure should return 25.
## Constraints
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
* $1 \le n \le 50\,000$
* $1 \le q \le 50\,000$
* $1 \le s[i], p[i] \le 10^7$ (for all $0 \le i \le n β 1$)
* There are at most 5 distinct values among all values of $s[i]$.
* $0 \le l[i], w[i] \le n$ (for all $0 \le i \le n β 1$)
* $w[i] > i$ (for all $0 \le i \le n β 1$)
* $0 \le x \le n β 1$
* $1 \le z \le 10^7$
## Sample grader
The sample grader reads the input in the following format:
- line 1: n q
- line 2: s[0] s[1] β¦ s[n β 1]
- line 3: p[0] p[1] β¦ p[n β 1]
- line 4: w[0] w[1] β¦ w[n β 1]
- line 5: l[0] l[1] β¦ l[n β 1]
- line 6 + i (0 β€ i β€ q β 1): x z for the i-th call to simulate.
The sample grader prints your answers in the following format:
- line 1 + i (0 β€ i β€ q β 1): the return value of the i-th call to simulate.
|
Python
|
seed_370
|
# Empodia
## Problem
The ancient mathematician and philosopher Pythagoras believed that reality is mathematical in nature. Present-day biologists study properties of biosequences. A **biosequence** is a sequence of \( M \) integers, which:
- contains each of the numbers \( 0, 1, \dots, M-1 \),
- starts with \( 0 \) and ends with \( M-1 \), and
- has no two elements \( E, E+1 \) in adjacent positions in this order.
A **subsequence** consisting of adjacent elements of a biosequence is called a **segment**.
A **segment** of a biosequence is called a **framed interval** if it includes all integers whose values are between the value of the first element (which must be the smallest element in the segment) and the last element (which must be the largest and different from the first). A framed interval is called an **empodio** if it does not contain any shorter framed intervals.
As an example, consider the biosequence \( (0, 3, 5, 4, 6, 2, 1, 7) \). The whole biosequence is a framed interval. However, it contains another framed interval \( (3, 5, 4, 6) \) and therefore it is not an empodio. The framed interval \( (3, 5, 4, 6) \) does not contain a shorter framed interval, so it is an empodio. Furthermore, it is the only empodio in that biosequence.
You are to write a program that, given a biosequence, finds all empodia (plural for empodio) in that biosequence.
## Input
The input file name is `empodia.in`. The first line contains a single integer \( M \): the number of integers in the input biosequence. The following \( M \) lines contain the integers of the biosequence in the order of the sequence. Each of these \( M \) lines contains a single integer.
## Output
The output file name is `empodia.out`. The first line in this file is to contain one integer \( H \): the number of empodia in the input biosequence. The following \( H \) lines describe all empodia of the input biosequence in the order of appearance of the starting point in the biosequence. Each of these lines is to contain two integers \( A \) and \( B \) (in that order) separated by a space, where the \( A \)-th element of the input biosequence is the first element of the empodio and the \( B \)-th element of the input biosequence is the last element of the empodio.
## Example Inputs and Outputs
**Input:** (`empodia.in`)
```
8
0
3
5
4
6
2
1
7
```
**Output:** (`empodia.out`)
```
1
2 5
```
## Constraints
- In one input, \( 1000000 \leq M \leq 1100000 \). In all other inputs, \( 1 \leq M \leq 60000 \).
- Additionally, in 50% of the inputs, \( M \leq 2600 \).
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
|
Python
|
seed_371
|
# Esolang Interpreters #2 - Custom Smallfuck Interpreter
## About this Kata Series
"Esolang Interpreters" is a Kata Series that originally began as three separate, independent esolang interpreter Kata authored by [@donaldsebleung](http://codewars.com/users/donaldsebleung) which all shared a similar format and were all somewhat inter-related. Under the influence of [a fellow Codewarrior](https://www.codewars.com/users/nickkwest), these three high-level inter-related Kata gradually evolved into what is known today as the "Esolang Interpreters" series.
This series is a high-level Kata Series designed to challenge the minds of bright and daring programmers by implementing interpreters for various [esoteric programming languages/Esolangs](http://esolangs.org), mainly [Brainfuck](http://esolangs.org/wiki/Brainfuck) derivatives but not limited to them, given a certain specification for a certain Esolang. Perhaps the only exception to this rule is the very first Kata in this Series which is intended as an introduction/taster to the world of esoteric programming languages and writing interpreters for them.
## The Language
Smallfuck is an [esoteric programming language/Esolang](http://esolangs.org) invented in 2002 which is a sized-down variant of the famous [Brainfuck](http://esolangs.org/wiki/Brainfuck) Esolang. Key differences include:
- Smallfuck operates only on bits as opposed to bytes
- It has a limited data storage which varies from implementation to implementation depending on the size of the tape
- It does not define input or output - the "input" is encoded in the initial state of the data storage (tape) and the "output" should be decoded in the final state of the data storage (tape)
Here are a list of commands in Smallfuck:
- `>` - Move pointer to the right (by 1 cell)
- `<` - Move pointer to the left (by 1 cell)
- `*` - Flip the bit at the current cell
- `[` - Jump past matching `]` if value at current cell is `0`
- `]` - Jump back to matching `[` (if value at current cell is nonzero)
As opposed to Brainfuck where a program terminates only when all of the commands in the program have been considered (left to right), Smallfuck terminates when any of the two conditions mentioned below become true:
- All commands have been considered from left to right
- The pointer goes out-of-bounds (i.e. if it moves to the left of the first cell or to the right of the last cell of the tape)
Smallfuck is considered to be Turing-complete **if and only if** it had a tape of infinite length; however, since the length of the tape is always defined as finite (as the interpreter cannot return a tape of infinite length), its computational class is of bounded-storage machines with bounded input.
More information on this Esolang can be found [here](http://esolangs.org/wiki/Smallfuck).
## The Task
Implement a custom Smallfuck interpreter `interpreter()` (`interpreter` in Haskell and F#, `Interpreter` in C#, `custom_small_fuck:interpreter/2` in Erlang) which accepts the following arguments:
1. `code` - **Required**. The Smallfuck program to be executed, passed in as a string. May contain non-command characters. Your interpreter should simply ignore any non-command characters.
2. `tape` - **Required**. The initial state of the data storage (tape), passed in **as a string**. For example, if the string `"00101100"` is passed in then it should translate to something of this form within your interpreter: `[0, 0, 1, 0, 1, 1, 0, 0]`. You may assume that all input strings for `tape` will be non-empty and will only contain `"0"`s and `"1"`s.
Your interpreter should return the final state of the data storage (tape) **as a string** in the same format that it was passed in. For example, if the tape in your interpreter ends up being `[1, 1, 1, 1, 1]` then return the string `"11111"`.
*NOTE: The pointer of the interpreter always starts from the first (leftmost) cell of the tape, same as in Brainfuck.*
Good luck :D
## Kata in this Series
1. [Esolang Interpreters #1 - Introduction to Esolangs and My First Interpreter (MiniStringFuck)](https://www.codewars.com/kata/esolang-interpreters-number-1-introduction-to-esolangs-and-my-first-interpreter-ministringfuck)
2. **Esolang Interpreters #2 - Custom Smallfuck Interpreter**
3. [Esolang Interpreters #3 - Custom Paintfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-3-custom-paintf-star-star-k-interpreter)
4. [Esolang Interpreters #4 - Boolfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-4-boolfuck-interpreter)
|
Python
|
seed_372
|
# Esolang Interpreters #3 - Custom Paintfuck Interpreter
## About this Kata Series
"Esolang Interpreters" is a Kata Series that originally began as three separate, independent esolang interpreter Kata authored by [@donaldsebleung](http://codewars.com/users/donaldsebleung) which all shared a similar format and were all somewhat inter-related. Under the influence of [a fellow Codewarrior](https://www.codewars.com/users/nickkwest), these three high-level inter-related Kata gradually evolved into what is known today as the "Esolang Interpreters" series.
This series is a high-level Kata Series designed to challenge the minds of bright and daring programmers by implementing interpreters for various [esoteric programming languages/Esolangs](http://esolangs.org), mainly [Brainfuck](http://esolangs.org/wiki/Brainfuck) derivatives but not limited to them, given a certain specification for a certain Esolang. Perhaps the only exception to this rule is the very first Kata in this Series which is intended as an introduction/taster to the world of esoteric programming languages and writing interpreters for them.
## The Language
Paintfuck is a [borderline-esoteric programming language/Esolang](http://esolangs.org) which is a derivative of [Smallfuck](http://esolangs.org/wiki/Smallfuck) (itself a derivative of the famous [Brainfuck](http://esolangs.org/wiki/Brainfuck)) that uses a two-dimensional data grid instead of a one-dimensional tape.
Valid commands in Paintfuck include:
- `n` - Move data pointer north (up)
- `e` - Move data pointer east (right)
- `s` - Move data pointer south (down)
- `w` - Move data pointer west (left)
- `*` - Flip the bit at the current cell (same as in Smallfuck)
- `[` - Jump past matching `]` if bit under current pointer is `0` (same as in Smallfuck)
- `]` - Jump back to the matching `[` (if bit under current pointer is nonzero) (same as in Smallfuck)
The specification states that any non-command character (i.e. any character other than those mentioned above) should simply be ignored. The output of the interpreter is the two-dimensional data grid itself, best as animation as the interpreter is running, but at least a representation of the data grid itself after a certain number of iterations (explained later in task).
In current implementations, the 2D datagrid is finite in size with toroidal (wrapping) behaviour. This is one of the few major differences of Paintfuck from Smallfuck as Smallfuck terminates (normally) whenever the pointer exceeds the bounds of the tape.
Similar to Smallfuck, Paintfuck is Turing-complete **if and only if** the 2D data grid/canvas were unlimited in size. However, since the size of the data grid is defined to be finite, it acts like a finite state machine.
More info on this Esolang can be found [here](http://esolangs.org/wiki/Paintfuck).
## The Task
Your task is to implement a custom Paintfuck interpreter `interpreter()`/`Interpret` which accepts the following arguments in the specified order:
1. `code` - **Required**. The Paintfuck code to be executed, passed in as a string. May contain comments (non-command characters), in which case your interpreter should simply ignore them. If empty, simply return the initial state of the data grid.
2. `iterations` - **Required**. A non-negative integer specifying the number of iterations to be performed before the final state of the data grid is returned. See notes for definition of 1 iteration. If equal to zero, simply return the initial state of the data grid.
3. `width` - **Required**. The width of the data grid in terms of the number of data cells in each row, passed in as a positive integer.
4. `height` - **Required**. The height of the data grid in cells (i.e. number of rows) passed in as a positive integer.
A few things to note:
- Your interpreter should treat all command characters as **case-sensitive** so `N`, `E`, `S` and `W` are **not** valid command characters
- Your interpreter should initialize all cells within the data grid to a value of `0` regardless of the width and height of the grid
- In this implementation, your pointer must always start at the **top-left hand corner** of the data grid (i.e. first row, first column). This is important as some implementations have the data pointer starting at the middle of the grid.
- One iteration is defined as one step in the program, i.e. the number of command characters evaluated. For example, given a program `nessewnnnewwwsswse` and an iteration count of `5`, your interpreter should evaluate `nesse` before returning the final state of the data grid. **Non-command characters should not count towards the number of iterations.**
- Regarding iterations, the act of skipping to the matching `]` when a `[` is encountered (or vice versa) is considered to be **one** iteration regardless of the number of command characters in between. The next iteration then commences at the command **right after** the matching `]` (or `[`).
- Your interpreter should terminate normally and return the final state of the 2D data grid whenever **any** of the mentioned conditions become true: (1) All commands have been considered left to right, or (2) Your interpreter has already performed the number of iterations specified in the second argument.
- The return value of your interpreter should be a representation of the final state of the 2D data grid where each row is separated from the next by a CRLF (`\r\n`). For example, if the final state of your datagrid is
```
[
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
]
```
... then your return string should be `"100\r\n010\r\n001"`.
Good luck :D
## Kata in this Series
1. [Esolang Interpreters #1 - Introduction to Esolangs and My First Interpreter (MiniStringFuck)](https://www.codewars.com/kata/esolang-interpreters-number-1-introduction-to-esolangs-and-my-first-interpreter-ministringfuck)
2. [Esolang Interpreters #2 - Custom Smallfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-2-custom-smallfuck-interpreter)
3. **Esolang Interpreters #3 - Custom Paintfuck Interpreter**
4. [Esolang Interpreters #4 - Boolfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-4-boolfuck-interpreter)
|
Python
|
seed_373
|
# Exclusive "or" (xor) Logical Operator
## Overview
In some scripting languages like PHP, there exists a logical operator (e.g. ```&&```, ```||```, ```and```, ```or```, etc.) called the "Exclusive Or" (hence the name of this Kata). The exclusive or evaluates two booleans. It then returns true if **exactly one of the two expressions are true**, false otherwise. For example:
## Task
Since we cannot define keywords in Javascript (well, at least I don't know how to do it), your task is to define a function ```xor(a, b)``` where a and b are the two expressions to be evaluated. Your ```xor``` function should have the behaviour described above, returning true if **exactly one of the two expressions evaluate to true**, false otherwise.
|
Python
|
seed_374
|
# Explanation
It's your first day in the robot factory and your supervisor thinks that you should start with an easy task. So you are responsible for purchasing raw materials needed to produce the robots.
A complete robot weights `50` kilogram. Iron is the only material needed to create a robot. All iron is inserted in the first machine; the output of this machine is the input for the next one, and so on. The whole process is sequential. Unfortunately not all machines are first class, so a given percentage of their inputs are destroyed during processing.
# Task
You need to figure out how many kilograms of iron you need to buy to build the requested number of robots.
# Example
Three machines are used to create a robot. Each of them produces `10%` scrap. Your target is to deliver `90` robots.
The method will be called with the following parameters:
```
CalculateScrap(scrapOfTheUsedMachines, numberOfRobotsToProduce)
CalculateScrap(int[] { 10, 10, 10 }, 90)
```
# Assumptions
* The scrap is less than `100%`.
* The scrap is never negative.
* There is at least one machine in the manufacturing line.
* Except for scrap there is no material lost during manufacturing.
* The number of produced robots is always a positive number.
* You can only buy full kilograms of iron.
|
Python
|
seed_375
|
# FISH
It was told by Scheherazade that far away, in the middle of the desert, there is a lake. Originally this lake had F fish in it. K different kinds of gemstones were chosen among the most valuable on Earth, and to each of the F fish exactly one gem was given for it to swallow. Note, that since K might be less than F, two or more fish might swallow gems of the same kind.
As time went by, some fish ate some of the other fish. One fish can eat another if and only if it is at least twice as long (fish A can eat fish B if and only if L_A >= 2 * L_B). There is no rule as to when a fish decides to eat. One fish might decide to eat several smaller fish one after another, while some fish may decide not to eat any fish, even if they can. When a fish eats a smaller one, its length doesnβt change, but the gems in the stomach of the smaller fish end up undamaged in the stomach of the larger fish.
Scheherazade has said that if you are able to find the lake, you will be allowed to take out one fish and keep all the gems in its stomach for yourself. You are willing to try your luck, but before you head out on the long journey, you want to know how many different combinations of gems you could obtain by catching a single fish.
### TASK
Write a program that given the length of each fish and the kind of gemstone originally swallowed by each fish, finds the number of different combinations of gems that can end up in the stomach of any fish, modulo some given integer M. A combination is defined only by the number of gems from each of the K kinds. There is no notion of order between gems, and any two gems of the same kind are indistinguishable.
### INPUT
Your program must read from the standard input the following data:
- Line 1 contains the integer F, the original number of fish in the lake.
- Line 2 contains the integer K, the number of kinds of gemstones.
- Line 3 contains the integer M.
- Each of the following F lines describes one fish using 2 integers separated by a single space: the length of the fish followed by the kind of gemstone originally swallowed by that fish.
**NOTE:** For all test cases used for evaluation, it is guaranteed that there is at least one gemstone from each of the K kinds.
### OUTPUT
Your program must write to the standard output a single line containing one integer between 0 and M-1 (inclusive): the number of different possible combinations of gemstones modulo M.
Note that for solving the task, the value of M has no importance other than simplifying computations.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
|
Python
|
seed_376
|
# Farmer
## Problem
A farmer has a set of fields, each of which is surrounded by cypress trees. Also, the farmer has a set of strips of land, each of which has a row of cypress trees. In both fields and strips, between every two consecutive cypress trees is a single olive tree. All of the farmerβs cypress trees either surround a field or are in a strip and all of the farmerβs olive trees are between two consecutive cypress trees in a field or in a strip.
One day the farmer became very ill and he felt that he was going to die. A few days before he passed away he called his eldest son and told him,
> βI give you any $Q$ cypress trees of your choice and all the olive trees which are between any two consecutive cypress trees you have chosen.β
From each field and from each strip the son can pick any combination of cypress trees. Since the eldest son loves olives he wants to pick the $Q$ cypress trees which will allow him to inherit as many olive trees as possible.

**Figure 1.** An example setting of cypress trees; olive trees are not shown.
In Figure 1, assume that the son is given $Q=17$ cypress trees. To maximize his olive inheritance he should choose all the cypress trees in Field 1 and Field 2, inheriting 17 olive trees.
You are to write a program which, given the information about the fields and the strips and the number of cypress trees the son can pick, determines the largest possible number of olive trees the son may inherit.
## Input
The input file name is `farmer.in`. The first line contains first the integer $Q$: the number of cypress trees the son is to select; then the integer $M$, the number of fields; and then the integer $K$, the number of strips. The second line contains $M$ integers $N_1, N_2, \dots, N_M$: the numbers of cypress trees in fields. The third line contains $K$ integers $R_1, R_2, \dots, R_K$: the numbers of cypress trees in strips.
## Output
The output file name is `farmer.out`. The file is to contain one line with one integer: the largest possible number of olive trees the son may inherit.
## Example Inputs and Outputs
**Input:** (`farmer.in`)
```
17 3 3
13 4 8
4 8 6
```
**Output:** (`farmer.out`)
```
17
```
## Constraints
In all inputs, $0 \leq Q \leq 150000$, $0 \leq M \leq 2000$, $0 \leq K \leq 2000$, $3 \leq N_i \leq 150$ for $i = 1, 2, \dots, M$, $2 \leq R_j \leq 150$ for $j = 1, 2, \dots, K$. The total number of cypress trees in the fields and strips is at least $Q$. Additionally, in 50% of the inputs, $Q \leq 1500$.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
|
Python
|
seed_379
|
# Finding Routers (routers)
There is a street of length l meters stretching from left to right, with n small routers occupying various distinct positions along it. The origin is defined to be the leftmost point of the street. The routers are labelled 0 to n β 1 from left to right, and router i is placed p[i] meters away from the origin.
It is guaranteed that router 0 is at the origin, and the distance in meters from each router to the origin is an even integer.
You wish to find out the position of each of the n routers. As the routers are very small and difficult to spot from afar, you've decided to use the following procedure to find them:
- Place a detector on a spot that is x meters away from the origin,
- Use the detector to find the label of the router closest to it. If there are two routers that are the same distance away from it, it will respond with the router with the smaller label.
You are allowed to use the detector at most q times. Devise a strategy to find the positions of all the routers.
## Implementation Details
You should implement the following procedure:
```
int[] find_routers(int l, int n, int q)
```
- l: length of the street in meters.
- n: number of routers.
- q: maximum number of times the detector can be used.
- This procedure will be called exactly once by the grader.
- It should return an array indicating the positions of each router, with p[i] being the distance between router i and the origin.
The above procedure can make calls to the following procedure:
```
int use_detector(int x)
```
- x: distance between the detector and the origin.
- x must be at least 0 and at most l.
- This procedure will return the label of the router closest to the detector. If there are two routers that are the same distance away from it, it will return the smaller label.
- This procedure may be called no more than q times.
## Examples
### Example 1
Consider the following call:
```
find_routers(5, 2, 10)
```
There are 2 routers on a street of length 5 meters and you are allowed at most 10 calls to use_detector. Suppose the routers are placed at 0 and 4 meters away from the origin respectively.
The find_routers procedure may choose to call use_detector(3), which returns 1, as router 1 at position 4 is closest to the detector.
The find_routers procedure may then choose to call use_detector(2), which returns 0, as both routers 0 and 1 are the same distance away from the detector and router 0 has a smaller label.
At this point, there is sufficient information to conclude that the routers are at positions 0 and 4 respectively.
As such, the find_routers procedure should return [0, 4].
### Example 2
Consider the following call:
```
find_routers(6, 3, 10)
```
There are 3 routers on a street of length 6 meters and you are allowed at most 10 calls to use_detector. Suppose the routers are placed at 0, 2 and 6 meters away from the origin respectively.
The find_routers procedure may choose to call use_detector(5), which returns 2 as router 2 is at position 6 and therefore is the closest to the detector.
The find_routers procedure may then choose to call use_detector(4), which returns 1, as routers 1 and 2 are an equal distance away from the detector.
At this point, there is sufficient information to conclude that the routers are at positions 0, 2 and 6 respectively.
As such, the find_routers procedure should return [0, 2, 6].
## Constraints
* $p[0] = 0$
* $0 < p[i] \le l$ and $p[i]$ is even. (for all $0 \le i \le n - 1$)
* $p[i] < p[i + 1]$ (for all $0 \le i \le n - 2$)
* $5 \le l \le 100\,000$
* $l = 100\,000, n = 1000, q = 20\,000$
* Let $m$ be the maximum number of times `use_detector` is called among all testcases.
* If $m > 20000$, you will score $0$ points.
* If $7500 < m \le 20\,000$, you will score $(20\,000-m)/12\,500 \cdot 40$ points.
* If $m \le 7500$, you will score $40$ points.
## Sample grader
The sample grader reads the input in the following format:
- line 1: l n q
- line 2: p[0] p[1] ... p[n β 1]
The sample grader prints your answers in the following format:
- line 1: p[0] p[1] ... p[n β 1] as reported by find_routers.
- line 2: the number of calls to use_detector.
|
Python
|
seed_380
|
# Finding Routers (routers)
There is a street of length l meters stretching from left to right, with n small routers occupying various distinct positions along it. The origin is defined to be the leftmost point of the street. The routers are labelled 0 to n β 1 from left to right, and router i is placed p[i] meters away from the origin.
It is guaranteed that router 0 is at the origin, and the distance in meters from each router to the origin is an even integer.
You wish to find out the position of each of the n routers. As the routers are very small and difficult to spot from afar, you've decided to use the following procedure to find them:
- Place a detector on a spot that is x meters away from the origin,
- Use the detector to find the label of the router closest to it. If there are two routers that are the same distance away from it, it will respond with the router with the smaller label.
You are allowed to use the detector at most q times. Devise a strategy to find the positions of all the routers.
## Implementation Details
You should implement the following procedure:
```
int[] find_routers(int l, int n, int q)
```
- l: length of the street in meters.
- n: number of routers.
- q: maximum number of times the detector can be used.
- This procedure will be called exactly once by the grader.
- It should return an array indicating the positions of each router, with p[i] being the distance between router i and the origin.
The above procedure can make calls to the following procedure:
```
int use_detector(int x)
```
- x: distance between the detector and the origin.
- x must be at least 0 and at most l.
- This procedure will return the label of the router closest to the detector. If there are two routers that are the same distance away from it, it will return the smaller label.
- This procedure may be called no more than q times.
## Examples
### Example 1
Consider the following call:
```
find_routers(5, 2, 10)
```
There are 2 routers on a street of length 5 meters and you are allowed at most 10 calls to use_detector. Suppose the routers are placed at 0 and 4 meters away from the origin respectively.
The find_routers procedure may choose to call use_detector(3), which returns 1, as router 1 at position 4 is closest to the detector.
The find_routers procedure may then choose to call use_detector(2), which returns 0, as both routers 0 and 1 are the same distance away from the detector and router 0 has a smaller label.
At this point, there is sufficient information to conclude that the routers are at positions 0 and 4 respectively.
As such, the find_routers procedure should return [0, 4].
### Example 2
Consider the following call:
```
find_routers(6, 3, 10)
```
There are 3 routers on a street of length 6 meters and you are allowed at most 10 calls to use_detector. Suppose the routers are placed at 0, 2 and 6 meters away from the origin respectively.
The find_routers procedure may choose to call use_detector(5), which returns 2 as router 2 is at position 6 and therefore is the closest to the detector.
The find_routers procedure may then choose to call use_detector(4), which returns 1, as routers 1 and 2 are an equal distance away from the detector.
At this point, there is sufficient information to conclude that the routers are at positions 0, 2 and 6 respectively.
As such, the find_routers procedure should return [0, 2, 6].
## Constraints
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
* $p[0] = 0$
* $0 < p[i] \le l$ and $p[i]$ is even. (for all $0 \le i \le n - 1$)
* $p[i] < p[i + 1]$ (for all $0 \le i \le n - 2$)
* $5 \le l \le 100\,000$
* $l = 100\,000, n = 100, q = 100\,001$
## Sample grader
The sample grader reads the input in the following format:
- line 1: l n q
- line 2: p[0] p[1] ... p[n β 1]
The sample grader prints your answers in the following format:
- line 1: p[0] p[1] ... p[n β 1] as reported by find_routers.
- line 2: the number of calls to use_detector.
|
Python
|
seed_381
|
# Finding Routers (routers)
There is a street of length l meters stretching from left to right, with n small routers occupying various distinct positions along it. The origin is defined to be the leftmost point of the street. The routers are labelled 0 to n β 1 from left to right, and router i is placed p[i] meters away from the origin.
It is guaranteed that router 0 is at the origin, and the distance in meters from each router to the origin is an even integer.
You wish to find out the position of each of the n routers. As the routers are very small and difficult to spot from afar, you've decided to use the following procedure to find them:
- Place a detector on a spot that is x meters away from the origin,
- Use the detector to find the label of the router closest to it. If there are two routers that are the same distance away from it, it will respond with the router with the smaller label.
You are allowed to use the detector at most q times. Devise a strategy to find the positions of all the routers.
## Implementation Details
You should implement the following procedure:
```
int[] find_routers(int l, int n, int q)
```
- l: length of the street in meters.
- n: number of routers.
- q: maximum number of times the detector can be used.
- This procedure will be called exactly once by the grader.
- It should return an array indicating the positions of each router, with p[i] being the distance between router i and the origin.
The above procedure can make calls to the following procedure:
```
int use_detector(int x)
```
- x: distance between the detector and the origin.
- x must be at least 0 and at most l.
- This procedure will return the label of the router closest to the detector. If there are two routers that are the same distance away from it, it will return the smaller label.
- This procedure may be called no more than q times.
## Examples
### Example 1
Consider the following call:
```
find_routers(5, 2, 10)
```
There are 2 routers on a street of length 5 meters and you are allowed at most 10 calls to use_detector. Suppose the routers are placed at 0 and 4 meters away from the origin respectively.
The find_routers procedure may choose to call use_detector(3), which returns 1, as router 1 at position 4 is closest to the detector.
The find_routers procedure may then choose to call use_detector(2), which returns 0, as both routers 0 and 1 are the same distance away from the detector and router 0 has a smaller label.
At this point, there is sufficient information to conclude that the routers are at positions 0 and 4 respectively.
As such, the find_routers procedure should return [0, 4].
### Example 2
Consider the following call:
```
find_routers(6, 3, 10)
```
There are 3 routers on a street of length 6 meters and you are allowed at most 10 calls to use_detector. Suppose the routers are placed at 0, 2 and 6 meters away from the origin respectively.
The find_routers procedure may choose to call use_detector(5), which returns 2 as router 2 is at position 6 and therefore is the closest to the detector.
The find_routers procedure may then choose to call use_detector(4), which returns 1, as routers 1 and 2 are an equal distance away from the detector.
At this point, there is sufficient information to conclude that the routers are at positions 0, 2 and 6 respectively.
As such, the find_routers procedure should return [0, 2, 6].
## Constraints
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
* $p[0] = 0$
* $0 < p[i] \le l$ and $p[i]$ is even. (for all $0 \le i \le n - 1$)
* $p[i] < p[i + 1]$ (for all $0 \le i \le n - 2$)
* $5 \le l \le 100\,000$
* $l = 100\,000, n = 2, q = 100\,001$
## Sample grader
The sample grader reads the input in the following format:
- line 1: l n q
- line 2: p[0] p[1] ... p[n β 1]
The sample grader prints your answers in the following format:
- line 1: p[0] p[1] ... p[n β 1] as reported by find_routers.
- line 2: the number of calls to use_detector.
|
Python
|
seed_382
|
# Finding Routers (routers)
There is a street of length l meters stretching from left to right, with n small routers occupying various distinct positions along it. The origin is defined to be the leftmost point of the street. The routers are labelled 0 to n β 1 from left to right, and router i is placed p[i] meters away from the origin.
It is guaranteed that router 0 is at the origin, and the distance in meters from each router to the origin is an even integer.
You wish to find out the position of each of the n routers. As the routers are very small and difficult to spot from afar, you've decided to use the following procedure to find them:
- Place a detector on a spot that is x meters away from the origin,
- Use the detector to find the label of the router closest to it. If there are two routers that are the same distance away from it, it will respond with the router with the smaller label.
You are allowed to use the detector at most q times. Devise a strategy to find the positions of all the routers.
## Implementation Details
You should implement the following procedure:
```
int[] find_routers(int l, int n, int q)
```
- l: length of the street in meters.
- n: number of routers.
- q: maximum number of times the detector can be used.
- This procedure will be called exactly once by the grader.
- It should return an array indicating the positions of each router, with p[i] being the distance between router i and the origin.
The above procedure can make calls to the following procedure:
```
int use_detector(int x)
```
- x: distance between the detector and the origin.
- x must be at least 0 and at most l.
- This procedure will return the label of the router closest to the detector. If there are two routers that are the same distance away from it, it will return the smaller label.
- This procedure may be called no more than q times.
## Examples
### Example 1
Consider the following call:
```
find_routers(5, 2, 10)
```
There are 2 routers on a street of length 5 meters and you are allowed at most 10 calls to use_detector. Suppose the routers are placed at 0 and 4 meters away from the origin respectively.
The find_routers procedure may choose to call use_detector(3), which returns 1, as router 1 at position 4 is closest to the detector.
The find_routers procedure may then choose to call use_detector(2), which returns 0, as both routers 0 and 1 are the same distance away from the detector and router 0 has a smaller label.
At this point, there is sufficient information to conclude that the routers are at positions 0 and 4 respectively.
As such, the find_routers procedure should return [0, 4].
### Example 2
Consider the following call:
```
find_routers(6, 3, 10)
```
There are 3 routers on a street of length 6 meters and you are allowed at most 10 calls to use_detector. Suppose the routers are placed at 0, 2 and 6 meters away from the origin respectively.
The find_routers procedure may choose to call use_detector(5), which returns 2 as router 2 is at position 6 and therefore is the closest to the detector.
The find_routers procedure may then choose to call use_detector(4), which returns 1, as routers 1 and 2 are an equal distance away from the detector.
At this point, there is sufficient information to conclude that the routers are at positions 0, 2 and 6 respectively.
As such, the find_routers procedure should return [0, 2, 6].
## Constraints
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
* $p[0] = 0$
* $0 < p[i] \le l$ and $p[i]$ is even. (for all $0 \le i \le n - 1$)
* $p[i] < p[i + 1]$ (for all $0 \le i \le n - 2$)
* $5 \le l \le 100\,000$
* $l = 100\,000, n = 2, q = 20$
## Sample grader
The sample grader reads the input in the following format:
- line 1: l n q
- line 2: p[0] p[1] ... p[n β 1]
The sample grader prints your answers in the following format:
- line 1: p[0] p[1] ... p[n β 1] as reported by find_routers.
- line 2: the number of calls to use_detector.
|
Python
|
seed_384
|
# Fix the Bugs (Syntax) - My First Kata
## Overview
Hello, this is my first Kata so forgive me if it is of poor quality.
In this Kata you should fix/create a program that ```return```s the following values:
- ```false/False``` if either a or b (or both) are not numbers
- ```a % b``` plus ```b % a``` if both arguments are numbers
You may assume the following:
1. If ```a``` and ```b``` are both numbers, neither of ```a``` or ```b``` will be ```0```.
## Language-Specific Instructions
### Javascript and PHP
In this Kata you should try to fix all the syntax errors found in the code.
Once you think all the bugs are fixed run the code to see if it works. A correct solution should return the values specified in the overview.
**Extension: Once you have fixed all the syntax errors present in the code (basic requirement), you may attempt to optimise the code or try a different approach by coding it from scratch.**
|
Python
|
seed_385
|
# Forbidden Subgraph
**IOI'06**
Official version
Day 1 -- Task 3
English
Version 1.2
## FORBIDDEN SUBGRAPH
Two undirected graphs $G$ and $H$ are said to be *isomorphic* if:
- they have the same number of vertices and
- a one-to-one correspondence exists between their vertices so that, for any two distinct vertices of $G$, there exists an edge between them if and only if there exists an edge between their corresponding vertices in $H$.
For example, the next two graphs are isomorphic, even though they look different here:

A possible one-to-one correspondence showing that these two graphs are isomorphic is given by $\{a \to 1, b \to 6, c \to 8, d \to 3, g \to 5, h \to 2, i \to 4, j \to 7\}$, but others exist too.
A *subgraph* of a graph $G$ is a graph whose sets of vertices and edges are subsets of those in $G$. Note that $G$ is a subgraph of itself. The following example shows a graph and one of its subgraphs:

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

## TASK
Given two undirected graphs $G$ and $H$, produce a subgraph $G'$ of $G$ such that:
- the number of vertices in $G$ and $G'$ is the same and
- $H$ is not contained in $G'$.
Naturally, there may be many subgraphs $G'$ with the above properties. Produce one of those subgraphs with as many edges as possible.
## Base Algorithm
Perhaps the most basic strategy to approach this problem is to consider the edges of $G$ in the order that they are represented in the input file, then attempting to add them one by one to $G'$, verifying at each step whether $H$ is contained in $G'$ or not. The correct implementation of this greedy algorithm will earn some points, but much better strategies exist.
## CONSTRAINTS
- $3 \leq m \leq 4$
The number of vertices of $H$.
- $3 \leq n \leq 1000$
The number of vertices of $G$.
## INPUT
You will be given 10 files `forbidden1.in` to `forbidden10.in` each with the following data:
| **`forbiddenK.in`** | **DESCRIPTION** |
|---------------------|-----------------|
| LINE 1: | Contains two space-separated integers, respectively: $m$ and $n$. |
| NEXT $m$ LINES: | Each line contains $m$ space-separated integers and represents one vertex of $H$ in the order $1, \dots, m$. The $i$-th element of the $j$-th line in this section is equal to $1$ if vertices $i$ and $j$ are joined by an edge in $H$ and is equal to $0$ otherwise. |
| NEXT $n$ LINES: | Each line contains $n$ space-separated integers and represents one vertex of $G$ in the order $1, \dots, n$. The $i$-th element of the $j$-th line in this section is equal to $1$ if vertices $i$ and $j$ are joined by an edge in $G$ and is equal to $0$ otherwise. |
Observe that, except for line 1, the above input represents the adjacency matrices of $H$ and $G$.
## OUTPUT
You must produce 10 files, one for each of the inputs. Each file must contain the following data:
| **`forbiddenK.out`** | **DESCRIPTION** |
|----------------------|-----------------|
| LINE 1: | The file header. The file header must contain `#FILE forbidden K` where $K$ is a number between $1$ and $10$ that corresponds to the input file solved. |
| LINE 2: | Contains one integer: $n$. |
| NEXT $n$ LINES: | Each line contains $n$ space-separated integers and represents one vertex of $G'$ in the order $1, \dots, n$. The $i$-th element of the $j$-th line in this section is equal to $1$ if vertices $i$ and $j$ are joined by an edge in $G'$, and is $0$ otherwise. |
Observe that, except for lines 1 and 2, the above output represents the adjacency matrix of $G'$. Note that there are many possible outputs, and that the above output is correct but not optimal.
## GRADING
Your score will depend on the number of edges in the $G'$ you output. Your score will be determined in the following way: you will receive a non-zero score for each output file only if it meets the task specification. If it does, your score will be calculated as follows. Let $E_f$ be the number of edges in your output, let $E_b$ be the number of edges in $G'$ as computed by the BASE ALGORITHM, and let $E_m$ be the maximum number of edges in the output of any of the contestants' submissions. Your score for the case will be:
\[
30 \cdot \frac{E_f}{E_b} \quad \text{if } E_f \leq E_b, \quad \text{or} \quad 30 + 70 \cdot \frac{(E_f - E_b)}{(E_m - E_b)} \quad \text{if } E_f > E_b.
\]
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
|
Python
|
seed_386
|
# Fountain Parks
In a nearby park, there are n fountains, labeled from 0 to n β 1. We model the fountains as points on a two-dimensional plane. Namely, fountain i (0 β€ i β€ n β 1) is a point (x[i], y[i]) where x[i] and y[i] are even integers. The locations of the fountains are all distinct.
Timothy the architect has been hired to plan the construction of some roads and the placement of one bench per road. A road is a horizontal or vertical line segment of length 2, whose endpoints are two distinct fountains. The roads should be constructed such that one can travel between any two fountains by moving along roads. Initially, there are no roads in the park.
For each road, exactly one bench needs to be placed in the park and assigned to (i.e., face) that road. Each bench must be placed at some point (a, b) such that a and b are odd integers. The locations of the benches must be all distinct. A bench at (a, b) can only be assigned to a road if both of the road's endpoints are among (a β 1, b β 1), (a β 1, b + 1), (a + 1, b β 1) and (a + 1, b + 1). For example, the bench at (3, 3) can only be assigned to a road, which is one of the four line segments (2, 2) β (2, 4), (2, 4) β (4, 4), (4, 4) β (4, 2), (4, 2) β (2, 2).
Help Timothy determine if it is possible to construct roads, and place and assign benches satisfying all conditions given above, and if so, provide him with a feasible solution. If there are multiple feasible solutions that satisfy all conditions, you can report any of them.
## Implementation Details
You should implement the following procedure:
```
int construct_roads(int[] x, int[] y)
```
- x, y: two arrays of length n. For each i (0 β€ i β€ n β 1), fountain i is a point (x[i], y[i]), where x[i] and y[i] are even integers.
- If a construction is possible, this procedure should make exactly one call to build (see below) to report a solution, following which it should return 1.
- Otherwise, the procedure should return 0 without making any calls to build.
- This procedure is called exactly once.
Your implementation can call the following procedure to provide a feasible construction of roads and a placement of benches:
```
void build(int[] u, int[] v, int[] a, int[] b)
```
- Let m be the total number of roads in the construction.
- u, v: two arrays of length m, representing the roads to be constructed. These roads are labeled from 0 to m β 1. For each j (0 β€ j β€ m β 1), road j connects fountains u[j] and v[j]. Each road must be a horizontal or vertical line segment of length 2. Any two distinct roads can have at most one point in common (a fountain). Once the roads are constructed, it should be possible to travel between any two fountains by moving along roads.
- a, b: two arrays of length m, representing the benches. For each j (0 β€ j β€ m β 1), a bench is placed at (a[j], b[j]), and is assigned to road j. No two distinct benches can have the same location.
## Examples
### Example 1
Consider the following call:
```
construct_roads([4, 4, 6, 4, 2], [4, 6, 4, 2, 4])
```
This means that there are 5 fountains:
- fountain 0 is located at (4, 4),
- fountain 1 is located at (4, 6),
- fountain 2 is located at (6, 4),
- fountain 3 is located at (4, 2),
- fountain 4 is located at (2, 4).
It is possible to construct the following 4 roads, where each road connects two fountains, and place the corresponding benches:
| Road label | Labels of the fountains the road connects | Location of the assigned bench |
|------------|-------------------------------------------|--------------------------------|
| 0 | 0, 2 | (5, 5) |
| 1 | 0, 1 | (3, 5) |
| 2 | 3, 0 | (5, 3) |
| 3 | 4, 0 | (3, 3) |
To report this solution, construct_roads should make the following call:
```
build([0, 0, 3, 4], [2, 1, 0, 0], [5, 3, 5, 3], [5, 5, 3, 3])
```
It should then return 1.
Note that in this case, there are multiple solutions that satisfy the requirements, all of which would be considered correct. For example, it is also correct to call build([1, 2, 3, 4], [0, 0, 0, 0], [5, 5, 3, 3], [5, 3, 3, 5]) and then return 1.
### Example 2
Consider the following call:
```
construct_roads([2, 4], [2, 6])
```
Fountain 0 is located at (2, 2) and fountain 1 is located at (4, 6). Since there is no way to construct roads that satisfy the requirements, construct_roads should return 0 without making any call to build.
## Constraints
* $1 \le n \le 200\,000$
* $2 \le x[i], y[i] \le 200\,000$ (for all $0 \le i \le n - 1$)
* $x[i]$ and $y[i]$ are even integers (for all $0 \le i \le n - 1$).
* No two fountains have the same location.
## Sample Grader
The sample grader reads the input in the following format:
- line 1: n
- line 2 + i (0 β€ i β€ n β 1): x[i] y[i]
The output of the sample grader is in the following format:
- line 1: the return value of construct_roads
If the return value of construct_roads is 1 and build(u, v, a, b) is called, the grader then additionally prints:
- line 2: m
- line 3 + j (0 β€ j β€ m β 1): u[j] v[j] a[j] b[j]
|
Python
|
seed_387
|
# Fountain Parks
In a nearby park, there are n fountains, labeled from 0 to n β 1. We model the fountains as points on a two-dimensional plane. Namely, fountain i (0 β€ i β€ n β 1) is a point (x[i], y[i]) where x[i] and y[i] are even integers. The locations of the fountains are all distinct.
Timothy the architect has been hired to plan the construction of some roads and the placement of one bench per road. A road is a horizontal or vertical line segment of length 2, whose endpoints are two distinct fountains. The roads should be constructed such that one can travel between any two fountains by moving along roads. Initially, there are no roads in the park.
For each road, exactly one bench needs to be placed in the park and assigned to (i.e., face) that road. Each bench must be placed at some point (a, b) such that a and b are odd integers. The locations of the benches must be all distinct. A bench at (a, b) can only be assigned to a road if both of the road's endpoints are among (a β 1, b β 1), (a β 1, b + 1), (a + 1, b β 1) and (a + 1, b + 1). For example, the bench at (3, 3) can only be assigned to a road, which is one of the four line segments (2, 2) β (2, 4), (2, 4) β (4, 4), (4, 4) β (4, 2), (4, 2) β (2, 2).
Help Timothy determine if it is possible to construct roads, and place and assign benches satisfying all conditions given above, and if so, provide him with a feasible solution. If there are multiple feasible solutions that satisfy all conditions, you can report any of them.
## Implementation Details
You should implement the following procedure:
```
int construct_roads(int[] x, int[] y)
```
- x, y: two arrays of length n. For each i (0 β€ i β€ n β 1), fountain i is a point (x[i], y[i]), where x[i] and y[i] are even integers.
- If a construction is possible, this procedure should make exactly one call to build (see below) to report a solution, following which it should return 1.
- Otherwise, the procedure should return 0 without making any calls to build.
- This procedure is called exactly once.
Your implementation can call the following procedure to provide a feasible construction of roads and a placement of benches:
```
void build(int[] u, int[] v, int[] a, int[] b)
```
- Let m be the total number of roads in the construction.
- u, v: two arrays of length m, representing the roads to be constructed. These roads are labeled from 0 to m β 1. For each j (0 β€ j β€ m β 1), road j connects fountains u[j] and v[j]. Each road must be a horizontal or vertical line segment of length 2. Any two distinct roads can have at most one point in common (a fountain). Once the roads are constructed, it should be possible to travel between any two fountains by moving along roads.
- a, b: two arrays of length m, representing the benches. For each j (0 β€ j β€ m β 1), a bench is placed at (a[j], b[j]), and is assigned to road j. No two distinct benches can have the same location.
## Examples
### Example 1
Consider the following call:
```
construct_roads([4, 4, 6, 4, 2], [4, 6, 4, 2, 4])
```
This means that there are 5 fountains:
- fountain 0 is located at (4, 4),
- fountain 1 is located at (4, 6),
- fountain 2 is located at (6, 4),
- fountain 3 is located at (4, 2),
- fountain 4 is located at (2, 4).
It is possible to construct the following 4 roads, where each road connects two fountains, and place the corresponding benches:
| Road label | Labels of the fountains the road connects | Location of the assigned bench |
|------------|-------------------------------------------|--------------------------------|
| 0 | 0, 2 | (5, 5) |
| 1 | 0, 1 | (3, 5) |
| 2 | 3, 0 | (5, 3) |
| 3 | 4, 0 | (3, 3) |
To report this solution, construct_roads should make the following call:
```
build([0, 0, 3, 4], [2, 1, 0, 0], [5, 3, 5, 3], [5, 5, 3, 3])
```
It should then return 1.
Note that in this case, there are multiple solutions that satisfy the requirements, all of which would be considered correct. For example, it is also correct to call build([1, 2, 3, 4], [0, 0, 0, 0], [5, 5, 3, 3], [5, 3, 3, 5]) and then return 1.
### Example 2
Consider the following call:
```
construct_roads([2, 4], [2, 6])
```
Fountain 0 is located at (2, 2) and fountain 1 is located at (4, 6). Since there is no way to construct roads that satisfy the requirements, construct_roads should return 0 without making any call to build.
## Constraints
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
* $1 \le n \le 200\,000$
* $2 \le x[i], y[i] \le 200\,000$ (for all $0 \le i \le n - 1$)
* $x[i]$ and $y[i]$ are even integers (for all $0 \le i \le n - 1$).
* No two fountains have the same location.
* $2 \le x[i] \le 4$ (for all $0 \le i \le n - 1$)
## Sample Grader
The sample grader reads the input in the following format:
- line 1: n
- line 2 + i (0 β€ i β€ n β 1): x[i] y[i]
The output of the sample grader is in the following format:
- line 1: the return value of construct_roads
If the return value of construct_roads is 1 and build(u, v, a, b) is called, the grader then additionally prints:
- line 2: m
- line 3 + j (0 β€ j β€ m β 1): u[j] v[j] a[j] b[j]
|
Python
|
seed_388
|
# Fountain Parks
In a nearby park, there are n fountains, labeled from 0 to n β 1. We model the fountains as points on a two-dimensional plane. Namely, fountain i (0 β€ i β€ n β 1) is a point (x[i], y[i]) where x[i] and y[i] are even integers. The locations of the fountains are all distinct.
Timothy the architect has been hired to plan the construction of some roads and the placement of one bench per road. A road is a horizontal or vertical line segment of length 2, whose endpoints are two distinct fountains. The roads should be constructed such that one can travel between any two fountains by moving along roads. Initially, there are no roads in the park.
For each road, exactly one bench needs to be placed in the park and assigned to (i.e., face) that road. Each bench must be placed at some point (a, b) such that a and b are odd integers. The locations of the benches must be all distinct. A bench at (a, b) can only be assigned to a road if both of the road's endpoints are among (a β 1, b β 1), (a β 1, b + 1), (a + 1, b β 1) and (a + 1, b + 1). For example, the bench at (3, 3) can only be assigned to a road, which is one of the four line segments (2, 2) β (2, 4), (2, 4) β (4, 4), (4, 4) β (4, 2), (4, 2) β (2, 2).
Help Timothy determine if it is possible to construct roads, and place and assign benches satisfying all conditions given above, and if so, provide him with a feasible solution. If there are multiple feasible solutions that satisfy all conditions, you can report any of them.
## Implementation Details
You should implement the following procedure:
```
int construct_roads(int[] x, int[] y)
```
- x, y: two arrays of length n. For each i (0 β€ i β€ n β 1), fountain i is a point (x[i], y[i]), where x[i] and y[i] are even integers.
- If a construction is possible, this procedure should make exactly one call to build (see below) to report a solution, following which it should return 1.
- Otherwise, the procedure should return 0 without making any calls to build.
- This procedure is called exactly once.
Your implementation can call the following procedure to provide a feasible construction of roads and a placement of benches:
```
void build(int[] u, int[] v, int[] a, int[] b)
```
- Let m be the total number of roads in the construction.
- u, v: two arrays of length m, representing the roads to be constructed. These roads are labeled from 0 to m β 1. For each j (0 β€ j β€ m β 1), road j connects fountains u[j] and v[j]. Each road must be a horizontal or vertical line segment of length 2. Any two distinct roads can have at most one point in common (a fountain). Once the roads are constructed, it should be possible to travel between any two fountains by moving along roads.
- a, b: two arrays of length m, representing the benches. For each j (0 β€ j β€ m β 1), a bench is placed at (a[j], b[j]), and is assigned to road j. No two distinct benches can have the same location.
## Examples
### Example 1
Consider the following call:
```
construct_roads([4, 4, 6, 4, 2], [4, 6, 4, 2, 4])
```
This means that there are 5 fountains:
- fountain 0 is located at (4, 4),
- fountain 1 is located at (4, 6),
- fountain 2 is located at (6, 4),
- fountain 3 is located at (4, 2),
- fountain 4 is located at (2, 4).
It is possible to construct the following 4 roads, where each road connects two fountains, and place the corresponding benches:
| Road label | Labels of the fountains the road connects | Location of the assigned bench |
|------------|-------------------------------------------|--------------------------------|
| 0 | 0, 2 | (5, 5) |
| 1 | 0, 1 | (3, 5) |
| 2 | 3, 0 | (5, 3) |
| 3 | 4, 0 | (3, 3) |
To report this solution, construct_roads should make the following call:
```
build([0, 0, 3, 4], [2, 1, 0, 0], [5, 3, 5, 3], [5, 5, 3, 3])
```
It should then return 1.
Note that in this case, there are multiple solutions that satisfy the requirements, all of which would be considered correct. For example, it is also correct to call build([1, 2, 3, 4], [0, 0, 0, 0], [5, 5, 3, 3], [5, 3, 3, 5]) and then return 1.
### Example 2
Consider the following call:
```
construct_roads([2, 4], [2, 6])
```
Fountain 0 is located at (2, 2) and fountain 1 is located at (4, 6). Since there is no way to construct roads that satisfy the requirements, construct_roads should return 0 without making any call to build.
## Constraints
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
* $1 \le n \le 200\,000$
* $2 \le x[i], y[i] \le 200\,000$ (for all $0 \le i \le n - 1$)
* $x[i]$ and $y[i]$ are even integers (for all $0 \le i \le n - 1$).
* No two fountains have the same location.
* $2 \le x[i] \le 6$ (for all $0 \le i \le n - 1$)
## Sample Grader
The sample grader reads the input in the following format:
- line 1: n
- line 2 + i (0 β€ i β€ n β 1): x[i] y[i]
The output of the sample grader is in the following format:
- line 1: the return value of construct_roads
If the return value of construct_roads is 1 and build(u, v, a, b) is called, the grader then additionally prints:
- line 2: m
- line 3 + j (0 β€ j β€ m β 1): u[j] v[j] a[j] b[j]
|
Python
|
seed_389
|
# Fountain Parks
In a nearby park, there are n fountains, labeled from 0 to n β 1. We model the fountains as points on a two-dimensional plane. Namely, fountain i (0 β€ i β€ n β 1) is a point (x[i], y[i]) where x[i] and y[i] are even integers. The locations of the fountains are all distinct.
Timothy the architect has been hired to plan the construction of some roads and the placement of one bench per road. A road is a horizontal or vertical line segment of length 2, whose endpoints are two distinct fountains. The roads should be constructed such that one can travel between any two fountains by moving along roads. Initially, there are no roads in the park.
For each road, exactly one bench needs to be placed in the park and assigned to (i.e., face) that road. Each bench must be placed at some point (a, b) such that a and b are odd integers. The locations of the benches must be all distinct. A bench at (a, b) can only be assigned to a road if both of the road's endpoints are among (a β 1, b β 1), (a β 1, b + 1), (a + 1, b β 1) and (a + 1, b + 1). For example, the bench at (3, 3) can only be assigned to a road, which is one of the four line segments (2, 2) β (2, 4), (2, 4) β (4, 4), (4, 4) β (4, 2), (4, 2) β (2, 2).
Help Timothy determine if it is possible to construct roads, and place and assign benches satisfying all conditions given above, and if so, provide him with a feasible solution. If there are multiple feasible solutions that satisfy all conditions, you can report any of them.
## Implementation Details
You should implement the following procedure:
```
int construct_roads(int[] x, int[] y)
```
- x, y: two arrays of length n. For each i (0 β€ i β€ n β 1), fountain i is a point (x[i], y[i]), where x[i] and y[i] are even integers.
- If a construction is possible, this procedure should make exactly one call to build (see below) to report a solution, following which it should return 1.
- Otherwise, the procedure should return 0 without making any calls to build.
- This procedure is called exactly once.
Your implementation can call the following procedure to provide a feasible construction of roads and a placement of benches:
```
void build(int[] u, int[] v, int[] a, int[] b)
```
- Let m be the total number of roads in the construction.
- u, v: two arrays of length m, representing the roads to be constructed. These roads are labeled from 0 to m β 1. For each j (0 β€ j β€ m β 1), road j connects fountains u[j] and v[j]. Each road must be a horizontal or vertical line segment of length 2. Any two distinct roads can have at most one point in common (a fountain). Once the roads are constructed, it should be possible to travel between any two fountains by moving along roads.
- a, b: two arrays of length m, representing the benches. For each j (0 β€ j β€ m β 1), a bench is placed at (a[j], b[j]), and is assigned to road j. No two distinct benches can have the same location.
## Examples
### Example 1
Consider the following call:
```
construct_roads([4, 4, 6, 4, 2], [4, 6, 4, 2, 4])
```
This means that there are 5 fountains:
- fountain 0 is located at (4, 4),
- fountain 1 is located at (4, 6),
- fountain 2 is located at (6, 4),
- fountain 3 is located at (4, 2),
- fountain 4 is located at (2, 4).
It is possible to construct the following 4 roads, where each road connects two fountains, and place the corresponding benches:
| Road label | Labels of the fountains the road connects | Location of the assigned bench |
|------------|-------------------------------------------|--------------------------------|
| 0 | 0, 2 | (5, 5) |
| 1 | 0, 1 | (3, 5) |
| 2 | 3, 0 | (5, 3) |
| 3 | 4, 0 | (3, 3) |
To report this solution, construct_roads should make the following call:
```
build([0, 0, 3, 4], [2, 1, 0, 0], [5, 3, 5, 3], [5, 5, 3, 3])
```
It should then return 1.
Note that in this case, there are multiple solutions that satisfy the requirements, all of which would be considered correct. For example, it is also correct to call build([1, 2, 3, 4], [0, 0, 0, 0], [5, 5, 3, 3], [5, 3, 3, 5]) and then return 1.
### Example 2
Consider the following call:
```
construct_roads([2, 4], [2, 6])
```
Fountain 0 is located at (2, 2) and fountain 1 is located at (4, 6). Since there is no way to construct roads that satisfy the requirements, construct_roads should return 0 without making any call to build.
## Constraints
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
* $1 \le n \le 200\,000$
* $2 \le x[i], y[i] \le 200\,000$ (for all $0 \le i \le n - 1$)
* $x[i]$ and $y[i]$ are even integers (for all $0 \le i \le n - 1$).
* No two fountains have the same location.
* $x[i] = 2$ (for all $0 \le i \le n - 1$)
## Sample Grader
The sample grader reads the input in the following format:
- line 1: n
- line 2 + i (0 β€ i β€ n β 1): x[i] y[i]
The output of the sample grader is in the following format:
- line 1: the return value of construct_roads
If the return value of construct_roads is 1 and build(u, v, a, b) is called, the grader then additionally prints:
- line 2: m
- line 3 + j (0 β€ j β€ m β 1): u[j] v[j] a[j] b[j]
|
Python
|
seed_390
|
# Fountain Parks
In a nearby park, there are n fountains, labeled from 0 to n β 1. We model the fountains as points on a two-dimensional plane. Namely, fountain i (0 β€ i β€ n β 1) is a point (x[i], y[i]) where x[i] and y[i] are even integers. The locations of the fountains are all distinct.
Timothy the architect has been hired to plan the construction of some roads and the placement of one bench per road. A road is a horizontal or vertical line segment of length 2, whose endpoints are two distinct fountains. The roads should be constructed such that one can travel between any two fountains by moving along roads. Initially, there are no roads in the park.
For each road, exactly one bench needs to be placed in the park and assigned to (i.e., face) that road. Each bench must be placed at some point (a, b) such that a and b are odd integers. The locations of the benches must be all distinct. A bench at (a, b) can only be assigned to a road if both of the road's endpoints are among (a β 1, b β 1), (a β 1, b + 1), (a + 1, b β 1) and (a + 1, b + 1). For example, the bench at (3, 3) can only be assigned to a road, which is one of the four line segments (2, 2) β (2, 4), (2, 4) β (4, 4), (4, 4) β (4, 2), (4, 2) β (2, 2).
Help Timothy determine if it is possible to construct roads, and place and assign benches satisfying all conditions given above, and if so, provide him with a feasible solution. If there are multiple feasible solutions that satisfy all conditions, you can report any of them.
## Implementation Details
You should implement the following procedure:
```
int construct_roads(int[] x, int[] y)
```
- x, y: two arrays of length n. For each i (0 β€ i β€ n β 1), fountain i is a point (x[i], y[i]), where x[i] and y[i] are even integers.
- If a construction is possible, this procedure should make exactly one call to build (see below) to report a solution, following which it should return 1.
- Otherwise, the procedure should return 0 without making any calls to build.
- This procedure is called exactly once.
Your implementation can call the following procedure to provide a feasible construction of roads and a placement of benches:
```
void build(int[] u, int[] v, int[] a, int[] b)
```
- Let m be the total number of roads in the construction.
- u, v: two arrays of length m, representing the roads to be constructed. These roads are labeled from 0 to m β 1. For each j (0 β€ j β€ m β 1), road j connects fountains u[j] and v[j]. Each road must be a horizontal or vertical line segment of length 2. Any two distinct roads can have at most one point in common (a fountain). Once the roads are constructed, it should be possible to travel between any two fountains by moving along roads.
- a, b: two arrays of length m, representing the benches. For each j (0 β€ j β€ m β 1), a bench is placed at (a[j], b[j]), and is assigned to road j. No two distinct benches can have the same location.
## Examples
### Example 1
Consider the following call:
```
construct_roads([4, 4, 6, 4, 2], [4, 6, 4, 2, 4])
```
This means that there are 5 fountains:
- fountain 0 is located at (4, 4),
- fountain 1 is located at (4, 6),
- fountain 2 is located at (6, 4),
- fountain 3 is located at (4, 2),
- fountain 4 is located at (2, 4).
It is possible to construct the following 4 roads, where each road connects two fountains, and place the corresponding benches:
| Road label | Labels of the fountains the road connects | Location of the assigned bench |
|------------|-------------------------------------------|--------------------------------|
| 0 | 0, 2 | (5, 5) |
| 1 | 0, 1 | (3, 5) |
| 2 | 3, 0 | (5, 3) |
| 3 | 4, 0 | (3, 3) |
To report this solution, construct_roads should make the following call:
```
build([0, 0, 3, 4], [2, 1, 0, 0], [5, 3, 5, 3], [5, 5, 3, 3])
```
It should then return 1.
Note that in this case, there are multiple solutions that satisfy the requirements, all of which would be considered correct. For example, it is also correct to call build([1, 2, 3, 4], [0, 0, 0, 0], [5, 5, 3, 3], [5, 3, 3, 5]) and then return 1.
### Example 2
Consider the following call:
```
construct_roads([2, 4], [2, 6])
```
Fountain 0 is located at (2, 2) and fountain 1 is located at (4, 6). Since there is no way to construct roads that satisfy the requirements, construct_roads should return 0 without making any call to build.
## Constraints
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
* $1 \le n \le 200\,000$
* $2 \le x[i], y[i] \le 200\,000$ (for all $0 \le i \le n - 1$)
* $x[i]$ and $y[i]$ are even integers (for all $0 \le i \le n - 1$).
* No two fountains have the same location.
* There do not exist four fountains that form the corners of a $2 \times 2$ square.
## Sample Grader
The sample grader reads the input in the following format:
- line 1: n
- line 2 + i (0 β€ i β€ n β 1): x[i] y[i]
The output of the sample grader is in the following format:
- line 1: the return value of construct_roads
If the return value of construct_roads is 1 and build(u, v, a, b) is called, the grader then additionally prints:
- line 2: m
- line 3 + j (0 β€ j β€ m β 1): u[j] v[j] a[j] b[j]
|
Python
|
seed_391
|
# Fountain Parks
In a nearby park, there are n fountains, labeled from 0 to n β 1. We model the fountains as points on a two-dimensional plane. Namely, fountain i (0 β€ i β€ n β 1) is a point (x[i], y[i]) where x[i] and y[i] are even integers. The locations of the fountains are all distinct.
Timothy the architect has been hired to plan the construction of some roads and the placement of one bench per road. A road is a horizontal or vertical line segment of length 2, whose endpoints are two distinct fountains. The roads should be constructed such that one can travel between any two fountains by moving along roads. Initially, there are no roads in the park.
For each road, exactly one bench needs to be placed in the park and assigned to (i.e., face) that road. Each bench must be placed at some point (a, b) such that a and b are odd integers. The locations of the benches must be all distinct. A bench at (a, b) can only be assigned to a road if both of the road's endpoints are among (a β 1, b β 1), (a β 1, b + 1), (a + 1, b β 1) and (a + 1, b + 1). For example, the bench at (3, 3) can only be assigned to a road, which is one of the four line segments (2, 2) β (2, 4), (2, 4) β (4, 4), (4, 4) β (4, 2), (4, 2) β (2, 2).
Help Timothy determine if it is possible to construct roads, and place and assign benches satisfying all conditions given above, and if so, provide him with a feasible solution. If there are multiple feasible solutions that satisfy all conditions, you can report any of them.
## Implementation Details
You should implement the following procedure:
```
int construct_roads(int[] x, int[] y)
```
- x, y: two arrays of length n. For each i (0 β€ i β€ n β 1), fountain i is a point (x[i], y[i]), where x[i] and y[i] are even integers.
- If a construction is possible, this procedure should make exactly one call to build (see below) to report a solution, following which it should return 1.
- Otherwise, the procedure should return 0 without making any calls to build.
- This procedure is called exactly once.
Your implementation can call the following procedure to provide a feasible construction of roads and a placement of benches:
```
void build(int[] u, int[] v, int[] a, int[] b)
```
- Let m be the total number of roads in the construction.
- u, v: two arrays of length m, representing the roads to be constructed. These roads are labeled from 0 to m β 1. For each j (0 β€ j β€ m β 1), road j connects fountains u[j] and v[j]. Each road must be a horizontal or vertical line segment of length 2. Any two distinct roads can have at most one point in common (a fountain). Once the roads are constructed, it should be possible to travel between any two fountains by moving along roads.
- a, b: two arrays of length m, representing the benches. For each j (0 β€ j β€ m β 1), a bench is placed at (a[j], b[j]), and is assigned to road j. No two distinct benches can have the same location.
## Examples
### Example 1
Consider the following call:
```
construct_roads([4, 4, 6, 4, 2], [4, 6, 4, 2, 4])
```
This means that there are 5 fountains:
- fountain 0 is located at (4, 4),
- fountain 1 is located at (4, 6),
- fountain 2 is located at (6, 4),
- fountain 3 is located at (4, 2),
- fountain 4 is located at (2, 4).
It is possible to construct the following 4 roads, where each road connects two fountains, and place the corresponding benches:
| Road label | Labels of the fountains the road connects | Location of the assigned bench |
|------------|-------------------------------------------|--------------------------------|
| 0 | 0, 2 | (5, 5) |
| 1 | 0, 1 | (3, 5) |
| 2 | 3, 0 | (5, 3) |
| 3 | 4, 0 | (3, 3) |
To report this solution, construct_roads should make the following call:
```
build([0, 0, 3, 4], [2, 1, 0, 0], [5, 3, 5, 3], [5, 5, 3, 3])
```
It should then return 1.
Note that in this case, there are multiple solutions that satisfy the requirements, all of which would be considered correct. For example, it is also correct to call build([1, 2, 3, 4], [0, 0, 0, 0], [5, 5, 3, 3], [5, 3, 3, 5]) and then return 1.
### Example 2
Consider the following call:
```
construct_roads([2, 4], [2, 6])
```
Fountain 0 is located at (2, 2) and fountain 1 is located at (4, 6). Since there is no way to construct roads that satisfy the requirements, construct_roads should return 0 without making any call to build.
## Constraints
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
* $1 \le n \le 200\,000$
* $2 \le x[i], y[i] \le 200\,000$ (for all $0 \le i \le n - 1$)
* $x[i]$ and $y[i]$ are even integers (for all $0 \le i \le n - 1$).
* No two fountains have the same location.
* There is at most one way of constructing the roads, such that one can travel between any two fountains by moving along roads.
## Sample Grader
The sample grader reads the input in the following format:
- line 1: n
- line 2 + i (0 β€ i β€ n β 1): x[i] y[i]
The output of the sample grader is in the following format:
- line 1: the return value of construct_roads
If the return value of construct_roads is 1 and build(u, v, a, b) is called, the grader then additionally prints:
- line 2: m
- line 3 + j (0 β€ j β€ m β 1): u[j] v[j] a[j] b[j]
|
Python
|
seed_395
|
# GARAGE
**Full Feedback Problem**
A parking garage has $N$ parking spaces, numbered from $1$ to $N$ inclusive. The garage opens empty each morning and operates in the following way throughout the day. Whenever a car arrives at the garage, the attendants check whether there are any parking spaces available. If there are none, then the car waits at the entrance until a parking space is released. If a parking space is available, or as soon as one becomes available, the car is parked in the available parking space. If there is more than one available parking space, the car will be parked at the space with the smallest number. If more cars arrive while some car is waiting, they all line up in a queue at the entrance, in the order in which they arrived.
The cost of parking in dollars is the weight of the car in kilograms multiplied by the specific rate of its parking space. The cost does not depend on how long a car stays in the garage.
The garage operator knows that today there will be $M$ cars coming and he knows the order of their arrivals and departures. Help him calculate how many dollars his revenue is going to be today.
## TASK
Write a program that, given the specific rates of the parking spaces, the weights of the cars and the order in which the cars arrive and depart, determines the total revenue of the garage in dollars.
## CONSTRAINTS
- $1 \leq N \leq 100$ The number of parking spaces
- $1 \leq M \leq 2,000$ The number of cars
- $1 \leq R_s \leq 100$ The rate of parking space $s$ in dollars per kilogram
- $1 \leq W_k \leq 10,000$ The weight of car $k$ in kilograms
## INPUT
Your program must read from standard input the following data:
- The first line contains the integers $N$ and $M$, separated by a space.
- The next $N$ lines describe the rates of the parking spaces. The $s$-th of these lines contains a single integer $R_s$, the rate of parking space number $s$ in dollars per kilogram.
- The next $M$ lines describe the weights of the cars. The cars are numbered from $1$ to $M$ inclusive in no particular order. The $k$-th of these $M$ lines contains a single integer $W_k$, the weight of car $k$ in kilograms.
- The next $2 \times M$ lines describe the arrivals and departures of all cars in chronological order. A positive integer $i$ indicates that car number $i$ arrives at the garage. A negative integer $-i$ indicates that car number $i$ departs from the garage. No car will depart from the garage before it has arrived, and all cars from $1$ to $M$ inclusive will appear exactly twice in this sequence, once arriving and once departing. Moreover, no car will depart the garage before it has parked (i.e., no car will leave while waiting in the queue).
## OUTPUT
Your program must write to standard output a single line containing a single integer: the total number of dollars that will be earned by the garage operator today.
## EXAMPLES
**Sample Input**
```
3 4
2
3
5
200
100
300
800
3
2
-3
1
4
-4
-2
-1
```
**Sample Output**
```
5300
```
**Explanation:**
- Car number $3$ goes to space number $1$ and pays $300 \times 2 = 600$ dollars.
- Car number $2$ goes to space number $2$ and pays $100 \times 3 = 300$ dollars.
- Car number $1$ goes to space number $1$ (which was released by car number $3$) and pays $200 \times 2 = 400$ dollars.
- Car number $4$ goes to space number $3$ (the last remaining) and pays $800 \times 5 = 4,000$ dollars.
**Sample Input**
```
2 4
5
2
100
500
1000
2000
3
1
2
4
-1
-3
-2
-4
```
**Sample Output**
```
16200
```
**Explanation:**
- Car number $3$ goes to space number $1$ and pays $1,000 \times 5 = 5,000$ dollars.
- Car number $1$ goes to space number $2$ and pays $100 \times 2 = 200$ dollars.
- Car number $2$ arrives and has to wait at the entrance.
- Car number $4$ arrives and has to wait at the entrance behind car number $2$.
- When car number $1$ releases its parking space, car number $2$ parks there and pays $500 \times 2 = 1,000$ dollars.
- When car number $3$ releases its parking space, car number $4$ parks there and pays $2,000 \times 5 = 10,000$ dollars.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
|
Python
|
seed_396
|
# Grains
Write a program that calculates the number of grains of wheat on a chessboard given that the number on each square is double the previous one.
There are 64 squares on a chessboard.
#Example:
square(1) = 1
square(2) = 2
square(3) = 4
square(4) = 8
etc...
Write a program that shows how many grains were on each square
|
Python
|
seed_397
|
# Grasshopper - Function syntax debugging
A student was working on a function and made some syntax mistakes while coding. Help them find their mistakes and fix them.
|
Python
|
seed_398
|
# Guess Which Cow (interactive task)
## TASK
The $N$ ($1 \leq N \leq 50$) cows in Farmer John's herd look very much alike and are numbered $1 \ldots N$. When Farmer John puts a cow to bed in her stall, he must determine which cow he is putting to bed so he can put her in the correct stall.
Cows are distinguished using $P$ ($1 \leq P \leq 8$) properties, numbered $1 \ldots P$, each of which has three possible values. For example, the color of a cow's ear tag might be yellow, green, or red. For simplicity, the values of every property are represented as the letters `X`, `Y`, and `Z`. Any pair of Farmer John's cows will differ in at least one property.
Write a program that, given the properties of the cows in Farmer John's herd, helps Farmer John determine which cow he is putting to bed. Your program can ask Farmer John no more than 100 questions of the form: *Is the cow's value for some property $T$ in some set $S$*? Try to ask as few questions as possible to determine the cow.
## Input: `guess.in`
- The first line of the input file contains two space-separated integers, $N$ and $P$.
- Each of the next $N$ lines describes a cow's properties using $P$ space-separated letters. The first letter on each line is the value of property 1, and so on. The second line in the input file describes cow 1, the third line describes cow 2, etc.
## Example input:
```
4 2
X Z
X Y
Y X
Y Y
```
## Interactivity: standard input and output
The question/answer phase takes place via standard input and standard output.
Your program asks a question about the cow being put to bed by writing to standard output a line that is a `Q` followed by a space, the property number, a space, and a space-separated set of one or more values. For example, \"Q 1 Z Y\" means \"Does property 1 have value either `Z` or `Y` for the cow being put to bed?\". The property must be an integer in the range $1 \ldots P$. All values must be `X`, `Y`, or `Z` and no value should be listed more than once for a single question.
After asking each question your program asks, read a single line containing a single integer. The integer 1 means the value of the specified property of the cow being put to bed is in the set of values given; the integer 0 means it is not.
The program's last line of output should be a `C` followed by a space and a single integer that specifies the cow that your program has determined Farmer John is putting to bed.
## Example exchange (for example input above):
| **Input** | **Output** | **Explanation** |
|-----------|------------|-----------------|
| 0 | Q 1 X Z | Could be cow 3 or cow 4. |
| 1 | Q 2 Y | Must be cow 4! |
| | C 4 | program exits |
## CONSTRAINTS
- **Running time:** 1 second of CPU
- **Memory:** 64 MB
## SCORING
**Correctness:** 30% of points
Programs will receive full score on correctness only if the cow specified is the only cow that is consistent with the answers given. A program that asks more than 100 questions for a test case will receive no points for that test case.
**Question count:** 70% of points
The remaining points will be determined by the number of questions required to correctly determine the cow. The test cases are designed to reward minimizing the worst-case question count. Partial credit will be given for near-optimal question counts.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
|
Python
|
seed_399
|
# Handcrafted Gift (gift)
Adam is making Bob a hand-crafted necklace as a gift. A necklace consists of n beads, numbered 0 to n β 1 from left to right. Each bead can either be red or blue in colour. Bob has sent Adam a list of r requirements for the necklace. The i-th requirement (0 β€ i < r) states that the beads from positions a[i] to b[i] inclusive should have x[i] unique colours.
Help Adam find a possible configuration of beads that satisfies all of Bob's requirements, or determine that it is impossible.
## Implementation Details
You should implement the following procedure:
```
int construct(int n, int r, int[] a, int[] b, int[] x)
```
- n: number of beads.
- r: number of requirements.
- a: an array of length r, the starting position of each requirement.
- b: an array of length r, the ending position of each requirement.
- x: an array of length r, the number of unique colours for each requirement.
- This procedure will be called exactly once.
- If a construction is possible, this procedure should make exactly one call to craft to report the construction, following which it should return 1.
- Otherwise, the procedure should return 0 without making any calls to craft.
Your program should call the following procedure to report the construction:
```
void craft(string s)
```
- s, a string of length n, with s[i] equal to 'R' if the i-th bead is red, or 'B' if it is blue.
## Examples
### Example 1
Consider the following call:
```
construct(4, 2, [0, 2], [2, 3], [1, 2])
```
This means that there are a total of 4 beads and 2 requirements as follows:
- positions 0 to 2 should have 1 unique colour,
- positions 2 to 3 should have 2 unique colours.
This can be achieved by colouring beads 0 to 2 red, and bead 3 blue.
Therefore, the construct procedure should make the following call:
```
craft("RRRB")
```
It should then return 1.
In this case, there are multiple constructions that fit the requirements, all of which would be considered correct.
### Example 2
Consider the following call:
```
construct(3, 3, [0, 1, 0], [1, 2, 2], [1, 1, 2])
```
This means that there are a total of 3 beads and 3 requirements as follows:
- positions 0 to 1 should have 1 unique colour,
- positions 1 to 2 should have 1 unique colour,
- positions 0 to 2 should have 2 unique colours.
In this case, there are no possible configuration of beads that satisfy all the requirements.
As such, the construct procedure should return 0 without making any call to craft.
## Constraints
* $1 \le n, r \le 500\,000$
* $0 \le a[i] \le b[i] \le n - 1$ (for all $0 \le i \le r - 1$)
* $1 \le x[i] \le 2$ (for all $0 \le i \le r - 1$)
## Sample grader
The sample grader reads the input in the following format:
- line 1: n r
- line 2 + i (0 β€ i β€ r β 1): a[i] b[i] x[i]
The sample grader prints your answers in the following format:
- line 1: the return value of construct.
- line 2: s
- If the return value of construct is 0, s will not be printed.
|
Python
|
seed_400
|
# Handcrafted Gift (gift)
Adam is making Bob a hand-crafted necklace as a gift. A necklace consists of n beads, numbered 0 to n β 1 from left to right. Each bead can either be red or blue in colour. Bob has sent Adam a list of r requirements for the necklace. The i-th requirement (0 β€ i < r) states that the beads from positions a[i] to b[i] inclusive should have x[i] unique colours.
Help Adam find a possible configuration of beads that satisfies all of Bob's requirements, or determine that it is impossible.
## Implementation Details
You should implement the following procedure:
```
int construct(int n, int r, int[] a, int[] b, int[] x)
```
- n: number of beads.
- r: number of requirements.
- a: an array of length r, the starting position of each requirement.
- b: an array of length r, the ending position of each requirement.
- x: an array of length r, the number of unique colours for each requirement.
- This procedure will be called exactly once.
- If a construction is possible, this procedure should make exactly one call to craft to report the construction, following which it should return 1.
- Otherwise, the procedure should return 0 without making any calls to craft.
Your program should call the following procedure to report the construction:
```
void craft(string s)
```
- s, a string of length n, with s[i] equal to 'R' if the i-th bead is red, or 'B' if it is blue.
## Examples
### Example 1
Consider the following call:
```
construct(4, 2, [0, 2], [2, 3], [1, 2])
```
This means that there are a total of 4 beads and 2 requirements as follows:
- positions 0 to 2 should have 1 unique colour,
- positions 2 to 3 should have 2 unique colours.
This can be achieved by colouring beads 0 to 2 red, and bead 3 blue.
Therefore, the construct procedure should make the following call:
```
craft("RRRB")
```
It should then return 1.
In this case, there are multiple constructions that fit the requirements, all of which would be considered correct.
### Example 2
Consider the following call:
```
construct(3, 3, [0, 1, 0], [1, 2, 2], [1, 1, 2])
```
This means that there are a total of 3 beads and 3 requirements as follows:
- positions 0 to 1 should have 1 unique colour,
- positions 1 to 2 should have 1 unique colour,
- positions 0 to 2 should have 2 unique colours.
In this case, there are no possible configuration of beads that satisfy all the requirements.
As such, the construct procedure should return 0 without making any call to craft.
## Constraints
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
* $1 \le n, r \le 18$
* $0 \le a[i] \le b[i] \le n - 1$ (for all $0 \le i \le r - 1$)
* $1 \le x[i] \le 2$ (for all $0 \le i \le r - 1$)
## Sample grader
The sample grader reads the input in the following format:
- line 1: n r
- line 2 + i (0 β€ i β€ r β 1): a[i] b[i] x[i]
The sample grader prints your answers in the following format:
- line 1: the return value of construct.
- line 2: s
- If the return value of construct is 0, s will not be printed.
|
Python
|
seed_401
|
# Handcrafted Gift (gift)
Adam is making Bob a hand-crafted necklace as a gift. A necklace consists of n beads, numbered 0 to n β 1 from left to right. Each bead can either be red or blue in colour. Bob has sent Adam a list of r requirements for the necklace. The i-th requirement (0 β€ i < r) states that the beads from positions a[i] to b[i] inclusive should have x[i] unique colours.
Help Adam find a possible configuration of beads that satisfies all of Bob's requirements, or determine that it is impossible.
## Implementation Details
You should implement the following procedure:
```
int construct(int n, int r, int[] a, int[] b, int[] x)
```
- n: number of beads.
- r: number of requirements.
- a: an array of length r, the starting position of each requirement.
- b: an array of length r, the ending position of each requirement.
- x: an array of length r, the number of unique colours for each requirement.
- This procedure will be called exactly once.
- If a construction is possible, this procedure should make exactly one call to craft to report the construction, following which it should return 1.
- Otherwise, the procedure should return 0 without making any calls to craft.
Your program should call the following procedure to report the construction:
```
void craft(string s)
```
- s, a string of length n, with s[i] equal to 'R' if the i-th bead is red, or 'B' if it is blue.
## Examples
### Example 1
Consider the following call:
```
construct(4, 2, [0, 2], [2, 3], [1, 2])
```
This means that there are a total of 4 beads and 2 requirements as follows:
- positions 0 to 2 should have 1 unique colour,
- positions 2 to 3 should have 2 unique colours.
This can be achieved by colouring beads 0 to 2 red, and bead 3 blue.
Therefore, the construct procedure should make the following call:
```
craft("RRRB")
```
It should then return 1.
In this case, there are multiple constructions that fit the requirements, all of which would be considered correct.
### Example 2
Consider the following call:
```
construct(3, 3, [0, 1, 0], [1, 2, 2], [1, 1, 2])
```
This means that there are a total of 3 beads and 3 requirements as follows:
- positions 0 to 1 should have 1 unique colour,
- positions 1 to 2 should have 1 unique colour,
- positions 0 to 2 should have 2 unique colours.
In this case, there are no possible configuration of beads that satisfy all the requirements.
As such, the construct procedure should return 0 without making any call to craft.
## Constraints
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
* $1 \le n, r \le 2000$
* $0 \le a[i] \le b[i] \le n - 1$ (for all $0 \le i \le r - 1$)
* $1 \le x[i] \le 2$ (for all $0 \le i \le r - 1$)
## Sample grader
The sample grader reads the input in the following format:
- line 1: n r
- line 2 + i (0 β€ i β€ r β 1): a[i] b[i] x[i]
The sample grader prints your answers in the following format:
- line 1: the return value of construct.
- line 2: s
- If the return value of construct is 0, s will not be printed.
|
Python
|
seed_402
|
# Handcrafted Gift (gift)
Adam is making Bob a hand-crafted necklace as a gift. A necklace consists of n beads, numbered 0 to n β 1 from left to right. Each bead can either be red or blue in colour. Bob has sent Adam a list of r requirements for the necklace. The i-th requirement (0 β€ i < r) states that the beads from positions a[i] to b[i] inclusive should have x[i] unique colours.
Help Adam find a possible configuration of beads that satisfies all of Bob's requirements, or determine that it is impossible.
## Implementation Details
You should implement the following procedure:
```
int construct(int n, int r, int[] a, int[] b, int[] x)
```
- n: number of beads.
- r: number of requirements.
- a: an array of length r, the starting position of each requirement.
- b: an array of length r, the ending position of each requirement.
- x: an array of length r, the number of unique colours for each requirement.
- This procedure will be called exactly once.
- If a construction is possible, this procedure should make exactly one call to craft to report the construction, following which it should return 1.
- Otherwise, the procedure should return 0 without making any calls to craft.
Your program should call the following procedure to report the construction:
```
void craft(string s)
```
- s, a string of length n, with s[i] equal to 'R' if the i-th bead is red, or 'B' if it is blue.
## Examples
### Example 1
Consider the following call:
```
construct(4, 2, [0, 2], [2, 3], [1, 2])
```
This means that there are a total of 4 beads and 2 requirements as follows:
- positions 0 to 2 should have 1 unique colour,
- positions 2 to 3 should have 2 unique colours.
This can be achieved by colouring beads 0 to 2 red, and bead 3 blue.
Therefore, the construct procedure should make the following call:
```
craft("RRRB")
```
It should then return 1.
In this case, there are multiple constructions that fit the requirements, all of which would be considered correct.
### Example 2
Consider the following call:
```
construct(3, 3, [0, 1, 0], [1, 2, 2], [1, 1, 2])
```
This means that there are a total of 3 beads and 3 requirements as follows:
- positions 0 to 1 should have 1 unique colour,
- positions 1 to 2 should have 1 unique colour,
- positions 0 to 2 should have 2 unique colours.
In this case, there are no possible configuration of beads that satisfy all the requirements.
As such, the construct procedure should return 0 without making any call to craft.
## Constraints
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
* $1 \le n, r \le 500\,000$
* $0 \le a[i] \le b[i] \le n - 1$ (for all $0 \le i \le r - 1$)
* $1 \le x[i] \le 2$ (for all $0 \le i \le r - 1$)
* $x[i] = 1$ (for all $0 \le i \le r - 1$)
## Sample grader
The sample grader reads the input in the following format:
- line 1: n r
- line 2 + i (0 β€ i β€ r β 1): a[i] b[i] x[i]
The sample grader prints your answers in the following format:
- line 1: the return value of construct.
- line 2: s
- If the return value of construct is 0, s will not be printed.
|
Python
|
seed_405
|
# Hermes
## Problem
In a modern city for Greek gods, the streets are geometrically arranged as a grid with integer coordinates with streets parallel to the \(x\) and \(y\) axes. For each integer value \(Z\), there is a horizontal street at \(y=Z\) and a vertical street at \(x=Z\). This way, integer coordinate pairs represent the street junctions. During the hot days, the gods rest in cafeterias at street junctions. Messenger Hermes is to send photon messages to gods resting in the cafeterias by only moving along the city streets. Each message is for a single god, and it does not matter if the other gods see the message.
The messages are to be sent in a given order, and Hermes is provided the coordinates of the cafeterias in that order. Hermes starts from \((0,0)\). To send a message to a cafeteria at \((X_i, Y_i)\), Hermes only needs to visit some point on the same horizontal street (with \(y\)-coordinate \(Y_i\)) or on the same vertical street (with \(x\)-coordinate \(X_i\)). Having sent all of the messages, Hermes stops.
You are to write a program that, given a sequence of cafeterias, finds the minimum total distance Hermes needs to travel to send the messages.
## Input
The input file name is `hermes.in`. The first line contains one integer \(N\): the number of messages to be sent. The following \(N\) lines contain the coordinates of the \(N\) street junctions where the messages are to be sent. These \(N\) lines are in the order in which the messages are to be sent. Each of these \(N\) lines contains two integers: first the \(x\)-coordinate and then the \(y\)-coordinate of the street junction.
## Output
The output file name is `hermes.out`. The file is to contain a single line containing one integer: the minimum total distance Hermes needs to travel to send the messages.
## Example Input and Output
### Input: `hermes.in`
```
5
8 3
7 -7
8 1
-2 1
6 -5
```
### Output: `hermes.out`
```
11
```
## Constraints
In all inputs, \(1 \leq N \leq 20000\), \(-1000 \leq X_i, Y_i \leq 1000\). Additionally, in 50% of the inputs, \(1 \leq N \leq 80\).
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
|
Python
|
seed_407
|
# Highway Tolls
In Japan, cities are connected by a network of highways. This network consists of $N$ cities and $M$ highways. Each highway connects a pair of distinct cities. No two highways connect the same pair of cities. Cities are numbered from $0$ through $N - 1$, and highways are numbered from $0$ through $M - 1$. You can drive on any highway in both directions. You can travel from any city to any other city by using the highways.
A toll is charged for driving on each highway. The toll for a highway depends on the **traffic** condition on the highway. The traffic is either *light* or *heavy*. When the traffic is light, the toll is $A$ yen (Japanese currency). When the traffic is heavy, the toll is $B$ yen. It's guaranteed that $A < B$. Note that you know the values of $A$ and $B$.
You have a machine which, given the traffic conditions of all highways, computes the smallest total toll that one has to pay to travel between the pair of cities $S$ and $T$ ($S
eq T$), under the specified traffic conditions.
However, the machine is just a prototype. The values of $S$ and $T$ are fixed (i.e., hardcoded in the machine) and not known to you. You would like to determine $S$ and $T$. In order to do so, you plan to specify several traffic conditions to the machine, and use the toll values that it outputs to deduce $S$ and $T$. Since specifying the traffic conditions is costly, you don't want to use the machine many times.
## Implementation details
You should implement the following procedure:
```
find_pair(int N, int[] U, int[] V, int A, int B)
```
- $N$: the number of cities.
- $U$ and $V$: arrays of length $M$, where $M$ is the number of highways connecting cities. For each $i$ ($0 \leq i \leq M - 1$), the highway $i$ connects the cities $U[i]$ and $V[i]$.
- $A$: the toll for a highway when the traffic is light.
- $B$: the toll for a highway when the traffic is heavy.
- This procedure is called exactly once for each test case.
- Note that the value of $M$ is the length of the arrays, and can be obtained as indicated in the implementation notice.
The procedure `find_pair` can call the following function:
```
int64 ask(int[] w)
```
- The length of $w$ must be $M$. The array $w$ describes the traffic conditions.
- For each $i$ ($0 \leq i \leq M - 1$), $w[i]$ gives the traffic condition on the highway $i$. The value of $w[i]$ must be either $0$ or $1$.
- $w[i] = 0$ means the traffic of the highway $i$ is light.
- $w[i] = 1$ means the traffic of the highway $i$ is heavy.
- This function returns the smallest total toll for travelling between the cities $S$ and $T$, under the traffic conditions specified by $w$.
- This function can be called at most $100$ times (for each test case).
`find_pair` should call the following procedure to report the answer:
```
answer(int s, int t)
```
- $s$ and $t$ must be the pair $S$ and $T$ (the order does not matter).
- This procedure must be called exactly once.
If some of the above conditions are not satisfied, your program is judged as **Wrong Answer**. Otherwise, your program is judged as **Accepted** and your score is calculated by the number of calls to `ask` (see Subtasks).
## Example
Let $N = 4$, $M = 4$, $U = [0, 0, 0, 1]$, $V = [1, 2, 3, 2]$, $A = 1$, $B = 3$, $S = 1$, and $T = 3$.
The grader calls
```
find_pair(4, [0, 0, 0, 1], [1, 2, 3, 2], 1, 3).
```

In the figure above, the edge with number $i$ corresponds to the highway $i$. Some possible calls to `ask` and the corresponding return values are listed below:
| **Call** | **Return** |
|------------------------|------------|
| `ask([0, 0, 0, 0])` | $2$ |
| `ask([0, 1, 1, 0])` | $4$ |
| `ask([1, 0, 1, 0])` | $5$ |
| `ask([1, 1, 1, 1])` | $6$ |
For the function call `ask([0, 0, 0, 0])`, the traffic of each highway is light and the toll for each highway is $1$. The cheapest route from $S = 1$ to $T = 3$ is $1 \to 0 \to 3$. The total toll for this route is $2$. Thus, this function returns $2$.
For a correct answer, the procedure `find_pair` should call `answer(1, 3)` or `answer(3, 1)`.
## Constraints
- $2 \leq N \leq 90,000$
- $1 \leq M \leq 130,000$
- $1 \leq A < B \leq 1,000,000,000$
- For each $0 \leq i \leq M - 1$:
- $0 \leq U[i] \leq N - 1$
- $0 \leq V[i] \leq N - 1$
- $U[i]
eq V[i]$
- $(U[i], V[i])
eq (U[j], V[j])$ and $(U[i], V[i])
eq (V[j], U[j])$ ($0 \leq i < j \leq M - 1$)
- You can travel from any city to any other city by using the highways.
- $0 \leq S \leq N - 1$
- $0 \leq T \leq N - 1$
- $S
eq T$
# Sample grader
The sample grader reads the input in the following format:
β’ line 1: N M A B S T
β’ line 2 + i (0 β€ i β€ M β 1): U[i] V[i]
If your program is judged as **Accepted**, the sample grader prints Accepted: q, with q the number of calls to ask.
If your program is judged as **Wrong Answer**, it prints Wrong Answer: MSG, where MSG is one of:
β’ answered not exactly once: The procedure answer was not called exactly once.
β’ w is invalid: The length of w given to ask is not M or w[i] is neither 0 nor 1 for some i (0 β€ i β€ M β 1).
β’ more than 100 calls to ask: The function ask is called more than 100 times.
β’ {s, t} is wrong: The procedure answer is called with an incorrect pair s and t.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
$A = 1$, $B = 2$.
|
Python
|
seed_408
|
# Highway Tolls
In Japan, cities are connected by a network of highways. This network consists of $N$ cities and $M$ highways. Each highway connects a pair of distinct cities. No two highways connect the same pair of cities. Cities are numbered from $0$ through $N - 1$, and highways are numbered from $0$ through $M - 1$. You can drive on any highway in both directions. You can travel from any city to any other city by using the highways.
A toll is charged for driving on each highway. The toll for a highway depends on the **traffic** condition on the highway. The traffic is either *light* or *heavy*. When the traffic is light, the toll is $A$ yen (Japanese currency). When the traffic is heavy, the toll is $B$ yen. It's guaranteed that $A < B$. Note that you know the values of $A$ and $B$.
You have a machine which, given the traffic conditions of all highways, computes the smallest total toll that one has to pay to travel between the pair of cities $S$ and $T$ ($S
eq T$), under the specified traffic conditions.
However, the machine is just a prototype. The values of $S$ and $T$ are fixed (i.e., hardcoded in the machine) and not known to you. You would like to determine $S$ and $T$. In order to do so, you plan to specify several traffic conditions to the machine, and use the toll values that it outputs to deduce $S$ and $T$. Since specifying the traffic conditions is costly, you don't want to use the machine many times.
## Implementation details
You should implement the following procedure:
```
find_pair(int N, int[] U, int[] V, int A, int B)
```
- $N$: the number of cities.
- $U$ and $V$: arrays of length $M$, where $M$ is the number of highways connecting cities. For each $i$ ($0 \leq i \leq M - 1$), the highway $i$ connects the cities $U[i]$ and $V[i]$.
- $A$: the toll for a highway when the traffic is light.
- $B$: the toll for a highway when the traffic is heavy.
- This procedure is called exactly once for each test case.
- Note that the value of $M$ is the length of the arrays, and can be obtained as indicated in the implementation notice.
The procedure `find_pair` can call the following function:
```
int64 ask(int[] w)
```
- The length of $w$ must be $M$. The array $w$ describes the traffic conditions.
- For each $i$ ($0 \leq i \leq M - 1$), $w[i]$ gives the traffic condition on the highway $i$. The value of $w[i]$ must be either $0$ or $1$.
- $w[i] = 0$ means the traffic of the highway $i$ is light.
- $w[i] = 1$ means the traffic of the highway $i$ is heavy.
- This function returns the smallest total toll for travelling between the cities $S$ and $T$, under the traffic conditions specified by $w$.
- This function can be called at most $100$ times (for each test case).
`find_pair` should call the following procedure to report the answer:
```
answer(int s, int t)
```
- $s$ and $t$ must be the pair $S$ and $T$ (the order does not matter).
- This procedure must be called exactly once.
If some of the above conditions are not satisfied, your program is judged as **Wrong Answer**. Otherwise, your program is judged as **Accepted** and your score is calculated by the number of calls to `ask` (see Subtasks).
## Example
Let $N = 4$, $M = 4$, $U = [0, 0, 0, 1]$, $V = [1, 2, 3, 2]$, $A = 1$, $B = 3$, $S = 1$, and $T = 3$.
The grader calls
```
find_pair(4, [0, 0, 0, 1], [1, 2, 3, 2], 1, 3).
```

In the figure above, the edge with number $i$ corresponds to the highway $i$. Some possible calls to `ask` and the corresponding return values are listed below:
| **Call** | **Return** |
|------------------------|------------|
| `ask([0, 0, 0, 0])` | $2$ |
| `ask([0, 1, 1, 0])` | $4$ |
| `ask([1, 0, 1, 0])` | $5$ |
| `ask([1, 1, 1, 1])` | $6$ |
For the function call `ask([0, 0, 0, 0])`, the traffic of each highway is light and the toll for each highway is $1$. The cheapest route from $S = 1$ to $T = 3$ is $1 \to 0 \to 3$. The total toll for this route is $2$. Thus, this function returns $2$.
For a correct answer, the procedure `find_pair` should call `answer(1, 3)` or `answer(3, 1)`.
## Constraints
- $2 \leq N \leq 90,000$
- $1 \leq M \leq 130,000$
- $1 \leq A < B \leq 1,000,000,000$
- For each $0 \leq i \leq M - 1$:
- $0 \leq U[i] \leq N - 1$
- $0 \leq V[i] \leq N - 1$
- $U[i]
eq V[i]$
- $(U[i], V[i])
eq (U[j], V[j])$ and $(U[i], V[i])
eq (V[j], U[j])$ ($0 \leq i < j \leq M - 1$)
- You can travel from any city to any other city by using the highways.
- $0 \leq S \leq N - 1$
- $0 \leq T \leq N - 1$
- $S
eq T$
# Sample grader
The sample grader reads the input in the following format:
β’ line 1: N M A B S T
β’ line 2 + i (0 β€ i β€ M β 1): U[i] V[i]
If your program is judged as **Accepted**, the sample grader prints Accepted: q, with q the number of calls to ask.
If your program is judged as **Wrong Answer**, it prints Wrong Answer: MSG, where MSG is one of:
β’ answered not exactly once: The procedure answer was not called exactly once.
β’ w is invalid: The length of w given to ask is not M or w[i] is neither 0 nor 1 for some i (0 β€ i β€ M β 1).
β’ more than 100 calls to ask: The function ask is called more than 100 times.
β’ {s, t} is wrong: The procedure answer is called with an incorrect pair s and t.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
$M = N - 1$, $U[i] = i$, $V[i] = i + 1$ ($0 \leq i \leq M - 1$).
|
Python
|
seed_409
|
# Highway Tolls
In Japan, cities are connected by a network of highways. This network consists of $N$ cities and $M$ highways. Each highway connects a pair of distinct cities. No two highways connect the same pair of cities. Cities are numbered from $0$ through $N - 1$, and highways are numbered from $0$ through $M - 1$. You can drive on any highway in both directions. You can travel from any city to any other city by using the highways.
A toll is charged for driving on each highway. The toll for a highway depends on the **traffic** condition on the highway. The traffic is either *light* or *heavy*. When the traffic is light, the toll is $A$ yen (Japanese currency). When the traffic is heavy, the toll is $B$ yen. It's guaranteed that $A < B$. Note that you know the values of $A$ and $B$.
You have a machine which, given the traffic conditions of all highways, computes the smallest total toll that one has to pay to travel between the pair of cities $S$ and $T$ ($S
eq T$), under the specified traffic conditions.
However, the machine is just a prototype. The values of $S$ and $T$ are fixed (i.e., hardcoded in the machine) and not known to you. You would like to determine $S$ and $T$. In order to do so, you plan to specify several traffic conditions to the machine, and use the toll values that it outputs to deduce $S$ and $T$. Since specifying the traffic conditions is costly, you don't want to use the machine many times.
## Implementation details
You should implement the following procedure:
```
find_pair(int N, int[] U, int[] V, int A, int B)
```
- $N$: the number of cities.
- $U$ and $V$: arrays of length $M$, where $M$ is the number of highways connecting cities. For each $i$ ($0 \leq i \leq M - 1$), the highway $i$ connects the cities $U[i]$ and $V[i]$.
- $A$: the toll for a highway when the traffic is light.
- $B$: the toll for a highway when the traffic is heavy.
- This procedure is called exactly once for each test case.
- Note that the value of $M$ is the length of the arrays, and can be obtained as indicated in the implementation notice.
The procedure `find_pair` can call the following function:
```
int64 ask(int[] w)
```
- The length of $w$ must be $M$. The array $w$ describes the traffic conditions.
- For each $i$ ($0 \leq i \leq M - 1$), $w[i]$ gives the traffic condition on the highway $i$. The value of $w[i]$ must be either $0$ or $1$.
- $w[i] = 0$ means the traffic of the highway $i$ is light.
- $w[i] = 1$ means the traffic of the highway $i$ is heavy.
- This function returns the smallest total toll for travelling between the cities $S$ and $T$, under the traffic conditions specified by $w$.
- This function can be called at most $100$ times (for each test case).
`find_pair` should call the following procedure to report the answer:
```
answer(int s, int t)
```
- $s$ and $t$ must be the pair $S$ and $T$ (the order does not matter).
- This procedure must be called exactly once.
If some of the above conditions are not satisfied, your program is judged as **Wrong Answer**. Otherwise, your program is judged as **Accepted** and your score is calculated by the number of calls to `ask` (see Subtasks).
## Example
Let $N = 4$, $M = 4$, $U = [0, 0, 0, 1]$, $V = [1, 2, 3, 2]$, $A = 1$, $B = 3$, $S = 1$, and $T = 3$.
The grader calls
```
find_pair(4, [0, 0, 0, 1], [1, 2, 3, 2], 1, 3).
```

In the figure above, the edge with number $i$ corresponds to the highway $i$. Some possible calls to `ask` and the corresponding return values are listed below:
| **Call** | **Return** |
|------------------------|------------|
| `ask([0, 0, 0, 0])` | $2$ |
| `ask([0, 1, 1, 0])` | $4$ |
| `ask([1, 0, 1, 0])` | $5$ |
| `ask([1, 1, 1, 1])` | $6$ |
For the function call `ask([0, 0, 0, 0])`, the traffic of each highway is light and the toll for each highway is $1$. The cheapest route from $S = 1$ to $T = 3$ is $1 \to 0 \to 3$. The total toll for this route is $2$. Thus, this function returns $2$.
For a correct answer, the procedure `find_pair` should call `answer(1, 3)` or `answer(3, 1)`.
## Constraints
- $2 \leq N \leq 90,000$
- $1 \leq M \leq 130,000$
- $1 \leq A < B \leq 1,000,000,000$
- For each $0 \leq i \leq M - 1$:
- $0 \leq U[i] \leq N - 1$
- $0 \leq V[i] \leq N - 1$
- $U[i]
eq V[i]$
- $(U[i], V[i])
eq (U[j], V[j])$ and $(U[i], V[i])
eq (V[j], U[j])$ ($0 \leq i < j \leq M - 1$)
- You can travel from any city to any other city by using the highways.
- $0 \leq S \leq N - 1$
- $0 \leq T \leq N - 1$
- $S
eq T$
# Sample grader
The sample grader reads the input in the following format:
β’ line 1: N M A B S T
β’ line 2 + i (0 β€ i β€ M β 1): U[i] V[i]
If your program is judged as **Accepted**, the sample grader prints Accepted: q, with q the number of calls to ask.
If your program is judged as **Wrong Answer**, it prints Wrong Answer: MSG, where MSG is one of:
β’ answered not exactly once: The procedure answer was not called exactly once.
β’ w is invalid: The length of w given to ask is not M or w[i] is neither 0 nor 1 for some i (0 β€ i β€ M β 1).
β’ more than 100 calls to ask: The function ask is called more than 100 times.
β’ {s, t} is wrong: The procedure answer is called with an incorrect pair s and t.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
$M = N - 1$.
|
Python
|
seed_410
|
# Highway Tolls
In Japan, cities are connected by a network of highways. This network consists of $N$ cities and $M$ highways. Each highway connects a pair of distinct cities. No two highways connect the same pair of cities. Cities are numbered from $0$ through $N - 1$, and highways are numbered from $0$ through $M - 1$. You can drive on any highway in both directions. You can travel from any city to any other city by using the highways.
A toll is charged for driving on each highway. The toll for a highway depends on the **traffic** condition on the highway. The traffic is either *light* or *heavy*. When the traffic is light, the toll is $A$ yen (Japanese currency). When the traffic is heavy, the toll is $B$ yen. It's guaranteed that $A < B$. Note that you know the values of $A$ and $B$.
You have a machine which, given the traffic conditions of all highways, computes the smallest total toll that one has to pay to travel between the pair of cities $S$ and $T$ ($S
eq T$), under the specified traffic conditions.
However, the machine is just a prototype. The values of $S$ and $T$ are fixed (i.e., hardcoded in the machine) and not known to you. You would like to determine $S$ and $T$. In order to do so, you plan to specify several traffic conditions to the machine, and use the toll values that it outputs to deduce $S$ and $T$. Since specifying the traffic conditions is costly, you don't want to use the machine many times.
## Implementation details
You should implement the following procedure:
```
find_pair(int N, int[] U, int[] V, int A, int B)
```
- $N$: the number of cities.
- $U$ and $V$: arrays of length $M$, where $M$ is the number of highways connecting cities. For each $i$ ($0 \leq i \leq M - 1$), the highway $i$ connects the cities $U[i]$ and $V[i]$.
- $A$: the toll for a highway when the traffic is light.
- $B$: the toll for a highway when the traffic is heavy.
- This procedure is called exactly once for each test case.
- Note that the value of $M$ is the length of the arrays, and can be obtained as indicated in the implementation notice.
The procedure `find_pair` can call the following function:
```
int64 ask(int[] w)
```
- The length of $w$ must be $M$. The array $w$ describes the traffic conditions.
- For each $i$ ($0 \leq i \leq M - 1$), $w[i]$ gives the traffic condition on the highway $i$. The value of $w[i]$ must be either $0$ or $1$.
- $w[i] = 0$ means the traffic of the highway $i$ is light.
- $w[i] = 1$ means the traffic of the highway $i$ is heavy.
- This function returns the smallest total toll for travelling between the cities $S$ and $T$, under the traffic conditions specified by $w$.
- This function can be called at most $100$ times (for each test case).
`find_pair` should call the following procedure to report the answer:
```
answer(int s, int t)
```
- $s$ and $t$ must be the pair $S$ and $T$ (the order does not matter).
- This procedure must be called exactly once.
If some of the above conditions are not satisfied, your program is judged as **Wrong Answer**. Otherwise, your program is judged as **Accepted** and your score is calculated by the number of calls to `ask` (see Subtasks).
## Example
Let $N = 4$, $M = 4$, $U = [0, 0, 0, 1]$, $V = [1, 2, 3, 2]$, $A = 1$, $B = 3$, $S = 1$, and $T = 3$.
The grader calls
```
find_pair(4, [0, 0, 0, 1], [1, 2, 3, 2], 1, 3).
```

In the figure above, the edge with number $i$ corresponds to the highway $i$. Some possible calls to `ask` and the corresponding return values are listed below:
| **Call** | **Return** |
|------------------------|------------|
| `ask([0, 0, 0, 0])` | $2$ |
| `ask([0, 1, 1, 0])` | $4$ |
| `ask([1, 0, 1, 0])` | $5$ |
| `ask([1, 1, 1, 1])` | $6$ |
For the function call `ask([0, 0, 0, 0])`, the traffic of each highway is light and the toll for each highway is $1$. The cheapest route from $S = 1$ to $T = 3$ is $1 \to 0 \to 3$. The total toll for this route is $2$. Thus, this function returns $2$.
For a correct answer, the procedure `find_pair` should call `answer(1, 3)` or `answer(3, 1)`.
## Constraints
- $2 \leq N \leq 90,000$
- $1 \leq M \leq 130,000$
- $1 \leq A < B \leq 1,000,000,000$
- For each $0 \leq i \leq M - 1$:
- $0 \leq U[i] \leq N - 1$
- $0 \leq V[i] \leq N - 1$
- $U[i]
eq V[i]$
- $(U[i], V[i])
eq (U[j], V[j])$ and $(U[i], V[i])
eq (V[j], U[j])$ ($0 \leq i < j \leq M - 1$)
- You can travel from any city to any other city by using the highways.
- $0 \leq S \leq N - 1$
- $0 \leq T \leq N - 1$
- $S
eq T$
# Sample grader
The sample grader reads the input in the following format:
β’ line 1: N M A B S T
β’ line 2 + i (0 β€ i β€ M β 1): U[i] V[i]
If your program is judged as **Accepted**, the sample grader prints Accepted: q, with q the number of calls to ask.
If your program is judged as **Wrong Answer**, it prints Wrong Answer: MSG, where MSG is one of:
β’ answered not exactly once: The procedure answer was not called exactly once.
β’ w is invalid: The length of w given to ask is not M or w[i] is neither 0 nor 1 for some i (0 β€ i β€ M β 1).
β’ more than 100 calls to ask: The function ask is called more than 100 times.
β’ {s, t} is wrong: The procedure answer is called with an incorrect pair s and t.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
No additional constraints.
|
Python
|
seed_411
|
# Highway Tolls
In Japan, cities are connected by a network of highways. This network consists of $N$ cities and $M$ highways. Each highway connects a pair of distinct cities. No two highways connect the same pair of cities. Cities are numbered from $0$ through $N - 1$, and highways are numbered from $0$ through $M - 1$. You can drive on any highway in both directions. You can travel from any city to any other city by using the highways.
A toll is charged for driving on each highway. The toll for a highway depends on the **traffic** condition on the highway. The traffic is either *light* or *heavy*. When the traffic is light, the toll is $A$ yen (Japanese currency). When the traffic is heavy, the toll is $B$ yen. It's guaranteed that $A < B$. Note that you know the values of $A$ and $B$.
You have a machine which, given the traffic conditions of all highways, computes the smallest total toll that one has to pay to travel between the pair of cities $S$ and $T$ ($S
eq T$), under the specified traffic conditions.
However, the machine is just a prototype. The values of $S$ and $T$ are fixed (i.e., hardcoded in the machine) and not known to you. You would like to determine $S$ and $T$. In order to do so, you plan to specify several traffic conditions to the machine, and use the toll values that it outputs to deduce $S$ and $T$. Since specifying the traffic conditions is costly, you don't want to use the machine many times.
## Implementation details
You should implement the following procedure:
```
find_pair(int N, int[] U, int[] V, int A, int B)
```
- $N$: the number of cities.
- $U$ and $V$: arrays of length $M$, where $M$ is the number of highways connecting cities. For each $i$ ($0 \leq i \leq M - 1$), the highway $i$ connects the cities $U[i]$ and $V[i]$.
- $A$: the toll for a highway when the traffic is light.
- $B$: the toll for a highway when the traffic is heavy.
- This procedure is called exactly once for each test case.
- Note that the value of $M$ is the length of the arrays, and can be obtained as indicated in the implementation notice.
The procedure `find_pair` can call the following function:
```
int64 ask(int[] w)
```
- The length of $w$ must be $M$. The array $w$ describes the traffic conditions.
- For each $i$ ($0 \leq i \leq M - 1$), $w[i]$ gives the traffic condition on the highway $i$. The value of $w[i]$ must be either $0$ or $1$.
- $w[i] = 0$ means the traffic of the highway $i$ is light.
- $w[i] = 1$ means the traffic of the highway $i$ is heavy.
- This function returns the smallest total toll for travelling between the cities $S$ and $T$, under the traffic conditions specified by $w$.
- This function can be called at most $100$ times (for each test case).
`find_pair` should call the following procedure to report the answer:
```
answer(int s, int t)
```
- $s$ and $t$ must be the pair $S$ and $T$ (the order does not matter).
- This procedure must be called exactly once.
If some of the above conditions are not satisfied, your program is judged as **Wrong Answer**. Otherwise, your program is judged as **Accepted** and your score is calculated by the number of calls to `ask` (see Subtasks).
## Example
Let $N = 4$, $M = 4$, $U = [0, 0, 0, 1]$, $V = [1, 2, 3, 2]$, $A = 1$, $B = 3$, $S = 1$, and $T = 3$.
The grader calls
```
find_pair(4, [0, 0, 0, 1], [1, 2, 3, 2], 1, 3).
```

In the figure above, the edge with number $i$ corresponds to the highway $i$. Some possible calls to `ask` and the corresponding return values are listed below:
| **Call** | **Return** |
|------------------------|------------|
| `ask([0, 0, 0, 0])` | $2$ |
| `ask([0, 1, 1, 0])` | $4$ |
| `ask([1, 0, 1, 0])` | $5$ |
| `ask([1, 1, 1, 1])` | $6$ |
For the function call `ask([0, 0, 0, 0])`, the traffic of each highway is light and the toll for each highway is $1$. The cheapest route from $S = 1$ to $T = 3$ is $1 \to 0 \to 3$. The total toll for this route is $2$. Thus, this function returns $2$.
For a correct answer, the procedure `find_pair` should call `answer(1, 3)` or `answer(3, 1)`.
## Constraints
- $2 \leq N \leq 90,000$
- $1 \leq M \leq 130,000$
- $1 \leq A < B \leq 1,000,000,000$
- For each $0 \leq i \leq M - 1$:
- $0 \leq U[i] \leq N - 1$
- $0 \leq V[i] \leq N - 1$
- $U[i]
eq V[i]$
- $(U[i], V[i])
eq (U[j], V[j])$ and $(U[i], V[i])
eq (V[j], U[j])$ ($0 \leq i < j \leq M - 1$)
- You can travel from any city to any other city by using the highways.
- $0 \leq S \leq N - 1$
- $0 \leq T \leq N - 1$
- $S
eq T$
# Sample grader
The sample grader reads the input in the following format:
β’ line 1: N M A B S T
β’ line 2 + i (0 β€ i β€ M β 1): U[i] V[i]
If your program is judged as **Accepted**, the sample grader prints Accepted: q, with q the number of calls to ask.
If your program is judged as **Wrong Answer**, it prints Wrong Answer: MSG, where MSG is one of:
β’ answered not exactly once: The procedure answer was not called exactly once.
β’ w is invalid: The length of w given to ask is not M or w[i] is neither 0 nor 1 for some i (0 β€ i β€ M β 1).
β’ more than 100 calls to ask: The function ask is called more than 100 times.
β’ {s, t} is wrong: The procedure answer is called with an incorrect pair s and t.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
One of $S$ or $T$ is $0$, $M = N - 1$.
|
Python
|
seed_413
|
# History
This kata is a sequel of my [Mixbonacci](https://www.codewars.com/kata/mixbonacci/python) kata. Zozonacci is a special integer sequence named after [**ZozoFouchtra**](https://www.codewars.com/users/ZozoFouchtra), who came up with this kata idea in the [Mixbonacci discussion](https://www.codewars.com/kata/mixbonacci/discuss/python).
This sequence combines the rules for computing the n-th elements of fibonacci, jacobstal, pell, padovan, tribonacci and tetranacci sequences according to a given pattern.
# Task
Compute the first `n` elements of the Zozonacci sequence for a given pattern `p`.
## Rules
1. `n` is given as integer and `p` is given as a list of as abbreviations as strings (e.g. `["fib", "jac", "pad"]`)
2. When `n` is 0 or `p` is empty return an empty list.
3. The first four elements of the sequence are determined by the first abbreviation in the pattern (see the table below).
4. Compute the fifth element using the formula corespoding to the first element of the pattern, the sixth element using the formula for the second element and so on. (see the table below and the examples)
5. If `n` is more than the length of `p` repeat the pattern.
```
+------------+--------------+------------------------------------------+---------------------+
| sequence | abbreviation | formula for n-th element | first four elements |
+------------|--------------+------------------------------------------|---------------------|
| fibonacci | fib | a[n] = a[n-1] + a[n-2] | 0, 0, 0, 1 |
| jacobsthal | jac | a[n] = a[n-1] + 2 * a[n-2] | 0, 0, 0, 1 |
| padovan | pad | a[n] = a[n-2] + a[n-3] | 0, 1, 0, 0 |
| pell | pel | a[n] = 2 * a[n-1] + a[n-2] | 0, 0, 0, 1 |
| tetranacci | tet | a[n] = a[n-1] + a[n-2] + a[n-3] + a[n-4] | 0, 0, 0, 1 |
| tribonacci | tri | a[n] = a[n-1] + a[n-2] + a[n-3] | 0, 0, 0, 1 |
+------------+--------------+------------------------------------------+---------------------+
```
## Example
```
zozonacci(["fib", "tri"], 7) == [0, 0, 0, 1, 1, 2, 3]
Explanation:
b d
/-----\/----\
[0, 0, 0, 1, 1, 2, 3]
\--------/
| \--------/
a c
a - [0, 0, 0, 1] as "fib" is the first abbreviation
b - 5th element is 1 as the 1st element of the pattern is "fib": 1 = 0 + 1
c - 6th element is 2 as the 2nd element of the pattern is "tri": 2 = 0 + 1 + 1
d - 7th element is 3 as the 3rd element of the pattern is "fib" (see rule no. 5): 3 = 2 + 1
```
## Sequences
* [fibonacci](https://oeis.org/A000045) : 0, 1, 1, 2, 3 ...
* [padovan](https://oeis.org/A000931): 1, 0, 0, 1, 0 ...
* [jacobsthal](https://oeis.org/A001045): 0, 1, 1, 3, 5 ...
* [pell](https://oeis.org/A000129): 0, 1, 2, 5, 12 ...
* [tribonacci](https://oeis.org/A000073): 0, 0, 1, 1, 2 ...
* [tetranacci](https://oeis.org/A000078): 0, 0, 0, 1, 1 ...
|
Python
|
seed_414
|
# Hoax Spreading
Pak Dengklek has just developed a social media site.
There are $N$ users using the site, numbered $0$ to $N - 1$.
There are $S$ hours in one day.
All of these users have a fixed usage schedule from day to day.
For each $i$ such that $0 \le i \le N - 1$, user $i$ will be online $T[i]$ times every day:
* from the start of the $A[i][0]^{th}$ hour to the end of the $B[i][0]^{th}$ hour,
* from the start of the $A[i][1]^{th}$ hour to the end of the $B[i][1]^{th}$ hour,
* ...
* and from the start of the $A[i][T[i] - 1]^{th}$ hour to the end of the $B[i][T[i] - 1]^{th}$ hour.
At any time, all users on the site like to share news to all other online users.
Unfortunately, one of the $N$ users has a hoax at the start of the first day and will spread it.
Hence, all users who meet the user with the hoax will also have the hoax at the end of the first day.
Two users are stated to be met if there is at least an hour where the two users are both online.
This hoax will also be spread on the second day.
Therefore, all users who meet the user with the hoax at the end of the first day will also have the hoax at the end of the second day.
This continued the following days.
There are $Q$ scenarios, each can be represented as an integer $P$.
For each scenario, the user who has the hoax at the start of the first day is user $P$.
A different scenario might cause a different hoax spreading.
Therefore, for each scenario, Pak Dengklek wonders on the number of users with the hoax at the end of the $N^{th}$ day, where $N$ is the number of users.
## Implementation Details
You should implement the following procedures:
```
void init(int N, int S, int[] T, int[][] A, int[][] B)
```
* $N$: the number of elements in the array $T$, $A$, and $B$.
* $S$: the number of hours in one day.
* $T$: an array of length $N$ describing the number of times each user will be online every day.
* $A, B$: arrays of length $N$. $A[i]$ and $B[i]$ are arrays of length $T[i]$ describing when user $i$ will be online every day.
* This procedure is called exactly once, before any calls to `count_users`.
```
int count_users(int P)
```
* $P$: the index of the user who has the hoax at the start of the first day.
* This procedure should return the number of users with the hoax at the end of the $N^{th}$ day, where $N$ is the number of users.
* This procedure is called exactly $Q$ times.
## Example
Consider the following sequence of calls:
```
init(5, 10, [2, 1, 1, 1, 1],
[[2, 7], [1], [1], [9], [5]], [[4, 9], [3], [1], [10], [6]])
```
```
count_users(0)
```
This means user $0$ has the hoax at the start of the first day.
User $0$ meets user $1$ (at the second hour to the third hour) and user $3$ (at the ninth hour).
Therefore, at the end of the first day, the two users will have the hoax.
User $1$ also meets user $2$ (at the first hour).
Therefore, at the end of the second day, user $2$ will also have the hoax.
There will be no hoax spreading on the third, fourth, and fifth day, thus $4$ users will have the hoax at the end of the fifth day.
Therefore, the procedure should return $4$.
```
count_users(4)
```
This means user $4$ has the hoax at the start of the first day.
User $4$ does not meet other users, thus other users will not have the hoax.
Therefore, the procedure should return $1$.
## Constraints
* $1 \le N \le 200\,000$
* $1 \le S \le 10^9$
* $1 \le Q \le 100\,000$
* $1 \le T[i] \le S$ (for each $i$ such that $0 \le i \le N - 1$)
* The sum of all elements of $T$ does not exceed $200\,000$.
* $1 \le A[i][j] \le B[i][j] \le S$ (for each $i$ and $j$ such that $0 \le i \le N - 1$ and $0 \le j \le T[i] - 1$)
* $B[i][j - 1] \lt A[i][j] $ (for each $i$ and $j$ such that $0 \le i \le N - 1$ and $1 \le j \le T[i] - 1$)
* $0 \le P \le N - 1$
* The values of $P$ among all scenarios are pairwise distinct.
## Sample Grader
The sample grader reads the input in the following format:
* line $1$: $N \; S \; Q$
* line $2 + i$ ($0 \le i \le N - 1$): $T[i] \; A[i][0] \; B[i][0] \; \ldots \; A[i][T[i] - 1] \; B[i][T[i] - 1]$
* line $2 + N + k$ ($0 \le k \le Q - 1$): $P$ for scenario $k$
The sample grader prints your answers in the following format:
* line $1 + k$ ($0 \le k \le Q - 1$): the return value of `count_users` for scenario $k$
|
Python
|
seed_415
|
# Hoax Spreading
Pak Dengklek has just developed a social media site.
There are $N$ users using the site, numbered $0$ to $N - 1$.
There are $S$ hours in one day.
All of these users have a fixed usage schedule from day to day.
For each $i$ such that $0 \le i \le N - 1$, user $i$ will be online $T[i]$ times every day:
* from the start of the $A[i][0]^{th}$ hour to the end of the $B[i][0]^{th}$ hour,
* from the start of the $A[i][1]^{th}$ hour to the end of the $B[i][1]^{th}$ hour,
* ...
* and from the start of the $A[i][T[i] - 1]^{th}$ hour to the end of the $B[i][T[i] - 1]^{th}$ hour.
At any time, all users on the site like to share news to all other online users.
Unfortunately, one of the $N$ users has a hoax at the start of the first day and will spread it.
Hence, all users who meet the user with the hoax will also have the hoax at the end of the first day.
Two users are stated to be met if there is at least an hour where the two users are both online.
This hoax will also be spread on the second day.
Therefore, all users who meet the user with the hoax at the end of the first day will also have the hoax at the end of the second day.
This continued the following days.
There are $Q$ scenarios, each can be represented as an integer $P$.
For each scenario, the user who has the hoax at the start of the first day is user $P$.
A different scenario might cause a different hoax spreading.
Therefore, for each scenario, Pak Dengklek wonders on the number of users with the hoax at the end of the $N^{th}$ day, where $N$ is the number of users.
## Implementation Details
You should implement the following procedures:
```
void init(int N, int S, int[] T, int[][] A, int[][] B)
```
* $N$: the number of elements in the array $T$, $A$, and $B$.
* $S$: the number of hours in one day.
* $T$: an array of length $N$ describing the number of times each user will be online every day.
* $A, B$: arrays of length $N$. $A[i]$ and $B[i]$ are arrays of length $T[i]$ describing when user $i$ will be online every day.
* This procedure is called exactly once, before any calls to `count_users`.
```
int count_users(int P)
```
* $P$: the index of the user who has the hoax at the start of the first day.
* This procedure should return the number of users with the hoax at the end of the $N^{th}$ day, where $N$ is the number of users.
* This procedure is called exactly $Q$ times.
## Example
Consider the following sequence of calls:
```
init(5, 10, [2, 1, 1, 1, 1],
[[2, 7], [1], [1], [9], [5]], [[4, 9], [3], [1], [10], [6]])
```
```
count_users(0)
```
This means user $0$ has the hoax at the start of the first day.
User $0$ meets user $1$ (at the second hour to the third hour) and user $3$ (at the ninth hour).
Therefore, at the end of the first day, the two users will have the hoax.
User $1$ also meets user $2$ (at the first hour).
Therefore, at the end of the second day, user $2$ will also have the hoax.
There will be no hoax spreading on the third, fourth, and fifth day, thus $4$ users will have the hoax at the end of the fifth day.
Therefore, the procedure should return $4$.
```
count_users(4)
```
This means user $4$ has the hoax at the start of the first day.
User $4$ does not meet other users, thus other users will not have the hoax.
Therefore, the procedure should return $1$.
## Constraints
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
* $N, Q \le 2000$ and the sum of all elements of $T$ does not exceed $2000$.
## Sample Grader
The sample grader reads the input in the following format:
* line $1$: $N \; S \; Q$
* line $2 + i$ ($0 \le i \le N - 1$): $T[i] \; A[i][0] \; B[i][0] \; \ldots \; A[i][T[i] - 1] \; B[i][T[i] - 1]$
* line $2 + N + k$ ($0 \le k \le Q - 1$): $P$ for scenario $k$
The sample grader prints your answers in the following format:
* line $1 + k$ ($0 \le k \le Q - 1$): the return value of `count_users` for scenario $k$
|
Python
|
seed_416
|
# Hoax Spreading
Pak Dengklek has just developed a social media site.
There are $N$ users using the site, numbered $0$ to $N - 1$.
There are $S$ hours in one day.
All of these users have a fixed usage schedule from day to day.
For each $i$ such that $0 \le i \le N - 1$, user $i$ will be online $T[i]$ times every day:
* from the start of the $A[i][0]^{th}$ hour to the end of the $B[i][0]^{th}$ hour,
* from the start of the $A[i][1]^{th}$ hour to the end of the $B[i][1]^{th}$ hour,
* ...
* and from the start of the $A[i][T[i] - 1]^{th}$ hour to the end of the $B[i][T[i] - 1]^{th}$ hour.
At any time, all users on the site like to share news to all other online users.
Unfortunately, one of the $N$ users has a hoax at the start of the first day and will spread it.
Hence, all users who meet the user with the hoax will also have the hoax at the end of the first day.
Two users are stated to be met if there is at least an hour where the two users are both online.
This hoax will also be spread on the second day.
Therefore, all users who meet the user with the hoax at the end of the first day will also have the hoax at the end of the second day.
This continued the following days.
There are $Q$ scenarios, each can be represented as an integer $P$.
For each scenario, the user who has the hoax at the start of the first day is user $P$.
A different scenario might cause a different hoax spreading.
Therefore, for each scenario, Pak Dengklek wonders on the number of users with the hoax at the end of the $N^{th}$ day, where $N$ is the number of users.
## Implementation Details
You should implement the following procedures:
```
void init(int N, int S, int[] T, int[][] A, int[][] B)
```
* $N$: the number of elements in the array $T$, $A$, and $B$.
* $S$: the number of hours in one day.
* $T$: an array of length $N$ describing the number of times each user will be online every day.
* $A, B$: arrays of length $N$. $A[i]$ and $B[i]$ are arrays of length $T[i]$ describing when user $i$ will be online every day.
* This procedure is called exactly once, before any calls to `count_users`.
```
int count_users(int P)
```
* $P$: the index of the user who has the hoax at the start of the first day.
* This procedure should return the number of users with the hoax at the end of the $N^{th}$ day, where $N$ is the number of users.
* This procedure is called exactly $Q$ times.
## Example
Consider the following sequence of calls:
```
init(5, 10, [2, 1, 1, 1, 1],
[[2, 7], [1], [1], [9], [5]], [[4, 9], [3], [1], [10], [6]])
```
```
count_users(0)
```
This means user $0$ has the hoax at the start of the first day.
User $0$ meets user $1$ (at the second hour to the third hour) and user $3$ (at the ninth hour).
Therefore, at the end of the first day, the two users will have the hoax.
User $1$ also meets user $2$ (at the first hour).
Therefore, at the end of the second day, user $2$ will also have the hoax.
There will be no hoax spreading on the third, fourth, and fifth day, thus $4$ users will have the hoax at the end of the fifth day.
Therefore, the procedure should return $4$.
```
count_users(4)
```
This means user $4$ has the hoax at the start of the first day.
User $4$ does not meet other users, thus other users will not have the hoax.
Therefore, the procedure should return $1$.
## Constraints
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
* $N, Q \le 300$ and the sum of all elements of $T$ does not exceed $300$.
## Sample Grader
The sample grader reads the input in the following format:
* line $1$: $N \; S \; Q$
* line $2 + i$ ($0 \le i \le N - 1$): $T[i] \; A[i][0] \; B[i][0] \; \ldots \; A[i][T[i] - 1] \; B[i][T[i] - 1]$
* line $2 + N + k$ ($0 \le k \le Q - 1$): $P$ for scenario $k$
The sample grader prints your answers in the following format:
* line $1 + k$ ($0 \le k \le Q - 1$): the return value of `count_users` for scenario $k$
|
Python
|
seed_417
|
# Hoax Spreading
Pak Dengklek has just developed a social media site.
There are $N$ users using the site, numbered $0$ to $N - 1$.
There are $S$ hours in one day.
All of these users have a fixed usage schedule from day to day.
For each $i$ such that $0 \le i \le N - 1$, user $i$ will be online $T[i]$ times every day:
* from the start of the $A[i][0]^{th}$ hour to the end of the $B[i][0]^{th}$ hour,
* from the start of the $A[i][1]^{th}$ hour to the end of the $B[i][1]^{th}$ hour,
* ...
* and from the start of the $A[i][T[i] - 1]^{th}$ hour to the end of the $B[i][T[i] - 1]^{th}$ hour.
At any time, all users on the site like to share news to all other online users.
Unfortunately, one of the $N$ users has a hoax at the start of the first day and will spread it.
Hence, all users who meet the user with the hoax will also have the hoax at the end of the first day.
Two users are stated to be met if there is at least an hour where the two users are both online.
This hoax will also be spread on the second day.
Therefore, all users who meet the user with the hoax at the end of the first day will also have the hoax at the end of the second day.
This continued the following days.
There are $Q$ scenarios, each can be represented as an integer $P$.
For each scenario, the user who has the hoax at the start of the first day is user $P$.
A different scenario might cause a different hoax spreading.
Therefore, for each scenario, Pak Dengklek wonders on the number of users with the hoax at the end of the $N^{th}$ day, where $N$ is the number of users.
## Implementation Details
You should implement the following procedures:
```
void init(int N, int S, int[] T, int[][] A, int[][] B)
```
* $N$: the number of elements in the array $T$, $A$, and $B$.
* $S$: the number of hours in one day.
* $T$: an array of length $N$ describing the number of times each user will be online every day.
* $A, B$: arrays of length $N$. $A[i]$ and $B[i]$ are arrays of length $T[i]$ describing when user $i$ will be online every day.
* This procedure is called exactly once, before any calls to `count_users`.
```
int count_users(int P)
```
* $P$: the index of the user who has the hoax at the start of the first day.
* This procedure should return the number of users with the hoax at the end of the $N^{th}$ day, where $N$ is the number of users.
* This procedure is called exactly $Q$ times.
## Example
Consider the following sequence of calls:
```
init(5, 10, [2, 1, 1, 1, 1],
[[2, 7], [1], [1], [9], [5]], [[4, 9], [3], [1], [10], [6]])
```
```
count_users(0)
```
This means user $0$ has the hoax at the start of the first day.
User $0$ meets user $1$ (at the second hour to the third hour) and user $3$ (at the ninth hour).
Therefore, at the end of the first day, the two users will have the hoax.
User $1$ also meets user $2$ (at the first hour).
Therefore, at the end of the second day, user $2$ will also have the hoax.
There will be no hoax spreading on the third, fourth, and fifth day, thus $4$ users will have the hoax at the end of the fifth day.
Therefore, the procedure should return $4$.
```
count_users(4)
```
This means user $4$ has the hoax at the start of the first day.
User $4$ does not meet other users, thus other users will not have the hoax.
Therefore, the procedure should return $1$.
## Constraints
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
* $N, Q \le 50$ and the sum of all elements of $T$ does not exceed $50$.
## Sample Grader
The sample grader reads the input in the following format:
* line $1$: $N \; S \; Q$
* line $2 + i$ ($0 \le i \le N - 1$): $T[i] \; A[i][0] \; B[i][0] \; \ldots \; A[i][T[i] - 1] \; B[i][T[i] - 1]$
* line $2 + N + k$ ($0 \le k \le Q - 1$): $P$ for scenario $k$
The sample grader prints your answers in the following format:
* line $1 + k$ ($0 \le k \le Q - 1$): the return value of `count_users` for scenario $k$
|
Python
|
seed_418
|
# Hoax Spreading
Pak Dengklek has just developed a social media site.
There are $N$ users using the site, numbered $0$ to $N - 1$.
There are $S$ hours in one day.
All of these users have a fixed usage schedule from day to day.
For each $i$ such that $0 \le i \le N - 1$, user $i$ will be online $T[i]$ times every day:
* from the start of the $A[i][0]^{th}$ hour to the end of the $B[i][0]^{th}$ hour,
* from the start of the $A[i][1]^{th}$ hour to the end of the $B[i][1]^{th}$ hour,
* ...
* and from the start of the $A[i][T[i] - 1]^{th}$ hour to the end of the $B[i][T[i] - 1]^{th}$ hour.
At any time, all users on the site like to share news to all other online users.
Unfortunately, one of the $N$ users has a hoax at the start of the first day and will spread it.
Hence, all users who meet the user with the hoax will also have the hoax at the end of the first day.
Two users are stated to be met if there is at least an hour where the two users are both online.
This hoax will also be spread on the second day.
Therefore, all users who meet the user with the hoax at the end of the first day will also have the hoax at the end of the second day.
This continued the following days.
There are $Q$ scenarios, each can be represented as an integer $P$.
For each scenario, the user who has the hoax at the start of the first day is user $P$.
A different scenario might cause a different hoax spreading.
Therefore, for each scenario, Pak Dengklek wonders on the number of users with the hoax at the end of the $N^{th}$ day, where $N$ is the number of users.
## Implementation Details
You should implement the following procedures:
```
void init(int N, int S, int[] T, int[][] A, int[][] B)
```
* $N$: the number of elements in the array $T$, $A$, and $B$.
* $S$: the number of hours in one day.
* $T$: an array of length $N$ describing the number of times each user will be online every day.
* $A, B$: arrays of length $N$. $A[i]$ and $B[i]$ are arrays of length $T[i]$ describing when user $i$ will be online every day.
* This procedure is called exactly once, before any calls to `count_users`.
```
int count_users(int P)
```
* $P$: the index of the user who has the hoax at the start of the first day.
* This procedure should return the number of users with the hoax at the end of the $N^{th}$ day, where $N$ is the number of users.
* This procedure is called exactly $Q$ times.
## Example
Consider the following sequence of calls:
```
init(5, 10, [2, 1, 1, 1, 1],
[[2, 7], [1], [1], [9], [5]], [[4, 9], [3], [1], [10], [6]])
```
```
count_users(0)
```
This means user $0$ has the hoax at the start of the first day.
User $0$ meets user $1$ (at the second hour to the third hour) and user $3$ (at the ninth hour).
Therefore, at the end of the first day, the two users will have the hoax.
User $1$ also meets user $2$ (at the first hour).
Therefore, at the end of the second day, user $2$ will also have the hoax.
There will be no hoax spreading on the third, fourth, and fifth day, thus $4$ users will have the hoax at the end of the fifth day.
Therefore, the procedure should return $4$.
```
count_users(4)
```
This means user $4$ has the hoax at the start of the first day.
User $4$ does not meet other users, thus other users will not have the hoax.
Therefore, the procedure should return $1$.
## Constraints
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
* $N, S, Q \le 50$ and the sum of all elements of $T$ does not exceed $50$.
## Sample Grader
The sample grader reads the input in the following format:
* line $1$: $N \; S \; Q$
* line $2 + i$ ($0 \le i \le N - 1$): $T[i] \; A[i][0] \; B[i][0] \; \ldots \; A[i][T[i] - 1] \; B[i][T[i] - 1]$
* line $2 + N + k$ ($0 \le k \le Q - 1$): $P$ for scenario $k$
The sample grader prints your answers in the following format:
* line $1 + k$ ($0 \le k \le Q - 1$): the return value of `count_users` for scenario $k$
|
Python
|
seed_420
|
# How many urinals are free?
In men's public toilets with urinals, there is this unwritten rule that you leave at least one urinal free
between you and the next person peeing.
For example if there are 3 urinals and one person is already peeing in the left one, you will choose the
urinal on the right and not the one in the middle.
That means that a maximum of 3 people can pee at the same time on public toilets with
5 urinals when following this rule (Only 2 if the first person pees into urinal 2 or 4).

## Your task:
You need to write a function that returns the maximum of free urinals as an integer according to the unwritten rule.
### Input
A String containing 1s and 0s (Example: `10001`) (1 <= Length <= 20)
A one stands for a taken urinal and a zero for a free one.
### Examples
`10001` returns 1 (10101)
`1001` returns 0 (1001)
`00000` returns 3 (10101)
`0000` returns 2 (1001)
`01000` returns 1 (01010 or 01001)
### Note
When there is already a mistake in the input string (for example `011`), then return `-1`
Have fun and don't pee into the wrong urinal ;)
|
Python
|
seed_421
|
# How many ways can you make the sum of a number?
From wikipedia: https://en.wikipedia.org/wiki/Partition_(number_theory)#
>In number theory and combinatorics, a partition of a positive integer *n*, also called an *integer partition*, is a way of writing n as a sum of positive integers. Two sums that differ only in the order of their summands are considered the same partition. If order matters, the sum becomes a composition. For example, 4 can be partitioned in five distinct ways:
```
4
3 + 1
2 + 2
2 + 1 + 1
1 + 1 + 1 + 1
```
## Examples
### Basic
```python
exp_sum(1) # 1
exp_sum(2) # 2 -> 1+1 , 2
exp_sum(3) # 3 -> 1+1+1, 1+2, 3
exp_sum(4) # 5 -> 1+1+1+1, 1+1+2, 1+3, 2+2, 4
exp_sum(5) # 7 -> 1+1+1+1+1, 1+1+1+2, 1+1+3, 1+2+2, 1+4, 5, 2+3
exp_sum(10) # 42
```
### Explosive
```python
exp_sum(50) # 204226
exp_sum(80) # 15796476
exp_sum(100) # 190569292
```
See [here](http://www.numericana.com/data/partition.htm) for more examples.
|
Python
|
seed_422
|
# How much is the fish! (- Scooter )
The ocean is full of colorful fishes. We as programmers want to know the hexadecimal value of these fishes.
## Task
Take all hexadecimal valid characters (a,b,c,d,e,f) of the given name and XOR them. Return the result as an integer.
## Input
The input is always a string, which can contain spaces, upper and lower case letters but no digits.
## Example
`fisHex("redlionfish") -> e,d,f -> XOR -> 12`
|
Python
|
seed_423
|
# INTERNATIONAL OLYMPIAD IN INFORMATICS 2007
**ZAGREB -- CROATIA**
**AUGUST 15 -- 22**
**COMPETITION DAY 1 -- ALIENS**
## ALIENS
Mirko is a big fan of crop circles, geometrical formations of flattened crops that are supposedly of alien origin. One summer night he decided to make his own formation on his grandmother's meadow. The great patriot that he is, Mirko decided to make a crop formation that would have the shape of the shield part of the Croatian coat of arms, which is a \(5 \times 5\) chessboard with 13 red squares and 12 white squares.

*The chessboard part of the Croatian coat of arms.*
Grandma's meadow is a square divided into \(N \times N\) cells. The cell in the lower left corner of the meadow is represented by the coordinates \((1, 1)\) and the cell in the upper right corner is represented by \((N, N)\). Mirko decided to flatten only the grass belonging to red squares in the chessboard, leaving the rest of the grass intact. He picked an odd integer \(M \geq 3\) and flattened the grass so that each square of the chessboard comprises \(M \times M\) cells in the meadow, and the chessboard completely fits inside the meadow.

*Example meadow and Mirko's crop formation, with \(N=19\) and \(M=3\).*
*Cells with flattened grass are shown in gray.*
*The center of the formation is at \((12, 9)\) and is marked with a black point.*
## TASK
After Mirko went to sleep, his peculiar creation drew the attention of real aliens! They are floating high above the meadow in their spaceship and examining Mirko's crop formation with a simple device. This device can only **determine whether the grass in a particular cell is flattened or not**.
The aliens have found one cell with flattened grass and now they want to find the **center cell** of Mirko's masterpiece, so that they may marvel at its beauty. **They do not know the size \(M\) of each square in Mirko's crop formation.**
Write a program that, given the size \(N\) (\(15 \leq N \leq 2,000,000,000\)) of the meadow, the coordinates \((X_0, Y_0)\) of one cell with flattened grass, and the ability to interact with the alien device, finds the coordinates of the center cell of Mirko's crop formation.
The device may be used at most 300 times in one test run.
## INTERACTION
This is an interactive task. Your program sends commands to the alien device using the standard output, and receives feedback from the device by reading from the standard input.
- At the beginning of your program, you should read three integers \(N, X_0, Y_0\) from the standard input, separated by single spaces. The number \(N\) is the size of the meadow, while \((X_0, Y_0)\) are the coordinates of one cell with flattened grass.
- To examine the grass in the cell \((X, Y)\) using the alien device, you should output a line of the form `examine X Y` to the standard output. If the coordinates \((X, Y)\) are not inside the meadow (the conditions \(1 \leq X \leq N\) and \(1 \leq Y \leq N\) are not satisfied), or if you use this facility more than 300 times, your program will receive a score of zero on that test run.
- The alien device will respond with a single line containing the word `true` if the grass in cell \((X, Y)\) is flattened and the word `false` otherwise.
- When your program has found the center cell, it should output a line of the form `solution Xc Yc` to the standard output, where \((X_c, Y_c)\) are the coordinates of the center cell. The execution of your program will be automatically terminated once your program outputs a solution.
In order to interact properly with the grader, your program needs to **flush the standard output** after every write operation; the provided code samples show how to do this.
## CODE SAMPLES
Code samples in all three programming languages are available for download on the "Tasks" page of the contest system. The purpose of the samples is only to show how to interact with the alien device; these are not the correct solutions and will not score all points.
## GRADING
- In test cases worth a total of 40 points, the size \(M\) of each of Mirko's squares will be at most 100.
- Each test run will have a unique correct answer that will not depend on the questions asked by your program.
## EXAMPLE
In the following example, commands are given in the left column, row by row. Feedback from the alien device is given in the second column of the corresponding row.
| **Output (command)** | **Input (feedback)** |
|----------------------|----------------------|
| `19 7 4` | |
| `examine 11 2` | `true` |
| `examine 2 5` | `false` |
| `examine 9 14` | `false` |
| `examine 18 3` | `true` |
| `solution 12 9` | |
## TESTING
During the contest, there are three ways to test your solutions.
- The first way is for you to simulate the alien device manually and interact with your program.
- The second way is to write a program which will simulate the alien device. To connect your solution and the device you wrote, you may use a utility called `connect`, available for download on the contest system. To use the utility issue a command such as `./connect ./solution ./device` from the console (substituting `solution` and `device` with the names of your two programs). Any additional command-line parameters will be passed on to the device program.
- The third way is to use the TEST facility of the grading system to automatically run your solution with a custom test case. When using the facility, the size of the meadow \(N\) is limited to 100.
A test case should contain three lines:
- The first line contains the size \(N\) of the meadow and the size \(M\) of a square in the chessboard.
- The second line contains the coordinates \(X_0\) and \(Y_0\) of one cell of the meadow with flattened grass, which will be given to your program.
- The third line contains the coordinates \(X_c\) and \(Y_c\) of the center cell of the chessboard.
The grading system will provide you with a detailed log of the execution, including error messages if:
- \(N\) doesnβt satisfy the constraints;
- \(M\) is not an odd integer greater than or equal to 3;
- The crop formation doesnβt fit in the meadow;
- The grass in cell \((X_0, Y_0)\) is not flattened.
Here is an example of a valid input file for the test facility. The example corresponds to the figure on the first page.
```
19 3
7 4
12 9
```
*Valid input for the test facility.*
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
|
Python
|
seed_424
|
# INTERNATIONAL OLYMPIAD IN INFORMATICS 2007
**ZAGREB -- CROATIA**
**AUGUST 15 -- 22**
**COMPETITION DAY 1 -- SAILS**
## SAILS
A new pirate sailing ship is being built. The ship has \( N \) masts (poles) divided into unit-sized segments -- the height of a mast is equal to the number of its segments. Each mast is fitted with a number of sails and each sail exactly fits into one segment. Sails on one mast can be arbitrarily distributed among different segments, but each segment can be fitted with at most one sail.
Different configurations of sails generate different amounts of thrust when exposed to the wind. Sails in front of other sails at the same height get less wind and contribute less thrust. For each sail, we define its **inefficiency** as the total number of sails that are **behind** this sail and **at the same height**. Note that \"in front of\" and \"behind\" relate to the orientation of the ship: in the figure below, \"in front of\" means to the left, and \"behind\" means to the right.
The **total inefficiency** of a configuration is the sum of the inefficiencies of all individual sails.
<center>
<image>
</center>
This ship has 6 masts, of heights \(3, 5, 4, 2, 4, 3\) from front (left side of image) to back. This distribution of sails gives a total inefficiency of \(10\). The individual inefficiency of each sail is written inside the sail.
## TASK
Write a program that, given the height and the number of sails on each of the \(N\) masts, determines the **smallest possible total inefficiency**.
## INPUT
The first line of input contains an integer \( N \; (2 \leq N \leq 100,000) \), the number of masts on the ship.
Each of the following \( N \) lines contains two integers \( H \) and \( K \; (1 \leq H \leq 100,000, \; 1 \leq K \leq H) \), the height and the number of sails on the corresponding mast. Masts are given in order from the front to the back of the ship.
## OUTPUT
Output should consist of a single integer, the smallest possible total inefficiency.
**Note:** Use a 64-bit integer type to calculate and output the result (`long long` in C/C++, `int64` in Pascal).
## EXAMPLE
**Input:**
```
6
3 2
5 3
4 1
2 1
4 3
3 2
```
**Output:**
```
10
```
This example corresponds to the figure on the previous page.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
|
Python
|
seed_425
|
# INTERNATIONAL OLYMPIAD IN INFORMATICS 2007
**ZAGREB -- CROATIA**
**AUGUST 15 -- 22**
**COMPETITION DAY 2 -- PAIRS**
## PAIRS
Mirko and Slavko are playing with toy animals. First, they choose one of three boards given in the figure below. Each board consists of cells (shown as circles in the figure) arranged into a one, two or three dimensional grid.

Mirko then places $N$ little *toy animals* into the cells.
The *distance* between two cells is the smallest number of moves that an animal would need in order to reach one cell from the other. In one move, the animal may step into one of the adjacent cells (connected by line segments in the figure).
Two animals can hear each other if the distance between their cells is at most $D$. Slavko's task is to calculate how many *pairs of animals* there are such that one animal can hear the other.
## TASK
Write a program that, given the board type, the locations of all animals, and the number $D$, finds the desired number of pairs.
## INPUT
The first line of input contains four integers in this order:
- The board type $B$ ($1 \leq B \leq 3$);
- The number of animals $N$ ($1 \leq N \leq 100,000$);
- The largest distance $D$ at which two animals can hear each other ($1 \leq D \leq 100,000,000$);
- The size of the board $M$ (the largest coordinate allowed to appear in the input):
- When $B=1$, $M$ will be at most $75,000,000$.
- When $B=2$, $M$ will be at most $75,000$.
- When $B=3$, $M$ will be at most $75$.
Each of the following $N$ lines contains $B$ integers separated by single spaces, the coordinates of one toy animal. Each coordinate will be between $1$ and $M$ (inclusive).
More than one animal may occupy the same cell.
## OUTPUT
Output should consist of a single integer, the number of pairs of animals that can hear each other.
**Note:** use a 64-bit integer type to calculate and output the result (`long long` in C/C++, `int64` in Pascal).
## EXAMPLES
| **Input** | **Input** | **Input** |
|-------------------|----------------|-----------------|
| `1 6 5 100` | `2 5 4 10` | `3 8 10 20` |
| `25` | `5 2` | `10 10 10` |
| `50` | `7 2` | `10 10 20` |
| `50` | `8 4` | `10 20 10` |
| `10` | `6 5` | `10 20 20` |
| `20` | `4 4` | `20 10 20` |
| `23` | | `20 20 10` |
| | | `20 20 20` |
| **Output** | **Output** | **Output** |
|-------------------|----------------|-----------------|
| `4` | `8` | `12` |
## Clarification for the leftmost example
Suppose the animals are numbered $1$ through $6$ in the order in which they are given. The four pairs are:
- $1-5$ (distance $5$)
- $1-6$ (distance $2$)
- $2-3$ (distance $0$)
- $5-6$ (distance $3$)
## Clarification for the middle example
The eight pairs are:
- $1-2$ (distance $2$)
- $1-4$ (distance $4$)
- $1-5$ (distance $3$)
- $2-3$ (distance $3$)
- $2-4$ (distance $4$)
- $3-4$ (distance $3$)
- $3-5$ (distance $4$)
- $4-5$ (distance $3$)
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
|
Python
|
seed_426
|
# INTERNATIONAL OLYMPIAD IN INFORMATICS 2007
**ZAGREB β CROATIA**
**AUGUST 15 β 22**
**COMPETITION DAY 2 β TRAINING**
# TRAINING
Mirko and Slavko are training hard for the annual tandem cycling marathon taking place in Croatia. They need to choose a route to train on.
There are $N$ cities and $M$ roads in their country. Every road connects two cities and can be traversed in both directions. Exactly $N-1$ of those roads are paved, while the rest of the roads are unpaved trails. Fortunately, the network of roads was designed so that each pair of cities is connected by a path consisting of paved roads. In other words, the $N$ cities and the $N-1$ paved roads form a *tree structure*.
Additionally, each city is an endpoint for **at most 10 roads total**.
A training route starts in some city, follows some roads and ends in the same city it started in. Mirko and Slavko like to see new places, so they made a rule **never to go through the same city nor travel the same road twice**. The training route may start in any city and does not need to visit every city.
Riding in the back seat is easier, since the rider is shielded from the wind by the rider in the front. Because of this, Mirko and Slavko change seats in every city. To ensure that they get the same amount of training, they must choose a route with an **even number of roads**.
Mirko and Slavko's competitors decided to **block some of the unpaved roads**, making it impossible for them to find a training route satisfying the above requirements. For each unpaved road there is a **cost** (a positive integer) associated with blocking the road. It is impossible to block paved roads.
## Task
Write a program that, given the description of the network of cities and roads, finds the **smallest total cost** needed to block the roads so that **no training route exists** satisfying the above requirements.
## Input
The first line of input contains two integers $N$ and $M$ ($2 \leq N \leq 1,000$, $N-1 \leq M \leq 5,000$), the number of cities and the total number of roads.
Each of the following $M$ lines contains three integers $A$, $B$ and $C$ ($1 \leq A \leq N$, $1 \leq B \leq N$, $0 \leq C \leq 10,000$), describing one road. The numbers $A$ and $B$ are different and they represent the cities directly connected by the road. If $C=0$, the road is paved; otherwise, the road is unpaved and $C$ represents the cost of blocking it.
Each city is an endpoint for at most 10 roads. There will never be more than one road directly connecting a single pair of cities.
## Output
Output should consist of a single integer, the smallest total cost as described in the problem statement.
## Detailed Feedback When Submitting
During the contest, you may select up to 10 submissions for this task to be evaluated (as soon as possible) on part of the official test data. After the evaluation is done, a summary of the results will be available on the contest system.
# EXAMPLES
### Input
```
5 8
2 1 0
3 2 0
4 3 0
5 4 0
1 3 2
3 5 2
2 4 5
2 5 1
```
### Output
```
5
```
### Input
```
9 14
1 2 0
1 3 0
2 3 14
2 6 15
3 4 0
3 5 0
3 6 12
3 7 13
4 6 10
5 6 0
5 7 0
5 8 0
6 9 11
8 9 0
```
### Output
```
48
```

The layout of the roads and cities in the first example. Paved roads are shown in bold.
There are five possible routes for Mirko and Slavko. If the roads 1-3, 3-5 and 2-5 are blocked, then Mirko and Slavko cannot use any of the five routes. The cost of blocking these three roads is 5.
It is also possible to block just two roads, 2-4 and 2-5, but this would result in a higher cost of 6.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
|
Python
|
seed_427
|
# INTERNATIONAL OLYMPIAD IN INFORMATICS 2007
## ZAGREB -- CROATIA
## AUGUST 15 -- 22
## COMPETITION DAY 1 -- FLOOD
## FLOOD
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.
<center>
<image>
</center>
*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 \leq N \leq 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 \leq W \leq 2N\)), the number of walls.
Each of the following \(W\) lines contains two different integers \(A\) and \(B\) (\(1 \leq A \leq N\), \(1 \leq B \leq 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.
## DETAILED FEEDBACK WHEN SUBMITTING
During the contest, you may select up to 10 submissions for this task to be evaluated (as soon as possible) on part of the official test data. After the evaluation is done, a summary of the results will be available on the contest system.
## EXAMPLE
**Input:**
```
15
1 1
8 1
4 2
7 2
2 3
4 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
```
*This example corresponds to the figure on the previous page.*
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
|
Python
|
seed_430
|
# International Olympiad In Informatics 2008
## August 16 -- 23, Cairo
## Contest Day 2 - Linear Garden
### LINEAR GARDEN
Rameses II has just returned victorious from battle. To commemorate his victory, he has decided to build a majestic garden. The garden will contain a long line of plants that will run all the way from his palace at Luxor to the temple of Karnak. It will consist only of lotus plants and papyrus plants, since they symbolize Upper and Lower Egypt respectively.
The garden must contain exactly $N$ plants. Also, it must be balanced: in any contiguous section of the garden, the numbers of lotus and papyrus plants must not differ by more than 2.
A garden can be represented as a string of letters `L` (lotus) and `P` (papyrus). For example, for $N=5$ there are 14 possible balanced gardens. In alphabetical order, these are:
```
LLLPL, LLLPP, LLPLP, LPPLL, LPPLP, LPLLL, LPLLP, LPLPL, PLLLL, PLLLP, PLLLP, PLLPL, PLPPL, PPLPL.
```
The possible balanced gardens of a certain length can be ordered alphabetically, and then numbered starting from 1. For example, for $N=5$, garden number 12 is the garden `PLPPL`.
### Task
Write a program that, given the number of plants $N$ and a string that represents a balanced garden, calculates the number assigned to this garden **modulo some given integer** $M$.
Note that for solving the task, the value of $M$ has no importance other than simplifying computations.
### Constraints
- $1 \leq N \leq 1,000,000$
- $7 \leq M \leq 10,000,000$
### Input
Your program must read from the standard input the following data:
- Line 1 contains the integer $N$, the number of plants in the garden.
- Line 2 contains the integer $M$.
- Line 3 contains a string of $N$ characters `L` (lotus) or `P` (papyrus) that represents a balanced garden.
### Output
Your program must write to the standard output a single line containing one integer between 0 and $M-1$ (inclusive), the number assigned to the garden described in the input, **modulo** $M$.
### Example
| **Sample input 1** | **Sample output 1** |
|---------------------|---------------------|
| 5 | 5 |
| 7 | |
| PLPPL | |
The actual number assigned to `PLPPL` is 12. So, the output is $12 \mod 7$, which is 5.
| **Sample input 2** | **Sample output 2** |
|---------------------|---------------------|
| 12 | 39 |
| 10000 | |
| LPLLLPLPPLLL | |
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
no additional constraints
|
Python
|
seed_431
|
# International Olympiad In Informatics 2008
## August 16 -- 23, Cairo
### Contest Day 2 -- Teleporters
### English 1.2
---
## TELEPORTERS
You are participating in a competition that involves crossing Egypt from west to east along a straight line segment. Initially you are located at the westmost point of the segment. It is a rule of the competition that you must always move along the segment, and always eastward.
There are $N$ teleporters on the segment. A teleporter has two endpoints. Whenever you reach one of the endpoints, the teleporter immediately teleports you to the other endpoint. (Note that, depending on which endpoint of the teleporter you reach, teleportation can transport you either eastward or westward of your current position.) After being teleported, you must continue to move eastward along the segment; you can never avoid a teleporter endpoint that is on your way. There will never be two teleporter endpoints at the same position. Endpoints will be strictly between the start and the end of the segment.
Every time you get teleported, you earn 1 point. The objective of the competition is to earn as many points as possible. In order to maximize the points you earn, you are allowed to add up to $M$ new teleporters to the segment before you start your journey. You also earn points for using the new teleporters.
You can set the endpoints of the new teleporters wherever you want (even at non-integer coordinates) as long as they do not occupy a position already occupied by another endpoint. That is, the positions of the endpoints of all teleporters must be unique. Also, endpoints of new teleporters must lie strictly between the start and the end of the segment.
Note that it is guaranteed that no matter how you add the teleporters, you can always reach the end of the segment.
---
## TASK
Write a program that, given the position of the endpoints of the $N$ teleporters, and the number $M$ of new teleporters that you can add, computes the maximum number of points you can earn.
---
## CONSTRAINTS
- $1 \leq N \leq 1,000,000$
The number of teleporters initially on the segment.
- $1 \leq M \leq 1,000,000$
The maximum number of new teleporters you can add.
- $1 \leq W_X < E_X \leq 2,000,000$
The distances from the beginning of the segment to the western and eastern endpoints of teleporter $X$.
---
## INPUT
Your program must read from the standard input the following data:
- Line 1 contains the integer $N$, the number of teleporters initially on the segment.
- Line 2 contains the integer $M$, the maximum number of new teleporters that you can add.
- Each of the next $N$ lines describes one teleporter. The $i^{\text{th}}$ of these lines describes the $i^{\text{th}}$ teleporter. Each line consists of 2 integers: $W_i$ and $E_i$ separated by a space. They represent respectively the distances from the beginning of the segment to the western and eastern endpoints of the teleporter.
No two endpoints of the given teleporters share the same position. The segment that you will be travelling on starts at position $0$ and ends at position $2,000,001$.
---
## OUTPUT
Your program must write to the standard output a single line containing one integer, the maximum number of points you can earn.
---
## EXAMPLE
### Sample input 1
```
3
1
10 11
1 4
2 3
```
### Sample output 1
```
6
```

The first figure shows a segment with the three original teleporters. The second figure shows the same segment after adding a new teleporter with endpoints at $0.5$ and at $1.5$.
After adding the new teleporter as shown in the figure, your travel would be the following:
- You start at position $0$, moving eastward.
- You reach the endpoint at position $0.5$ and get teleported to position $1.5$ (you earn 1 point).
- You continue to move east and reach endpoint at position $2$; you get teleported to position $3$ (you have 2 points).
- You reach endpoint at position $4$, and get teleported to $1$ (you have 3 points).
- You reach endpoint at $1$, and get teleported to $4$ (you have 4 points).
- You reach endpoint at $10$, and get teleported to $11$ (you have 6 points).
- You continue until you reach the end of the segment finishing with a total score of 6 points.
### Sample input 2
```
3
3
5 7
6 10
1999999 2000000
```
### Sample output 2
```
12
```
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
|
Python
|
seed_432
|
# International Olympiad In Informatics 2008
**August 16 -- 23, Cairo**
**Contest Day 1 - Islands**
**English 1.3**
## ISLANDS
You are visiting a park which has $N$ islands. From each island $i$, exactly one bridge was constructed. The length of that bridge is denoted by $L_i$. The total number of bridges in the park is $N$. Although each bridge was built from one island to another, now every bridge can be traversed in both directions. Also, for each pair of islands, there is a unique ferry that travels back and forth between them.
Since you like walking better than riding ferries, you want to maximize the sum of the lengths of the bridges you cross, subject to the constraints below.
- You can start your visit at an island of your choice.
- You may not visit any island more than once.
- At any time you may move from your current island $S$ to another island $D$ that you have not visited before. You can go from $S$ to $D$ either by:
- **Walking:** Only possible if there is a bridge between the two islands. With this option the length of the bridge is added to the total distance you have walked, or
- **Ferry:** You can choose this option only if $D$ is not reachable from $S$ using any combination of bridges and/or previously used ferries. (When checking whether it is reachable or not, you consider all paths, including paths passing through islands that you have already visited.)
Note that you do not have to visit all the islands, and it may be impossible to cross all the bridges.
## TASK
Write a program that, given the $N$ bridges along with their lengths, computes the maximum distance you can walk over the bridges obeying the rules described above.
## CONSTRAINTS
- $2 \leq N \leq 1,000,000$ (The number of islands in the park.)
- $1 \leq L_i \leq 100,000,000$ (The length of bridge $i$.)
## INPUT
Your program must read from the standard input the following data:
- Line 1 contains the integer $N$, the number of islands in the park. Islands are numbered from $1$ to $N$, inclusive.
- Each of the next $N$ lines describes a bridge. The $i$th of these lines describes the bridge constructed from island $i$ using two integers separated by a single space. The first integer represents the island at the other endpoint of the bridge, the second integer represents the length $L_i$ of the bridge. You may assume that for each bridge, its endpoints are always on two different islands.
## OUTPUT
Your program must write to the standard output a single line containing one integer, the maximum possible walking distance.
## NOTE 1
For some of the test cases the answer will not fit in a 32-bit integer, you might need `int64` in Pascal or `long long` in C/C++ to score full points on this problem.
## NOTE 2
When running Pascal programs in the contest environment, it is significantly slower to read in 64-bit data types than 32-bit data types from standard input even when the values being read in fit in 32 bits. We recommend that you read the input data into 32-bit data types.
## EXAMPLE
**Sample input**
```
7
3 8
7 2
4 2
1 4
1 9
3 4
2 3
```
**Sample output**
```
24
```
The $N=7$ bridges in the sample are (1-3), (2-7), (3-4), (4-1), (5-1), (6-3) and (7-2). Note that there are two different bridges connecting islands 2 and 7.
One way that you can achieve maximum walking distance follows:
- Start on island 5.
- Walk the bridge of length 9 to reach island 1.
- Walk the bridge of length 8 to reach island 3.
- Walk the bridge of length 4 to reach island 6.
- Take the ferry from island 6 to island 7.
- Walk the bridge of length 3 to reach island 2.
By the end you are on island 2 and your total walking distance is $9+8+4+3=24$.
The only island that was not visited is island 4. Note that at the end of the trip described above you cannot visit this island any more. More precisely:
- You are not able to visit it by walking, because there is no bridge connecting island 2 (where you currently stand) and island 4.
- You are not able to visit it using a ferry, because island 4 is reachable from island 2, where you currently stand. A way to reach it is: use the bridge (2-7), then use a ferry you already used to get from island 7 to island 6, then the bridge (6-3), and finally the bridge (3-4).
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
|
Python
|
seed_433
|
# International Olympiad In Informatics 2009
## Contest Day 1 - Hiring
### HIRING
You have to hire workers for a construction project. There are \( N \) candidates applying for the job, numbered from 1 to \( N \) inclusive. Each candidate \( k \) requires that if he is hired, he must be paid at least \( S_k \) dollars. Also, each candidate \( k \) has a qualification level \( Q_k \). The regulations of the construction industry require that you pay your workers in proportion to their qualification level, relative to each other. For example, if you hire two workers \( A \) and \( B \), and \( Q_A = 3 \ast Q_B \), then you have to pay worker \( A \) exactly three times as much as you pay worker \( B \). You are allowed to pay your workers non-integer amounts of money. This even includes quantities that cannot be written with a finite number of digits in decimal form, such as a third or a sixth of a dollar.
You have \( W \) dollars at hand and you want to hire as many workers as possible. You decide whom to hire and how much to pay them, but you have to meet the minimum salary requirements of those you choose to hire, and you have to obey the industry regulations. You also have to fit within your budget of \( W \) dollars.
The nature of your project is such that the qualification level is completely irrelevant, so you are only interested in maximizing the number of workers without regard to their qualification level. However, if there is more than one way to achieve this, then you want to select the one where the total amount of money you have to pay your workers is as small as possible. In case there is more than one way to achieve this, then you are indifferent among these ways and you would be satisfied with any one of them.
### TASK
Write a program that, given the different salary requirements and qualification levels of the candidates, as well as the amount of money you have, determines which candidates you should hire. You must hire as many of them as possible and you must do so with as little money as possible, while complying with the industry regulations specified above.
### CONSTRAINTS
```
1 <= N <= 500,000 # The number of candidates
1 <= S_k <= 20,000 # The minimum salary requirement of candidate k
1 <= Q_k <= 20,000 # The qualification level of candidate k
1 <= W <= 10,000,000,000 # The amount of money available to you
```
**IMPORTANT NOTE**
The maximum value of \( W \) does not fit in 32 bits. You have to use a 64-bit data type, such as `long long` in C/C++ or `int64` in Pascal, in order to store the value of \( W \) in a single variable. Please see the technical info sheet for details.
### INPUT
Your program must read from standard input the following data:
- The first line contains the integers \( N \) and \( W \), separated by a space.
- The next \( N \) lines describe the candidates, one candidate per line. The \( k \)-th of these lines describes candidate number \( k \) and it contains the integers \( S_k \) and \( Q_k \), separated by a space.
### OUTPUT
Your program must write to standard output the following data:
- The first line must contain a single integer \( H \), the number of workers that you hire.
- The next \( H \) lines must list the identifying numbers of the candidates you choose to hire (each of them a different number between 1 and \( N \)), one per line, in any order.
### EXAMPLES
#### Sample Input
```
4 100
5 1000
10 100
8 10
20 1
```
#### Sample Output
```
2
2
3
```
The only combination for which you can afford to hire two workers and still meet all the constraints is if you select workers 2 and 3. You can pay them 80 and 8 dollars respectively and thus fit in your budget of 100.
#### Sample Input
```
3 4
1 2
1 3
1 3
```
#### Sample Output
```
3
1
2
3
```
Here you can afford to hire all three workers. You pay 1 dollar to worker 1 and 1.50 dollars each to workers 2 and 3, and you manage to hire everyone with the 4 dollars that you have.
#### Sample Input
```
3 40
10 1
10 2
10 3
```
#### Sample Output
```
2
2
3
```
Here you cannot afford to hire all three workers, as it would cost you 60 dollars, but you can afford to hire any two of them. You choose to hire workers 2 and 3 because they would cost you the smallest sum of money, compared to the other two-worker combinations. You can pay 10 dollars to worker 2 and 15 dollars to worker 3 for a total of 25 dollars. If you were to hire workers 1 and 2 you would have to pay them at least 10 and 20 dollars respectively. If you were to hire 1 and 3, then you would have to pay them at least 10 and 30 dollars respectively.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
|
Python
|
seed_434
|
# International Olympiad In Informatics 2009
## Contest Day 2 - Salesman
### Salesman
The traveling salesman has decided that optimally scheduling his trips on land is an intractable computational problem, so he is moving his business to the linear world of the Danube River. He has a very fast boat that can get him from anywhere to anywhere along the river in no time, but unfortunately the boat has terrible fuel consumption. It costs the salesman $U$ dollars for every meter traveled upstream (towards the source of the river) and $D$ dollars for every meter traveled downstream (away from the source of the river).
There are $N$ trade fairs that the salesman would like to visit along the river. Each trade fair is held for one day only. For each trade fair $X$, the traveling salesman knows its date $T_x$, measured in the number of days since he purchased his boat. He also knows the fair's location $L_x$, measured as the distance in meters from the source of the river downstream to the fair, as well as the number of dollars $M_x$ that the salesman is going to gain if he attends this trade fair. He has to start and end his journey at his waterfront home on the river, which is at location $S$, measured also in meters downstream from the source of the river.
Help the traveling salesman choose which trade fairs to attend (if any) and in what order, so that he may maximize his profit at the end of his travels. The traveling salesman's total profit is defined as the sum of the dollars he gained at the fairs he attended, minus the total sum of dollars he spent traveling up and down the river.
Keep in mind that if trade fair $A$ is held earlier than trade fair $B$, the salesman can visit them only in this order (i.e., he cannot visit $B$ and then visit $A$). However, if two fairs are held on the same date, the salesman can visit them both in any order. There is no limit to how many fairs the salesman can visit in a day, but naturally he can't visit the same fair twice and reap the gains twice. He can pass through fairs he has already visited without gaining anything.
### Task
Write a program that, given the date, location and profitability of all fairs, as well as the location of the traveling salesman's home and his costs of traveling, determines the maximum possible profit he can make by the end of his journey.
### Constraints
- $1 \leq N \leq 500,000$ The number of fairs
- $1 \leq D \leq U \leq 10$ The cost of traveling one meter upstream ($U$) or downstream ($D$)
- $1 \leq S \leq 500,001$ The location of the salesman's home
- $1 \leq T_k \leq 500,000$ The day on which fair $k$ is held
- $1 \leq L_k \leq 500,001$ The location of fair $k$
- $1 \leq M_k \leq 4,000$ The number of dollars the salesman would earn if he attends fair $k$
### Input
Your program must read from standard input the following data:
- The first line contains the integers $N$, $U$, $D$ and $S$, in this order, separated by single spaces.
- The next $N$ lines describe the $N$ fairs in no particular order. The $k^{\text{th}}$ of these $N$ lines describes the day of the fair $T_k$, its location $L_k$, and its profitability for the salesman $M_k$.
**NOTE:** All locations given in the input will be different. That is to say, no two fairs will happen at the same location and no fair will happen at the salesman's home.
### Output
Your program must write to standard output a single line containing a single integer: the maximum profit the salesman can possibly make by the end of his journey.
### Example
| Sample Input | Sample Output |
|----------------------|---------------|
| 4 5 3 100 | 50 |
| 2 80 100 | |
| 20 125 130 | |
| 10 75 150 | |
| 5 120 110 | |
### Explanation
An optimal schedule would visit fairs 1 and 3 (the ones at locations 80 and 75). The sequence of events and their associated profits and costs would be as follows:
- The salesman travels 20 meters upstream at a cost of 100 dollars. Profit so far: $-100$
- He attends fair number 1 and earns 100. Profit so far: $0$
- He travels 5 meters upstream at a cost of 25. Profit so far: $-25$
- He attends fair number 3 where he earns 150. Profit so far: $125$
- He travels 25 meters downstream to return home at a cost of 75. Profit at the end: $50$
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
|
Python
|
seed_435
|
# International Olympiad in Informatics 2007
## Zagreb -- Croatia
### August 15 -- 22
### Competition Day 2 -- Miners
## MINERS
There are two coal mines, each employing a group of miners. Mining coal is hard work, so miners need food to keep at it. Every time a shipment of food arrives at their mine, the miners produce some amount of coal. There are three types of food shipments: meat shipments, fish shipments and bread shipments.
Miners like variety in their diet and they will be more productive if their food supply is kept varied. More precisely, every time a new shipment arrives to their mine, they will *consider the new shipment and the previous two shipments* (or fewer if there haven't been that many) and then:
- If all shipments were of the same type, they will produce one unit of coal.
- If there were two different types of food among the shipments, they will produce two units of coal.
- If there were three different types of food, they will produce three units of coal.
We know in advance the types of food shipments and the order in which they will be sent. It is possible to influence the amount of coal that is produced by determining which shipment should go to which mine. Shipments cannot be divided; each shipment must be sent to one mine or the other in its entirety.
The two mines don't necessarily have to receive the same number of shipments (in fact, it is permitted to send all shipments to one mine).
## Task
Your program will be given the types of food shipments, in the order in which they are to be sent. Write a program that finds the **largest total amount of coal** that can be produced (in both mines) by deciding which shipments should be sent to mine 1 and which shipments should be sent to mine 2.
## Input
The first line of input contains an integer $N$ ($1 \leq N \leq 100,000$), the number of food shipments.
The second line contains a string consisting of $N$ characters, the types of shipments in the order in which they are to be distributed. Each character will be one of the uppercase letters `M` (for meat), `F` (for fish) or `B` (for bread).
## Output
Output a single integer, the largest total amount of coal that can be produced.
## Detailed Feedback When Submitting
During the contest, you may select up to 10 submissions for this task to be evaluated (as soon as possible) on part of the official test data. After the evaluation is done, a summary of the results will be available on the contest system.
## Examples
| **Input** | **Input** |
|-----------|-----------|
| 6 | 16 |
| MBMFFB | MMBMBBBBMMMMMBMB |
| **Output** | **Output** |
|------------|------------|
| 12 | 29 |
In the left sample, by distributing the shipments in this order: mine 1, mine 1, mine 2, mine 2, mine 1, mine 2, the shipments will result in $1, 2, 1, 2, 3$ and $3$ units of coal produced in that order, for a total of 12 units. There are other ways to achieve this largest amount.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
|
Python
|
seed_437
|
# International Olympiad in Informatics 2011
## Competition Tasks -- Day 2
# ELEPHANTS
## Dancing Elephants
**Dancing Elephants** is a spectacular show in Pattaya that features $N$ elephants dancing on a line, known as the *stage*.
After years of training, elephants in this show are capable of many amazing dances. The show consists of a series of acts. In each act, exactly one elephant performs a cute dance while possibly moving to a different position.
The show producers want to produce a photo book that contains pictures of the entire show. After each act, they want to take pictures of all elephants as seen by the spectators.
At any time during the show, multiple elephants may share the same position. In that case, they simply stand behind one another at the same position.
A single camera can take a picture of a group of elephants if and only if all their positions lie on some segment of length $L$ (including both its endpoints). As the elephants can spread out across the stage, multiple cameras may be needed in order to take simultaneous snapshots of all the elephants.
As an example, suppose that $L=10$ and that the elephants are at positions $10$, $15$, $17$, and $20$ on the stage. At this moment, a single camera can take their picture, as shown below. (Elephants are shown as triangles; cameras are shown as trapezoids.)
<center>
<image>
</center>
In the following act, the elephant at position $15$ dances to position $32$. After this act, we need at least two cameras to take the snapshot.
<center>
<image>
</center>
In the next act, the elephant at position $10$ moves to position $7$. For the new arrangement of elephants, we need three cameras to photograph all of them.
<center>
<image>
</center>
In this interactive task, you have to determine the **minimum** number of cameras needed to take the pictures after each of the acts. Note that the number of cameras needed may increase, decrease, or stay the same between acts.
## Your Task
Write the following procedures:
- **Procedure** `init(N,L,X)` that takes the following parameters:
- $N$ -- the number of elephants. The elephants are numbered $0$ through $N-1$.
- $L$ -- the length of the segment captured by a single camera. You may assume that $L$ is an integer such that $0 \leq L \leq 1,000,000,000$.
- $X$ -- a one-dimensional array of integers representing the initial positions of the elephants. For $0 \leq i < N$, elephant $i$ starts at the position $X[i]$. The initial positions are in sorted order. More precisely, you may assume that $0 \leq X[0] \leq \ldots \leq X[N-1] \leq 1,000,000,000$. Note that during the dance the elephants may reorder themselves.
This procedure will be called only once, prior to all calls to `update`. It does not return any value.
- **Procedure** `update(i,y)` that takes the following parameters:
- $i$ -- the number of the elephant that moves in the current act.
- $y$ -- the position where the elephant $i$ will stand after the current act. You may assume that $y$ is an integer such that $0 \leq y \leq 1,000,000,000$.
This procedure will be called multiple times. Each call corresponds to a single act (which follows on from all of the previous acts). Each call must return the **minimum number of cameras needed** to photograph all elephants after the corresponding act.
### Example
Consider the case where $N=4$, $L=10$, and the initial positions of the elephants are:
```
X = [10, 15, 17, 20]
```
First, your procedure `init` will be called with these parameters. Afterwards, your procedure `update` will be called once for each act. Here is an example sequence of calls and their correct return values:
<center>
| **Act** | **Call Parameters** | **Return Value** |
|---------|----------------------|------------------|
| 1 | `update(2,16)` | 1 |
| 2 | `update(1,25)` | 2 |
| 3 | `update(3,35)` | 2 |
| 4 | `update(0,38)` | 2 |
| 5 | `update(2,0)` | 3 |
</center>
## Implementation Details
### Limits
- **CPU time limit:** 9 seconds
- *Note:* The collection templates in the C++ Standard Library (STL) can be slow; in particular, it might not be possible to solve subtask 5 if you use them.
- **Memory limit:** 256 MB
- *Note:* There is no explicit limit for the size of stack memory. Stack memory counts towards the total memory usage.
## Interface (API)
- **Implementation folder:** `elephants/`
- **To be implemented by contestant:** `elephants.c` or `elephants.cpp` or `elephants.pas`
- **Contestant interface:** `elephants.h` or `elephants.pas`
- **Sample grader:** `grader.c` or `grader.cpp` or `grader.pas`
- **Sample grader input:** `grader.in.1, grader.in.2, ...`
**Note:** The sample grader reads the input in the following format:
- Line 1: $N$, $L$, and $M$, where $M$ is the number of acts in the show.
- Lines 2 to $N+1$: The initial positions; i.e., line $k+2$ contains $X[k]$ for $0 \leq k < N$.
- Lines $N+2$ to $N+M+1$: Information on $M$ acts; i.e. line $N+1+j$ contains $i[j]$, $y[j]$, and $s[j]$, separated by a space, denoting that in the $j$-th act elephant $i[j]$ moves to position $y[j]$, and after that act, $s[j]$ is the minimal number of cameras needed, for $1 \leq j \leq M$.
**Expected output for sample grader input:** `grader.expect.1, grader.expect.2, ...`
For this task, each one of these files should contain precisely the text \"Correct.\"
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
- $1 \leq N \leq 150,000$.
- Elephants may share the same position.
- Your procedure `update` will be called at most $150,000$ times.
- Please see the note about the CPU time limit under the Implementation Details Section.
|
Python
|
seed_442
|
# International Olympiad in Informatics 2011
22--29 July 2011, Pattaya City, Thailand
## Competition Tasks -- Day 1
### GARDEN
_English 1.5_
## Tropical Garden
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, \ldots, 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 \leq 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 \leq 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 \leq i < Q\), \(G[i]\) is the number of trails \(K\) that the \(i\)-th group will take.
For \(0 \leq 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)`.
## Examples
### 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 \to 2 \to 1 \to 0\), and
- \(5 \to 4 \to 3 \to 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)`.

### Example 2
Consider the case shown in Figure 2, where \(N = 5\), \(M = 5\), \(P = 2\), \(Q = 2\), \(G[0] = 3\), \(G[1] = 1\), and
```
R =
[ [1, 0],
[1, 2],
[3, 2],
[1, 3],
[4, 2] ]
```
For the first group, there is only one valid route that reaches fountain \(2\) after following 3 trails:
```
1 -> 0 -> 1 -> 2
```
For the second group, there are two valid routes that reach fountain \(2\) after following 1 trail:
```
3 -> 2, and 4 -> 2
```
Therefore, the correct implementation of `count_routes` should first call `answer(1)` to report the answer for the first group, and then call `answer(2)` to report the answer for the second group.

## Implementation details
- **Limits:**
- CPU time limit: 5 seconds
- Memory limit: 256 MB
*Note:* There is no explicit limit for the size of stack memory. Stack memory counts towards the total memory usage.
- **Interface (API):**
- Implementation folder: `garden/`
- To be implemented by contestant: `garden.c` or `garden.cpp` or `garden.pas`
- Contestant interface: `garden.h` or `garden.pas`
- Grader interface: `gardenlib.h` or `gardenlib.pas`
- Sample grader: `grader.c` or `grader.cpp` or `grader.pas`
- Sample grader input: `grader.in.1`, `grader.in.2`, ...
*Note:* The sample grader reads the input in the following format:
- Line 1: \(N, M, P\).
- Lines 2 to \(M+1\): Description of the trails; i.e., line \(i+2\) contains \(R[i][0]\) and \(R[i][1]\), separated by a space, for \(0 \leq i < M\).
- Line \(M+2\): \(Q\).
- Line \(M+3\): Array \(G\) as a sequence of space-separated integers.
- Line \(M+4\): Array of expected solutions as a sequence of space-separated integers.
Expected output for sample grader input: `grader.expect.1`, `grader.expect.2`, ...
For this task, each one of these files should contain precisely the text \"Correct.\"
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
- \(2 \leq N \leq 150,000\)
- \(1 \leq M \leq 150,000\)
- \(1 \leq Q \leq 2,000\)
- Each element of \(G\) is an integer between \(1\) and \(1,000,000,000\), inclusive.
|
Python
|
seed_443
|
# International Olympiad in Informatics 2011
22--29 July 2011, Pattaya City, Thailand
## Competition Tasks -- Day 1
### GARDEN
_English 1.5_
## Tropical Garden
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, \ldots, 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 \leq 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 \leq 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 \leq i < Q\), \(G[i]\) is the number of trails \(K\) that the \(i\)-th group will take.
For \(0 \leq 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)`.
## Examples
### 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 \to 2 \to 1 \to 0\), and
- \(5 \to 4 \to 3 \to 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)`.

### Example 2
Consider the case shown in Figure 2, where \(N = 5\), \(M = 5\), \(P = 2\), \(Q = 2\), \(G[0] = 3\), \(G[1] = 1\), and
```
R =
[ [1, 0],
[1, 2],
[3, 2],
[1, 3],
[4, 2] ]
```
For the first group, there is only one valid route that reaches fountain \(2\) after following 3 trails:
```
1 -> 0 -> 1 -> 2
```
For the second group, there are two valid routes that reach fountain \(2\) after following 1 trail:
```
3 -> 2, and 4 -> 2
```
Therefore, the correct implementation of `count_routes` should first call `answer(1)` to report the answer for the first group, and then call `answer(2)` to report the answer for the second group.

## Implementation details
- **Limits:**
- CPU time limit: 5 seconds
- Memory limit: 256 MB
*Note:* There is no explicit limit for the size of stack memory. Stack memory counts towards the total memory usage.
- **Interface (API):**
- Implementation folder: `garden/`
- To be implemented by contestant: `garden.c` or `garden.cpp` or `garden.pas`
- Contestant interface: `garden.h` or `garden.pas`
- Grader interface: `gardenlib.h` or `gardenlib.pas`
- Sample grader: `grader.c` or `grader.cpp` or `grader.pas`
- Sample grader input: `grader.in.1`, `grader.in.2`, ...
*Note:* The sample grader reads the input in the following format:
- Line 1: \(N, M, P\).
- Lines 2 to \(M+1\): Description of the trails; i.e., line \(i+2\) contains \(R[i][0]\) and \(R[i][1]\), separated by a space, for \(0 \leq i < M\).
- Line \(M+2\): \(Q\).
- Line \(M+3\): Array \(G\) as a sequence of space-separated integers.
- Line \(M+4\): Array of expected solutions as a sequence of space-separated integers.
Expected output for sample grader input: `grader.expect.1`, `grader.expect.2`, ...
For this task, each one of these files should contain precisely the text \"Correct.\"
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
- \(2 \leq N \leq 150,000\)
- \(1 \leq M \leq 150,000\)
- \(Q = 1\)
- Each element of \(G\) is an integer between \(1\) and \(1,000,000,000\), inclusive.
|
Python
|
seed_444
|
# International Olympiad in Informatics 2012
## Ideal City
Leonardo, like many other Italian scientists and artists of his age, was extremely interested in city planning and urban design. He aimed to model an ideal city: comfortable, spacious and rational in its usage of resources, far away from the narrow, claustrophobic cities of the Middle Ages.
### The Ideal City
The city is made of $N$ blocks placed on an infinite grid of cells. Each cell is identified by a pair of coordinates (row, column). Given a cell $(i, j)$, the adjacent cells are:
```
(i-1, j), (i+1, j), (i, j-1), (i, j+1).
```
Each block, when placed onto the grid, covers exactly one of the cells. A block can be placed onto the cell $(i, j)$ if and only if:
```
1 β€ i, j β€ 2^{31} - 2.
```
We will use the coordinates of the cells to also refer to the blocks on top of them. Two blocks are adjacent if they are placed in adjacent cells.
In an ideal city, all of its blocks are connected in such a way that there are no \"holes\" inside its border, that is, the cells must satisfy both conditions below:
- For any two *empty* cells, there exists at least one sequence of adjacent *empty* cells connecting them.
- For any two *non-empty* cells, there exists at least one sequence of adjacent *non-empty* cells connecting them.
#### Example 1
None of the configurations of blocks below represent an ideal city: the first two on the left do not satisfy the first condition, the third one does not satisfy the second condition, and the fourth one does not satisfy either of the conditions.

### Distance
When traversing the city, a *hop* indicates going from one block to an adjacent one. Empty cells cannot be traversed. Let $v_0, v_1, \dots, v_{N-1}$ be the coordinates of the $N$ blocks placed on the grid. For any two distinct blocks at coordinates $v_i$ and $v_j$, their distance $d(v_i, v_j)$ is the smallest number of hops that are required to go from one of these blocks to the other one.
#### Example 2
The configuration below represents an ideal city made of $N = 11$ blocks at coordinates:
```
v_0 = (2, 5), v_1 = (2, 6), v_2 = (3, 3), v_3 = (3, 6), v_4 = (4, 3),
v_5 = (4, 4), v_6 = (4, 5), v_7 = (4, 6), v_8 = (5, 3), v_9 = (5, 4), v_{10} = (5, 6).
```
For example:
```
d(v_1, v_5) = 1, d(v_1, v_8) = 6, d(v_6, v_{10}) = 2, d(v_9, v_{10}) = 4.
```

### Statement
Your task is to, given an ideal city, write a program to compute the sum of all pairwise distances between blocks $v_i$ and $v_j$ for which $i < j$. Formally, your program should compute the value of the following sum:
```
β_{0 β€ i < j β€ N-1} d(v_i, v_j).
```
Specifically, you have to implement a routine `DistanceSum(N, X, Y)` that, given $N$ and two arrays $X$ and $Y$ that describe the city, calculates the formula above. Both $X$ and $Y$ are of size $N$; block $i$ is at coordinates $(X[i], Y[i])$ for $0 β€ i β€ N-1$, and
```
1 β€ X[i], Y[i] β€ 2^{31} - 2.
```
Since the result may be too big to be represented using 32 bits, you should report it modulo $1,000,000,000$ (one billion).
In Example 2, there are $11 Γ 10 / 2 = 55$ pairs of blocks. The sum of all the pairwise distances is $174$.
### Implementation Details
You have to submit exactly one file, called `city.c`, `city.cpp` or `city.pas`. This file must implement the subprogram described above using the following signatures:
#### C/C++ programs
```c
int DistanceSum(int N, int *X, int *Y);
```
#### Pascal programs
```pascal
function DistanceSum(N : LongInt; var X, Y : array of LongInt) : LongInt;
```
This subprogram must behave as described above. Of course you are free to implement other subprograms for its internal use. Your submissions must not interact in any way with standard input/output, nor with any other file.
#### Sample Grader
The sample grader provided with the task environment will expect input in the following format:
- Line 1: $N$;
- Lines 2, ..., $N+1$: $X[i], Y[i]$.
### Time and Memory Limits
- **Time limit**: 1 second.
- **Memory limit**: 256 MiB.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
N β€ 100,000
|
Python
|
seed_445
|
# International Olympiad in Informatics 2012
## Ideal City
Leonardo, like many other Italian scientists and artists of his age, was extremely interested in city planning and urban design. He aimed to model an ideal city: comfortable, spacious and rational in its usage of resources, far away from the narrow, claustrophobic cities of the Middle Ages.
### The Ideal City
The city is made of $N$ blocks placed on an infinite grid of cells. Each cell is identified by a pair of coordinates (row, column). Given a cell $(i, j)$, the adjacent cells are:
```
(i-1, j), (i+1, j), (i, j-1), (i, j+1).
```
Each block, when placed onto the grid, covers exactly one of the cells. A block can be placed onto the cell $(i, j)$ if and only if:
```
1 β€ i, j β€ 2^{31} - 2.
```
We will use the coordinates of the cells to also refer to the blocks on top of them. Two blocks are adjacent if they are placed in adjacent cells.
In an ideal city, all of its blocks are connected in such a way that there are no \"holes\" inside its border, that is, the cells must satisfy both conditions below:
- For any two *empty* cells, there exists at least one sequence of adjacent *empty* cells connecting them.
- For any two *non-empty* cells, there exists at least one sequence of adjacent *non-empty* cells connecting them.
#### Example 1
None of the configurations of blocks below represent an ideal city: the first two on the left do not satisfy the first condition, the third one does not satisfy the second condition, and the fourth one does not satisfy either of the conditions.

### Distance
When traversing the city, a *hop* indicates going from one block to an adjacent one. Empty cells cannot be traversed. Let $v_0, v_1, \dots, v_{N-1}$ be the coordinates of the $N$ blocks placed on the grid. For any two distinct blocks at coordinates $v_i$ and $v_j$, their distance $d(v_i, v_j)$ is the smallest number of hops that are required to go from one of these blocks to the other one.
#### Example 2
The configuration below represents an ideal city made of $N = 11$ blocks at coordinates:
```
v_0 = (2, 5), v_1 = (2, 6), v_2 = (3, 3), v_3 = (3, 6), v_4 = (4, 3),
v_5 = (4, 4), v_6 = (4, 5), v_7 = (4, 6), v_8 = (5, 3), v_9 = (5, 4), v_{10} = (5, 6).
```
For example:
```
d(v_1, v_5) = 1, d(v_1, v_8) = 6, d(v_6, v_{10}) = 2, d(v_9, v_{10}) = 4.
```

### Statement
Your task is to, given an ideal city, write a program to compute the sum of all pairwise distances between blocks $v_i$ and $v_j$ for which $i < j$. Formally, your program should compute the value of the following sum:
```
β_{0 β€ i < j β€ N-1} d(v_i, v_j).
```
Specifically, you have to implement a routine `DistanceSum(N, X, Y)` that, given $N$ and two arrays $X$ and $Y$ that describe the city, calculates the formula above. Both $X$ and $Y$ are of size $N$; block $i$ is at coordinates $(X[i], Y[i])$ for $0 β€ i β€ N-1$, and
```
1 β€ X[i], Y[i] β€ 2^{31} - 2.
```
Since the result may be too big to be represented using 32 bits, you should report it modulo $1,000,000,000$ (one billion).
In Example 2, there are $11 Γ 10 / 2 = 55$ pairs of blocks. The sum of all the pairwise distances is $174$.
### Implementation Details
You have to submit exactly one file, called `city.c`, `city.cpp` or `city.pas`. This file must implement the subprogram described above using the following signatures:
#### C/C++ programs
```c
int DistanceSum(int N, int *X, int *Y);
```
#### Pascal programs
```pascal
function DistanceSum(N : LongInt; var X, Y : array of LongInt) : LongInt;
```
This subprogram must behave as described above. Of course you are free to implement other subprograms for its internal use. Your submissions must not interact in any way with standard input/output, nor with any other file.
#### Sample Grader
The sample grader provided with the task environment will expect input in the following format:
- Line 1: $N$;
- Lines 2, ..., $N+1$: $X[i], Y[i]$.
### Time and Memory Limits
- **Time limit**: 1 second.
- **Memory limit**: 256 MiB.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
N β€ 2,000
|
Python
|
seed_447
|
# International Olympiad in Informatics 2012
## Parachute rings
An early and quite sophisticated version of what we now call a parachute is described in Leonardo's *Codex Atlanticus* (ca. 1485). Leonardo's parachute consisted of a sealed linen cloth held open by a pyramid-shaped wooden structure.
### Linked rings
Skydiver Adrian Nicholas tested Leonardo's design more than 500 years later. For this, a modern lightweight structure tied Leonardo's parachute to the human body. We want to use linked rings, which also provide hooks for the sealed linen cloth. Each ring is made of flexible and strong material. Rings can be easily linked together as every ring can be opened and re-closed. A special configuration of linked rings is the *chain*. A *chain* is a sequence of rings in which each ring is only connected to its (at most two) neighbours, as illustrated below. This sequence must have a start and an end (rings that are connected to at most one other ring each). Specifically, a single ring is also a chain.
<center>
<image>
</center>
Other configurations are clearly possible, since a ring can be linked to three or more other rings. We say that a ring is *critical* if after opening and removing it, all remaining rings form a set of chains (or there are no other rings left). In other words, there can be nothing but chains left.
### Example
Consider the 7 rings in the next figure, numbered from 0 to 6. There are two critical rings. One critical ring is 2: after its removal, the remaining rings form chains [1], [0, 5, 3, 4] and [6]. The other critical ring is 3: after its removal, the remaining rings form chains [1, 2, 0, 5], [4] and [6]. If we remove any other ring, we do not obtain a set of disjoint chains. For example, after removing ring 5: although we have that [6] is a chain, the linked rings 0, 1, 2, 3 and 4 do not form a chain.
<center>
<image>
</center>
## Statement
Your task is to count the number of critical rings in a given configuration that will be communicated to your program.
At the beginning, there are a certain number of disjoint rings. After that, rings are linked together. At any given time, you can be asked to return the number of critical rings in the current configuration. Specifically, you have to implement three routines:
- `Init(N)` β it is called exactly once at the beginning to communicate that there are N disjoint rings numbered from 0 to N - 1 (inclusive) in the initial configuration.
- `Link(A, B)` β the two rings numbered A and B get linked together. It is guaranteed that A and B are different and not already linked directly; apart from this, there are no additional conditions on A and B, in particular no conditions arising from physical constraints. Clearly, `Link(A, B)` and `Link(B, A)` are equivalent.
- `CountCritical()` β return the number of critical rings for the current configuration of linked rings.
### Example
Consider our figure with N = 7 rings and suppose that they are initially unlinked. We show a possible sequence of calls, where after the last call we obtain the situation depicted in our figure.
| **Call** | **Returns** |
|---------------------|-------------|
| `Init(7)` | |
| `CountCritical()` | 7 |
| `Link(1, 2)` | |
| `CountCritical()` | 7 |
| `Link(0, 5)` | |
| `CountCritical()` | 7 |
| `Link(2, 0)` | |
| `CountCritical()` | 7 |
| `Link(3, 2)` | |
| `CountCritical()` | 4 |
| `Link(3, 5)` | |
| `CountCritical()` | 3 |
| `Link(4, 3)` | |
| `CountCritical()` | 2 |
## Implementation details
You have to submit exactly one file, called `rings.c`, `rings.cpp` or `rings.pas`. This file implements the subprograms described above using the following signatures.
### C/C++ programs
```c
void Init(int N);
void Link(int A, int B);
int CountCritical();
```
### Pascal programs
```pascal
procedure Init(N : LongInt);
procedure Link(A, B : LongInt);
function CountCritical() : LongInt;
```
These subprograms must behave as described above. Of course you are free to implement other subprograms for their internal use. Your submissions must not interact in any way with standard input/output, nor with any other file.
### Sample grader
The sample grader reads the input in the following format:
- line 1: N, L;
- lines 2, ..., L + 1:
- `-1` to invoke `CountCritical`;
- `A, B` parameters to `Link`.
The sample grader will print all results from `CountCritical`.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
- N β€ 1,000,000.
- The function `CountCritical` is called only once, after all the other calls; the function `Link` is called at most 1,000,000 times.
|
Python
|
seed_448
|
# International Olympiad in Informatics 2012
## Parachute rings
An early and quite sophisticated version of what we now call a parachute is described in Leonardo's *Codex Atlanticus* (ca. 1485). Leonardo's parachute consisted of a sealed linen cloth held open by a pyramid-shaped wooden structure.
### Linked rings
Skydiver Adrian Nicholas tested Leonardo's design more than 500 years later. For this, a modern lightweight structure tied Leonardo's parachute to the human body. We want to use linked rings, which also provide hooks for the sealed linen cloth. Each ring is made of flexible and strong material. Rings can be easily linked together as every ring can be opened and re-closed. A special configuration of linked rings is the *chain*. A *chain* is a sequence of rings in which each ring is only connected to its (at most two) neighbours, as illustrated below. This sequence must have a start and an end (rings that are connected to at most one other ring each). Specifically, a single ring is also a chain.
<center>
<image>
</center>
Other configurations are clearly possible, since a ring can be linked to three or more other rings. We say that a ring is *critical* if after opening and removing it, all remaining rings form a set of chains (or there are no other rings left). In other words, there can be nothing but chains left.
### Example
Consider the 7 rings in the next figure, numbered from 0 to 6. There are two critical rings. One critical ring is 2: after its removal, the remaining rings form chains [1], [0, 5, 3, 4] and [6]. The other critical ring is 3: after its removal, the remaining rings form chains [1, 2, 0, 5], [4] and [6]. If we remove any other ring, we do not obtain a set of disjoint chains. For example, after removing ring 5: although we have that [6] is a chain, the linked rings 0, 1, 2, 3 and 4 do not form a chain.
<center>
<image>
</center>
## Statement
Your task is to count the number of critical rings in a given configuration that will be communicated to your program.
At the beginning, there are a certain number of disjoint rings. After that, rings are linked together. At any given time, you can be asked to return the number of critical rings in the current configuration. Specifically, you have to implement three routines:
- `Init(N)` β it is called exactly once at the beginning to communicate that there are N disjoint rings numbered from 0 to N - 1 (inclusive) in the initial configuration.
- `Link(A, B)` β the two rings numbered A and B get linked together. It is guaranteed that A and B are different and not already linked directly; apart from this, there are no additional conditions on A and B, in particular no conditions arising from physical constraints. Clearly, `Link(A, B)` and `Link(B, A)` are equivalent.
- `CountCritical()` β return the number of critical rings for the current configuration of linked rings.
### Example
Consider our figure with N = 7 rings and suppose that they are initially unlinked. We show a possible sequence of calls, where after the last call we obtain the situation depicted in our figure.
| **Call** | **Returns** |
|---------------------|-------------|
| `Init(7)` | |
| `CountCritical()` | 7 |
| `Link(1, 2)` | |
| `CountCritical()` | 7 |
| `Link(0, 5)` | |
| `CountCritical()` | 7 |
| `Link(2, 0)` | |
| `CountCritical()` | 7 |
| `Link(3, 2)` | |
| `CountCritical()` | 4 |
| `Link(3, 5)` | |
| `CountCritical()` | 3 |
| `Link(4, 3)` | |
| `CountCritical()` | 2 |
## Implementation details
You have to submit exactly one file, called `rings.c`, `rings.cpp` or `rings.pas`. This file implements the subprograms described above using the following signatures.
### C/C++ programs
```c
void Init(int N);
void Link(int A, int B);
int CountCritical();
```
### Pascal programs
```pascal
procedure Init(N : LongInt);
procedure Link(A, B : LongInt);
function CountCritical() : LongInt;
```
These subprograms must behave as described above. Of course you are free to implement other subprograms for their internal use. Your submissions must not interact in any way with standard input/output, nor with any other file.
### Sample grader
The sample grader reads the input in the following format:
- line 1: N, L;
- lines 2, ..., L + 1:
- `-1` to invoke `CountCritical`;
- `A, B` parameters to `Link`.
The sample grader will print all results from `CountCritical`.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
- N β€ 1,000,000.
- The functions `CountCritical` and `Link` are called, in total, at most 1,000,000 times.
|
Python
|
seed_449
|
# International Olympiad in Informatics 2012
## Parachute rings
An early and quite sophisticated version of what we now call a parachute is described in Leonardo's *Codex Atlanticus* (ca. 1485). Leonardo's parachute consisted of a sealed linen cloth held open by a pyramid-shaped wooden structure.
### Linked rings
Skydiver Adrian Nicholas tested Leonardo's design more than 500 years later. For this, a modern lightweight structure tied Leonardo's parachute to the human body. We want to use linked rings, which also provide hooks for the sealed linen cloth. Each ring is made of flexible and strong material. Rings can be easily linked together as every ring can be opened and re-closed. A special configuration of linked rings is the *chain*. A *chain* is a sequence of rings in which each ring is only connected to its (at most two) neighbours, as illustrated below. This sequence must have a start and an end (rings that are connected to at most one other ring each). Specifically, a single ring is also a chain.
<center>
<image>
</center>
Other configurations are clearly possible, since a ring can be linked to three or more other rings. We say that a ring is *critical* if after opening and removing it, all remaining rings form a set of chains (or there are no other rings left). In other words, there can be nothing but chains left.
### Example
Consider the 7 rings in the next figure, numbered from 0 to 6. There are two critical rings. One critical ring is 2: after its removal, the remaining rings form chains [1], [0, 5, 3, 4] and [6]. The other critical ring is 3: after its removal, the remaining rings form chains [1, 2, 0, 5], [4] and [6]. If we remove any other ring, we do not obtain a set of disjoint chains. For example, after removing ring 5: although we have that [6] is a chain, the linked rings 0, 1, 2, 3 and 4 do not form a chain.
<center>
<image>
</center>
## Statement
Your task is to count the number of critical rings in a given configuration that will be communicated to your program.
At the beginning, there are a certain number of disjoint rings. After that, rings are linked together. At any given time, you can be asked to return the number of critical rings in the current configuration. Specifically, you have to implement three routines:
- `Init(N)` β it is called exactly once at the beginning to communicate that there are N disjoint rings numbered from 0 to N - 1 (inclusive) in the initial configuration.
- `Link(A, B)` β the two rings numbered A and B get linked together. It is guaranteed that A and B are different and not already linked directly; apart from this, there are no additional conditions on A and B, in particular no conditions arising from physical constraints. Clearly, `Link(A, B)` and `Link(B, A)` are equivalent.
- `CountCritical()` β return the number of critical rings for the current configuration of linked rings.
### Example
Consider our figure with N = 7 rings and suppose that they are initially unlinked. We show a possible sequence of calls, where after the last call we obtain the situation depicted in our figure.
| **Call** | **Returns** |
|---------------------|-------------|
| `Init(7)` | |
| `CountCritical()` | 7 |
| `Link(1, 2)` | |
| `CountCritical()` | 7 |
| `Link(0, 5)` | |
| `CountCritical()` | 7 |
| `Link(2, 0)` | |
| `CountCritical()` | 7 |
| `Link(3, 2)` | |
| `CountCritical()` | 4 |
| `Link(3, 5)` | |
| `CountCritical()` | 3 |
| `Link(4, 3)` | |
| `CountCritical()` | 2 |
## Implementation details
You have to submit exactly one file, called `rings.c`, `rings.cpp` or `rings.pas`. This file implements the subprograms described above using the following signatures.
### C/C++ programs
```c
void Init(int N);
void Link(int A, int B);
int CountCritical();
```
### Pascal programs
```pascal
procedure Init(N : LongInt);
procedure Link(A, B : LongInt);
function CountCritical() : LongInt;
```
These subprograms must behave as described above. Of course you are free to implement other subprograms for their internal use. Your submissions must not interact in any way with standard input/output, nor with any other file.
### Sample grader
The sample grader reads the input in the following format:
- line 1: N, L;
- lines 2, ..., L + 1:
- `-1` to invoke `CountCritical`;
- `A, B` parameters to `Link`.
The sample grader will print all results from `CountCritical`.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
- N β€ 100,000.
- The functions `CountCritical` and `Link` are called, in total, at most 100,000 times.
|
Python
|
seed_450
|
# International Olympiad in Informatics 2012
## Parachute rings
An early and quite sophisticated version of what we now call a parachute is described in Leonardo's *Codex Atlanticus* (ca. 1485). Leonardo's parachute consisted of a sealed linen cloth held open by a pyramid-shaped wooden structure.
### Linked rings
Skydiver Adrian Nicholas tested Leonardo's design more than 500 years later. For this, a modern lightweight structure tied Leonardo's parachute to the human body. We want to use linked rings, which also provide hooks for the sealed linen cloth. Each ring is made of flexible and strong material. Rings can be easily linked together as every ring can be opened and re-closed. A special configuration of linked rings is the *chain*. A *chain* is a sequence of rings in which each ring is only connected to its (at most two) neighbours, as illustrated below. This sequence must have a start and an end (rings that are connected to at most one other ring each). Specifically, a single ring is also a chain.
<center>
<image>
</center>
Other configurations are clearly possible, since a ring can be linked to three or more other rings. We say that a ring is *critical* if after opening and removing it, all remaining rings form a set of chains (or there are no other rings left). In other words, there can be nothing but chains left.
### Example
Consider the 7 rings in the next figure, numbered from 0 to 6. There are two critical rings. One critical ring is 2: after its removal, the remaining rings form chains [1], [0, 5, 3, 4] and [6]. The other critical ring is 3: after its removal, the remaining rings form chains [1, 2, 0, 5], [4] and [6]. If we remove any other ring, we do not obtain a set of disjoint chains. For example, after removing ring 5: although we have that [6] is a chain, the linked rings 0, 1, 2, 3 and 4 do not form a chain.
<center>
<image>
</center>
## Statement
Your task is to count the number of critical rings in a given configuration that will be communicated to your program.
At the beginning, there are a certain number of disjoint rings. After that, rings are linked together. At any given time, you can be asked to return the number of critical rings in the current configuration. Specifically, you have to implement three routines:
- `Init(N)` β it is called exactly once at the beginning to communicate that there are N disjoint rings numbered from 0 to N - 1 (inclusive) in the initial configuration.
- `Link(A, B)` β the two rings numbered A and B get linked together. It is guaranteed that A and B are different and not already linked directly; apart from this, there are no additional conditions on A and B, in particular no conditions arising from physical constraints. Clearly, `Link(A, B)` and `Link(B, A)` are equivalent.
- `CountCritical()` β return the number of critical rings for the current configuration of linked rings.
### Example
Consider our figure with N = 7 rings and suppose that they are initially unlinked. We show a possible sequence of calls, where after the last call we obtain the situation depicted in our figure.
| **Call** | **Returns** |
|---------------------|-------------|
| `Init(7)` | |
| `CountCritical()` | 7 |
| `Link(1, 2)` | |
| `CountCritical()` | 7 |
| `Link(0, 5)` | |
| `CountCritical()` | 7 |
| `Link(2, 0)` | |
| `CountCritical()` | 7 |
| `Link(3, 2)` | |
| `CountCritical()` | 4 |
| `Link(3, 5)` | |
| `CountCritical()` | 3 |
| `Link(4, 3)` | |
| `CountCritical()` | 2 |
## Implementation details
You have to submit exactly one file, called `rings.c`, `rings.cpp` or `rings.pas`. This file implements the subprograms described above using the following signatures.
### C/C++ programs
```c
void Init(int N);
void Link(int A, int B);
int CountCritical();
```
### Pascal programs
```pascal
procedure Init(N : LongInt);
procedure Link(A, B : LongInt);
function CountCritical() : LongInt;
```
These subprograms must behave as described above. Of course you are free to implement other subprograms for their internal use. Your submissions must not interact in any way with standard input/output, nor with any other file.
### Sample grader
The sample grader reads the input in the following format:
- line 1: N, L;
- lines 2, ..., L + 1:
- `-1` to invoke `CountCritical`;
- `A, B` parameters to `Link`.
The sample grader will print all results from `CountCritical`.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
- N β€ 20,000.
- The function `CountCritical` is called at most 100 times; the function `Link` is called at most 10,000 times.
|
Python
|
seed_453
|
# International Olympiad in Informatics 2012
**23-30 September 2012**
Sirmione - Montichiari, Italy
Competition tasks, day 1: Leonardo's inventions and projects
**Pebbling odometer**
Leonardo invented the original *odometer*: a cart which could measure distances by dropping pebbles as the cart's wheels turned. Counting the pebbles gave the number of turns of the wheel, which allowed the user to compute the distance travelled by the odometer. As computer scientists, we have added software control to the odometer, extending its functionalities. Your task is to program the odometer under the rules specified below.
## Operation grid
The odometer moves on an imaginary square grid of 256 Γ 256 unit cells. Each cell can contain at most 15 pebbles and is identified by a pair of coordinates (*row*, *column*), where each coordinate is in the range 0, ..., 255. Given a cell (i, j), the cells adjacent to it are (if they exist) (i - 1, j), (i + 1, j), (i, j - 1), and (i, j + 1). Any cell lying on the first or last row, or on the first or last column, is called a *border*. The odometer always starts at cell (0, 0) (the north-west corner), facing north.
## Basic commands
The odometer can be programmed using the following commands.
- `left` β turn 90 degrees to the left (counterclockwise) and remain in the current cell (e.g., if it was facing south before, then it will face east after the command).
- `right` β turn 90 degrees to the right (clockwise) and remain in the current cell (e.g., if it was facing west before, then it will face north after the command).
- `move` β move one unit forward (in the direction the odometer is facing) into an adjacent cell. If no such cell exists (i.e., the border in that direction has been already reached), then this command has no effect.
- `get` β remove one pebble from the current cell. If the current cell has no pebbles, then the command has no effect.
- `put` β add one pebble to the current cell. If the current cell already contains 15 pebbles, then the command has no effect. The odometer never runs out of pebbles.
- `halt` β terminate the execution.
The odometer executes the commands in the order they are given in the program. The program must contain at most one command per line. Empty lines are ignored. The symbol `#` indicates a comment; any text that follows, up to the end of the line, is ignored. If the odometer reaches the end of the program, execution is terminated.
## Example 1
Consider the following program for the odometer. It takes the odometer to the cell (0, 2), facing east. (Note that the first `move` is ignored, because the odometer is on the north-west corner facing north.)
```
move # no effect
right
# now the odometer is facing east
move
move
```
## Labels, borders and pebbles
To alter the flow of the program depending on the current status, you can use *labels*, which are case-sensitive strings of at most 128 symbols chosen from `a, ..., z, A, ..., Z, 0, ..., 9`. The new commands concerning labels are listed below. In the descriptions below, *L* denotes any valid label.
- `L:` (i.e., *L* followed by a colon `:`) β declares the location within a program of a label *L*. All declared labels must be unique. Declaring a label has no effect on the odometer.
- `jump L` β continue the execution by unconditionally jumping to the line with label *L*.
- `border L` β continue the execution jumping to the line with label *L*, if the odometer is on a border facing the edge of the grid (i.e., a `move` instruction would have no effect); otherwise, the execution continues normally and this command has no effect.
- `pebble L` β continue the execution jumping to the line with label *L*, if the current cell contains at least one pebble; otherwise, the execution continues normally and this command has no effect.
## Example 2
The following program locates the first (westmost) pebble in row 0 and stops there; if there are no pebbles in row 0, it stops on the border at the end of the row. It uses two labels `leonardo` and `davinci`.
```
right
leonardo:
pebble davinci # pebble found
border davinci # end of the row
move
jump leonardo
davinci:
halt
```
The odometer starts by turning to its right. The loop begins with the label declaration `leonardo:` and ends with the `jump leonardo` command. In the loop, the odometer checks for the presence of a pebble or the border at the end of the row; if not so, the odometer makes a `move` from the current cell (0, j) to the adjacent cell (0, j + 1) since the latter exists. (The `halt` command is not strictly necessary here as the program terminates anyway.)
## Statement
You should submit a program in the odometer's own language, as described above, that makes the odometer behave as expected. Each subtask specifies a behavior the odometer is required to fulfill and the constraints the submitted solution must satisfy. The constraints concern the two following matters.
- **Program size** β the program must be short enough. The size of a program is the number of commands in it. Label declarations, comments and blank lines are *not* counted in the size.
- **Execution length** β the program must terminate fast enough. The execution length is the number of performed *steps*: every single command execution counts as a step, regardless of whether the command had an effect or not; label declarations, comments and blank lines do not count as a step.
### Example 1
The program size is 4 and the execution length is 4. In **Example 2**, the program size is 6 and, when executed on a grid with a single pebble in cell (0, 10), the execution length is 43 steps: `right`, 10 iterations of the loop, each iteration taking 4 steps (`pebble davinci`, `border davinci`, `move`, `jump leonardo`), and finally, `pebble davinci` and `halt`.
## Implementation details
You have to submit exactly one file per subtask, written according to the syntax rules specified above. Each submitted file can have a maximum size of 5 MiB. For each subtask, your odometer code will be tested on a few test cases, and you will receive some feedback on the resources used by your code. In the case the code is not syntactically correct and thus impossible to test, you will receive information on the specific syntax error.
It is not necessary that your submissions contain odometer programs for all the subtasks. If your current submission does not contain the odometer program for subtask X, your most recent submission for subtask X is automatically included; if there is no such program, the subtask will score zero for that submission.
## Simulator
For testing purposes, you are provided with an odometer simulator, which you can feed with your programs and input grids. Odometer programs will be written in the same format used for submission (i.e., the one described above).
Grid descriptions will be given using the following format: each line of the file must contain three numbers, R, C, and P, meaning that the cell at row R and column C contains P pebbles. All cells not specified in the grid description are assumed to contain no pebbles. For example, consider the file:
```
0 10 3
4 5 12
```
The grid described by this file would contain 15 pebbles: 3 in the cell (0, 10) and 12 in the cell (4, 5).
You can invoke the test simulator by calling the program `simulator.py` in your task directory, passing the program file name as argument. The simulator program will accept the following command line options:
- `-h` will give a brief overview of the available options;
- `-g GRID_FILE` loads the grid description from file `GRID_FILE` (default: empty grid);
- `-s GRID_SIDE` sets the size of the grid to `GRID_SIDE Γ GRID_SIDE` (default: 256, as used in the problem specification); usage of smaller grids can be useful for program debugging;
- `-m STEPS` limits the number of execution steps in the simulation to at most `STEPS`;
- `-c` enters compilation mode; in compilation mode, the simulator returns exactly the same output, but instead of doing the simulation with Python, it generates and compiles a small C program. This causes a larger overhead when starting, but then gives significantly faster results; you are advised to use it when your program is expected to run for more than about 10,000,000 steps.
**Number of submissions:** The maximum number of submissions allowed for this task is 128.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
Same task as above but when the program ends, the cell (0, 0) must contain exactly x pebbles and cell (0, 1) must contain exactly y pebbles. Program size β€ 200, execution length β€ 2,000.
|
Python
|
seed_454
|
# International Olympiad in Informatics 2012
**23-30 September 2012**
Sirmione - Montichiari, Italy
Competition tasks, day 1: Leonardo's inventions and projects
**Pebbling odometer**
Leonardo invented the original *odometer*: a cart which could measure distances by dropping pebbles as the cart's wheels turned. Counting the pebbles gave the number of turns of the wheel, which allowed the user to compute the distance travelled by the odometer. As computer scientists, we have added software control to the odometer, extending its functionalities. Your task is to program the odometer under the rules specified below.
## Operation grid
The odometer moves on an imaginary square grid of 256 Γ 256 unit cells. Each cell can contain at most 15 pebbles and is identified by a pair of coordinates (*row*, *column*), where each coordinate is in the range 0, ..., 255. Given a cell (i, j), the cells adjacent to it are (if they exist) (i - 1, j), (i + 1, j), (i, j - 1), and (i, j + 1). Any cell lying on the first or last row, or on the first or last column, is called a *border*. The odometer always starts at cell (0, 0) (the north-west corner), facing north.
## Basic commands
The odometer can be programmed using the following commands.
- `left` β turn 90 degrees to the left (counterclockwise) and remain in the current cell (e.g., if it was facing south before, then it will face east after the command).
- `right` β turn 90 degrees to the right (clockwise) and remain in the current cell (e.g., if it was facing west before, then it will face north after the command).
- `move` β move one unit forward (in the direction the odometer is facing) into an adjacent cell. If no such cell exists (i.e., the border in that direction has been already reached), then this command has no effect.
- `get` β remove one pebble from the current cell. If the current cell has no pebbles, then the command has no effect.
- `put` β add one pebble to the current cell. If the current cell already contains 15 pebbles, then the command has no effect. The odometer never runs out of pebbles.
- `halt` β terminate the execution.
The odometer executes the commands in the order they are given in the program. The program must contain at most one command per line. Empty lines are ignored. The symbol `#` indicates a comment; any text that follows, up to the end of the line, is ignored. If the odometer reaches the end of the program, execution is terminated.
## Example 1
Consider the following program for the odometer. It takes the odometer to the cell (0, 2), facing east. (Note that the first `move` is ignored, because the odometer is on the north-west corner facing north.)
```
move # no effect
right
# now the odometer is facing east
move
move
```
## Labels, borders and pebbles
To alter the flow of the program depending on the current status, you can use *labels*, which are case-sensitive strings of at most 128 symbols chosen from `a, ..., z, A, ..., Z, 0, ..., 9`. The new commands concerning labels are listed below. In the descriptions below, *L* denotes any valid label.
- `L:` (i.e., *L* followed by a colon `:`) β declares the location within a program of a label *L*. All declared labels must be unique. Declaring a label has no effect on the odometer.
- `jump L` β continue the execution by unconditionally jumping to the line with label *L*.
- `border L` β continue the execution jumping to the line with label *L*, if the odometer is on a border facing the edge of the grid (i.e., a `move` instruction would have no effect); otherwise, the execution continues normally and this command has no effect.
- `pebble L` β continue the execution jumping to the line with label *L*, if the current cell contains at least one pebble; otherwise, the execution continues normally and this command has no effect.
## Example 2
The following program locates the first (westmost) pebble in row 0 and stops there; if there are no pebbles in row 0, it stops on the border at the end of the row. It uses two labels `leonardo` and `davinci`.
```
right
leonardo:
pebble davinci # pebble found
border davinci # end of the row
move
jump leonardo
davinci:
halt
```
The odometer starts by turning to its right. The loop begins with the label declaration `leonardo:` and ends with the `jump leonardo` command. In the loop, the odometer checks for the presence of a pebble or the border at the end of the row; if not so, the odometer makes a `move` from the current cell (0, j) to the adjacent cell (0, j + 1) since the latter exists. (The `halt` command is not strictly necessary here as the program terminates anyway.)
## Statement
You should submit a program in the odometer's own language, as described above, that makes the odometer behave as expected. Each subtask specifies a behavior the odometer is required to fulfill and the constraints the submitted solution must satisfy. The constraints concern the two following matters.
- **Program size** β the program must be short enough. The size of a program is the number of commands in it. Label declarations, comments and blank lines are *not* counted in the size.
- **Execution length** β the program must terminate fast enough. The execution length is the number of performed *steps*: every single command execution counts as a step, regardless of whether the command had an effect or not; label declarations, comments and blank lines do not count as a step.
### Example 1
The program size is 4 and the execution length is 4. In **Example 2**, the program size is 6 and, when executed on a grid with a single pebble in cell (0, 10), the execution length is 43 steps: `right`, 10 iterations of the loop, each iteration taking 4 steps (`pebble davinci`, `border davinci`, `move`, `jump leonardo`), and finally, `pebble davinci` and `halt`.
## Implementation details
You have to submit exactly one file per subtask, written according to the syntax rules specified above. Each submitted file can have a maximum size of 5 MiB. For each subtask, your odometer code will be tested on a few test cases, and you will receive some feedback on the resources used by your code. In the case the code is not syntactically correct and thus impossible to test, you will receive information on the specific syntax error.
It is not necessary that your submissions contain odometer programs for all the subtasks. If your current submission does not contain the odometer program for subtask X, your most recent submission for subtask X is automatically included; if there is no such program, the subtask will score zero for that submission.
## Simulator
For testing purposes, you are provided with an odometer simulator, which you can feed with your programs and input grids. Odometer programs will be written in the same format used for submission (i.e., the one described above).
Grid descriptions will be given using the following format: each line of the file must contain three numbers, R, C, and P, meaning that the cell at row R and column C contains P pebbles. All cells not specified in the grid description are assumed to contain no pebbles. For example, consider the file:
```
0 10 3
4 5 12
```
The grid described by this file would contain 15 pebbles: 3 in the cell (0, 10) and 12 in the cell (4, 5).
You can invoke the test simulator by calling the program `simulator.py` in your task directory, passing the program file name as argument. The simulator program will accept the following command line options:
- `-h` will give a brief overview of the available options;
- `-g GRID_FILE` loads the grid description from file `GRID_FILE` (default: empty grid);
- `-s GRID_SIDE` sets the size of the grid to `GRID_SIDE Γ GRID_SIDE` (default: 256, as used in the problem specification); usage of smaller grids can be useful for program debugging;
- `-m STEPS` limits the number of execution steps in the simulation to at most `STEPS`;
- `-c` enters compilation mode; in compilation mode, the simulator returns exactly the same output, but instead of doing the simulation with Python, it generates and compiles a small C program. This causes a larger overhead when starting, but then gives significantly faster results; you are advised to use it when your program is expected to run for more than about 10,000,000 steps.
**Number of submissions:** The maximum number of submissions allowed for this task is 128.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
There are at most 15 pebbles in the grid, no two of them in the same cell. Program size β€ 200. Execution length constraints: 32 points if L β€ 200,000; 32 - 32 log10(L / 200,000) points if 200,000 < L < 2,000,000; 0 points if L β₯ 2,000,000.
|
Python
|
seed_455
|
# International Olympiad in Informatics 2012
**23-30 September 2012**
Sirmione - Montichiari, Italy
Competition tasks, day 1: Leonardo's inventions and projects
**Pebbling odometer**
Leonardo invented the original *odometer*: a cart which could measure distances by dropping pebbles as the cart's wheels turned. Counting the pebbles gave the number of turns of the wheel, which allowed the user to compute the distance travelled by the odometer. As computer scientists, we have added software control to the odometer, extending its functionalities. Your task is to program the odometer under the rules specified below.
## Operation grid
The odometer moves on an imaginary square grid of 256 Γ 256 unit cells. Each cell can contain at most 15 pebbles and is identified by a pair of coordinates (*row*, *column*), where each coordinate is in the range 0, ..., 255. Given a cell (i, j), the cells adjacent to it are (if they exist) (i - 1, j), (i + 1, j), (i, j - 1), and (i, j + 1). Any cell lying on the first or last row, or on the first or last column, is called a *border*. The odometer always starts at cell (0, 0) (the north-west corner), facing north.
## Basic commands
The odometer can be programmed using the following commands.
- `left` β turn 90 degrees to the left (counterclockwise) and remain in the current cell (e.g., if it was facing south before, then it will face east after the command).
- `right` β turn 90 degrees to the right (clockwise) and remain in the current cell (e.g., if it was facing west before, then it will face north after the command).
- `move` β move one unit forward (in the direction the odometer is facing) into an adjacent cell. If no such cell exists (i.e., the border in that direction has been already reached), then this command has no effect.
- `get` β remove one pebble from the current cell. If the current cell has no pebbles, then the command has no effect.
- `put` β add one pebble to the current cell. If the current cell already contains 15 pebbles, then the command has no effect. The odometer never runs out of pebbles.
- `halt` β terminate the execution.
The odometer executes the commands in the order they are given in the program. The program must contain at most one command per line. Empty lines are ignored. The symbol `#` indicates a comment; any text that follows, up to the end of the line, is ignored. If the odometer reaches the end of the program, execution is terminated.
## Example 1
Consider the following program for the odometer. It takes the odometer to the cell (0, 2), facing east. (Note that the first `move` is ignored, because the odometer is on the north-west corner facing north.)
```
move # no effect
right
# now the odometer is facing east
move
move
```
## Labels, borders and pebbles
To alter the flow of the program depending on the current status, you can use *labels*, which are case-sensitive strings of at most 128 symbols chosen from `a, ..., z, A, ..., Z, 0, ..., 9`. The new commands concerning labels are listed below. In the descriptions below, *L* denotes any valid label.
- `L:` (i.e., *L* followed by a colon `:`) β declares the location within a program of a label *L*. All declared labels must be unique. Declaring a label has no effect on the odometer.
- `jump L` β continue the execution by unconditionally jumping to the line with label *L*.
- `border L` β continue the execution jumping to the line with label *L*, if the odometer is on a border facing the edge of the grid (i.e., a `move` instruction would have no effect); otherwise, the execution continues normally and this command has no effect.
- `pebble L` β continue the execution jumping to the line with label *L*, if the current cell contains at least one pebble; otherwise, the execution continues normally and this command has no effect.
## Example 2
The following program locates the first (westmost) pebble in row 0 and stops there; if there are no pebbles in row 0, it stops on the border at the end of the row. It uses two labels `leonardo` and `davinci`.
```
right
leonardo:
pebble davinci # pebble found
border davinci # end of the row
move
jump leonardo
davinci:
halt
```
The odometer starts by turning to its right. The loop begins with the label declaration `leonardo:` and ends with the `jump leonardo` command. In the loop, the odometer checks for the presence of a pebble or the border at the end of the row; if not so, the odometer makes a `move` from the current cell (0, j) to the adjacent cell (0, j + 1) since the latter exists. (The `halt` command is not strictly necessary here as the program terminates anyway.)
## Statement
You should submit a program in the odometer's own language, as described above, that makes the odometer behave as expected. Each subtask specifies a behavior the odometer is required to fulfill and the constraints the submitted solution must satisfy. The constraints concern the two following matters.
- **Program size** β the program must be short enough. The size of a program is the number of commands in it. Label declarations, comments and blank lines are *not* counted in the size.
- **Execution length** β the program must terminate fast enough. The execution length is the number of performed *steps*: every single command execution counts as a step, regardless of whether the command had an effect or not; label declarations, comments and blank lines do not count as a step.
### Example 1
The program size is 4 and the execution length is 4. In **Example 2**, the program size is 6 and, when executed on a grid with a single pebble in cell (0, 10), the execution length is 43 steps: `right`, 10 iterations of the loop, each iteration taking 4 steps (`pebble davinci`, `border davinci`, `move`, `jump leonardo`), and finally, `pebble davinci` and `halt`.
## Implementation details
You have to submit exactly one file per subtask, written according to the syntax rules specified above. Each submitted file can have a maximum size of 5 MiB. For each subtask, your odometer code will be tested on a few test cases, and you will receive some feedback on the resources used by your code. In the case the code is not syntactically correct and thus impossible to test, you will receive information on the specific syntax error.
It is not necessary that your submissions contain odometer programs for all the subtasks. If your current submission does not contain the odometer program for subtask X, your most recent submission for subtask X is automatically included; if there is no such program, the subtask will score zero for that submission.
## Simulator
For testing purposes, you are provided with an odometer simulator, which you can feed with your programs and input grids. Odometer programs will be written in the same format used for submission (i.e., the one described above).
Grid descriptions will be given using the following format: each line of the file must contain three numbers, R, C, and P, meaning that the cell at row R and column C contains P pebbles. All cells not specified in the grid description are assumed to contain no pebbles. For example, consider the file:
```
0 10 3
4 5 12
```
The grid described by this file would contain 15 pebbles: 3 in the cell (0, 10) and 12 in the cell (4, 5).
You can invoke the test simulator by calling the program `simulator.py` in your task directory, passing the program file name as argument. The simulator program will accept the following command line options:
- `-h` will give a brief overview of the available options;
- `-g GRID_FILE` loads the grid description from file `GRID_FILE` (default: empty grid);
- `-s GRID_SIDE` sets the size of the grid to `GRID_SIDE Γ GRID_SIDE` (default: 256, as used in the problem specification); usage of smaller grids can be useful for program debugging;
- `-m STEPS` limits the number of execution steps in the simulation to at most `STEPS`;
- `-c` enters compilation mode; in compilation mode, the simulator returns exactly the same output, but instead of doing the simulation with Python, it generates and compiles a small C program. This causes a larger overhead when starting, but then gives significantly faster results; you are advised to use it when your program is expected to run for more than about 10,000,000 steps.
**Number of submissions:** The maximum number of submissions allowed for this task is 128.
Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
There are exactly two pebbles somewhere in row 0: one is in cell (0, x), the other in cell (0, y); x and y are distinct, and x + y is even. Program size β€ 100, execution length β€ 200,000.
|
Python
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.