message
stringlengths 2
45.8k
| message_type
stringclasses 2
values | message_id
int64 0
1
| conversation_id
int64 254
108k
| cluster
float64 3
3
| __index_level_0__
int64 508
217k
|
|---|---|---|---|---|---|
Provide a correct Python 3 solution for this coding contest problem.
During a voyage of the starship Hakodate-maru (see Problem A), researchers found strange synchronized movements of stars. Having heard these observations, Dr. Extreme proposed a theory of "super stars". Do not take this term as a description of actors or singers. It is a revolutionary theory in astronomy.
According to this theory, stars we are observing are not independent objects, but only small portions of larger objects called super stars. A super star is filled with invisible (or transparent) material, and only a number of points inside or on its surface shine. These points are observed as stars by us.
In order to verify this theory, Dr. Extreme wants to build motion equations of super stars and to compare the solutions of these equations with observed movements of stars. As the first step, he assumes that a super star is sphere-shaped, and has the smallest possible radius such that the sphere contains all given stars in or on it. This assumption makes it possible to estimate the volume of a super star, and thus its mass (the density of the invisible material is known).
You are asked to help Dr. Extreme by writing a program which, given the locations of a number of stars, finds the smallest sphere containing all of them in or on it. In this computation, you should ignore the sizes of stars. In other words, a star should be regarded as a point. You may assume the universe is a Euclidean space.
Input
The input consists of multiple data sets. Each data set is given in the following format.
n
x1 y1 z1
x2 y2 z2
...
xn yn zn
The first line of a data set contains an integer n, which is the number of points. It satisfies the condition 4 β€ n β€ 30.
The locations of n points are given by three-dimensional orthogonal coordinates: (xi, yi, zi) (i = 1,..., n). Three coordinates of a point appear in a line, separated by a space character.
Each value is given by a decimal fraction, and is between 0.0 and 100.0 (both ends inclusive). Points are at least 0.01 distant from each other.
The end of the input is indicated by a line containing a zero.
Output
For each data set, the radius ofthe smallest sphere containing all given points should be printed, each in a separate line. The printed values should have 5 digits after the decimal point. They may not have an error greater than 0.00001.
Example
Input
4
10.00000 10.00000 10.00000
20.00000 10.00000 10.00000
20.00000 20.00000 10.00000
10.00000 20.00000 10.00000
4
10.00000 10.00000 10.00000
10.00000 50.00000 50.00000
50.00000 10.00000 50.00000
50.00000 50.00000 10.00000
0
Output
7.07107
34.64102
|
instruction
| 0
| 101,995
| 3
| 203,990
|
"Correct Solution:
```
while True:
n = int(input())
if not n:
break
star = [list(map(float, input().split())) for i in range(n)]
start = [0.0, 0.0, 0.0]
move = 0.5
for _ in range(500):
for j in range(100):
tmpmax = 0
a = 0
for i in range(n):
k = (star[i][0] - start[0]) ** 2 + (star[i][1] - start[1]) ** 2 + (star[i][2] - start[2]) ** 2
if tmpmax < k:
tmpmax = k
a = i
start = [start[i] - (start[i] - star[a][i]) * move for i in range(3)]
move /= 2
tmpmax = 0
for i in range(n):
k = (star[i][0] - start[0]) ** 2 + (star[i][1] - start[1]) ** 2 + (star[i][2] - start[2]) ** 2
if tmpmax < k:
tmpmax = k
print(round(tmpmax ** 0.5, 5))
```
|
output
| 1
| 101,995
| 3
| 203,991
|
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an interactive problem.
Natasha is going to fly to Mars. Finally, Natasha sat in the rocket. She flies, flies... but gets bored. She wishes to arrive to Mars already! So she decides to find something to occupy herself. She couldn't think of anything better to do than to calculate the distance to the red planet.
Let's define x as the distance to Mars. Unfortunately, Natasha does not know x. But it is known that 1 β€ x β€ m, where Natasha knows the number m. Besides, x and m are positive integers.
Natasha can ask the rocket questions. Every question is an integer y (1 β€ y β€ m). The correct answer to the question is -1, if x<y, 0, if x=y, and 1, if x>y. But the rocket is broken β it does not always answer correctly. Precisely: let the correct answer to the current question be equal to t, then, if the rocket answers this question correctly, then it will answer t, otherwise it will answer -t.
In addition, the rocket has a sequence p of length n. Each element of the sequence is either 0 or 1. The rocket processes this sequence in the cyclic order, that is 1-st element, 2-nd, 3-rd, β¦, (n-1)-th, n-th, 1-st, 2-nd, 3-rd, β¦, (n-1)-th, n-th, β¦. If the current element is 1, the rocket answers correctly, if 0 β lies. Natasha doesn't know the sequence p, but she knows its length β n.
You can ask the rocket no more than 60 questions.
Help Natasha find the distance to Mars. Assume, that the distance to Mars does not change while Natasha is asking questions.
Your solution will not be accepted, if it does not receive an answer 0 from the rocket (even if the distance to Mars is uniquely determined by the already received rocket's answers).
Input
The first line contains two integers m and n (1 β€ m β€ 10^9, 1 β€ n β€ 30) β the maximum distance to Mars and the number of elements in the sequence p.
Interaction
You can ask the rocket no more than 60 questions.
To ask a question, print a number y (1β€ yβ€ m) and an end-of-line character, then do the operation flush and read the answer to the question.
If the program reads 0, then the distance is correct and you must immediately terminate the program (for example, by calling exit(0)). If you ignore this, you can get any verdict, since your program will continue to read from the closed input stream.
If at some point your program reads -2 as an answer, it must immediately end (for example, by calling exit(0)). You will receive the "Wrong answer" verdict, and this will mean that the request is incorrect or the number of requests exceeds 60. If you ignore this, you can get any verdict, since your program will continue to read from the closed input stream.
If your program's request is not a valid integer between -2^{31} and 2^{31}-1 (inclusive) without leading zeros, then you can get any verdict.
You can get "Idleness limit exceeded" if you don't print anything or if you forget to flush the output.
To flush the output buffer you can use (after printing a query and end-of-line):
* fflush(stdout) in C++;
* System.out.flush() in Java;
* stdout.flush() in Python;
* flush(output) in Pascal;
* See the documentation for other languages.
Hacking
Use the following format for hacking:
In the first line, print 3 integers m,n,x (1β€ xβ€ mβ€ 10^9, 1β€ nβ€ 30) β the maximum distance to Mars, the number of elements in the sequence p and the current distance to Mars.
In the second line, enter n numbers, each of which is equal to 0 or 1 β sequence p.
The hacked solution will not have access to the number x and sequence p.
Example
Input
5 2
1
-1
-1
1
0
Output
1
2
4
5
3
Note
In the example, hacking would look like this:
5 2 3
1 0
This means that the current distance to Mars is equal to 3, Natasha knows that it does not exceed 5, and the rocket answers in order: correctly, incorrectly, correctly, incorrectly ...
Really:
on the first query (1) the correct answer is 1, the rocket answered correctly: 1;
on the second query (2) the correct answer is 1, the rocket answered incorrectly: -1;
on the third query (4) the correct answer is -1, the rocket answered correctly: -1;
on the fourth query (5) the correct answer is -1, the rocket answered incorrectly: 1;
on the fifth query (3) the correct and incorrect answer is 0.
|
instruction
| 0
| 102,032
| 3
| 204,064
|
Tags: binary search, interactive
Correct Solution:
```
from sys import stdin
from math import *
from sys import stdout
line = stdin.readline().rstrip().split()
m = int(line[0])
n = int(line[1])
bits = []
for i in range(n):
print(m)
stdout.flush()
line = stdin.readline().rstrip().split()
res = int(line[0])
if res == 0:
exit(0)
if res == 1:
bits.append(-1)
else:
bits.append(1)
minN = 1
maxN = m
i = 0
while True:
current = int((minN + maxN) / 2)
print(current)
stdout.flush()
line = stdin.readline().rstrip().split()
res = int(line[0])
if res == 0:
exit(0)
res *= bits[i]
i = (i+1) % n
if res == 1:
minN = current + 1
else:
maxN = current - 1
```
|
output
| 1
| 102,032
| 3
| 204,065
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
Natasha is going to fly to Mars. Finally, Natasha sat in the rocket. She flies, flies... but gets bored. She wishes to arrive to Mars already! So she decides to find something to occupy herself. She couldn't think of anything better to do than to calculate the distance to the red planet.
Let's define x as the distance to Mars. Unfortunately, Natasha does not know x. But it is known that 1 β€ x β€ m, where Natasha knows the number m. Besides, x and m are positive integers.
Natasha can ask the rocket questions. Every question is an integer y (1 β€ y β€ m). The correct answer to the question is -1, if x<y, 0, if x=y, and 1, if x>y. But the rocket is broken β it does not always answer correctly. Precisely: let the correct answer to the current question be equal to t, then, if the rocket answers this question correctly, then it will answer t, otherwise it will answer -t.
In addition, the rocket has a sequence p of length n. Each element of the sequence is either 0 or 1. The rocket processes this sequence in the cyclic order, that is 1-st element, 2-nd, 3-rd, β¦, (n-1)-th, n-th, 1-st, 2-nd, 3-rd, β¦, (n-1)-th, n-th, β¦. If the current element is 1, the rocket answers correctly, if 0 β lies. Natasha doesn't know the sequence p, but she knows its length β n.
You can ask the rocket no more than 60 questions.
Help Natasha find the distance to Mars. Assume, that the distance to Mars does not change while Natasha is asking questions.
Your solution will not be accepted, if it does not receive an answer 0 from the rocket (even if the distance to Mars is uniquely determined by the already received rocket's answers).
Input
The first line contains two integers m and n (1 β€ m β€ 10^9, 1 β€ n β€ 30) β the maximum distance to Mars and the number of elements in the sequence p.
Interaction
You can ask the rocket no more than 60 questions.
To ask a question, print a number y (1β€ yβ€ m) and an end-of-line character, then do the operation flush and read the answer to the question.
If the program reads 0, then the distance is correct and you must immediately terminate the program (for example, by calling exit(0)). If you ignore this, you can get any verdict, since your program will continue to read from the closed input stream.
If at some point your program reads -2 as an answer, it must immediately end (for example, by calling exit(0)). You will receive the "Wrong answer" verdict, and this will mean that the request is incorrect or the number of requests exceeds 60. If you ignore this, you can get any verdict, since your program will continue to read from the closed input stream.
If your program's request is not a valid integer between -2^{31} and 2^{31}-1 (inclusive) without leading zeros, then you can get any verdict.
You can get "Idleness limit exceeded" if you don't print anything or if you forget to flush the output.
To flush the output buffer you can use (after printing a query and end-of-line):
* fflush(stdout) in C++;
* System.out.flush() in Java;
* stdout.flush() in Python;
* flush(output) in Pascal;
* See the documentation for other languages.
Hacking
Use the following format for hacking:
In the first line, print 3 integers m,n,x (1β€ xβ€ mβ€ 10^9, 1β€ nβ€ 30) β the maximum distance to Mars, the number of elements in the sequence p and the current distance to Mars.
In the second line, enter n numbers, each of which is equal to 0 or 1 β sequence p.
The hacked solution will not have access to the number x and sequence p.
Example
Input
5 2
1
-1
-1
1
0
Output
1
2
4
5
3
Note
In the example, hacking would look like this:
5 2 3
1 0
This means that the current distance to Mars is equal to 3, Natasha knows that it does not exceed 5, and the rocket answers in order: correctly, incorrectly, correctly, incorrectly ...
Really:
on the first query (1) the correct answer is 1, the rocket answered correctly: 1;
on the second query (2) the correct answer is 1, the rocket answered incorrectly: -1;
on the third query (4) the correct answer is -1, the rocket answered correctly: -1;
on the fourth query (5) the correct answer is -1, the rocket answered incorrectly: 1;
on the fifth query (3) the correct and incorrect answer is 0.
Submitted Solution:
```
from sys import stdin
from math import *
from sys import stdout
line = stdin.readline().rstrip().split()
m = int(line[0])
n = int(line[1])
bits = []
for i in range(n):
print(m + 1)
stdout.flush()
line = stdin.readline().rstrip().split()
res = int(line[0])
if res == 1:
bits.append(1)
else:
bits.append(-1)
minN = 1
maxN = m
i = 0
while True:
current = int((minN + maxN) / 2)
print(current)
stdout.flush()
line = stdin.readline().rstrip().split()
res = int(line[0])
if res == 0:
exit(0)
res *= bits[i]
i = (i+1) % n
if res == 1:
minN = current + 1
else:
maxN = current - 1
```
|
instruction
| 0
| 102,033
| 3
| 204,066
|
No
|
output
| 1
| 102,033
| 3
| 204,067
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
Natasha is going to fly to Mars. Finally, Natasha sat in the rocket. She flies, flies... but gets bored. She wishes to arrive to Mars already! So she decides to find something to occupy herself. She couldn't think of anything better to do than to calculate the distance to the red planet.
Let's define x as the distance to Mars. Unfortunately, Natasha does not know x. But it is known that 1 β€ x β€ m, where Natasha knows the number m. Besides, x and m are positive integers.
Natasha can ask the rocket questions. Every question is an integer y (1 β€ y β€ m). The correct answer to the question is -1, if x<y, 0, if x=y, and 1, if x>y. But the rocket is broken β it does not always answer correctly. Precisely: let the correct answer to the current question be equal to t, then, if the rocket answers this question correctly, then it will answer t, otherwise it will answer -t.
In addition, the rocket has a sequence p of length n. Each element of the sequence is either 0 or 1. The rocket processes this sequence in the cyclic order, that is 1-st element, 2-nd, 3-rd, β¦, (n-1)-th, n-th, 1-st, 2-nd, 3-rd, β¦, (n-1)-th, n-th, β¦. If the current element is 1, the rocket answers correctly, if 0 β lies. Natasha doesn't know the sequence p, but she knows its length β n.
You can ask the rocket no more than 60 questions.
Help Natasha find the distance to Mars. Assume, that the distance to Mars does not change while Natasha is asking questions.
Your solution will not be accepted, if it does not receive an answer 0 from the rocket (even if the distance to Mars is uniquely determined by the already received rocket's answers).
Input
The first line contains two integers m and n (1 β€ m β€ 10^9, 1 β€ n β€ 30) β the maximum distance to Mars and the number of elements in the sequence p.
Interaction
You can ask the rocket no more than 60 questions.
To ask a question, print a number y (1β€ yβ€ m) and an end-of-line character, then do the operation flush and read the answer to the question.
If the program reads 0, then the distance is correct and you must immediately terminate the program (for example, by calling exit(0)). If you ignore this, you can get any verdict, since your program will continue to read from the closed input stream.
If at some point your program reads -2 as an answer, it must immediately end (for example, by calling exit(0)). You will receive the "Wrong answer" verdict, and this will mean that the request is incorrect or the number of requests exceeds 60. If you ignore this, you can get any verdict, since your program will continue to read from the closed input stream.
If your program's request is not a valid integer between -2^{31} and 2^{31}-1 (inclusive) without leading zeros, then you can get any verdict.
You can get "Idleness limit exceeded" if you don't print anything or if you forget to flush the output.
To flush the output buffer you can use (after printing a query and end-of-line):
* fflush(stdout) in C++;
* System.out.flush() in Java;
* stdout.flush() in Python;
* flush(output) in Pascal;
* See the documentation for other languages.
Hacking
Use the following format for hacking:
In the first line, print 3 integers m,n,x (1β€ xβ€ mβ€ 10^9, 1β€ nβ€ 30) β the maximum distance to Mars, the number of elements in the sequence p and the current distance to Mars.
In the second line, enter n numbers, each of which is equal to 0 or 1 β sequence p.
The hacked solution will not have access to the number x and sequence p.
Example
Input
5 2
1
-1
-1
1
0
Output
1
2
4
5
3
Note
In the example, hacking would look like this:
5 2 3
1 0
This means that the current distance to Mars is equal to 3, Natasha knows that it does not exceed 5, and the rocket answers in order: correctly, incorrectly, correctly, incorrectly ...
Really:
on the first query (1) the correct answer is 1, the rocket answered correctly: 1;
on the second query (2) the correct answer is 1, the rocket answered incorrectly: -1;
on the third query (4) the correct answer is -1, the rocket answered correctly: -1;
on the fourth query (5) the correct answer is -1, the rocket answered incorrectly: 1;
on the fifth query (3) the correct and incorrect answer is 0.
Submitted Solution:
```
from sys import stdin, stdout
m, n = map(int, input().split())
a = []
for i in range(n):
print(1)
stdout.flush()
a.append(int(input()))
if(a[-1] == 0):
exit(0)
l = 0
r = m
for i in range(60 - n):
i = i % len(a)
print((r + l) // 2)
stdout.flush()
ans = int(input())
if a[i] == -1:
ans = -ans
if ans == 0:
exit(0)
elif ans == 1:
l = (r + l) // 2
else:
r = (r + l) // 2
```
|
instruction
| 0
| 102,034
| 3
| 204,068
|
No
|
output
| 1
| 102,034
| 3
| 204,069
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
Natasha is going to fly to Mars. Finally, Natasha sat in the rocket. She flies, flies... but gets bored. She wishes to arrive to Mars already! So she decides to find something to occupy herself. She couldn't think of anything better to do than to calculate the distance to the red planet.
Let's define x as the distance to Mars. Unfortunately, Natasha does not know x. But it is known that 1 β€ x β€ m, where Natasha knows the number m. Besides, x and m are positive integers.
Natasha can ask the rocket questions. Every question is an integer y (1 β€ y β€ m). The correct answer to the question is -1, if x<y, 0, if x=y, and 1, if x>y. But the rocket is broken β it does not always answer correctly. Precisely: let the correct answer to the current question be equal to t, then, if the rocket answers this question correctly, then it will answer t, otherwise it will answer -t.
In addition, the rocket has a sequence p of length n. Each element of the sequence is either 0 or 1. The rocket processes this sequence in the cyclic order, that is 1-st element, 2-nd, 3-rd, β¦, (n-1)-th, n-th, 1-st, 2-nd, 3-rd, β¦, (n-1)-th, n-th, β¦. If the current element is 1, the rocket answers correctly, if 0 β lies. Natasha doesn't know the sequence p, but she knows its length β n.
You can ask the rocket no more than 60 questions.
Help Natasha find the distance to Mars. Assume, that the distance to Mars does not change while Natasha is asking questions.
Your solution will not be accepted, if it does not receive an answer 0 from the rocket (even if the distance to Mars is uniquely determined by the already received rocket's answers).
Input
The first line contains two integers m and n (1 β€ m β€ 10^9, 1 β€ n β€ 30) β the maximum distance to Mars and the number of elements in the sequence p.
Interaction
You can ask the rocket no more than 60 questions.
To ask a question, print a number y (1β€ yβ€ m) and an end-of-line character, then do the operation flush and read the answer to the question.
If the program reads 0, then the distance is correct and you must immediately terminate the program (for example, by calling exit(0)). If you ignore this, you can get any verdict, since your program will continue to read from the closed input stream.
If at some point your program reads -2 as an answer, it must immediately end (for example, by calling exit(0)). You will receive the "Wrong answer" verdict, and this will mean that the request is incorrect or the number of requests exceeds 60. If you ignore this, you can get any verdict, since your program will continue to read from the closed input stream.
If your program's request is not a valid integer between -2^{31} and 2^{31}-1 (inclusive) without leading zeros, then you can get any verdict.
You can get "Idleness limit exceeded" if you don't print anything or if you forget to flush the output.
To flush the output buffer you can use (after printing a query and end-of-line):
* fflush(stdout) in C++;
* System.out.flush() in Java;
* stdout.flush() in Python;
* flush(output) in Pascal;
* See the documentation for other languages.
Hacking
Use the following format for hacking:
In the first line, print 3 integers m,n,x (1β€ xβ€ mβ€ 10^9, 1β€ nβ€ 30) β the maximum distance to Mars, the number of elements in the sequence p and the current distance to Mars.
In the second line, enter n numbers, each of which is equal to 0 or 1 β sequence p.
The hacked solution will not have access to the number x and sequence p.
Example
Input
5 2
1
-1
-1
1
0
Output
1
2
4
5
3
Note
In the example, hacking would look like this:
5 2 3
1 0
This means that the current distance to Mars is equal to 3, Natasha knows that it does not exceed 5, and the rocket answers in order: correctly, incorrectly, correctly, incorrectly ...
Really:
on the first query (1) the correct answer is 1, the rocket answered correctly: 1;
on the second query (2) the correct answer is 1, the rocket answered incorrectly: -1;
on the third query (4) the correct answer is -1, the rocket answered correctly: -1;
on the fourth query (5) the correct answer is -1, the rocket answered incorrectly: 1;
on the fifth query (3) the correct and incorrect answer is 0.
Submitted Solution:
```
n , m = map(int,input().split())
seq = [0 for i in range(n)]
import sys
for i in range(n):
print(1)
sys.stdout.flush()
curr = int(input())
if curr == 0 or curr == -2:
exit(0)
if curr == -1:
seq[i] = 1
l = 1
r = m
turn = 0
while r - l > -1:
mid = (l + r) // 2
print(mid)
sys.stdout.flush()
curr = int(input())
if curr == 0 or curr == -2:
exit(0)
if seq[turn] == 0:
curr *= -1
turn += 1
turn %=n
if curr == 1:
r = mid - 1
else:
l = mid +1
```
|
instruction
| 0
| 102,035
| 3
| 204,070
|
No
|
output
| 1
| 102,035
| 3
| 204,071
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
Natasha is going to fly to Mars. Finally, Natasha sat in the rocket. She flies, flies... but gets bored. She wishes to arrive to Mars already! So she decides to find something to occupy herself. She couldn't think of anything better to do than to calculate the distance to the red planet.
Let's define x as the distance to Mars. Unfortunately, Natasha does not know x. But it is known that 1 β€ x β€ m, where Natasha knows the number m. Besides, x and m are positive integers.
Natasha can ask the rocket questions. Every question is an integer y (1 β€ y β€ m). The correct answer to the question is -1, if x<y, 0, if x=y, and 1, if x>y. But the rocket is broken β it does not always answer correctly. Precisely: let the correct answer to the current question be equal to t, then, if the rocket answers this question correctly, then it will answer t, otherwise it will answer -t.
In addition, the rocket has a sequence p of length n. Each element of the sequence is either 0 or 1. The rocket processes this sequence in the cyclic order, that is 1-st element, 2-nd, 3-rd, β¦, (n-1)-th, n-th, 1-st, 2-nd, 3-rd, β¦, (n-1)-th, n-th, β¦. If the current element is 1, the rocket answers correctly, if 0 β lies. Natasha doesn't know the sequence p, but she knows its length β n.
You can ask the rocket no more than 60 questions.
Help Natasha find the distance to Mars. Assume, that the distance to Mars does not change while Natasha is asking questions.
Your solution will not be accepted, if it does not receive an answer 0 from the rocket (even if the distance to Mars is uniquely determined by the already received rocket's answers).
Input
The first line contains two integers m and n (1 β€ m β€ 10^9, 1 β€ n β€ 30) β the maximum distance to Mars and the number of elements in the sequence p.
Interaction
You can ask the rocket no more than 60 questions.
To ask a question, print a number y (1β€ yβ€ m) and an end-of-line character, then do the operation flush and read the answer to the question.
If the program reads 0, then the distance is correct and you must immediately terminate the program (for example, by calling exit(0)). If you ignore this, you can get any verdict, since your program will continue to read from the closed input stream.
If at some point your program reads -2 as an answer, it must immediately end (for example, by calling exit(0)). You will receive the "Wrong answer" verdict, and this will mean that the request is incorrect or the number of requests exceeds 60. If you ignore this, you can get any verdict, since your program will continue to read from the closed input stream.
If your program's request is not a valid integer between -2^{31} and 2^{31}-1 (inclusive) without leading zeros, then you can get any verdict.
You can get "Idleness limit exceeded" if you don't print anything or if you forget to flush the output.
To flush the output buffer you can use (after printing a query and end-of-line):
* fflush(stdout) in C++;
* System.out.flush() in Java;
* stdout.flush() in Python;
* flush(output) in Pascal;
* See the documentation for other languages.
Hacking
Use the following format for hacking:
In the first line, print 3 integers m,n,x (1β€ xβ€ mβ€ 10^9, 1β€ nβ€ 30) β the maximum distance to Mars, the number of elements in the sequence p and the current distance to Mars.
In the second line, enter n numbers, each of which is equal to 0 or 1 β sequence p.
The hacked solution will not have access to the number x and sequence p.
Example
Input
5 2
1
-1
-1
1
0
Output
1
2
4
5
3
Note
In the example, hacking would look like this:
5 2 3
1 0
This means that the current distance to Mars is equal to 3, Natasha knows that it does not exceed 5, and the rocket answers in order: correctly, incorrectly, correctly, incorrectly ...
Really:
on the first query (1) the correct answer is 1, the rocket answered correctly: 1;
on the second query (2) the correct answer is 1, the rocket answered incorrectly: -1;
on the third query (4) the correct answer is -1, the rocket answered correctly: -1;
on the fourth query (5) the correct answer is -1, the rocket answered incorrectly: 1;
on the fifth query (3) the correct and incorrect answer is 0.
Submitted Solution:
```
from sys import stdout
m, n = map(int,input().split())
a = []
for i in range(n):
print(1)
stdout.flush()
k = int(input())
if k == 0 or k == -2:
exit(0)
elif k > 0:
a.append(1)
else:
a.append(0)
numb = n
left = 1
right = m + 1
while(left != right):
mid = ( left + right ) // 2
print(mid)
stdout.flush()
ans = int(input())
if( ans == 0 or ans == -2 ):
exit(0)
if a[n%len(a)] == 0:
ans = -ans
if( ans > 0 ):
left = mid + 1
else:
right = mid
```
|
instruction
| 0
| 102,036
| 3
| 204,072
|
No
|
output
| 1
| 102,036
| 3
| 204,073
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch.
Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts t1 seconds and the second part lasts t2 seconds. The first and the second part are separated by a little break.
After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of vi meters per second. After t1 seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by k percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of ui meters per second. After a t2 seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary.
Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds ai and bi, then there are two strategies: he either uses speed ai before the break and speed bi after it, or vice versa.
Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results.
The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).
Input
The first input line contains four integer numbers n, t1, t2, k (1 β€ n, t1, t2 β€ 1000; 1 β€ k β€ 100) β the number of participants, the time before the break, the time after the break and the percentage, by which the mushroom growth drops during the break, correspondingly.
Each of the following n lines contains two integers. The i-th (1 β€ i β€ n) line contains space-separated integers ai, bi (1 β€ ai, bi β€ 1000) β the speeds which the participant number i chose.
Output
Print the final results' table: n lines, each line should contain the number of the corresponding dwarf and the final maximum height of his mushroom with exactly two digits after the decimal point. The answer will be considered correct if it is absolutely accurate.
Examples
Input
2 3 3 50
2 4
4 2
Output
1 15.00
2 15.00
Input
4 1 1 1
544 397
280 101
280 101
693 970
Output
4 1656.07
1 937.03
2 379.99
3 379.99
Note
* First example: for each contestant it is optimal to use firstly speed 2 and afterwards speed 4, because 2Β·3Β·0.5 + 4Β·3 > 4Β·3Β·0.5 + 2Β·3.
|
instruction
| 0
| 102,333
| 3
| 204,666
|
Tags: greedy, sortings
Correct Solution:
```
n, t1, t2, k=map(int, input().split(' '))
nums=[[0, 0] for t in range(n)]
for line in range(n):
a, b=map(int, input().split(' '))
nums[line][0]=max(a*t2+b*(t1*(1-k/100)), b*t2+a*(t1*(1-k/100)))
nums[line][1]=13379001-line
nums.sort()
nums.reverse()
for a in range(len(nums)):
print(13379001-nums[a][1]+1, "{0:.2f}".format(nums[a][0]))
```
|
output
| 1
| 102,333
| 3
| 204,667
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch.
Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts t1 seconds and the second part lasts t2 seconds. The first and the second part are separated by a little break.
After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of vi meters per second. After t1 seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by k percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of ui meters per second. After a t2 seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary.
Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds ai and bi, then there are two strategies: he either uses speed ai before the break and speed bi after it, or vice versa.
Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results.
The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).
Input
The first input line contains four integer numbers n, t1, t2, k (1 β€ n, t1, t2 β€ 1000; 1 β€ k β€ 100) β the number of participants, the time before the break, the time after the break and the percentage, by which the mushroom growth drops during the break, correspondingly.
Each of the following n lines contains two integers. The i-th (1 β€ i β€ n) line contains space-separated integers ai, bi (1 β€ ai, bi β€ 1000) β the speeds which the participant number i chose.
Output
Print the final results' table: n lines, each line should contain the number of the corresponding dwarf and the final maximum height of his mushroom with exactly two digits after the decimal point. The answer will be considered correct if it is absolutely accurate.
Examples
Input
2 3 3 50
2 4
4 2
Output
1 15.00
2 15.00
Input
4 1 1 1
544 397
280 101
280 101
693 970
Output
4 1656.07
1 937.03
2 379.99
3 379.99
Note
* First example: for each contestant it is optimal to use firstly speed 2 and afterwards speed 4, because 2Β·3Β·0.5 + 4Β·3 > 4Β·3Β·0.5 + 2Β·3.
|
instruction
| 0
| 102,334
| 3
| 204,668
|
Tags: greedy, sortings
Correct Solution:
```
n,t1,t2,k=map(int,input().split())
k=k/100
c=[]
for i in range(n):
a,b=map(int,input().split())
cal=max((a*t1)-(a*t1*k)+(b*t2),(b*t1)-(b*t1*k)+(a*t2))
c.append((i+1,cal))
# print(c)
c.sort(key=lambda x:x[1],reverse=True)
# print(c)
for i in c:
print(i[0],end=' ')
print('%.2f'%(i[1]),end=' ')
print()
```
|
output
| 1
| 102,334
| 3
| 204,669
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch.
Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts t1 seconds and the second part lasts t2 seconds. The first and the second part are separated by a little break.
After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of vi meters per second. After t1 seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by k percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of ui meters per second. After a t2 seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary.
Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds ai and bi, then there are two strategies: he either uses speed ai before the break and speed bi after it, or vice versa.
Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results.
The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).
Input
The first input line contains four integer numbers n, t1, t2, k (1 β€ n, t1, t2 β€ 1000; 1 β€ k β€ 100) β the number of participants, the time before the break, the time after the break and the percentage, by which the mushroom growth drops during the break, correspondingly.
Each of the following n lines contains two integers. The i-th (1 β€ i β€ n) line contains space-separated integers ai, bi (1 β€ ai, bi β€ 1000) β the speeds which the participant number i chose.
Output
Print the final results' table: n lines, each line should contain the number of the corresponding dwarf and the final maximum height of his mushroom with exactly two digits after the decimal point. The answer will be considered correct if it is absolutely accurate.
Examples
Input
2 3 3 50
2 4
4 2
Output
1 15.00
2 15.00
Input
4 1 1 1
544 397
280 101
280 101
693 970
Output
4 1656.07
1 937.03
2 379.99
3 379.99
Note
* First example: for each contestant it is optimal to use firstly speed 2 and afterwards speed 4, because 2Β·3Β·0.5 + 4Β·3 > 4Β·3Β·0.5 + 2Β·3.
|
instruction
| 0
| 102,335
| 3
| 204,670
|
Tags: greedy, sortings
Correct Solution:
```
'''http://codeforces.com/contest/186/problem/B'''
n,t1,t2,k = map(int, input().split(" "))
factor = 1- (k/100)
listX = []
for i in range(n):
a,b = map(int, input().split(" "))
maxX = max(((a*t1*factor) + (b*t2)),((b*t1*factor)+(a*t2)))
# print(maxX)
listX.append(maxX)
maxVal = max(listX)
while (maxVal!=-1):
indexMax = listX.index(maxVal)
print(indexMax +1,'%.2f'%maxVal)
listX[indexMax] = -1
maxVal = max(listX)
```
|
output
| 1
| 102,335
| 3
| 204,671
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch.
Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts t1 seconds and the second part lasts t2 seconds. The first and the second part are separated by a little break.
After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of vi meters per second. After t1 seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by k percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of ui meters per second. After a t2 seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary.
Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds ai and bi, then there are two strategies: he either uses speed ai before the break and speed bi after it, or vice versa.
Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results.
The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).
Input
The first input line contains four integer numbers n, t1, t2, k (1 β€ n, t1, t2 β€ 1000; 1 β€ k β€ 100) β the number of participants, the time before the break, the time after the break and the percentage, by which the mushroom growth drops during the break, correspondingly.
Each of the following n lines contains two integers. The i-th (1 β€ i β€ n) line contains space-separated integers ai, bi (1 β€ ai, bi β€ 1000) β the speeds which the participant number i chose.
Output
Print the final results' table: n lines, each line should contain the number of the corresponding dwarf and the final maximum height of his mushroom with exactly two digits after the decimal point. The answer will be considered correct if it is absolutely accurate.
Examples
Input
2 3 3 50
2 4
4 2
Output
1 15.00
2 15.00
Input
4 1 1 1
544 397
280 101
280 101
693 970
Output
4 1656.07
1 937.03
2 379.99
3 379.99
Note
* First example: for each contestant it is optimal to use firstly speed 2 and afterwards speed 4, because 2Β·3Β·0.5 + 4Β·3 > 4Β·3Β·0.5 + 2Β·3.
|
instruction
| 0
| 102,336
| 3
| 204,672
|
Tags: greedy, sortings
Correct Solution:
```
n, t1, t2, k = [int(i) for i in input().split()]
ans = []
for i in range(n):
v, u = [int(i) for i in input().split()]
h = max(v*t1*(100 - k)/100 + u*t2, u*t1*(100 - k)/100 + v*t2)
ans.append((i, h))
ans.sort(key = lambda x : x[1] , reverse = True)
for i, h in ans:
print(i+1, "{0:.2f}".format(h))
```
|
output
| 1
| 102,336
| 3
| 204,673
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch.
Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts t1 seconds and the second part lasts t2 seconds. The first and the second part are separated by a little break.
After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of vi meters per second. After t1 seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by k percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of ui meters per second. After a t2 seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary.
Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds ai and bi, then there are two strategies: he either uses speed ai before the break and speed bi after it, or vice versa.
Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results.
The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).
Input
The first input line contains four integer numbers n, t1, t2, k (1 β€ n, t1, t2 β€ 1000; 1 β€ k β€ 100) β the number of participants, the time before the break, the time after the break and the percentage, by which the mushroom growth drops during the break, correspondingly.
Each of the following n lines contains two integers. The i-th (1 β€ i β€ n) line contains space-separated integers ai, bi (1 β€ ai, bi β€ 1000) β the speeds which the participant number i chose.
Output
Print the final results' table: n lines, each line should contain the number of the corresponding dwarf and the final maximum height of his mushroom with exactly two digits after the decimal point. The answer will be considered correct if it is absolutely accurate.
Examples
Input
2 3 3 50
2 4
4 2
Output
1 15.00
2 15.00
Input
4 1 1 1
544 397
280 101
280 101
693 970
Output
4 1656.07
1 937.03
2 379.99
3 379.99
Note
* First example: for each contestant it is optimal to use firstly speed 2 and afterwards speed 4, because 2Β·3Β·0.5 + 4Β·3 > 4Β·3Β·0.5 + 2Β·3.
|
instruction
| 0
| 102,337
| 3
| 204,674
|
Tags: greedy, sortings
Correct Solution:
```
n, t1, t2, k = list(map(int, input().split()))
rank = []
for seed_grower in range(n):
speed1, speed2 = list(map(int, input().split()))
var1 = speed1 * t1 * (1-(k/100)) + speed2 * t2
var2 = speed2 * t1 * (1-(k/100)) + speed1 * t2
total = max(var1, var2)
rank.append((seed_grower+1, total))
for seed_grower, plant_height in sorted(sorted(rank, key = lambda x : x[0]), key = lambda x : x[1], reverse = True):
print(seed_grower, "{:.2f}".format(plant_height))
```
|
output
| 1
| 102,337
| 3
| 204,675
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch.
Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts t1 seconds and the second part lasts t2 seconds. The first and the second part are separated by a little break.
After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of vi meters per second. After t1 seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by k percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of ui meters per second. After a t2 seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary.
Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds ai and bi, then there are two strategies: he either uses speed ai before the break and speed bi after it, or vice versa.
Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results.
The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).
Input
The first input line contains four integer numbers n, t1, t2, k (1 β€ n, t1, t2 β€ 1000; 1 β€ k β€ 100) β the number of participants, the time before the break, the time after the break and the percentage, by which the mushroom growth drops during the break, correspondingly.
Each of the following n lines contains two integers. The i-th (1 β€ i β€ n) line contains space-separated integers ai, bi (1 β€ ai, bi β€ 1000) β the speeds which the participant number i chose.
Output
Print the final results' table: n lines, each line should contain the number of the corresponding dwarf and the final maximum height of his mushroom with exactly two digits after the decimal point. The answer will be considered correct if it is absolutely accurate.
Examples
Input
2 3 3 50
2 4
4 2
Output
1 15.00
2 15.00
Input
4 1 1 1
544 397
280 101
280 101
693 970
Output
4 1656.07
1 937.03
2 379.99
3 379.99
Note
* First example: for each contestant it is optimal to use firstly speed 2 and afterwards speed 4, because 2Β·3Β·0.5 + 4Β·3 > 4Β·3Β·0.5 + 2Β·3.
|
instruction
| 0
| 102,338
| 3
| 204,676
|
Tags: greedy, sortings
Correct Solution:
```
n,t1,t2,k=map(int,input().split())
lst=[]
for i in range(n):
a,b=map(int,input().split())
lst.append((-max((a*t1*((100-k)/100)+b*t2),(b*t1*((100-k)/100)+a*t2)),i+1))
lst.sort()
for i in range(n):
print('%d %.2f'%(lst[i][1],-lst[i][0]))
```
|
output
| 1
| 102,338
| 3
| 204,677
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch.
Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts t1 seconds and the second part lasts t2 seconds. The first and the second part are separated by a little break.
After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of vi meters per second. After t1 seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by k percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of ui meters per second. After a t2 seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary.
Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds ai and bi, then there are two strategies: he either uses speed ai before the break and speed bi after it, or vice versa.
Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results.
The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).
Input
The first input line contains four integer numbers n, t1, t2, k (1 β€ n, t1, t2 β€ 1000; 1 β€ k β€ 100) β the number of participants, the time before the break, the time after the break and the percentage, by which the mushroom growth drops during the break, correspondingly.
Each of the following n lines contains two integers. The i-th (1 β€ i β€ n) line contains space-separated integers ai, bi (1 β€ ai, bi β€ 1000) β the speeds which the participant number i chose.
Output
Print the final results' table: n lines, each line should contain the number of the corresponding dwarf and the final maximum height of his mushroom with exactly two digits after the decimal point. The answer will be considered correct if it is absolutely accurate.
Examples
Input
2 3 3 50
2 4
4 2
Output
1 15.00
2 15.00
Input
4 1 1 1
544 397
280 101
280 101
693 970
Output
4 1656.07
1 937.03
2 379.99
3 379.99
Note
* First example: for each contestant it is optimal to use firstly speed 2 and afterwards speed 4, because 2Β·3Β·0.5 + 4Β·3 > 4Β·3Β·0.5 + 2Β·3.
|
instruction
| 0
| 102,339
| 3
| 204,678
|
Tags: greedy, sortings
Correct Solution:
```
# ip = open("testdata.txt", "r")
# def input():
# return ip.readline().strip()
n, t1, t2, k = map(int, input().split())
arr = [0]*n
redn = (100-k)/100
for i in range(n):
a, b = map(int, input().split())
res = max(t1*a*redn + t2*b, t1*b*redn + t2*a)
arr[i] = [i+1, res]
arr.sort(key=lambda x: (-x[1], x[0]))
for ele in arr:
print(ele[0], '%.2f'%ele[1])
```
|
output
| 1
| 102,339
| 3
| 204,679
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch.
Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts t1 seconds and the second part lasts t2 seconds. The first and the second part are separated by a little break.
After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of vi meters per second. After t1 seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by k percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of ui meters per second. After a t2 seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary.
Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds ai and bi, then there are two strategies: he either uses speed ai before the break and speed bi after it, or vice versa.
Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results.
The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).
Input
The first input line contains four integer numbers n, t1, t2, k (1 β€ n, t1, t2 β€ 1000; 1 β€ k β€ 100) β the number of participants, the time before the break, the time after the break and the percentage, by which the mushroom growth drops during the break, correspondingly.
Each of the following n lines contains two integers. The i-th (1 β€ i β€ n) line contains space-separated integers ai, bi (1 β€ ai, bi β€ 1000) β the speeds which the participant number i chose.
Output
Print the final results' table: n lines, each line should contain the number of the corresponding dwarf and the final maximum height of his mushroom with exactly two digits after the decimal point. The answer will be considered correct if it is absolutely accurate.
Examples
Input
2 3 3 50
2 4
4 2
Output
1 15.00
2 15.00
Input
4 1 1 1
544 397
280 101
280 101
693 970
Output
4 1656.07
1 937.03
2 379.99
3 379.99
Note
* First example: for each contestant it is optimal to use firstly speed 2 and afterwards speed 4, because 2Β·3Β·0.5 + 4Β·3 > 4Β·3Β·0.5 + 2Β·3.
|
instruction
| 0
| 102,340
| 3
| 204,680
|
Tags: greedy, sortings
Correct Solution:
```
"""
Problem link:
Solution By Keshav Mishra
"""
from sys import stdin,stdout
from collections import Counter , deque
from queue import PriorityQueue
import math
helperConstants = True
helperUtilityFunctions = True
def input(): return stdin.readline().strip()
# def print(s): stdout.write(str(s)+'\n')
if helperConstants:
YES = 'YES'
NO = 'NO'
yes = 'yes'
no = 'no'
true = 'true'
false = 'false'
FALSE = 'FALSE'
TRUE = 'TRUE'
IMPOSSIBLE = 'IMPOSSIBLE'
POSSIBLE = 'POSSIBLE'
INF = float('inf')
if helperUtilityFunctions:
# Input utility functions
def getInputArray():
return list(map(int, input().split()))
def getIntegerInputs():
return map(int, input().split())
def getInputIntegerMatrix(n):
matrix = []
for i in range(n):
matrix.append(list(map(int,input().split())))
return matrix
def getInputStringMatrix(n):
matrix = []
for i in range(n):
matrix.append(input())
return matrix
# Output Utility functions
def outputIntegerMatrix(matrix):
for i in range(len(matrix)):
print(*matrix[i])
def outputStringMatrix(matrix):
for i in range(len(matrix)):
print(matrix[i])
def kickstartoutput(testcase,*outputs):
print('Case #%d:'%(testcase), *outputs)
def solve():
n, t1, t2, k = getIntegerInputs()
participants = []
k = 1 - k*0.01
for i in range(n):
a, b = getIntegerInputs()
ans1 = 0
ans2 = 0
ans1 += a*t1
ans1 = ans1*k
ans1 += b*t2
ans2 += b*t1
ans2 = ans2*k
ans2 += a*t2
ans = max(ans1,ans2)
participants.append({'index':i + 1, 'value':ans})
participants.sort(reverse = True, key = lambda x : x['value'])
for participant in participants:
print('%d %.2f'%(participant['index'], participant['value']))
if __name__ == '__main__':
solve()
```
|
output
| 1
| 102,340
| 3
| 204,681
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch.
Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts t1 seconds and the second part lasts t2 seconds. The first and the second part are separated by a little break.
After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of vi meters per second. After t1 seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by k percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of ui meters per second. After a t2 seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary.
Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds ai and bi, then there are two strategies: he either uses speed ai before the break and speed bi after it, or vice versa.
Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results.
The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).
Input
The first input line contains four integer numbers n, t1, t2, k (1 β€ n, t1, t2 β€ 1000; 1 β€ k β€ 100) β the number of participants, the time before the break, the time after the break and the percentage, by which the mushroom growth drops during the break, correspondingly.
Each of the following n lines contains two integers. The i-th (1 β€ i β€ n) line contains space-separated integers ai, bi (1 β€ ai, bi β€ 1000) β the speeds which the participant number i chose.
Output
Print the final results' table: n lines, each line should contain the number of the corresponding dwarf and the final maximum height of his mushroom with exactly two digits after the decimal point. The answer will be considered correct if it is absolutely accurate.
Examples
Input
2 3 3 50
2 4
4 2
Output
1 15.00
2 15.00
Input
4 1 1 1
544 397
280 101
280 101
693 970
Output
4 1656.07
1 937.03
2 379.99
3 379.99
Note
* First example: for each contestant it is optimal to use firstly speed 2 and afterwards speed 4, because 2Β·3Β·0.5 + 4Β·3 > 4Β·3Β·0.5 + 2Β·3.
Submitted Solution:
```
#!/usr/bin/env python
import os
import re
import sys
from bisect import bisect, bisect_left, insort, insort_left
from collections import Counter, defaultdict, deque
from copy import deepcopy
from decimal import Decimal
from fractions import gcd
from io import BytesIO, IOBase
from itertools import (
accumulate, combinations, combinations_with_replacement, groupby,
permutations, product)
from math import (
acos, asin, atan, ceil, cos, degrees, factorial, hypot, log2, pi, radians,
sin, sqrt, tan)
from operator import itemgetter, mul
from string import ascii_lowercase, ascii_uppercase, digits
def inp():
return(int(input()))
def inlist():
return(list(map(int, input().split())))
def instr():
s = input()
return(list(s[:len(s)]))
def invr():
return(map(int, input().split()))
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
def input(): return sys.stdin.readline().rstrip("\r\n")
# endregion
def valid(x, y, n, m):
if x <= n and x >= 1 and y <= m and y >= 1:
return True
return False
def findValidSteps(x, y, dx, dy, n, m):
l = 0
r = max(n, m)
res = 0
while l <= r:
mid = l + (r - l) // 2
tx, ty = x + dx*mid, y + dy*mid
if valid(tx, ty, n, m):
res = mid
l = mid + 1
else:
r = mid - 1
return res
n, t1, t2, k = invr()
k /= 100
res = []
for i in range(1, n+1):
a, b = invr()
res.append([i, max((t1*a - t1*a*k) + t2*b, (t1*b - t1*b*k)+t2*a)])
res = sorted(res, key=lambda d: d[1], reverse=True)
for r in res:
print(r[0], end=" ")
print("%.2f" % (r[1]))
```
|
instruction
| 0
| 102,341
| 3
| 204,682
|
Yes
|
output
| 1
| 102,341
| 3
| 204,683
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch.
Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts t1 seconds and the second part lasts t2 seconds. The first and the second part are separated by a little break.
After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of vi meters per second. After t1 seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by k percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of ui meters per second. After a t2 seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary.
Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds ai and bi, then there are two strategies: he either uses speed ai before the break and speed bi after it, or vice versa.
Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results.
The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).
Input
The first input line contains four integer numbers n, t1, t2, k (1 β€ n, t1, t2 β€ 1000; 1 β€ k β€ 100) β the number of participants, the time before the break, the time after the break and the percentage, by which the mushroom growth drops during the break, correspondingly.
Each of the following n lines contains two integers. The i-th (1 β€ i β€ n) line contains space-separated integers ai, bi (1 β€ ai, bi β€ 1000) β the speeds which the participant number i chose.
Output
Print the final results' table: n lines, each line should contain the number of the corresponding dwarf and the final maximum height of his mushroom with exactly two digits after the decimal point. The answer will be considered correct if it is absolutely accurate.
Examples
Input
2 3 3 50
2 4
4 2
Output
1 15.00
2 15.00
Input
4 1 1 1
544 397
280 101
280 101
693 970
Output
4 1656.07
1 937.03
2 379.99
3 379.99
Note
* First example: for each contestant it is optimal to use firstly speed 2 and afterwards speed 4, because 2Β·3Β·0.5 + 4Β·3 > 4Β·3Β·0.5 + 2Β·3.
Submitted Solution:
```
I = lambda: map(int, input().split())
n, t1, t2, k = I()
res = []
for i in range(n):
a, b = I()
res.append((i, max((1-k/100)*a*t1+b*t2, (1-k/100)*b*t1+a*t2)))
for i,h in sorted(res, key=lambda x: (-x[1], x[0])):
print(i+1, f'{h:.2f}')
```
|
instruction
| 0
| 102,342
| 3
| 204,684
|
Yes
|
output
| 1
| 102,342
| 3
| 204,685
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch.
Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts t1 seconds and the second part lasts t2 seconds. The first and the second part are separated by a little break.
After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of vi meters per second. After t1 seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by k percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of ui meters per second. After a t2 seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary.
Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds ai and bi, then there are two strategies: he either uses speed ai before the break and speed bi after it, or vice versa.
Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results.
The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).
Input
The first input line contains four integer numbers n, t1, t2, k (1 β€ n, t1, t2 β€ 1000; 1 β€ k β€ 100) β the number of participants, the time before the break, the time after the break and the percentage, by which the mushroom growth drops during the break, correspondingly.
Each of the following n lines contains two integers. The i-th (1 β€ i β€ n) line contains space-separated integers ai, bi (1 β€ ai, bi β€ 1000) β the speeds which the participant number i chose.
Output
Print the final results' table: n lines, each line should contain the number of the corresponding dwarf and the final maximum height of his mushroom with exactly two digits after the decimal point. The answer will be considered correct if it is absolutely accurate.
Examples
Input
2 3 3 50
2 4
4 2
Output
1 15.00
2 15.00
Input
4 1 1 1
544 397
280 101
280 101
693 970
Output
4 1656.07
1 937.03
2 379.99
3 379.99
Note
* First example: for each contestant it is optimal to use firstly speed 2 and afterwards speed 4, because 2Β·3Β·0.5 + 4Β·3 > 4Β·3Β·0.5 + 2Β·3.
Submitted Solution:
```
"""
βββ βββββββ βββ βββββββ βββββββ βββ ββββββ
βββββββββββββββ βββββββββββββββββββββββββββββ
ββββββ ββββββ ββββββββββββββββββββββββββββ
ββββββ ββββββ βββββββ βββββββββ βββ βββββββ
βββββββββββββββ βββββββββββββββββ βββ βββββββ
βββ βββββββ βββ ββββββββ βββββββ βββ ββββββ
"""
def sort(lst):
for i in range(len(lst)):
for j in range(len(lst)):
if lst[i][0] > lst[j][0]:
lst[i], lst[j] = lst[j], lst[i]
if lst[i][0] == lst[j][0]:
if lst[i][1] < lst[j][1]:
lst[i], lst[j] = lst[j], lst[i]
n, t1, t2, k = map(int, input().split())
table = []
for i in range(n):
a, b = map(int, input().split())
table += [[max(t1 * a * (100 - k) / 100 + t2 * b, t1 * b * (100 - k) / 100 + t2 * a), i + 1]]
sort(table)
for i in table:
print(i[1], "%.2f" %i[0])
```
|
instruction
| 0
| 102,343
| 3
| 204,686
|
Yes
|
output
| 1
| 102,343
| 3
| 204,687
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch.
Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts t1 seconds and the second part lasts t2 seconds. The first and the second part are separated by a little break.
After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of vi meters per second. After t1 seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by k percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of ui meters per second. After a t2 seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary.
Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds ai and bi, then there are two strategies: he either uses speed ai before the break and speed bi after it, or vice versa.
Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results.
The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).
Input
The first input line contains four integer numbers n, t1, t2, k (1 β€ n, t1, t2 β€ 1000; 1 β€ k β€ 100) β the number of participants, the time before the break, the time after the break and the percentage, by which the mushroom growth drops during the break, correspondingly.
Each of the following n lines contains two integers. The i-th (1 β€ i β€ n) line contains space-separated integers ai, bi (1 β€ ai, bi β€ 1000) β the speeds which the participant number i chose.
Output
Print the final results' table: n lines, each line should contain the number of the corresponding dwarf and the final maximum height of his mushroom with exactly two digits after the decimal point. The answer will be considered correct if it is absolutely accurate.
Examples
Input
2 3 3 50
2 4
4 2
Output
1 15.00
2 15.00
Input
4 1 1 1
544 397
280 101
280 101
693 970
Output
4 1656.07
1 937.03
2 379.99
3 379.99
Note
* First example: for each contestant it is optimal to use firstly speed 2 and afterwards speed 4, because 2Β·3Β·0.5 + 4Β·3 > 4Β·3Β·0.5 + 2Β·3.
Submitted Solution:
```
from decimal import Decimal
n, t1, t2, k = map(int, input().strip().split())
l = []
i = 1
while n != 0:
x, y = map(int, input().strip().split())
p1 = x * t1 - (((x * t1) / 100) * k) + y * t2
p2 = y * t1 - (((y * t1) / 100) * k) + x * t2
g = max(p1, p2)
l.append([i,g])
i += 1
n -= 1
l.sort(key=lambda el: el[1], reverse=True)
for i in range(0, len(l)):
print('%d %.2f' %(l[i][0], l[i][1]))
```
|
instruction
| 0
| 102,344
| 3
| 204,688
|
Yes
|
output
| 1
| 102,344
| 3
| 204,689
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch.
Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts t1 seconds and the second part lasts t2 seconds. The first and the second part are separated by a little break.
After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of vi meters per second. After t1 seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by k percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of ui meters per second. After a t2 seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary.
Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds ai and bi, then there are two strategies: he either uses speed ai before the break and speed bi after it, or vice versa.
Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results.
The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).
Input
The first input line contains four integer numbers n, t1, t2, k (1 β€ n, t1, t2 β€ 1000; 1 β€ k β€ 100) β the number of participants, the time before the break, the time after the break and the percentage, by which the mushroom growth drops during the break, correspondingly.
Each of the following n lines contains two integers. The i-th (1 β€ i β€ n) line contains space-separated integers ai, bi (1 β€ ai, bi β€ 1000) β the speeds which the participant number i chose.
Output
Print the final results' table: n lines, each line should contain the number of the corresponding dwarf and the final maximum height of his mushroom with exactly two digits after the decimal point. The answer will be considered correct if it is absolutely accurate.
Examples
Input
2 3 3 50
2 4
4 2
Output
1 15.00
2 15.00
Input
4 1 1 1
544 397
280 101
280 101
693 970
Output
4 1656.07
1 937.03
2 379.99
3 379.99
Note
* First example: for each contestant it is optimal to use firstly speed 2 and afterwards speed 4, because 2Β·3Β·0.5 + 4Β·3 > 4Β·3Β·0.5 + 2Β·3.
Submitted Solution:
```
import sys
def input(): return sys.stdin.readline().strip()
n, t1, t2, k = map(int, input().split())
speed = []
for i in range(n):
speed.append([int(i) for i in input().split()])
h = []
for i in range(n):
h.append([(t1*min(speed[i]))*(1-k/100)+t2*max(speed[i]), i+1])
h.sort(reverse=True)
i = 0
while i < n-1:
j = i+1
ind = [h[i][1]]
while j < n and h[i][0] == h[j][0]:
ind.append(h[j][1])
j += 1
ind.sort()
for k in range(i, j):
h[k][1] = ind[k-i]
i = j
for i in range(n):
print(h[i][1], "%.2f"%h[i][0])
```
|
instruction
| 0
| 102,345
| 3
| 204,690
|
No
|
output
| 1
| 102,345
| 3
| 204,691
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch.
Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts t1 seconds and the second part lasts t2 seconds. The first and the second part are separated by a little break.
After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of vi meters per second. After t1 seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by k percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of ui meters per second. After a t2 seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary.
Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds ai and bi, then there are two strategies: he either uses speed ai before the break and speed bi after it, or vice versa.
Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results.
The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).
Input
The first input line contains four integer numbers n, t1, t2, k (1 β€ n, t1, t2 β€ 1000; 1 β€ k β€ 100) β the number of participants, the time before the break, the time after the break and the percentage, by which the mushroom growth drops during the break, correspondingly.
Each of the following n lines contains two integers. The i-th (1 β€ i β€ n) line contains space-separated integers ai, bi (1 β€ ai, bi β€ 1000) β the speeds which the participant number i chose.
Output
Print the final results' table: n lines, each line should contain the number of the corresponding dwarf and the final maximum height of his mushroom with exactly two digits after the decimal point. The answer will be considered correct if it is absolutely accurate.
Examples
Input
2 3 3 50
2 4
4 2
Output
1 15.00
2 15.00
Input
4 1 1 1
544 397
280 101
280 101
693 970
Output
4 1656.07
1 937.03
2 379.99
3 379.99
Note
* First example: for each contestant it is optimal to use firstly speed 2 and afterwards speed 4, because 2Β·3Β·0.5 + 4Β·3 > 4Β·3Β·0.5 + 2Β·3.
Submitted Solution:
```
from operator import itemgetter
n, t1, t2, k = [int(s) for s in input().split()]
a = []
b = []
for _ in range(n):
x, y = [int(s) for s in input().split()]
a.append(x)
b.append(y)
t_min = t1 if t1 * (100 - k) < 100 * t2 else t2
t_max = t1 + t2 - t_min
h = []
for i in range(n):
h.append((i, t_min * min(a[i], b[i]) * (100 - k) + 100 * t_max * max(a[i], b[i])))
h.sort(key=itemgetter(0), reverse=True)
h.sort(key=itemgetter(1))
for idx, height in reversed(h):
print(idx+1, "%.2f" % (height/100))
```
|
instruction
| 0
| 102,346
| 3
| 204,692
|
No
|
output
| 1
| 102,346
| 3
| 204,693
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch.
Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts t1 seconds and the second part lasts t2 seconds. The first and the second part are separated by a little break.
After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of vi meters per second. After t1 seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by k percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of ui meters per second. After a t2 seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary.
Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds ai and bi, then there are two strategies: he either uses speed ai before the break and speed bi after it, or vice versa.
Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results.
The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).
Input
The first input line contains four integer numbers n, t1, t2, k (1 β€ n, t1, t2 β€ 1000; 1 β€ k β€ 100) β the number of participants, the time before the break, the time after the break and the percentage, by which the mushroom growth drops during the break, correspondingly.
Each of the following n lines contains two integers. The i-th (1 β€ i β€ n) line contains space-separated integers ai, bi (1 β€ ai, bi β€ 1000) β the speeds which the participant number i chose.
Output
Print the final results' table: n lines, each line should contain the number of the corresponding dwarf and the final maximum height of his mushroom with exactly two digits after the decimal point. The answer will be considered correct if it is absolutely accurate.
Examples
Input
2 3 3 50
2 4
4 2
Output
1 15.00
2 15.00
Input
4 1 1 1
544 397
280 101
280 101
693 970
Output
4 1656.07
1 937.03
2 379.99
3 379.99
Note
* First example: for each contestant it is optimal to use firstly speed 2 and afterwards speed 4, because 2Β·3Β·0.5 + 4Β·3 > 4Β·3Β·0.5 + 2Β·3.
Submitted Solution:
```
n,t1,t2,k=map(int,input().split())
arr=[]
for i in range(n):
curr=list(map(int,input().split()))
curr.sort()
a=curr[0]
b=curr[1]
arr.append([a,b])
ans = []
y=1
for i in arr:
a=i[0]
b=i[1]
curr= (a*(t1-(t1*(k/100)))+(b*t2))
x= "{:.2f}".format(curr)
ans.append([x,y])
y+=1
ans.sort(reverse=True,key= lambda arr:float(arr[0]))
for i in ans:
print (i[1] ,i[0])
```
|
instruction
| 0
| 102,347
| 3
| 204,694
|
No
|
output
| 1
| 102,347
| 3
| 204,695
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch.
Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts t1 seconds and the second part lasts t2 seconds. The first and the second part are separated by a little break.
After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of vi meters per second. After t1 seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by k percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of ui meters per second. After a t2 seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary.
Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds ai and bi, then there are two strategies: he either uses speed ai before the break and speed bi after it, or vice versa.
Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results.
The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).
Input
The first input line contains four integer numbers n, t1, t2, k (1 β€ n, t1, t2 β€ 1000; 1 β€ k β€ 100) β the number of participants, the time before the break, the time after the break and the percentage, by which the mushroom growth drops during the break, correspondingly.
Each of the following n lines contains two integers. The i-th (1 β€ i β€ n) line contains space-separated integers ai, bi (1 β€ ai, bi β€ 1000) β the speeds which the participant number i chose.
Output
Print the final results' table: n lines, each line should contain the number of the corresponding dwarf and the final maximum height of his mushroom with exactly two digits after the decimal point. The answer will be considered correct if it is absolutely accurate.
Examples
Input
2 3 3 50
2 4
4 2
Output
1 15.00
2 15.00
Input
4 1 1 1
544 397
280 101
280 101
693 970
Output
4 1656.07
1 937.03
2 379.99
3 379.99
Note
* First example: for each contestant it is optimal to use firstly speed 2 and afterwards speed 4, because 2Β·3Β·0.5 + 4Β·3 > 4Β·3Β·0.5 + 2Β·3.
Submitted Solution:
```
n, t1, t2, k = map(int, input().split())
t1 *= (100 - k) / 100
p = [map(int, input().split()) for i in range(n)]
if t1 < t2: l = [(t1 * a + t2 * b if a < b else t1 * b + t2 * a, - i) for i, (a, b) in enumerate(p, 1)]
else: l = [(t1 * a + t2 * b if a < b else t1 * b + t2 * a, - i) for i, (a, b) in enumerate(p, 1)]
l.sort(reverse = True)
print('\n'.join(str(- k) + ' ' + str(int(r)) + '.' + str(int(100 * (1 + r)) % 100) for r, k in l))
```
|
instruction
| 0
| 102,348
| 3
| 204,696
|
No
|
output
| 1
| 102,348
| 3
| 204,697
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 β€ |s| β€ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
Submitted Solution:
```
s=input()
z=s.find('^')
a=s[:z]
b=s[z+1:]
x='123456789'
s1=0
s2=0
if set(a)==set(b) and set(a)=={'='}:
print("balance")
else:
for i in range(len(a)):
if a[i] in x:
s1+=int(a[i])*(len(a)-i)
for j in range(len(b)):
if b[j] in x:
s2+=int(b[j])*(j+1)
if s1==s2:
print("balance")
elif s1>s2:
print("left")
else:
print("right")
```
|
instruction
| 0
| 102,410
| 3
| 204,820
|
Yes
|
output
| 1
| 102,410
| 3
| 204,821
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 β€ |s| β€ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
Submitted Solution:
```
s = str(input())
l = s[:s.find("^")]
r = s[s.find("^")+1:]
r = r[::-1]
lw = 0
rw = 0
for i in range(len(l)):
if l[i] != "=":
lw+=int(l[i])*len(l[i:])
for i in range(len(r)):
if r[i] != "=":
rw+=int(r[i])*len(r[i:])
if rw>lw: print("right")
elif rw<lw: print("left")
else: print("balance")
```
|
instruction
| 0
| 102,411
| 3
| 204,822
|
Yes
|
output
| 1
| 102,411
| 3
| 204,823
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 β€ |s| β€ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
Submitted Solution:
```
s = str(input())
for cont in range(0,len(s)):
if s[cont] == '^':
pos = cont
break
left = 0
right = 0
for d in range(0, pos):
if s[d].isdigit():
left += int(s[d])*(pos-d)
for d in range(pos+1,len(s)):
if s[d].isdigit():
right += int(s[d])*(d-pos)
if left == right:
print('balance')
elif right> left:
print('right')
else:
print('left')
```
|
instruction
| 0
| 102,412
| 3
| 204,824
|
Yes
|
output
| 1
| 102,412
| 3
| 204,825
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 β€ |s| β€ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
Submitted Solution:
```
# Made By Mostafa_Khaled
bot = True
l = input()
p = l.index('^')
b = sum((i - p) * int(x) for i, x in enumerate(l) if x.isdigit())
if b != 0:
b //= abs(b)
print(['left', 'balance', 'right'][b + 1])
# Made By Mostafa_Khaled
```
|
instruction
| 0
| 102,413
| 3
| 204,826
|
Yes
|
output
| 1
| 102,413
| 3
| 204,827
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 β€ |s| β€ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
Submitted Solution:
```
s = input()
sm = 0
for i in range(len(s)):
if s[i] == '^':
ind = i
break
if s[i] != '=':
sm += int(s[i])
for i in range(ind + 1, len(s)):
if s[i] != '=':
sm -= int(s[i])
if sm == 0: print("balance")
elif sm > 0: print("left")
else: print("right")
```
|
instruction
| 0
| 102,414
| 3
| 204,828
|
No
|
output
| 1
| 102,414
| 3
| 204,829
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 β€ |s| β€ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
Submitted Solution:
```
from sys import stdout, stdin, setrecursionlimit
from io import BytesIO, IOBase
from collections import *
from itertools import *
from random import *
from bisect import *
from string import *
from queue import *
from heapq import *
from math import *
from re import *
from os import *
####################################---fast-input-output----#########################################
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = read(self._fd, max(fstat(self._fd).st_size, 8192))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = read(self._fd, max(fstat(self._fd).st_size, 8192))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
stdin, stdout = IOWrapper(stdin), IOWrapper(stdout)
graph, mod, szzz = {}, 10**9 + 7, lambda: sorted(zzz())
def getInt(): return int(input())
def listStr(): return list(input())
def getStrs(): return input().split()
def isInt(s): return '0' <= s[0] <= '9'
def input(): return stdin.readline().strip()
def zzz(): return [int(i) for i in input().split()]
def output(answer, end='\n'): stdout.write(str(answer) + end)
def lcd(xnum1, xnum2): return (xnum1 * xnum2 // gcd(xnum1, xnum2))
dx = [-1, 1, 0, 0, 1, -1, 1, -1]
dy = [0, 0, 1, -1, 1, -1, -1, 1]
daysInMounth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
#################################################---Some Rule For Me To Follow---#################################
"""
--instants of Reading problem continuously try to understand them.
--If you Know some-one , Then you probably don't know him !
--Try & again try
"""
##################################################---START-CODING---###############################################
l,r = input().split('^')
l=l[::-1]
left=0
right=0
for i in range(len(l)):
if isInt(l[i]):
left+=(i*1)*int(l[i])
for i in range(len(r)):
if isInt(r[i]):
right+=(i+1)*int(r[i])
if right>left:
print('right')
elif right<left:
print('left')
else:
print('balance')
# s=input()
# r=s.index("^")
# sum=0
# for i in range(len(s)):
# if s[i]!="=" and s[i]!="^":
# sum+=int(s[i])*(i-r)
# if sum<0:
# print("left")
# elif sum>0:
# print("right")
# else:
# print("balance")
#
```
|
instruction
| 0
| 102,415
| 3
| 204,830
|
No
|
output
| 1
| 102,415
| 3
| 204,831
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 β€ |s| β€ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
Submitted Solution:
```
s = input()
left = 0
right = 0
ind = s.find('^')
for i in range(ind):
#print("right: ",right," ele: ",i)
if(s[i]=='='):
left-=1
else:
left+=int(s[i])
for i in range(ind+1,len(s)):
if(s[i]=='='):
right-=1
else:
right+=int(s[i])
#print(left,right)
if(right<0):
right = 0
if(left<0):
left = 0
if(left==right):
print("balance")
elif(left>right):
print("left")
else:
print("right")
```
|
instruction
| 0
| 102,416
| 3
| 204,832
|
No
|
output
| 1
| 102,416
| 3
| 204,833
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 β€ |s| β€ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
Submitted Solution:
```
s = input()
m = s.find('^')
res = [(int(x)*s.find(x)+1)*(m-s.find(x)+1) for x in s if x.isdigit()]
if sum(res) == 0: print('balance')
elif sum(res) < 0: print('left')
else: print('right')
```
|
instruction
| 0
| 102,417
| 3
| 204,834
|
No
|
output
| 1
| 102,417
| 3
| 204,835
|
Provide tags and a correct Python 3 solution for this coding contest problem.
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.
Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 β€ fi β€ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.
It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
Input
The first line contains a positive integer n (1 β€ n β€ 2Β·105) β the number of fragments.
The second line contains n different integers fi (1 β€ fi β€ n) β the number of the fragment written in the i-th sector.
Output
Print the only integer β the number of time units needed to read the file.
Examples
Input
3
3 1 2
Output
3
Input
5
1 3 5 4 2
Output
10
Note
In the second example the head moves in the following way:
* 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units
* 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units
* 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units
* 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units
So the answer to the second example is 4 + 3 + 2 + 1 = 10.
|
instruction
| 0
| 102,490
| 3
| 204,980
|
Tags: implementation, math
Correct Solution:
```
from collections import *
from itertools import *
from random import *
from bisect import *
from string import *
from queue import *
from heapq import *
from math import *
from re import *
from sys import *
def fast(): return stdin.readline().strip()
def zzz(): return [int(i) for i in fast().split()]
z, zz = input, lambda: list(map(int, z().split()))
szz, graph, mod, szzz = lambda: sorted(
zz()), {}, 10**9 + 7, lambda: sorted(zzz())
def lcd(xnum1, xnum2): return (xnum1 * xnum2 // gcd(xnum1, xnum2))
def output(answer): stdout.write(str(answer))
dx = [-1, 1, 0, 0, 1, -1, 1, -1]
dy = [0, 0, 1, -1, 1, -1, -1, 1]
###########################---Test-Case---#################################
"""
If you Know me , Then you probably don't know me !
"""
###########################---START-CODING---##############################
# n, m = zzz()
# for _ in range(m):
# x, y, w = zzz()
# try:
# graph[x]
# except:
# graph[x] = []
# try:
# graph[y]
# except:
# graph[y] = []
# graph[x].append((y, w))
# graph[y].append((x, w))
# path = [0] * (n + 1)
# dis = [float('inf')] * (n + 1)
# hp = [(0, 1)]
# while hp:
# try:
# dcur, cur = heappop(hp)
# print(hp)
# for d, w in graph[cur]:
# if dcur + w < dis[d]:
# dis[d] = dcur + w
# path[d] = cur
# heappush(hp, (dis[d], d))
# print(hp)
# except:
# exit(print(-1))
# l = [n]
# x = n
# print(path)
# print(dis)
# if path[n] > 0:
# while x != 1:
# x = path[x]
# l.append(x)
# print(*l[::-1])
# else:
# print(-1)
# #
# root = {}
# def build(string, index):
# node = root
# for letter in string:
# if letter not in node:
# node[letter] = {}
# node = node[letter]
# node['index'] = index
# def contains(string):
# node = root
# for letter in string:
# if letter not in node:
# return False
# node = node[letter]
# return node['index']
# n, l = zzz()
# s = fast() * 2
# q = int(fast())
# for i in range(q):
# build(input(), i + 1)
# pos = False
# ans = [0] * n
# for i in range(l):
# pos = True
# found = [False] * (q + 1)
# for j in range(n):
# loc = contains(s[i + j * l: i + (j + 1) * l])
# if not loc or found[loc]:
# pos = False
# break
# found[loc] = True
# ans[j] = loc
# if pos:
# break
# if not pos:
# print("NO")
# else:
# print("YES")
# # print(' '.join([str(x) for x in ans]))
# for i in ans:
# print(i)
# num = int(z())
# for _ in range(num):
# a, b = zzz()
# arr = zzz()
# for i in arr:
# while 0 < i < b * 10 and i % b:
# i -= 10
# if i < b:
# print('NO')
# else:
# print('YES', i)
# num = int(z())
# def has(x, d):
# return str(x).count((str(d))) > 0
# for _ in range(num):
# arr = zzz()
# dp = [0] * (1005)
# dp[0] = 1
# for i in range(1, 1002):
# if has(i, d):
# for j in range(0, 1003 - i):
# if dp[j] > 0:
# dp[i + j] = 1
# for i in arr:
# if i > 1000 or dp[x]:
# print('YES')
# else:
# print('NO')
# n, m = zzz()
# arr = list(fast() + '***')
# k, res = 0, []
# for i in range(n):
# if arr[i] == arr[i + 1] == '.':
# k += 1
# for i in range(m):
# x, y = fast().split(' ')
# x = int(x) - 1
# if arr[x] == '.':
# if y != '.':
# if x > 0 and arr[x - 1] == '.':
# k -= 1
# if x < n - 1 and arr[x + 1] == '.':
# k -= 1
# else:
# if y == '.':
# if x > 0 and arr[x - 1] == '.':
# k += 1
# if x < n - 1 and arr[x + 1] == '.':
# k += 1
# print(k)
# arr[x] = y
n = int(fast())
arr = zzz()
lst = []
for i in range(n):
lst.append((arr[i], i))
lst = sorted(lst)
ans = 0
for i in range(n - 1):
ans += abs(lst[i][1] - lst[i + 1][1])
print(ans)
```
|
output
| 1
| 102,490
| 3
| 204,981
|
Provide tags and a correct Python 3 solution for this coding contest problem.
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.
Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 β€ fi β€ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.
It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
Input
The first line contains a positive integer n (1 β€ n β€ 2Β·105) β the number of fragments.
The second line contains n different integers fi (1 β€ fi β€ n) β the number of the fragment written in the i-th sector.
Output
Print the only integer β the number of time units needed to read the file.
Examples
Input
3
3 1 2
Output
3
Input
5
1 3 5 4 2
Output
10
Note
In the second example the head moves in the following way:
* 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units
* 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units
* 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units
* 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units
So the answer to the second example is 4 + 3 + 2 + 1 = 10.
|
instruction
| 0
| 102,491
| 3
| 204,982
|
Tags: implementation, math
Correct Solution:
```
n=int(input())
a=[];v=[];o=0
a=list(map(int,input().split()))
for i in range(0,n+1):
v.append(0)
for i in range(n):
v[a[i]]=i+1
for i in range(1,n):
o+=abs(v[i]-v[i+1])
print(o)
```
|
output
| 1
| 102,491
| 3
| 204,983
|
Provide tags and a correct Python 3 solution for this coding contest problem.
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.
Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 β€ fi β€ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.
It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
Input
The first line contains a positive integer n (1 β€ n β€ 2Β·105) β the number of fragments.
The second line contains n different integers fi (1 β€ fi β€ n) β the number of the fragment written in the i-th sector.
Output
Print the only integer β the number of time units needed to read the file.
Examples
Input
3
3 1 2
Output
3
Input
5
1 3 5 4 2
Output
10
Note
In the second example the head moves in the following way:
* 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units
* 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units
* 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units
* 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units
So the answer to the second example is 4 + 3 + 2 + 1 = 10.
|
instruction
| 0
| 102,492
| 3
| 204,984
|
Tags: implementation, math
Correct Solution:
```
n=int(input())
k=0
a=list(map(int,input().split()))
b=[0]*1000000
for i in range(n):
b[a[i]-1]=i
for i in range(n-1):
k+=abs(b[i]-b[i+1])
print(k)
```
|
output
| 1
| 102,492
| 3
| 204,985
|
Provide tags and a correct Python 3 solution for this coding contest problem.
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.
Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 β€ fi β€ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.
It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
Input
The first line contains a positive integer n (1 β€ n β€ 2Β·105) β the number of fragments.
The second line contains n different integers fi (1 β€ fi β€ n) β the number of the fragment written in the i-th sector.
Output
Print the only integer β the number of time units needed to read the file.
Examples
Input
3
3 1 2
Output
3
Input
5
1 3 5 4 2
Output
10
Note
In the second example the head moves in the following way:
* 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units
* 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units
* 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units
* 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units
So the answer to the second example is 4 + 3 + 2 + 1 = 10.
|
instruction
| 0
| 102,493
| 3
| 204,986
|
Tags: implementation, math
Correct Solution:
```
n= int(input())
arr= list(map(int,input().split()))
map={}
for i in range(n):
map[arr[i]]=i+1
ans=0
for i in range(1,n):
ans+=abs(map[i]-map[i+1])
print (ans)
```
|
output
| 1
| 102,493
| 3
| 204,987
|
Provide tags and a correct Python 3 solution for this coding contest problem.
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.
Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 β€ fi β€ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.
It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
Input
The first line contains a positive integer n (1 β€ n β€ 2Β·105) β the number of fragments.
The second line contains n different integers fi (1 β€ fi β€ n) β the number of the fragment written in the i-th sector.
Output
Print the only integer β the number of time units needed to read the file.
Examples
Input
3
3 1 2
Output
3
Input
5
1 3 5 4 2
Output
10
Note
In the second example the head moves in the following way:
* 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units
* 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units
* 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units
* 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units
So the answer to the second example is 4 + 3 + 2 + 1 = 10.
|
instruction
| 0
| 102,494
| 3
| 204,988
|
Tags: implementation, math
Correct Solution:
```
R = lambda : map(int, input().split())
n = int(input())
v = list(R())
d = {}
for i in range(n):
d[v[i]] = i
c = 0
for i in range(2,n+1):
c += abs(d[i]-d[i-1])
print(c)
```
|
output
| 1
| 102,494
| 3
| 204,989
|
Provide tags and a correct Python 3 solution for this coding contest problem.
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.
Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 β€ fi β€ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.
It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
Input
The first line contains a positive integer n (1 β€ n β€ 2Β·105) β the number of fragments.
The second line contains n different integers fi (1 β€ fi β€ n) β the number of the fragment written in the i-th sector.
Output
Print the only integer β the number of time units needed to read the file.
Examples
Input
3
3 1 2
Output
3
Input
5
1 3 5 4 2
Output
10
Note
In the second example the head moves in the following way:
* 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units
* 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units
* 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units
* 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units
So the answer to the second example is 4 + 3 + 2 + 1 = 10.
|
instruction
| 0
| 102,495
| 3
| 204,990
|
Tags: implementation, math
Correct Solution:
```
n = int(input())
L = list(map(int,input().split()))
A = []
for i in range(n):
A.append([L[i],i])
A.sort()
cnt = 0
for i in range(1,n):
cnt += abs(A[i][1] - A[i-1][1])
print(cnt)
```
|
output
| 1
| 102,495
| 3
| 204,991
|
Provide tags and a correct Python 3 solution for this coding contest problem.
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.
Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 β€ fi β€ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.
It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
Input
The first line contains a positive integer n (1 β€ n β€ 2Β·105) β the number of fragments.
The second line contains n different integers fi (1 β€ fi β€ n) β the number of the fragment written in the i-th sector.
Output
Print the only integer β the number of time units needed to read the file.
Examples
Input
3
3 1 2
Output
3
Input
5
1 3 5 4 2
Output
10
Note
In the second example the head moves in the following way:
* 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units
* 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units
* 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units
* 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units
So the answer to the second example is 4 + 3 + 2 + 1 = 10.
|
instruction
| 0
| 102,496
| 3
| 204,992
|
Tags: implementation, math
Correct Solution:
```
def hdd(n, lst):
res, answer = [0] * n, 0
for i in range(n):
res[lst[i] - 1] = i
for i in range(n - 1):
answer += abs(res[i] - res[i + 1])
return answer
m = int(input())
a = [int(j) for j in input().split()]
print(hdd(m, a))
```
|
output
| 1
| 102,496
| 3
| 204,993
|
Provide tags and a correct Python 3 solution for this coding contest problem.
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.
Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 β€ fi β€ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.
It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
Input
The first line contains a positive integer n (1 β€ n β€ 2Β·105) β the number of fragments.
The second line contains n different integers fi (1 β€ fi β€ n) β the number of the fragment written in the i-th sector.
Output
Print the only integer β the number of time units needed to read the file.
Examples
Input
3
3 1 2
Output
3
Input
5
1 3 5 4 2
Output
10
Note
In the second example the head moves in the following way:
* 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units
* 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units
* 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units
* 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units
So the answer to the second example is 4 + 3 + 2 + 1 = 10.
|
instruction
| 0
| 102,497
| 3
| 204,994
|
Tags: implementation, math
Correct Solution:
```
n=int(input())
ls=list(map(int,input().split()))
arr=[0]*n
for x in range(n):
arr[ls[x]-1]=x
su=0
for x in range(1,n):
su+=abs(arr[x]-arr[x-1])
print(su)
```
|
output
| 1
| 102,497
| 3
| 204,995
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.
Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 β€ fi β€ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.
It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
Input
The first line contains a positive integer n (1 β€ n β€ 2Β·105) β the number of fragments.
The second line contains n different integers fi (1 β€ fi β€ n) β the number of the fragment written in the i-th sector.
Output
Print the only integer β the number of time units needed to read the file.
Examples
Input
3
3 1 2
Output
3
Input
5
1 3 5 4 2
Output
10
Note
In the second example the head moves in the following way:
* 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units
* 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units
* 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units
* 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units
So the answer to the second example is 4 + 3 + 2 + 1 = 10.
Submitted Solution:
```
n = int(input())
pos = [0] * (n+1)
for idx, num in enumerate(map(int, input().split())):
pos[num] = idx
count = 0
for a, b in zip(pos[1:], pos[2:]):
count += abs(a-b)
print(count)
```
|
instruction
| 0
| 102,498
| 3
| 204,996
|
Yes
|
output
| 1
| 102,498
| 3
| 204,997
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.
Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 β€ fi β€ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.
It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
Input
The first line contains a positive integer n (1 β€ n β€ 2Β·105) β the number of fragments.
The second line contains n different integers fi (1 β€ fi β€ n) β the number of the fragment written in the i-th sector.
Output
Print the only integer β the number of time units needed to read the file.
Examples
Input
3
3 1 2
Output
3
Input
5
1 3 5 4 2
Output
10
Note
In the second example the head moves in the following way:
* 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units
* 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units
* 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units
* 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units
So the answer to the second example is 4 + 3 + 2 + 1 = 10.
Submitted Solution:
```
n=int(input());a=list(map(int,input().split()));p=0
i=0;x={}
while i<n:x[a[i]]=i;i+=1
while n>1:p=p+abs(x[n]-x[n-1]);n-=1
print(p)
```
|
instruction
| 0
| 102,499
| 3
| 204,998
|
Yes
|
output
| 1
| 102,499
| 3
| 204,999
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.
Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 β€ fi β€ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.
It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
Input
The first line contains a positive integer n (1 β€ n β€ 2Β·105) β the number of fragments.
The second line contains n different integers fi (1 β€ fi β€ n) β the number of the fragment written in the i-th sector.
Output
Print the only integer β the number of time units needed to read the file.
Examples
Input
3
3 1 2
Output
3
Input
5
1 3 5 4 2
Output
10
Note
In the second example the head moves in the following way:
* 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units
* 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units
* 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units
* 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units
So the answer to the second example is 4 + 3 + 2 + 1 = 10.
Submitted Solution:
```
fragment_count = int(input())
line = input()
fragments = []
fragments = [int(i) for i in line.split()]
places = [0 for i in range(fragment_count)]
for index, frag in enumerate(fragments):
places[frag - 1] = index
total_sum = 0
index = 0
for i in places:
if index == len(places) - 1:
break
total_sum = total_sum + abs(i - places[index + 1])
index = index + 1
print(total_sum)
```
|
instruction
| 0
| 102,500
| 3
| 205,000
|
Yes
|
output
| 1
| 102,500
| 3
| 205,001
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.
Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 β€ fi β€ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.
It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
Input
The first line contains a positive integer n (1 β€ n β€ 2Β·105) β the number of fragments.
The second line contains n different integers fi (1 β€ fi β€ n) β the number of the fragment written in the i-th sector.
Output
Print the only integer β the number of time units needed to read the file.
Examples
Input
3
3 1 2
Output
3
Input
5
1 3 5 4 2
Output
10
Note
In the second example the head moves in the following way:
* 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units
* 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units
* 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units
* 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units
So the answer to the second example is 4 + 3 + 2 + 1 = 10.
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
b = [0] * (n + 1)
for i, x in enumerate(a):
b[x] = i
print(sum([abs(b[i] - b[i - 1]) for i in range(2, n + 1)]))
```
|
instruction
| 0
| 102,501
| 3
| 205,002
|
Yes
|
output
| 1
| 102,501
| 3
| 205,003
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.
Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 β€ fi β€ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.
It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
Input
The first line contains a positive integer n (1 β€ n β€ 2Β·105) β the number of fragments.
The second line contains n different integers fi (1 β€ fi β€ n) β the number of the fragment written in the i-th sector.
Output
Print the only integer β the number of time units needed to read the file.
Examples
Input
3
3 1 2
Output
3
Input
5
1 3 5 4 2
Output
10
Note
In the second example the head moves in the following way:
* 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units
* 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units
* 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units
* 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units
So the answer to the second example is 4 + 3 + 2 + 1 = 10.
Submitted Solution:
```
n=int(input())
a=list(map(int,input().split()))
ans=0
c=0
for i in range(2,n+1):
for j in range(n):
if i==a[j]:
ans+=abs(c-j)
c=j
break
print(ans)
```
|
instruction
| 0
| 102,502
| 3
| 205,004
|
No
|
output
| 1
| 102,502
| 3
| 205,005
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.
Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 β€ fi β€ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.
It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
Input
The first line contains a positive integer n (1 β€ n β€ 2Β·105) β the number of fragments.
The second line contains n different integers fi (1 β€ fi β€ n) β the number of the fragment written in the i-th sector.
Output
Print the only integer β the number of time units needed to read the file.
Examples
Input
3
3 1 2
Output
3
Input
5
1 3 5 4 2
Output
10
Note
In the second example the head moves in the following way:
* 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units
* 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units
* 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units
* 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units
So the answer to the second example is 4 + 3 + 2 + 1 = 10.
Submitted Solution:
```
n = int(input())
l = [int(i) for i in input().split(" ")]
new = [None] * n
print(new)
for i in range(n):
new[l[i]-1] = i
print(new)
s = 0
x = new[0]
for i in range(1, n):
s += abs(x - new[i])
x = new[i]
print(s)
```
|
instruction
| 0
| 102,503
| 3
| 205,006
|
No
|
output
| 1
| 102,503
| 3
| 205,007
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.
Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 β€ fi β€ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.
It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
Input
The first line contains a positive integer n (1 β€ n β€ 2Β·105) β the number of fragments.
The second line contains n different integers fi (1 β€ fi β€ n) β the number of the fragment written in the i-th sector.
Output
Print the only integer β the number of time units needed to read the file.
Examples
Input
3
3 1 2
Output
3
Input
5
1 3 5 4 2
Output
10
Note
In the second example the head moves in the following way:
* 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units
* 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units
* 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units
* 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units
So the answer to the second example is 4 + 3 + 2 + 1 = 10.
Submitted Solution:
```
n = input()
sectors = [int(x) for x in input().split()]
def my_arg_sort(list_of_sectors):
new_list = [0]*len(list_of_sectors)
for i, elem in enumerate(list_of_sectors):
new_list[elem-1] = i
return new_list
sorted = my_arg_sort(sectors)
print(sorted)
ans = 0
actual_position = sorted[0]
for k in sorted:
print('k = {}, act_pos = {}'.format(k, actual_position))
ans += abs(k - actual_position)
actual_position = k
print(ans)
```
|
instruction
| 0
| 102,504
| 3
| 205,008
|
No
|
output
| 1
| 102,504
| 3
| 205,009
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.
Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 β€ fi β€ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.
It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
Input
The first line contains a positive integer n (1 β€ n β€ 2Β·105) β the number of fragments.
The second line contains n different integers fi (1 β€ fi β€ n) β the number of the fragment written in the i-th sector.
Output
Print the only integer β the number of time units needed to read the file.
Examples
Input
3
3 1 2
Output
3
Input
5
1 3 5 4 2
Output
10
Note
In the second example the head moves in the following way:
* 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units
* 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units
* 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units
* 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units
So the answer to the second example is 4 + 3 + 2 + 1 = 10.
Submitted Solution:
```
n=int(input())
m=list(map(int,input().split()))
k=0
for i in range(0,len(m)):
k=k+m[i]
print(k-n)
```
|
instruction
| 0
| 102,505
| 3
| 205,010
|
No
|
output
| 1
| 102,505
| 3
| 205,011
|
Provide tags and a correct Python 3 solution for this coding contest problem.
After a successful field test, Heidi is considering deploying a trap along some Corridor, possibly not the first one. She wants to avoid meeting the Daleks inside the Time Vortex, so for abundance of caution she considers placing the traps only along those Corridors that are not going to be used according to the current Daleks' plan β which is to use a minimum spanning tree of Corridors. Heidi knows that all energy requirements for different Corridors are now different, and that the Daleks have a single unique plan which they are intending to use.
Your task is to calculate the number E_{max}(c), which is defined in the same way as in the easy version β i.e., the largest e β€ 10^9 such that if we changed the energy of corridor c to e, the Daleks might use it β but now for every corridor that Heidi considers.
Input
The first line: number n of destinations, number m of Time Corridors (2 β€ n β€ 10^5, n - 1 β€ m β€ 10^6). The next m lines: destinations a, b and energy e (1 β€ a, b β€ n, a β b, 0 β€ e β€ 10^9).
No pair \\{a, b\} will repeat. The graph is guaranteed to be connected. All energy requirements e are distinct.
Output
Output m-(n-1) lines, each containing one integer: E_{max}(c_i) for the i-th Corridor c_i from the input that is not part of the current Daleks' plan (minimum spanning tree).
Example
Input
3 3
1 2 8
2 3 3
3 1 4
Output
4
Note
If m = n-1, then you need not output anything.
|
instruction
| 0
| 102,972
| 3
| 205,944
|
Tags: dfs and similar, graphs, shortest paths, trees
Correct Solution:
```
def naiveSolve():
return
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
def find(self, a): #return parent of a. a and b are in same set if they have same parent
acopy = a
while a != self.parent[a]:
a = self.parent[a]
while acopy != a: #path compression
self.parent[acopy], acopy = a, self.parent[acopy]
return a
def union(self, a, b): #union a and b
self.parent[self.find(b)] = self.find(a)
def main():
n,m=readIntArr()
a=[]
b=[]
c=[]
for _ in range(m):
aa,bb,cc=readIntArr()
a.append(aa); b.append(bb); c.append(cc)
idxes=list(range(m))
idxes.sort(key=lambda i:c[i])
uf=UnionFind(n+1)
inA=[] # in MST
inB=[]
inC=[]
outA=[] # not in MST
outB=[]
outIdxes=[]
for i in range(m):
aa=a[idxes[i]]
bb=b[idxes[i]]
cc=c[idxes[i]]
if uf.find(aa)!=uf.find(bb):
uf.union(aa,bb)
inA.append(aa)
inB.append(bb)
inC.append(cc)
else:
outIdxes.append(idxes[i])
outIdxes.sort()
for i in outIdxes:
outA.append(a[i])
outB.append(b[i])
# find largest edge between each outA and outB
adj=[[] for _ in range(n+1)] # store (edge,cost)
assert len(inA)==n-1
for i in range(n-1):
u,v,c=inA[i],inB[i],inC[i]
adj[u].append((v,c))
adj[v].append((u,c))
@bootstrap
def dfs(node,p,cost):
up[node][0]=p
maxEdge[node][0]=cost
tin[node]=time[0]
time[0]+=1
for v,c in adj[node]:
if v!=p:
yield dfs(v,node,c)
tout[node]=time[0]
time[0]+=1
yield None
time=[0]
tin=[-1]*(n+1)
tout=[-1]*(n+1)
# binary lifting to find LCA
maxPow=0
while pow(2,maxPow)<n:
maxPow+=1
maxPow+=1
up=[[-1 for _ in range(maxPow)] for __ in range(n+1)]
maxEdge=[[-inf for _ in range(maxPow)] for __ in range(n+1)]
dfs(1,-1,-inf)
for i in range(1,maxPow):
for u in range(2,n+1):
if up[u][i-1]==-1 or up[up[u][i-1]][i-1]==-1: # reached beyond root
continue
up[u][i]=up[up[u][i-1]][i-1]
maxEdge[u][i]=max(maxEdge[u][i-1],maxEdge[up[u][i-1]][i-1])
def isAncestor(u,v): # True if u is ancestor of v
return tin[u]<=tin[v] and tout[u]>=tout[v]
def findMaxEdgeValue(u,v):
# traverse u to LCA, then v to LCA
res=0
if not isAncestor(u,v):
u2=u
for i in range(maxPow-1,-1,-1):
if up[u2][i]!=-1 and not isAncestor(up[u2][i],v):
res=max(res,maxEdge[u2][i])
u2=up[u2][i]
# next level up is lca
res=max(res,maxEdge[u2][0])
if not isAncestor(v,u):
v2=v
while not isAncestor(up[v2][0],u): # still have to move up
for i in range(maxPow-1,-1,-1):
if up[v2][i]!=-1 and not isAncestor(up[v2][i],u):
res=max(res,maxEdge[v2][i])
v2=up[v2][i]
# print('v2:{} u:{}'.format(v2,u)) ##
# if v2==1:
# print(isAncestor(v,u)) ##
# break
# next level up is lca
res=max(res,maxEdge[v2][0])
return res
# for i in range(1,4):
# for j in range(1,4):
# if i!=j:
# print('i:{} j:{} anc:{}'.format(i,j,isAncestor(i,j)))
ans=[]
# print(outA,outB)
# for u in range(1,n+1):
# print('u:{} up:{} maxEdge:{}'.format(u,up[u],maxEdge[u])) ##
for i in range(len(outA)):
u,v=outA[i],outB[i]
ans.append(findMaxEdgeValue(u,v))
multiLineArrayPrint(ans)
return
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
# input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
dv=defaultValFactory;da=dimensionArr
if len(da)==1:return [dv() for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
def queryInteractive(r):
print('? {}'.format(r))
sys.stdout.flush()
return readIntArr()
def answerInteractive(adj,n):
print('!')
for u in range(1,n+1):
for v in adj[u]:
if v>u:
print('{} {}'.format(u,v))
sys.stdout.flush()
inf=float('inf')
MOD=10**9+7
# MOD=998244353
from math import gcd,floor,ceil
# from math import floor,ceil # for Python2
for _abc in range(1):
main()
```
|
output
| 1
| 102,972
| 3
| 205,945
|
Provide tags and a correct Python 3 solution for this coding contest problem.
After a successful field test, Heidi is considering deploying a trap along some Corridor, possibly not the first one. She wants to avoid meeting the Daleks inside the Time Vortex, so for abundance of caution she considers placing the traps only along those Corridors that are not going to be used according to the current Daleks' plan β which is to use a minimum spanning tree of Corridors. Heidi knows that all energy requirements for different Corridors are now different, and that the Daleks have a single unique plan which they are intending to use.
Your task is to calculate the number E_{max}(c), which is defined in the same way as in the easy version β i.e., the largest e β€ 10^9 such that if we changed the energy of corridor c to e, the Daleks might use it β but now for every corridor that Heidi considers.
Input
The first line: number n of destinations, number m of Time Corridors (2 β€ n β€ 10^5, n - 1 β€ m β€ 10^6). The next m lines: destinations a, b and energy e (1 β€ a, b β€ n, a β b, 0 β€ e β€ 10^9).
No pair \\{a, b\} will repeat. The graph is guaranteed to be connected. All energy requirements e are distinct.
Output
Output m-(n-1) lines, each containing one integer: E_{max}(c_i) for the i-th Corridor c_i from the input that is not part of the current Daleks' plan (minimum spanning tree).
Example
Input
3 3
1 2 8
2 3 3
3 1 4
Output
4
Note
If m = n-1, then you need not output anything.
|
instruction
| 0
| 102,973
| 3
| 205,946
|
Tags: dfs and similar, graphs, shortest paths, trees
Correct Solution:
```
def naiveSolve():
return
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
def find(self, a): #return parent of a. a and b are in same set if they have same parent
acopy = a
while a != self.parent[a]:
a = self.parent[a]
while acopy != a: #path compression
self.parent[acopy], acopy = a, self.parent[acopy]
return a
def union(self, a, b): #union a and b
self.parent[self.find(b)] = self.find(a)
def main():
n,m=readIntArr()
a=[]
b=[]
c=[]
for _ in range(m):
aa,bb,cc=readIntArr()
a.append(aa); b.append(bb); c.append(cc)
idxes=list(range(m))
idxes.sort(key=lambda i:c[i])
uf=UnionFind(n+1)
inA=[] # in MST
inB=[]
inC=[]
outA=[] # not in MST
outB=[]
outIdxes=[]
for i in range(m):
aa=a[idxes[i]]
bb=b[idxes[i]]
cc=c[idxes[i]]
if uf.find(aa)!=uf.find(bb):
uf.union(aa,bb)
inA.append(aa)
inB.append(bb)
inC.append(cc)
else:
outIdxes.append(idxes[i])
outIdxes.sort()
for i in outIdxes:
outA.append(a[i])
outB.append(b[i])
# find largest edge between each outA and outB
adj=[[] for _ in range(n+1)] # store (edge,cost)
assert len(inA)==n-1
for i in range(n-1):
u,v,c=inA[i],inB[i],inC[i]
adj[u].append((v,c))
adj[v].append((u,c))
@bootstrap
def dfs(node,p,cost):
up[node][0]=p
maxEdge[node][0]=cost
tin[node]=time[0]
time[0]+=1
for v,c in adj[node]:
if v!=p:
yield dfs(v,node,c)
tout[node]=time[0]
time[0]+=1
yield None
time=[0]
tin=[-1]*(n+1)
tout=[-1]*(n+1)
# binary lifting to find LCA
maxPow=0
while pow(2,maxPow)<n:
maxPow+=1
maxPow+=1
up=[[-1 for _ in range(maxPow)] for __ in range(n+1)]
maxEdge=[[-inf for _ in range(maxPow)] for __ in range(n+1)]
dfs(1,-1,-inf)
for i in range(1,maxPow):
for u in range(2,n+1):
if up[u][i-1]==-1 or up[up[u][i-1]][i-1]==-1: # reached beyond root
continue
up[u][i]=up[up[u][i-1]][i-1]
maxEdge[u][i]=max(maxEdge[u][i-1],maxEdge[up[u][i-1]][i-1])
def isAncestor(u,v): # True if u is ancestor of v
return tin[u]<=tin[v] and tout[u]>=tout[v]
def findMaxEdgeValue(u,v):
# traverse u to LCA, then v to LCA
res=0
if not isAncestor(u,v):
u2=u
for i in range(maxPow-1,-1,-1):
if up[u2][i]!=-1 and not isAncestor(up[u2][i],v):
res=max(res,maxEdge[u2][i])
u2=up[u2][i]
res=max(res,maxEdge[u2][0])
if not isAncestor(v,u):
v2=v
for i in range(maxPow-1,-1,-1):
if up[v2][i]!=-1 and not isAncestor(up[v2][i],u):
res=max(res,maxEdge[v2][i])
v2=up[v2][i]
res=max(res,maxEdge[v2][0])
return res
ans=[]
for i in range(len(outA)):
u,v=outA[i],outB[i]
ans.append(findMaxEdgeValue(u,v))
multiLineArrayPrint(ans)
return
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
# input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
dv=defaultValFactory;da=dimensionArr
if len(da)==1:return [dv() for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
def queryInteractive(r):
print('? {}'.format(r))
sys.stdout.flush()
return readIntArr()
def answerInteractive(adj,n):
print('!')
for u in range(1,n+1):
for v in adj[u]:
if v>u:
print('{} {}'.format(u,v))
sys.stdout.flush()
inf=float('inf')
MOD=10**9+7
# MOD=998244353
from math import gcd,floor,ceil
# from math import floor,ceil # for Python2
for _abc in range(1):
main()
```
|
output
| 1
| 102,973
| 3
| 205,947
|
Provide tags and a correct Python 3 solution for this coding contest problem.
After a successful field test, Heidi is considering deploying a trap along some Corridor, possibly not the first one. She wants to avoid meeting the Daleks inside the Time Vortex, so for abundance of caution she considers placing the traps only along those Corridors that are not going to be used according to the current Daleks' plan β which is to use a minimum spanning tree of Corridors. Heidi knows that all energy requirements for different Corridors are now different, and that the Daleks have a single unique plan which they are intending to use.
Your task is to calculate the number E_{max}(c), which is defined in the same way as in the easy version β i.e., the largest e β€ 10^9 such that if we changed the energy of corridor c to e, the Daleks might use it β but now for every corridor that Heidi considers.
Input
The first line: number n of destinations, number m of Time Corridors (2 β€ n β€ 10^5, n - 1 β€ m β€ 10^6). The next m lines: destinations a, b and energy e (1 β€ a, b β€ n, a β b, 0 β€ e β€ 10^9).
No pair \\{a, b\} will repeat. The graph is guaranteed to be connected. All energy requirements e are distinct.
Output
Output m-(n-1) lines, each containing one integer: E_{max}(c_i) for the i-th Corridor c_i from the input that is not part of the current Daleks' plan (minimum spanning tree).
Example
Input
3 3
1 2 8
2 3 3
3 1 4
Output
4
Note
If m = n-1, then you need not output anything.
|
instruction
| 0
| 102,974
| 3
| 205,948
|
Tags: dfs and similar, graphs, shortest paths, trees
Correct Solution:
```
def naiveSolve():
return
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
def find(self, a): #return parent of a. a and b are in same set if they have same parent
acopy = a
while a != self.parent[a]:
a = self.parent[a]
while acopy != a: #path compression
self.parent[acopy], acopy = a, self.parent[acopy]
return a
def union(self, a, b): #union a and b
self.parent[self.find(b)] = self.find(a)
def main():
n,m=readIntArr()
a=[]
b=[]
c=[]
for _ in range(m):
aa,bb,cc=readIntArr()
a.append(aa); b.append(bb); c.append(cc)
idxes=list(range(m))
idxes.sort(key=lambda i:c[i])
uf=UnionFind(n+1)
inA=[] # in MST
inB=[]
inC=[]
outA=[] # not in MST
outB=[]
outIdxes=[]
for i in range(m):
aa=a[idxes[i]]
bb=b[idxes[i]]
cc=c[idxes[i]]
if uf.find(aa)!=uf.find(bb):
uf.union(aa,bb)
inA.append(aa)
inB.append(bb)
inC.append(cc)
else:
outIdxes.append(idxes[i])
outIdxes.sort()
for i in outIdxes:
outA.append(a[i])
outB.append(b[i])
# find largest edge between each outA and outB
adj=[[] for _ in range(n+1)] # store (edge,cost)
assert len(inA)==n-1
for i in range(n-1):
u,v,c=inA[i],inB[i],inC[i]
adj[u].append((v,c))
adj[v].append((u,c))
@bootstrap
def dfs(node,p,cost):
up[node][0]=p
maxEdge[node][0]=cost
tin[node]=time[0]
time[0]+=1
for v,c in adj[node]:
if v!=p:
yield dfs(v,node,c)
tout[node]=time[0]
time[0]+=1
yield None
time=[0]
tin=[-1]*(n+1)
tout=[-1]*(n+1)
# binary lifting to find LCA
maxPow=0
while pow(2,maxPow)<n:
maxPow+=1
maxPow+=1
up=[[-1 for _ in range(maxPow)] for __ in range(n+1)]
maxEdge=[[-inf for _ in range(maxPow)] for __ in range(n+1)]
dfs(1,-1,-inf)
for i in range(1,maxPow):
for u in range(2,n+1):
if up[u][i-1]==-1 or up[up[u][i-1]][i-1]==-1: # reached beyond root
continue
up[u][i]=up[up[u][i-1]][i-1]
maxEdge[u][i]=max(maxEdge[u][i-1],maxEdge[up[u][i-1]][i-1])
def isAncestor(u,v): # True if u is ancestor of v
return tin[u]<=tin[v] and tout[u]>=tout[v]
def findMaxEdgeValue(u,v):
# traverse u to LCA, then v to LCA
res=0
if not isAncestor(u,v):
u2=u
while not isAncestor(up[u2][0],v): # still have to move up
for i in range(maxPow-1,-1,-1):
if up[u2][i]!=-1 and not isAncestor(up[u2][i],v):
res=max(res,maxEdge[u2][i])
u2=up[u2][i]
# print('u2:{}'.format(u2)) ##
# next level up is lca
res=max(res,maxEdge[u2][0])
if not isAncestor(v,u):
v2=v
while not isAncestor(up[v2][0],u): # still have to move up
for i in range(maxPow-1,-1,-1):
if up[v2][i]!=-1 and not isAncestor(up[v2][i],u):
res=max(res,maxEdge[v2][i])
v2=up[v2][i]
# print('v2:{} u:{}'.format(v2,u)) ##
# if v2==1:
# print(isAncestor(v,u)) ##
# break
# next level up is lca
res=max(res,maxEdge[v2][0])
return res
# for i in range(1,4):
# for j in range(1,4):
# if i!=j:
# print('i:{} j:{} anc:{}'.format(i,j,isAncestor(i,j)))
ans=[]
# print(outA,outB)
# for u in range(1,n+1):
# print('u:{} up:{} maxEdge:{}'.format(u,up[u],maxEdge[u])) ##
for i in range(len(outA)):
u,v=outA[i],outB[i]
ans.append(findMaxEdgeValue(u,v))
multiLineArrayPrint(ans)
return
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
# input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
dv=defaultValFactory;da=dimensionArr
if len(da)==1:return [dv() for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
def queryInteractive(r):
print('? {}'.format(r))
sys.stdout.flush()
return readIntArr()
def answerInteractive(adj,n):
print('!')
for u in range(1,n+1):
for v in adj[u]:
if v>u:
print('{} {}'.format(u,v))
sys.stdout.flush()
inf=float('inf')
MOD=10**9+7
# MOD=998244353
from math import gcd,floor,ceil
# from math import floor,ceil # for Python2
for _abc in range(1):
main()
```
|
output
| 1
| 102,974
| 3
| 205,949
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After a successful field test, Heidi is considering deploying a trap along some Corridor, possibly not the first one. She wants to avoid meeting the Daleks inside the Time Vortex, so for abundance of caution she considers placing the traps only along those Corridors that are not going to be used according to the current Daleks' plan β which is to use a minimum spanning tree of Corridors. Heidi knows that all energy requirements for different Corridors are now different, and that the Daleks have a single unique plan which they are intending to use.
Your task is to calculate the number E_{max}(c), which is defined in the same way as in the easy version β i.e., the largest e β€ 10^9 such that if we changed the energy of corridor c to e, the Daleks might use it β but now for every corridor that Heidi considers.
Input
The first line: number n of destinations, number m of Time Corridors (2 β€ n β€ 10^5, n - 1 β€ m β€ 10^6). The next m lines: destinations a, b and energy e (1 β€ a, b β€ n, a β b, 0 β€ e β€ 10^9).
No pair \\{a, b\} will repeat. The graph is guaranteed to be connected. All energy requirements e are distinct.
Output
Output m-(n-1) lines, each containing one integer: E_{max}(c_i) for the i-th Corridor c_i from the input that is not part of the current Daleks' plan (minimum spanning tree).
Example
Input
3 3
1 2 8
2 3 3
3 1 4
Output
4
Note
If m = n-1, then you need not output anything.
Submitted Solution:
```
def naiveSolve():
return
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
def find(self, a): #return parent of a. a and b are in same set if they have same parent
acopy = a
while a != self.parent[a]:
a = self.parent[a]
while acopy != a: #path compression
self.parent[acopy], acopy = a, self.parent[acopy]
return a
def union(self, a, b): #union a and b
self.parent[self.find(b)] = self.find(a)
def main():
n,m=readIntArr()
a=[]
b=[]
c=[]
for _ in range(m):
aa,bb,cc=readIntArr()
a.append(aa); b.append(bb); c.append(cc)
idxes=list(range(m))
idxes.sort(key=lambda i:c[i])
uf=UnionFind(n+1)
inA=[] # in MST
inB=[]
inC=[]
outA=[] # not in MST
outB=[]
for i in range(m):
aa=a[idxes[i]]
bb=b[idxes[i]]
cc=c[idxes[i]]
if uf.find(aa)!=uf.find(bb):
uf.union(aa,bb)
inA.append(aa)
inB.append(bb)
inC.append(cc)
else:
outA.append(aa)
outB.append(bb)
# find largest edge between each outA and outB
adj=[[] for _ in range(n+1)] # store (edge,cost)
assert len(inA)==n-1
for i in range(n-1):
u,v,c=inA[i],inB[i],inC[i]
adj[u].append((v,c))
adj[v].append((u,c))
@bootstrap
def dfs(node,p,cost):
up[node][0]=p
maxEdge[node][0]=cost
tin[node]=time[0]
time[0]+=1
for v,c in adj[node]:
if v!=p:
yield dfs(v,node,c)
tout[node]=time[0]
time[0]+=1
yield None
time=[0]
tin=[-1]*(n+1)
tout=[-1]*(n+1)
# binary lifting to find LCA
maxPow=0
while pow(2,maxPow)<n:
maxPow+=1
maxPow+=1
up=[[-1 for _ in range(maxPow)] for __ in range(n+1)]
maxEdge=[[-inf for _ in range(maxPow)] for __ in range(n+1)]
dfs(1,-1,-inf)
for i in range(1,maxPow):
for u in range(1,n+1):
if up[u][i-1]==-1: # reached beyond root
continue
up[u][i]=up[up[u][i-1]][i-1]
maxEdge[u][i]=max(maxEdge[u][i-1],maxEdge[up[u][i-1]][i-1])
def isAncestor(u,v): # True if u is ancestor of v
return tin[u]<=tin[v] and tout[u]>=tout[v]
def findMaxEdgeValue(u,v):
# traverse u to LCA, then v to LCA
res=0
if not isAncestor(u,v):
u2=u
while not isAncestor(up[u2][0],v): # still have to move up
for i in range(maxPow-1,-1,-1):
if up[u2][i]!=-1 and not isAncestor(up[u2][i],v):
res=max(res,maxEdge[u2][i])
u2=up[u2][i]
# print('u2:{}'.format(u2)) ##
# next level up is lca
res=max(res,maxEdge[u2][0])
if not isAncestor(v,u):
v2=v
while not isAncestor(up[v2][0],u): # still have to move up
for i in range(maxPow-1,-1,-1):
if up[v2][i]!=-1 and not isAncestor(up[v2][i],u):
res=max(res,maxEdge[v2][i])
v2=up[v2][i]
# print('v2:{} u:{}'.format(v2,u)) ##
# if v2==1:
# print(isAncestor(v,u)) ##
# break
# next level up is lca
res=max(res,maxEdge[v2][0])
return res
# for i in range(1,4):
# for j in range(1,4):
# if i!=j:
# print('i:{} j:{} anc:{}'.format(i,j,isAncestor(i,j)))
ans=[]
# print(outA,outB)
# for u in range(1,n+1):
# print('u:{} up:{} maxEdge:{}'.format(u,up[u],maxEdge[u])) ##
for i in range(len(outA)):
u,v=outA[i],outB[i]
ans.append(findMaxEdgeValue(u,v))
multiLineArrayPrint(ans)
return
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
# input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
dv=defaultValFactory;da=dimensionArr
if len(da)==1:return [dv() for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
def queryInteractive(r):
print('? {}'.format(r))
sys.stdout.flush()
return readIntArr()
def answerInteractive(adj,n):
print('!')
for u in range(1,n+1):
for v in adj[u]:
if v>u:
print('{} {}'.format(u,v))
sys.stdout.flush()
inf=float('inf')
MOD=10**9+7
# MOD=998244353
from math import gcd,floor,ceil
# from math import floor,ceil # for Python2
for _abc in range(1):
main()
```
|
instruction
| 0
| 102,975
| 3
| 205,950
|
No
|
output
| 1
| 102,975
| 3
| 205,951
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.