code
stringlengths 46
15.9k
| language
stringclasses 3
values | AST_depth
int64 3
30
| alphanumeric_fraction
float64 0.2
0.75
| max_line_length
int64 13
399
| avg_line_length
float64 5.01
116
| num_lines
int64 7
299
| task
stringlengths 151
14k
| source
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|
t = int(input())
while t > 0:
t -= 1
n = int(input())
x = [int(x) for x in input().split()]
arr1 = []
arr2 = []
for item in x:
if item in arr1:
arr2.append(item)
else:
arr1.append(item)
print(*arr1)
| python | 11 | 0.550926 | 38 | 15.615385 | 13 | A permutation of length $n$ is a sequence of integers from $1$ to $n$ of length $n$ containing each number exactly once. For example, $[1]$, $[4, 3, 5, 1, 2]$, $[3, 2, 1]$ are permutations, and $[1, 1]$, $[0, 1]$, $[2, 2, 1, 4]$ are not.
There was a permutation $p[1 \dots n]$. It was merged with itself. In other words, let's take two instances of $p$ and insert elements of the second $p$ into the first maintaining relative order of elements. The result is a sequence of the length $2n$.
For example, if $p=[3, 1, 2]$ some possible results are: $[3, 1, 2, 3, 1, 2]$, $[3, 3, 1, 1, 2, 2]$, $[3, 1, 3, 1, 2, 2]$. The following sequences are not possible results of a merging: $[1, 3, 2, 1, 2, 3$], [$3, 1, 2, 3, 2, 1]$, $[3, 3, 1, 2, 2, 1]$.
For example, if $p=[2, 1]$ the possible results are: $[2, 2, 1, 1]$, $[2, 1, 2, 1]$. The following sequences are not possible results of a merging: $[1, 1, 2, 2$], [$2, 1, 1, 2]$, $[1, 2, 2, 1]$.
Your task is to restore the permutation $p$ by the given resulting sequence $a$. It is guaranteed that the answer exists and is unique.
You have to answer $t$ independent test cases.
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 400$) — the number of test cases. Then $t$ test cases follow.
The first line of the test case contains one integer $n$ ($1 \le n \le 50$) — the length of permutation. The second line of the test case contains $2n$ integers $a_1, a_2, \dots, a_{2n}$ ($1 \le a_i \le n$), where $a_i$ is the $i$-th element of $a$. It is guaranteed that the array $a$ represents the result of merging of some permutation $p$ with the same permutation $p$.
-----Output-----
For each test case, print the answer: $n$ integers $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$), representing the initial permutation. It is guaranteed that the answer exists and is unique.
-----Example-----
Input
5
2
1 1 2 2
4
1 3 1 4 3 4 2 2
5
1 2 1 2 3 4 3 5 4 5
3
1 2 3 1 2 3
4
2 3 2 4 1 3 4 1
Output
1 2
1 3 4 2
1 2 3 4 5
1 2 3
2 3 4 1 | taco |
(n, m) = map(int, input().split())
a = [[int(i) for i in input().split()] for _ in range(n)]
left = [[0 for _ in range(m)] for _ in range(n)]
right = [[0 for _ in range(m)] for _ in range(n)]
up = [[0 for _ in range(m)] for _ in range(n)]
down = [[0 for _ in range(m)] for _ in range(n)]
for i in range(n):
for j in range(m):
left[i][j] = a[i][j]
if j > 0:
left[i][j] |= left[i][j - 1]
for i in range(n):
for j in range(m - 1, -1, -1):
right[i][j] = a[i][j]
if j + 1 < m:
right[i][j] |= right[i][j + 1]
for j in range(m):
for i in range(n):
up[i][j] = a[i][j]
if i > 0:
up[i][j] |= up[i - 1][j]
for j in range(m):
for i in range(n - 1, -1, -1):
down[i][j] = a[i][j]
if i + 1 < n:
down[i][j] |= down[i + 1][j]
ways = 0
for i in range(n):
for j in range(m):
if a[i][j] == 0:
ways += left[i][j] + right[i][j] + up[i][j] + down[i][j]
print(ways)
| python | 14 | 0.492045 | 59 | 26.5 | 32 | Theater stage is a rectangular field of size n × m. The director gave you the stage's plan which actors will follow. For each cell it is stated in the plan if there would be an actor in this cell or not.
You are to place a spotlight on the stage in some good position. The spotlight will project light in one of the four directions (if you look at the stage from above) — left, right, up or down. Thus, the spotlight's position is a cell it is placed to and a direction it shines.
A position is good if two conditions hold: there is no actor in the cell the spotlight is placed to; there is at least one actor in the direction the spotlight projects.
Count the number of good positions for placing the spotlight. Two positions of spotlight are considered to be different if the location cells or projection direction differ.
-----Input-----
The first line contains two positive integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the plan.
The next n lines contain m integers, 0 or 1 each — the description of the plan. Integer 1, means there will be an actor in the corresponding cell, while 0 means the cell will remain empty. It is guaranteed that there is at least one actor in the plan.
-----Output-----
Print one integer — the number of good positions for placing the spotlight.
-----Examples-----
Input
2 4
0 1 0 0
1 0 1 0
Output
9
Input
4 4
0 0 0 0
1 0 0 1
0 1 1 0
0 1 0 0
Output
20
-----Note-----
In the first example the following positions are good: the (1, 1) cell and right direction; the (1, 1) cell and down direction; the (1, 3) cell and left direction; the (1, 3) cell and down direction; the (1, 4) cell and left direction; the (2, 2) cell and left direction; the (2, 2) cell and up direction; the (2, 2) and right direction; the (2, 4) cell and left direction.
Therefore, there are 9 good positions in this example. | taco |
import os
def f(n):
if n == 0:
return 0
if n == 1:
return 1
i = 0
while 2 ** i < n:
i += 1
i -= 1
if 2 ** (i + 1) == n:
return 2 ** (i + 2) - 1
return 2 ** (i + 1) - 1 + f(n - 2 ** i)
t = int(input())
ans = t * [None]
for i in range(t):
n = int(input())
ans[i] = str(f(n))
out = '\n'.join(ans)
out = out.encode(encoding='UTF-8')
os.write(1, out)
| python | 10 | 0.472527 | 40 | 15.545455 | 22 | The last contest held on Johnny's favorite competitive programming platform has been received rather positively. However, Johnny's rating has dropped again! He thinks that the presented tasks are lovely, but don't show the truth about competitors' skills.
The boy is now looking at the ratings of consecutive participants written in a binary system. He thinks that the more such ratings differ, the more unfair is that such people are next to each other. He defines the difference between two numbers as the number of bit positions, where one number has zero, and another has one (we suppose that numbers are padded with leading zeros to the same length). For example, the difference of $5 = 101_2$ and $14 = 1110_2$ equals to $3$, since $0101$ and $1110$ differ in $3$ positions. Johnny defines the unfairness of the contest as the sum of such differences counted for neighboring participants.
Johnny has just sent you the rating sequence and wants you to find the unfairness of the competition. You have noticed that you've got a sequence of consecutive integers from $0$ to $n$. That's strange, but the boy stubbornly says that everything is right. So help him and find the desired unfairness for received numbers.
-----Input-----
The input consists of multiple test cases. The first line contains one integer $t$ ($1 \leq t \leq 10\,000$) — the number of test cases. The following $t$ lines contain a description of test cases.
The first and only line in each test case contains a single integer $n$ ($1 \leq n \leq 10^{18})$.
-----Output-----
Output $t$ lines. For each test case, you should output a single line with one integer — the unfairness of the contest if the rating sequence equals to $0$, $1$, ..., $n - 1$, $n$.
-----Example-----
Input
5
5
7
11
1
2000000000000
Output
8
11
19
1
3999999999987
-----Note-----
For $n = 5$ we calculate unfairness of the following sequence (numbers from $0$ to $5$ written in binary with extra leading zeroes, so they all have the same length): $000$ $001$ $010$ $011$ $100$ $101$
The differences are equal to $1$, $2$, $1$, $3$, $1$ respectively, so unfairness is equal to $1 + 2 + 1 + 3 + 1 = 8$. | taco |
import math
class Solution:
def isPowerofFour(self, n):
x = math.log(n, 4)
for i in range(n):
if x == i:
return 1
return 0
| python | 10 | 0.604317 | 28 | 12.9 | 10 | Given a number N, check if N is power of 4 or not.
Example 1:
Input:
N = 64
Output: 1
Explanation:
4^{3}= 64
Example 2:
Input:
N = 75
Output : 0
Explanation :
75 is not a power of 4.
Your task:
You don't have to read input or print anything. Your task is to complete the function isPowerOfFour() which takes an integer N and returns 1 if the number is a power of four else returns 0.
Expected Time Complexity: O(N)
Expected Auxiliary Space : O(1)
Constraints:
1<=N<=10^{5} | taco |
n = int(input())
l = ['<', '>']
ll = []
linf = []
lsup = []
for i in range(n):
cinf = 0
csup = 0
a = int(input())
b = input()
cmp = 0
ll.append(b[a - 1])
for j in range(a):
ll.append(0)
ll.append(b[j])
for k in range(len(ll)):
if ll[k] == 0:
if ll[k - 1] == '-' or ll[k + 1] == '-':
cmp = cmp + 1
for m in range(a):
if b[m] == '<':
cinf = cinf + 1
elif b[m] == '>':
csup = csup + 1
if cinf == 0 or csup == 0:
print(a)
else:
print(cmp)
ll = []
| python | 12 | 0.452282 | 43 | 15.62069 | 29 | In the snake exhibition, there are $n$ rooms (numbered $0$ to $n - 1$) arranged in a circle, with a snake in each room. The rooms are connected by $n$ conveyor belts, and the $i$-th conveyor belt connects the rooms $i$ and $(i+1) \bmod n$. In the other words, rooms $0$ and $1$, $1$ and $2$, $\ldots$, $n-2$ and $n-1$, $n-1$ and $0$ are connected with conveyor belts.
The $i$-th conveyor belt is in one of three states: If it is clockwise, snakes can only go from room $i$ to $(i+1) \bmod n$. If it is anticlockwise, snakes can only go from room $(i+1) \bmod n$ to $i$. If it is off, snakes can travel in either direction. [Image]
Above is an example with $4$ rooms, where belts $0$ and $3$ are off, $1$ is clockwise, and $2$ is anticlockwise.
Each snake wants to leave its room and come back to it later. A room is returnable if the snake there can leave the room, and later come back to it using the conveyor belts. How many such returnable rooms are there?
-----Input-----
Each test contains multiple test cases. The first line contains a single integer $t$ ($1 \le t \le 1000$): the number of test cases. The description of the test cases follows.
The first line of each test case description contains a single integer $n$ ($2 \le n \le 300\,000$): the number of rooms.
The next line of each test case description contains a string $s$ of length $n$, consisting of only '<', '>' and '-'. If $s_{i} = $ '>', the $i$-th conveyor belt goes clockwise. If $s_{i} = $ '<', the $i$-th conveyor belt goes anticlockwise. If $s_{i} = $ '-', the $i$-th conveyor belt is off.
It is guaranteed that the sum of $n$ among all test cases does not exceed $300\,000$.
-----Output-----
For each test case, output the number of returnable rooms.
-----Example-----
Input
4
4
-><-
5
>>>>>
3
<--
2
<>
Output
3
5
3
0
-----Note-----
In the first test case, all rooms are returnable except room $2$. The snake in the room $2$ is trapped and cannot exit. This test case corresponds to the picture from the problem statement.
In the second test case, all rooms are returnable by traveling on the series of clockwise belts. | taco |
class Cat:
def __init__(self, name):
self.name = name
def speak(self):
return self.name + ' meows.'
cat = Cat('Mr Whiskers')
print(cat.speak())
| python | 8 | 0.625 | 30 | 15.888889 | 9 | Classy Extensions
Classy Extensions, this kata is mainly aimed at the new JS ES6 Update introducing extends keyword. You will be preloaded with the Animal class, so you should only edit the Cat class.
Task
Your task is to complete the Cat class which Extends Animal and replace the speak method to return the cats name + meows.
e.g. 'Mr Whiskers meows.'
The name attribute is passed with this.name (JS), @name (Ruby) or self.name (Python).
Reference: [JS](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), [Ruby](http://rubylearning.com/satishtalim/ruby_inheritance.html), [Python](https://docs.python.org/2/tutorial/classes.html#inheritance). | taco |
t = []
l = []
r = []
for _ in range(int(input())):
(s, g) = map(int, input().split())
t.append(s)
l.append(s)
r.append(g + s)
for i in range(1, len(l)):
if l[i] < l[i - 1]:
l[i] = l[i - 1] - 1
if r[i] > r[i - 1]:
r[i] = r[i - 1] + 1
for i in range(len(l) - 2, -1, -1):
if l[i] < l[i + 1]:
l[i] = l[i + 1] - 1
if r[i] > r[i + 1]:
r[i] = r[i + 1] + 1
if [1 for (a, b) in zip(l, r) if a > b]:
print(-1)
else:
print(sum([b - a for (a, b) in zip(t, r)]))
print(' '.join(map(str, r)))
| python | 13 | 0.435743 | 44 | 20.652174 | 23 | Mayor of city S just hates trees and lawns. They take so much space and there could be a road on the place they occupy!
The Mayor thinks that one of the main city streets could be considerably widened on account of lawn nobody needs anyway. Moreover, that might help reduce the car jams which happen from time to time on the street.
The street is split into n equal length parts from left to right, the i-th part is characterized by two integers: width of road s_{i} and width of lawn g_{i}. [Image]
For each of n parts the Mayor should decide the size of lawn to demolish. For the i-th part he can reduce lawn width by integer x_{i} (0 ≤ x_{i} ≤ g_{i}). After it new road width of the i-th part will be equal to s'_{i} = s_{i} + x_{i} and new lawn width will be equal to g'_{i} = g_{i} - x_{i}.
On the one hand, the Mayor wants to demolish as much lawn as possible (and replace it with road). On the other hand, he does not want to create a rapid widening or narrowing of the road, which would lead to car accidents. To avoid that, the Mayor decided that width of the road for consecutive parts should differ by at most 1, i.e. for each i (1 ≤ i < n) the inequation |s'_{i} + 1 - s'_{i}| ≤ 1 should hold. Initially this condition might not be true.
You need to find the the total width of lawns the Mayor will destroy according to his plan.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 2·10^5) — number of parts of the street.
Each of the following n lines contains two integers s_{i}, g_{i} (1 ≤ s_{i} ≤ 10^6, 0 ≤ g_{i} ≤ 10^6) — current width of road and width of the lawn on the i-th part of the street.
-----Output-----
In the first line print the total width of lawns which will be removed.
In the second line print n integers s'_1, s'_2, ..., s'_{n} (s_{i} ≤ s'_{i} ≤ s_{i} + g_{i}) — new widths of the road starting from the first part and to the last.
If there is no solution, print the only integer -1 in the first line.
-----Examples-----
Input
3
4 5
4 5
4 10
Output
16
9 9 10
Input
4
1 100
100 1
1 100
100 1
Output
202
101 101 101 101
Input
3
1 1
100 100
1 1
Output
-1 | taco |
size = int(input())
array = list(map(int, input().split()))
array = sorted(array)
currentSum = array[0]
counter = 0
for i in range(1, size):
if array[i] >= currentSum:
currentSum += array[i]
counter += 1
print(counter + 1)
| python | 11 | 0.649123 | 39 | 21.8 | 10 | Little girl Susie went shopping with her mom and she wondered how to improve service quality.
There are n people in the queue. For each person we know time t_{i} needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total time when all the people who stand in the queue in front of him are served. Susie thought that if we swap some people in the queue, then we can decrease the number of people who are disappointed.
Help Susie find out what is the maximum number of not disappointed people can be achieved by swapping people in the queue.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 10^5).
The next line contains n integers t_{i} (1 ≤ t_{i} ≤ 10^9), separated by spaces.
-----Output-----
Print a single number — the maximum number of not disappointed people in the queue.
-----Examples-----
Input
5
15 2 1 5 3
Output
4
-----Note-----
Value 4 is achieved at such an arrangement, for example: 1, 2, 3, 5, 15. Thus, you can make everything feel not disappointed except for the person with time 5. | taco |
t = int(input())
for _ in range(t):
n = int(input())
a = list(str(input()))
d = dict()
d['A'] = 'T'
d['T'] = 'A'
d['C'] = 'G'
d['G'] = 'C'
res = ''
for el in a:
res += d[el]
print(res)
| python | 11 | 0.426396 | 23 | 14.153846 | 13 | You are given the sequence of Nucleotides of one strand of DNA through a string S of length N. S contains the character A, T, C, and G only.
Chef knows that:
A is complementary to T.
T is complementary to A.
C is complementary to G.
G is complementary to C.
Using the string S, determine the sequence of the complementary strand of the DNA.
------ Input Format ------
- First line will contain T, number of test cases. Then the test cases follow.
- First line of each test case contains an integer N - denoting the length of string S.
- Second line contains N characters denoting the string S.
------ Output Format ------
For each test case, output the string containing N characters - sequence of nucleotides of the complementary strand.
------ Constraints ------
$1 ≤ T ≤ 100$
$1 ≤ N ≤ 100$
$S$ contains A, T, C, and G only
----- Sample Input 1 ------
4
4
ATCG
4
GTCC
5
AAAAA
3
TAC
----- Sample Output 1 ------
TAGC
CAGG
TTTTT
ATG
----- explanation 1 ------
Test case $1$: Based on the rules, the complements of A, T, C, and G are T, A, G, and C respectively. Thus, the complementary string of the given string ATCG is TAGC.
Test case $2$: Based on the rules, the complements of G, T, and C are C, A, and G respectively. Thus, the complementary string of the given string GTCC is CAGG.
Test case $3$: Based on the rules, the complement of A is T. Thus, the complementary string of the given string AAAAA is TTTTT.
Test case $4$: Based on the rules, the complements of T, A, and C are A, T, and G respectively. Thus, the complementary string of the given string TAC is ATG. | taco |
import sys
fast_input = sys.stdin.readline
t = int(fast_input())
while t:
t -= 1
n = int(fast_input())
a = list(map(int, fast_input().split()))
b = list(map(int, fast_input().split()))
new = []
for i in range(n):
new.append([a[i], i])
new.append([b[i], i])
new.sort(reverse=True)
res = 2 * n
(x, y) = (n, n)
for ne in new:
if ne[0] % 2 == 0:
x = min(x, ne[1])
else:
res = min(res, x + ne[1])
print(res)
| python | 14 | 0.546729 | 41 | 19.380952 | 21 | You are given two arrays $a$ and $b$ of length $n$. Array $a$ contains each odd integer from $1$ to $2n$ in an arbitrary order, and array $b$ contains each even integer from $1$ to $2n$ in an arbitrary order.
You can perform the following operation on those arrays:
choose one of the two arrays
pick an index $i$ from $1$ to $n-1$
swap the $i$-th and the $(i+1)$-th elements of the chosen array
Compute the minimum number of operations needed to make array $a$ lexicographically smaller than array $b$.
For two different arrays $x$ and $y$ of the same length $n$, we say that $x$ is lexicographically smaller than $y$ if in the first position where $x$ and $y$ differ, the array $x$ has a smaller element than the corresponding element in $y$.
-----Input-----
Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^4$).
The first line of each test case contains a single integer $n$ ($1 \le n \le 10^5$) — the length of the arrays.
The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 2n$, all $a_i$ are odd and pairwise distinct) — array $a$.
The third line of each test case contains $n$ integers $b_1, b_2, \ldots, b_n$ ($1 \le b_i \le 2n$, all $b_i$ are even and pairwise distinct) — array $b$.
It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$.
-----Output-----
For each test case, print one integer: the minimum number of operations needed to make array $a$ lexicographically smaller than array $b$.
We can show that an answer always exists.
-----Examples-----
Input
3
2
3 1
4 2
3
5 3 1
2 4 6
5
7 5 9 1 3
2 4 6 10 8
Output
0
2
3
-----Note-----
In the first example, the array $a$ is already lexicographically smaller than array $b$, so no operations are required.
In the second example, we can swap $5$ and $3$ and then swap $2$ and $4$, which results in $[3, 5, 1]$ and $[4, 2, 6]$. Another correct way is to swap $3$ and $1$ and then swap $5$ and $1$, which results in $[1, 5, 3]$ and $[2, 4, 6]$. Yet another correct way is to swap $4$ and $6$ and then swap $2$ and $6$, which results in $[5, 3, 1]$ and $[6, 2, 4]$. | taco |
def calculate_rotations_number(string):
string = 'a' + string
total = 0
for i in range(len(string) - 1):
num = abs(ord(string[i + 1]) - ord(string[i]))
if num < 13:
total += num
else:
total += 26 - num
return total
string = input()
print(calculate_rotations_number(string))
| python | 14 | 0.641379 | 48 | 23.166667 | 12 | Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character. The device consists of a wheel with a lowercase English letters written in a circle, static pointer to the current letter and a button that print the chosen letter. At one move it's allowed to rotate the alphabetic wheel one step clockwise or counterclockwise. Initially, static pointer points to letter 'a'. Other letters are located as shown on the picture: [Image]
After Grigoriy add new item to the base he has to print its name on the plastic tape and attach it to the corresponding exhibit. It's not required to return the wheel to its initial position with pointer on the letter 'a'.
Our hero is afraid that some exhibits may become alive and start to attack him, so he wants to print the names as fast as possible. Help him, for the given string find the minimum number of rotations of the wheel required to print it.
-----Input-----
The only line of input contains the name of some exhibit — the non-empty string consisting of no more than 100 characters. It's guaranteed that the string consists of only lowercase English letters.
-----Output-----
Print one integer — the minimum number of rotations of the wheel, required to print the name given in the input.
-----Examples-----
Input
zeus
Output
18
Input
map
Output
35
Input
ares
Output
34
-----Note-----
[Image]
To print the string from the first sample it would be optimal to perform the following sequence of rotations: from 'a' to 'z' (1 rotation counterclockwise), from 'z' to 'e' (5 clockwise rotations), from 'e' to 'u' (10 rotations counterclockwise), from 'u' to 's' (2 counterclockwise rotations). In total, 1 + 5 + 10 + 2 = 18 rotations are required. | taco |
for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
move = 0
pre = list(a)
suf = list(a)
for i in range(1, n):
pre[i] += pre[i - 1]
for j in range(n - 2, -1, -1):
suf[j] += suf[j + 1]
(l, r) = (-1, n)
(ca, cb) = (0, 0)
(pa, pb) = (0, 0)
t = 1
while ca + cb < pre[-1]:
if t:
fl = False
for i in range(l + 1, r):
if pre[i] - ca > pb:
fl = True
pa = pre[i] - ca
ca = pre[i]
l = i
break
if not fl:
l = r - 1
ca = pre[l]
else:
fl = False
for j in range(r - 1, l, -1):
if suf[j] - cb > pa:
fl = True
pb = suf[j] - cb
cb = suf[j]
r = j
break
if not fl:
r = l + 1
cb = suf[r]
move += 1
t ^= 1
print(move, ca, cb)
| python | 16 | 0.427623 | 36 | 16.928571 | 42 | There are $n$ candies in a row, they are numbered from left to right from $1$ to $n$. The size of the $i$-th candy is $a_i$.
Alice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy from left to right, and Bob — from right to left. The game ends if all the candies are eaten.
The process consists of moves. During a move, the player eats one or more sweets from her/his side (Alice eats from the left, Bob — from the right).
Alice makes the first move. During the first move, she will eat $1$ candy (its size is $a_1$). Then, each successive move the players alternate — that is, Bob makes the second move, then Alice, then again Bob and so on.
On each move, a player counts the total size of candies eaten during the current move. Once this number becomes strictly greater than the total size of candies eaten by the other player on their previous move, the current player stops eating and the move ends. In other words, on a move, a player eats the smallest possible number of candies such that the sum of the sizes of candies eaten on this move is strictly greater than the sum of the sizes of candies that the other player ate on the previous move. If there are not enough candies to make a move this way, then the player eats up all the remaining candies and the game ends.
For example, if $n=11$ and $a=[3,1,4,1,5,9,2,6,5,3,5]$, then: move 1: Alice eats one candy of size $3$ and the sequence of candies becomes $[1,4,1,5,9,2,6,5,3,5]$. move 2: Alice ate $3$ on the previous move, which means Bob must eat $4$ or more. Bob eats one candy of size $5$ and the sequence of candies becomes $[1,4,1,5,9,2,6,5,3]$. move 3: Bob ate $5$ on the previous move, which means Alice must eat $6$ or more. Alice eats three candies with the total size of $1+4+1=6$ and the sequence of candies becomes $[5,9,2,6,5,3]$. move 4: Alice ate $6$ on the previous move, which means Bob must eat $7$ or more. Bob eats two candies with the total size of $3+5=8$ and the sequence of candies becomes $[5,9,2,6]$. move 5: Bob ate $8$ on the previous move, which means Alice must eat $9$ or more. Alice eats two candies with the total size of $5+9=14$ and the sequence of candies becomes $[2,6]$. move 6 (the last): Alice ate $14$ on the previous move, which means Bob must eat $15$ or more. It is impossible, so Bob eats the two remaining candies and the game ends.
Print the number of moves in the game and two numbers: $a$ — the total size of all sweets eaten by Alice during the game; $b$ — the total size of all sweets eaten by Bob during the game.
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 5000$) — the number of test cases in the input. The following are descriptions of the $t$ test cases.
Each test case consists of two lines. The first line contains an integer $n$ ($1 \le n \le 1000$) — the number of candies. The second line contains a sequence of integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) — the sizes of candies in the order they are arranged from left to right.
It is guaranteed that the sum of the values of $n$ for all sets of input data in a test does not exceed $2\cdot10^5$.
-----Output-----
For each set of input data print three integers — the number of moves in the game and the required values $a$ and $b$.
-----Example-----
Input
7
11
3 1 4 1 5 9 2 6 5 3 5
1
1000
3
1 1 1
13
1 2 3 4 5 6 7 8 9 10 11 12 13
2
2 1
6
1 1 1 1 1 1
7
1 1 1 1 1 1 1
Output
6 23 21
1 1000 0
2 1 2
6 45 46
2 2 1
3 4 2
4 4 3 | taco |
q = int(input())
def step(a, b, d):
step = 0
extra = 0
if d > 2 * max(a, b):
extra = d // max(a, b) - 1
d = d - extra * max(a, b)
step = step_small(a, b, d) + extra
return step
def step_small(a, b, d):
if d == 0:
step = 0
elif d == a or d == b:
step = 1
else:
step = 2
return step
for i in range(q):
(a, b, d) = map(int, input().split())
step_min = step(a, b, d)
print(step_min)
| python | 11 | 0.51861 | 38 | 16.521739 | 23 | You are standing at point $(0,0)$ on an infinite plane. In one step, you can move from some point $(x_f,y_f)$ to any point $(x_t,y_t)$ as long as the Euclidean distance, $\sqrt{(x_f-x_t)^2+(y_f-y_t)^2}$, between the two points is either $\boldsymbol{a}$ or $\boldsymbol{b}$. In other words, each step you take must be exactly $\boldsymbol{a}$ or $\boldsymbol{b}$ in length.
You are given $\textit{q}$ queries in the form of $\boldsymbol{a}$, $\boldsymbol{b}$, and $\boldsymbol{d}$. For each query, print the minimum number of steps it takes to get from point $(0,0)$ to point $\left(d,0\right)$ on a new line.
Input Format
The first line contains an integer, $\textit{q}$, denoting the number of queries you must process.
Each of the $\textit{q}$ subsequent lines contains three space-separated integers describing the respective values of $\boldsymbol{a}$, $\boldsymbol{b}$, and $\boldsymbol{d}$ for a query.
Constraints
$1\leq q\leq10^5$
$1\leq a<b\leq10^9$
$0\leq d\leq10^9$
Output Format
For each query, print the minimum number of steps necessary to get to point $\left(d,0\right)$ on a new line.
Sample Input 0
3
2 3 1
1 2 0
3 4 11
Sample Output 0
2
0
3
Explanation 0
We perform the following $q=3$ queries:
One optimal possible path requires two steps of length $\boldsymbol{a}=2$: $(0,0)\underset{2}{\longrightarrow}(\frac{1}{2},\frac{\sqrt{15}}{2})\underset{2}{\longrightarrow}(1,0)$. Thus, we print the number of steps, $2$, on a new line.
The starting and destination points are both $(0,0)$, so we needn't take any steps. Thus, we print $\mbox{0}$ on a new line.
One optimal possible path requires two steps of length $\boldsymbol{b}=4$ and one step of length $\boldsymbol{a}=3$: $(0,0)\underset{4}{\longrightarrow}(4,0)\underset{4}{\longrightarrow}(8,0)\underset{3}{\longrightarrow}(11,0)$. Thus, we print $3$ on a new line. | taco |
from sys import *
input = stdin.readline
s = input()
m = len(s)
n = int(input())
d = [0]
c = 0
for i in range(1, m):
if s[i] == s[i - 1]:
c = c + 1
d.append(c)
for i in range(n):
(x, y) = map(int, input().split())
print(d[y - 1] - d[x - 1])
| python | 11 | 0.51417 | 35 | 16.642857 | 14 | Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.
You've got string s = s_1s_2... s_{n} (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers l_{i}, r_{i} (1 ≤ l_{i} < r_{i} ≤ n). The answer to the query l_{i}, r_{i} is the number of such integers i (l_{i} ≤ i < r_{i}), that s_{i} = s_{i} + 1.
Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
-----Input-----
The first line contains string s of length n (2 ≤ n ≤ 10^5). It is guaranteed that the given string only consists of characters "." and "#".
The next line contains integer m (1 ≤ m ≤ 10^5) — the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers l_{i}, r_{i} (1 ≤ l_{i} < r_{i} ≤ n).
-----Output-----
Print m integers — the answers to the queries in the order in which they are given in the input.
-----Examples-----
Input
......
4
3 4
2 3
1 6
2 6
Output
1
1
5
4
Input
#..###
5
1 3
5 6
1 5
3 6
3 4
Output
1
1
2
2
0 | taco |
def two_highest(arg1):
pass
if len(arg1) == 0:
return []
a = sorted(arg1, reverse=True)
if a[0] == a[-1]:
return [a[0]]
else:
return [a[0], a[a.count(a[0])]]
| python | 12 | 0.556213 | 33 | 17.777778 | 9 | In this kata, your job is to return the two distinct highest values in a list. If there're less than 2 unique values, return as many of them, as possible.
The result should also be ordered from highest to lowest.
Examples:
```
[4, 10, 10, 9] => [10, 9]
[1, 1, 1] => [1]
[] => []
``` | taco |
n = int(input())
arr = []
m = -1
for i in range(n):
arr.append(int(input()))
arr.sort(reverse=True)
for i in range(n - 1):
if m > arr[i]:
break
temp = arr[i] & arr[i + 1]
if temp > m:
m = temp
print(m)
| python | 10 | 0.557143 | 27 | 15.153846 | 13 | Read problems statements in Mandarin Chinese .
Given an array of n non-negative integers: A_{1}, A_{2}, …, A_{N}. Your mission is finding a pair of integers A_{u}, A_{v} (1 ≤ u < v ≤ N) such that (A_{u} and A_{v}) is as large as possible.
And is a bit-wise operation which is corresponding to & in C++ and Java.
------ Input ------
The first line of the input contains a single integer N. The ith line in the next N lines contains the A_{i}.
------ Output ------
Contains a single integer which is the largest value of A_{u} and A_{v} where 1 ≤ u < v ≤ N.
------ Constraints ------
50 points:
$2 ≤ N ≤ 5000$
$0 ≤ A_{i} ≤ 10^{9}$
50 points:
$2 ≤ N ≤ 3 × 10^{5}$
$0 ≤ A_{i} ≤ 10^{9}$
----- Sample Input 1 ------
4
2
4
8
10
----- Sample Output 1 ------
8
----- explanation 1 ------
2 and 4 = 0
2 and 8 = 0
2 and 10 = 2
4 and 8 = 0
4 and 10 = 0
8 and 10 = 8 | taco |
t=eval(input())
for x in range(0,t):
s=input('')
if s==s[::-1]:
n=len(s)
n=n/2
print(ord(s[n]))
else:
print(-1)
| python | 11 | 0.378049 | 28 | 15.4 | 10 | Solve the mystery.
Input:
First line contains a single integer denoting number of test cases(T).
Next T lines have one test case per line.
Each test case is a string of alphabets [a-z].
Output:
Print answer to each test case in an individual line.
Constraints:
1 ≤ T ≤ 100
1 ≤ |S| ≤ 100
a ≤ S[i] ≤ z
Problem Setter : Siddharth Seth
SAMPLE INPUT
5
malayalam
ariyama
alla
brook
kurruk
SAMPLE OUTPUT
121
-1
108
-1
114 | taco |
def main():
(n, aa) = (int(input()), list(map(int, input().split())))
(partialsum, s, d, ranges) = ([0] * n, 0, {}, [])
for (i, a) in enumerate(aa):
if a > 0:
s += a
partialsum[i] = s
if a in d:
d[a].append(i)
else:
d[a] = [i]
ranges = []
for (a, l) in d.items():
(lo, hi) = (l[0], l[-1])
if lo < hi:
ranges.append((partialsum[hi - 1] - partialsum[lo] + a * 2, lo, hi))
(s, lo, hi) = max(ranges)
res = list(range(1, lo + 1))
for i in range(lo + 1, hi):
if aa[i] < 0:
res.append(i + 1)
res.extend(range(hi + 2, n + 1))
print(s, len(res))
print(' '.join(map(str, res)))
main()
| python | 15 | 0.502439 | 71 | 23.6 | 25 | — Oh my sweet Beaverette, would you fancy a walk along a wonderful woodland belt with me?
— Of course, my Smart Beaver! Let us enjoy the splendid view together. How about Friday night?
At this point the Smart Beaver got rushing. Everything should be perfect by Friday, so he needed to prepare the belt to the upcoming walk. He needed to cut down several trees.
Let's consider the woodland belt as a sequence of trees. Each tree i is described by the esthetic appeal ai — some trees are very esthetically pleasing, others are 'so-so', and some trees are positively ugly!
The Smart Beaver calculated that he needed the following effects to win the Beaverette's heart:
* The first objective is to please the Beaverette: the sum of esthetic appeal of the remaining trees must be maximum possible;
* the second objective is to surprise the Beaverette: the esthetic appeal of the first and the last trees in the resulting belt must be the same;
* and of course, the walk should be successful: there must be at least two trees in the woodland belt left.
Now help the Smart Beaver! Which trees does he need to cut down to win the Beaverette's heart?
Input
The first line contains a single integer n — the initial number of trees in the woodland belt, 2 ≤ n. The second line contains space-separated integers ai — the esthetic appeals of each tree. All esthetic appeals do not exceed 109 in their absolute value.
* to get 30 points, you need to solve the problem with constraints: n ≤ 100 (subproblem A1);
* to get 100 points, you need to solve the problem with constraints: n ≤ 3·105 (subproblems A1+A2).
Output
In the first line print two integers — the total esthetic appeal of the woodland belt after the Smart Beaver's intervention and the number of the cut down trees k.
In the next line print k integers — the numbers of the trees the Beaver needs to cut down. Assume that the trees are numbered from 1 to n from left to right.
If there are multiple solutions, print any of them. It is guaranteed that at least two trees have equal esthetic appeal.
Examples
Input
5
1 2 3 1 2
Output
8 1
1
Input
5
1 -2 3 1 -2
Output
5 2
2 5 | taco |
n = int(input())
l = [int(i) for i in input().split()]
l.sort()
mini = 10 ** 100
for i in range(2 * n):
for j in range(0, 2 * n):
inst = 0
l1 = []
for k in range(2 * n):
if k == i or k == j:
continue
l1.append(l[k])
l1.sort()
for x in range(1, len(l1), 2):
inst += l1[x] - l1[x - 1]
mini = min(mini, inst)
print(mini)
| python | 12 | 0.511628 | 37 | 19.235294 | 17 | Vadim is really keen on travelling. Recently he heard about kayaking activity near his town and became very excited about it, so he joined a party of kayakers.
Now the party is ready to start its journey, but firstly they have to choose kayaks. There are 2·n people in the group (including Vadim), and they have exactly n - 1 tandem kayaks (each of which, obviously, can carry two people) and 2 single kayaks. i-th person's weight is w_{i}, and weight is an important matter in kayaking — if the difference between the weights of two people that sit in the same tandem kayak is too large, then it can crash. And, of course, people want to distribute their seats in kayaks in order to minimize the chances that kayaks will crash.
Formally, the instability of a single kayak is always 0, and the instability of a tandem kayak is the absolute difference between weights of the people that are in this kayak. Instability of the whole journey is the total instability of all kayaks.
Help the party to determine minimum possible total instability!
-----Input-----
The first line contains one number n (2 ≤ n ≤ 50).
The second line contains 2·n integer numbers w_1, w_2, ..., w_2n, where w_{i} is weight of person i (1 ≤ w_{i} ≤ 1000).
-----Output-----
Print minimum possible total instability.
-----Examples-----
Input
2
1 2 3 4
Output
1
Input
4
1 3 4 6 3 4 100 200
Output
5 | taco |
(s, n) = (input(), int(input()))
z = [int(x) for x in input().split()]
ans = 0
for i in range(len(s)):
ans += (i + 1) * z[ord(s[i]) - ord('a')]
for i in range(n):
ans += (i + 1 + len(s)) * max(z)
print(ans)
| python | 11 | 0.492823 | 41 | 25.125 | 8 | DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value w_{c}. For each special string s = s_1s_2... s_{|}s| (|s| is the length of the string) he represents its value with a function f(s), where $f(s) = \sum_{i = 1}^{|s|}(w_{s_{i}} \cdot i)$
Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?
-----Input-----
The first line contains a single string s (1 ≤ |s| ≤ 10^3).
The second line contains a single integer k (0 ≤ k ≤ 10^3).
The third line contains twenty-six integers from w_{a} to w_{z}. Each such number is non-negative and doesn't exceed 1000.
-----Output-----
Print a single integer — the largest possible value of the resulting string DZY could get.
-----Examples-----
Input
abc
3
1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Output
41
-----Note-----
In the test sample DZY can obtain "abcbbc", value = 1·1 + 2·2 + 3·2 + 4·2 + 5·2 + 6·2 = 41. | taco |
class Solution:
def validMountainArray(self, A: List[int]) -> bool:
if len(A) < 3:
return False
nprev = A[0]
for i in range(1, len(A)):
if A[i] <= nprev:
nprev = A[i - 1]
start = i
break
nprev = A[i]
if i == len(A) - 1:
return False
for i in range(start, len(A)):
if A[i] >= nprev:
return False
nprev = A[i]
if start == 1 and i == len(A) - 1:
return False
return True
| python | 13 | 0.541176 | 52 | 19.238095 | 21 | Given an array A of integers, return true if and only if it is a valid mountain array.
Recall that A is a mountain array if and only if:
A.length >= 3
There exists some i with 0 < i < A.length - 1 such that:
A[0] < A[1] < ... A[i-1] < A[i]
A[i] > A[i+1] > ... > A[A.length - 1]
Example 1:
Input: [2,1]
Output: false
Example 2:
Input: [3,5,5]
Output: false
Example 3:
Input: [0,3,2,1]
Output: true
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000 | taco |
n = input()
x = len(n)
n = int(n)
def f(n, x):
l = [4, 7]
if x == 2:
l = [4, 7, 44, 47, 74, 77]
elif x == 3:
l = [4, 7, 44, 47, 74, 77, 444, 447, 474, 477, 744, 747, 774, 777]
for i in range(0, len(l)):
if n % l[i] == 0:
return 'YES'
return 'NO'
a = f(n, x)
print(a)
| python | 9 | 0.460993 | 68 | 16.625 | 16 | Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find out if the given number n is almost lucky.
Input
The single line contains an integer n (1 ≤ n ≤ 1000) — the number that needs to be checked.
Output
In the only line print "YES" (without the quotes), if number n is almost lucky. Otherwise, print "NO" (without the quotes).
Examples
Input
47
Output
YES
Input
16
Output
YES
Input
78
Output
NO
Note
Note that all lucky numbers are almost lucky as any number is evenly divisible by itself.
In the first sample 47 is a lucky number. In the second sample 16 is divisible by 4. | taco |
(ln, k) = map(str, input().split())
n = str(input())
k = int(k)
numlist = [int(i) for i in list(n)]
cnt = 0
if cnt == k:
print(n)
else:
if numlist[0] != 1:
numlist[0] = 1
cnt += 1
for i in range(1, len(numlist)):
if cnt == k:
break
elif numlist[i] != 0:
numlist[i] = 0
cnt += 1
ans = [str(i) for i in numlist]
if ans == ['1']:
print(0)
else:
print(''.join(ans))
| python | 13 | 0.529563 | 35 | 16.681818 | 22 | Ania has a large integer $S$. Its decimal representation has length $n$ and doesn't contain any leading zeroes. Ania is allowed to change at most $k$ digits of $S$. She wants to do it in such a way that $S$ still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?
-----Input-----
The first line contains two integers $n$ and $k$ ($1 \leq n \leq 200\,000$, $0 \leq k \leq n$) — the number of digits in the decimal representation of $S$ and the maximum allowed number of changed digits.
The second line contains the integer $S$. It's guaranteed that $S$ has exactly $n$ digits and doesn't contain any leading zeroes.
-----Output-----
Output the minimal possible value of $S$ which Ania can end with. Note that the resulting integer should also have $n$ digits.
-----Examples-----
Input
5 3
51528
Output
10028
Input
3 2
102
Output
100
Input
1 1
1
Output
0
-----Note-----
A number has leading zeroes if it consists of at least two digits and its first digit is $0$. For example, numbers $00$, $00069$ and $0101$ have leading zeroes, while $0$, $3000$ and $1010$ don't have leading zeroes. | taco |
import sys
ntests = int(sys.stdin.readline().strip())
while ntests > 0:
ntests -= 1
N = int(sys.stdin.readline().strip())
state = [(0, 0)]
for r in range(0, N):
fields = list(map(int, sys.stdin.readline().strip().split()))
fields.sort()
i = len(state) - 1
j = len(fields) - 1
nstate = []
while i >= 0 and j >= 0:
if fields[j] > state[i][0]:
nstate.insert(0, (fields[j], fields[j] + state[i][1]))
j -= 1
else:
i -= 1
state = nstate
if len(state) > 0:
print(state[-1][1])
else:
print('-1')
| python | 18 | 0.558491 | 63 | 22.043478 | 23 | You are given N integer sequences A1, A2, ..., AN. Each of these sequences contains N elements. You should pick N elements, one from each sequence; let's denote the element picked from sequence Ai by Ei. For each i (2 ≤ i ≤ N), Ei should be strictly greater than Ei-1.
Compute the maximum possible value of E1 + E2 + ... + EN. If it's impossible to pick the elements E1, E2, ..., EN, print -1 instead.
-----Input-----
- The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
- The first line of each test case contains a single integer N.
- N lines follow. For each valid i, the i-th of these lines contains N space-separated integers Ai1, Ai2, ..., AiN denoting the elements of the sequence Ai.
-----Output-----
For each test case, print a single line containing one integer — the maximum sum of picked elements.
-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 700
- 1 ≤ sum of N in all test-cases ≤ 3700
- 1 ≤ Aij ≤ 109 for each valid i, j
-----Subtasks-----
Subtask #1 (18 points): 1 ≤ Aij ≤ N for each valid i, j
Subtask #2 (82 points): original constraints
-----Example-----
Input:
1
3
1 2 3
4 5 6
7 8 9
Output:
18
-----Explanation-----
Example case 1: To maximise the score, pick 3 from the first row, 6 from the second row and 9 from the third row. The resulting sum is E1+E2+E3 = 3+6+9 = 18. | taco |
class Solution:
def countDigits(self, a, b):
n = a * b
c = 0
n = abs(n)
while n > 0:
c = c + 1
n = n // 10
return c
| python | 10 | 0.477612 | 29 | 12.4 | 10 | Given two integers a and b. Write a program to find the number of digits in the product of these two integers.
Example 1:
Input: a = 12, b = 4
Output: 2
Explanation: 12*4 = 48
Hence its a 2 digit number.
Example 2:
Input: a = -24, b = 33
Output: 3
Explanation: -24*33 = -792
Hence its a 3 digit number.
Your Task:
You dont need to read input or print anything. Complete the function countDigits() which takes a and b as input parameter and returns the number of digits in the product of the two numbers.
Expected Time Complexity: O(1)
Expected Auxiliary Space: O(1)
Constraints:
-10^{8}<= a,b <=10^{8} | taco |
line = input().split(' ')
n = int(line[0])
t = int(line[1])
cells = [int(a) for a in input().split(' ')]
cell_index = 0
while cell_index < t - 1:
cell_index += cells[cell_index]
if cell_index == t - 1:
print('YES')
else:
print('NO')
| python | 9 | 0.584746 | 44 | 20.454545 | 11 | New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.
So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a_1, a_2, ..., a_{n} - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ a_{i} ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + a_{i}), and one can travel from cell i to cell (i + a_{i}) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + a_{i}) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ a_{i} ≤ n - i one can't leave the Line World using portals.
Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
-----Input-----
The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 10^4) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to.
The second line contains n - 1 space-separated integers a_1, a_2, ..., a_{n} - 1 (1 ≤ a_{i} ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
-----Output-----
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
-----Examples-----
Input
8 4
1 2 1 2 1 2 1
Output
YES
Input
8 5
1 2 1 2 1 1 1
Output
NO
-----Note-----
In the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.
In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit. | taco |
class Solution:
def Learning(self, arr, n):
p = 0
N = 0
z = 0
for i in range(n):
if arr[i] > 0:
p += 1
elif arr[i] < 0:
N += 1
else:
z += 1
p = n / p
N = n / N
z = n / z
if p % 1 == 0:
p = int(p)
else:
p = round(p, 5)
p = str(p)
if len(p) > 7:
p = p[:7]
if N % 1 == 0:
N = int(N)
else:
N = round(N, 5)
N = str(N)
if len(N) > 7:
N = N[:7]
if z % 1 == 0:
z = int(z)
else:
z = round(z, 5)
z = str(z)
if len(z) > 7:
z = z[:7]
return [p, N, z]
| python | 14 | 0.381041 | 28 | 13.157895 | 38 | Being a Programmer you have to learn how to make your output looks better. According to the company, its company programmers have to present its output in a different manner as: If your output is 10.000000 you can save the decimal places and thus your output becomes 10. Now u have the learn the way to output. You are given elements of an array A[N] and you have to divide N by total no. of +ve integers, N by total no. of -ve integers, and N by total no. of zero value integers.
Example 1:
Input :
N = 10
A[] = {7, 7, 7, 7, 7, 7, -9, -9, -9, 0}
Output :
1.66667
3.33333
10
Explanation :
Positive count = 6, therefore 10/6 = 1.66667
Negative count = 3, therefore 10/3 = 3.33333
Zero's count = 1, therefore 10/1 = 10
Your Task:
You don't need to read input or print anything. Your task is to complete the function Learning() which takes the array A[], its size N, pos, neg and zero as inputs and stores the answers in the reference variables pos, neg and zero the following:-
N by Total no. of +ve integers
N by Total no. of -ve integers
N by Total no. of zero value integers
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints :
1 ≤ N ≤ 10^{5}
-10^{5} ≤ A[i] ≤ 10^{5} | taco |
class Solution:
def findLongestConseqSubseq(self, arr, N):
from collections import Counter
dic = dict(Counter(arr))
longseq = 0
for i in arr:
curseq = 0
if i - 1 not in dic:
curnum = i
curseq = 1
while curnum + 1 in dic:
curnum += 1
curseq += 1
longseq = max(longseq, curseq)
return longseq
| python | 13 | 0.625749 | 43 | 19.875 | 16 | Given an array of positive integers. Find the length of the longest sub-sequence such that elements in the subsequence are consecutive integers, the consecutive numbers can be in any order.
Example 1:
Input:
N = 7
a[] = {2,6,1,9,4,5,3}
Output:
6
Explanation:
The consecutive numbers here
are 1, 2, 3, 4, 5, 6. These 6
numbers form the longest consecutive
subsquence.
Example 2:
Input:
N = 7
a[] = {1,9,3,10,4,20,2}
Output:
4
Explanation:
1, 2, 3, 4 is the longest
consecutive subsequence.
Your Task:
You don't need to read input or print anything. Your task is to complete the function findLongestConseqSubseq() which takes the array arr[] and the size of the array as inputs and returns the length of the longest subsequence of consecutive integers.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 <= N <= 10^{5}
0 <= a[i] <= 10^{5} | taco |
(m, n) = map(int, input().split())
L1 = list(map(int, input().split()))
L2 = list(map(int, input().split()))
A = [0] * 10
B = [0] * 10
FLAG = 0
for i in range(m):
A[L1[i]] += 1
for i in range(n):
B[L2[i]] += 1
for i in range(10):
if A[i] > 0 and B[i] > 0:
print(i)
FLAG = 1
break
if FLAG == 0:
Z = min(L1)
Y = min(L2)
if Z < Y:
print(Z, end='')
print(Y)
elif Z > Y:
print(Y, end='')
print(Z)
| python | 11 | 0.503632 | 36 | 16.208333 | 24 | You are given two lists of non-zero digits.
Let's call an integer pretty if its (base 10) representation has at least one digit from the first list and at least one digit from the second list. What is the smallest positive pretty integer?
-----Input-----
The first line contains two integers n and m (1 ≤ n, m ≤ 9) — the lengths of the first and the second lists, respectively.
The second line contains n distinct digits a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 9) — the elements of the first list.
The third line contains m distinct digits b_1, b_2, ..., b_{m} (1 ≤ b_{i} ≤ 9) — the elements of the second list.
-----Output-----
Print the smallest pretty integer.
-----Examples-----
Input
2 3
4 2
5 7 6
Output
25
Input
8 8
1 2 3 4 5 6 7 8
8 7 6 5 4 3 2 1
Output
1
-----Note-----
In the first example 25, 46, 24567 are pretty, as well as many other integers. The smallest among them is 25. 42 and 24 are not pretty because they don't have digits from the second list.
In the second example all integers that have at least one digit different from 9 are pretty. It's obvious that the smallest among them is 1, because it's the smallest positive integer. | taco |
from math import gcd, sqrt, log
def isPower(num, base):
power = int(log(num, base) + 0.5)
return base ** power == num
for _ in range(int(input())):
a = int(input())
ans = bin(a).split('b')[1]
if isPower(a + 1, 2):
flag = False
for x in range(2, int(sqrt(a // 2)) + 2):
if a % x == 0:
ans = a // x
flag = True
break
print(ans if flag else 1)
else:
new = '0b'
b = bin(a).split('b')[1]
for x in b:
if x is '1':
new += '0'
else:
new += '1'
b = int(new, 2)
print(gcd(a ^ b, a & b))
| python | 14 | 0.512287 | 43 | 19.346154 | 26 | Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question.
Suppose you are given a positive integer $a$. You want to choose some integer $b$ from $1$ to $a - 1$ inclusive in such a way that the greatest common divisor (GCD) of integers $a \oplus b$ and $a \> \& \> b$ is as large as possible. In other words, you'd like to compute the following function:
$$f(a) = \max_{0 < b < a}{gcd(a \oplus b, a \> \& \> b)}.$$
Here $\oplus$ denotes the bitwise XOR operation, and $\&$ denotes the bitwise AND operation.
The greatest common divisor of two integers $x$ and $y$ is the largest integer $g$ such that both $x$ and $y$ are divided by $g$ without remainder.
You are given $q$ integers $a_1, a_2, \ldots, a_q$. For each of these integers compute the largest possible value of the greatest common divisor (when $b$ is chosen optimally).
-----Input-----
The first line contains an integer $q$ ($1 \le q \le 10^3$) — the number of integers you need to compute the answer for.
After that $q$ integers are given, one per line: $a_1, a_2, \ldots, a_q$ ($2 \le a_i \le 2^{25} - 1$) — the integers you need to compute the answer for.
-----Output-----
For each integer, print the answer in the same order as the integers are given in input.
-----Example-----
Input
3
2
3
5
Output
3
1
7
-----Note-----
For the first integer the optimal choice is $b = 1$, then $a \oplus b = 3$, $a \> \& \> b = 0$, and the greatest common divisor of $3$ and $0$ is $3$.
For the second integer one optimal choice is $b = 2$, then $a \oplus b = 1$, $a \> \& \> b = 2$, and the greatest common divisor of $1$ and $2$ is $1$.
For the third integer the optimal choice is $b = 2$, then $a \oplus b = 7$, $a \> \& \> b = 0$, and the greatest common divisor of $7$ and $0$ is $7$. | taco |
def computeGCD(x, y):
while y:
(x, y) = (y, x % y)
return x
li = [2, 6]
r = [3, 4]
n = 40
for i in range(4, n):
pro = computeGCD(li[-1], i)
if pro != i:
k = li[-1] * i // pro
li.append(k)
l = i
while k % l == 0:
l = l + 1
r.append(l)
mod = 10 ** 9 + 7
for _ in range(int(input())):
n = int(input())
k = (n + 1) // 2
ans = 2 * k
ans = ans + 3 * (n // 2)
for i in range(1, len(li)):
a = n // li[i]
ans = (ans + a * r[i] - a * r[i - 1]) % mod
print(ans)
| python | 13 | 0.447917 | 45 | 17.461538 | 26 | Let $f(i)$ denote the minimum positive integer $x$ such that $x$ is not a divisor of $i$.
Compute $\sum_{i=1}^n f(i)$ modulo $10^9+7$. In other words, compute $f(1)+f(2)+\dots+f(n)$ modulo $10^9+7$.
-----Input-----
The first line contains a single integer $t$ ($1\leq t\leq 10^4$), the number of test cases. Then $t$ cases follow.
The only line of each test case contains a single integer $n$ ($1\leq n\leq 10^{16}$).
-----Output-----
For each test case, output a single integer $ans$, where $ans=\sum_{i=1}^n f(i)$ modulo $10^9+7$.
-----Examples-----
Input
6
1
2
3
4
10
10000000000000000
Output
2
5
7
10
26
366580019
-----Note-----
In the fourth test case $n=4$, so $ans=f(1)+f(2)+f(3)+f(4)$.
$1$ is a divisor of $1$ but $2$ isn't, so $2$ is the minimum positive integer that isn't a divisor of $1$. Thus, $f(1)=2$.
$1$ and $2$ are divisors of $2$ but $3$ isn't, so $3$ is the minimum positive integer that isn't a divisor of $2$. Thus, $f(2)=3$.
$1$ is a divisor of $3$ but $2$ isn't, so $2$ is the minimum positive integer that isn't a divisor of $3$. Thus, $f(3)=2$.
$1$ and $2$ are divisors of $4$ but $3$ isn't, so $3$ is the minimum positive integer that isn't a divisor of $4$. Thus, $f(4)=3$.
Therefore, $ans=f(1)+f(2)+f(3)+f(4)=2+3+2+3=10$. | taco |
def recurse(A, maxim):
if len(A) > 1:
return maxim - A[0] + recurse(A[1:], maxim)
else:
return maxim - A[0]
n = int(input())
A = list(map(int, input().split()))
maximum = max(A)
print(recurse(A, maximum))
| python | 11 | 0.606635 | 45 | 22.444444 | 9 | In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury.
Totally in Berland there are n citizens, the welfare of each of them is estimated as the integer in a_{i} burles (burle is the currency in Berland).
You are the royal treasurer, which needs to count the minimum charges of the kingdom on the king's present. The king can only give money, he hasn't a power to take away them.
-----Input-----
The first line contains the integer n (1 ≤ n ≤ 100) — the number of citizens in the kingdom.
The second line contains n integers a_1, a_2, ..., a_{n}, where a_{i} (0 ≤ a_{i} ≤ 10^6) — the welfare of the i-th citizen.
-----Output-----
In the only line print the integer S — the minimum number of burles which are had to spend.
-----Examples-----
Input
5
0 1 2 3 4
Output
10
Input
5
1 1 0 1 1
Output
1
Input
3
1 3 1
Output
4
Input
1
12
Output
0
-----Note-----
In the first example if we add to the first citizen 4 burles, to the second 3, to the third 2 and to the fourth 1, then the welfare of all citizens will equal 4.
In the second example it is enough to give one burle to the third citizen.
In the third example it is necessary to give two burles to the first and the third citizens to make the welfare of citizens equal 3.
In the fourth example it is possible to give nothing to everyone because all citizens have 12 burles. | taco |
x = int(input()[-1])
if x in [2, 4, 5, 7, 9]:
print('hon')
elif x in [0, 1, 6, 8]:
print('pon')
else:
print('bon')
| python | 8 | 0.5 | 24 | 15.857143 | 7 | The cat Snuke wants to play a popular Japanese game called ÅtCoder, so Iroha has decided to teach him Japanese.
When counting pencils in Japanese, the counter word "本" follows the number. The pronunciation of this word varies depending on the number. Specifically, the pronunciation of "本" in the phrase "N 本" for a positive integer N not exceeding 999 is as follows:
- hon when the digit in the one's place of N is 2, 4, 5, 7, or 9;
- pon when the digit in the one's place of N is 0, 1, 6 or 8;
- bon when the digit in the one's place of N is 3.
Given N, print the pronunciation of "本" in the phrase "N 本".
-----Constraints-----
- N is a positive integer not exceeding 999.
-----Input-----
Input is given from Standard Input in the following format:
N
-----Output-----
Print the answer.
-----Sample Input-----
16
-----Sample Output-----
pon
The digit in the one's place of 16 is 6, so the "本" in "16 本" is pronounced pon. | taco |
def stability(array):
return max(array) - min(array)
def remove_to_stabilize(num, array):
max_val = max(array)
min_val = min(array)
array.remove(max_val)
max_array_stab = stability(array)
array.append(max_val)
array.remove(min_val)
min_array_stab = stability(array)
array.append(min_val)
if max_array_stab > min_array_stab:
array.remove(min_val)
else:
array.remove(max_val)
return array
num = int(input())
array = [int(x) for x in input().split()]
removed = remove_to_stabilize(num, array)
print(stability(removed))
| python | 9 | 0.711069 | 41 | 24.380952 | 21 | You are given an array $a$ consisting of $n$ integer numbers.
Let instability of the array be the following value: $\max\limits_{i = 1}^{n} a_i - \min\limits_{i = 1}^{n} a_i$.
You have to remove exactly one element from this array to minimize instability of the resulting $(n-1)$-elements array. Your task is to calculate the minimum possible instability.
-----Input-----
The first line of the input contains one integer $n$ ($2 \le n \le 10^5$) — the number of elements in the array $a$.
The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^5$) — elements of the array $a$.
-----Output-----
Print one integer — the minimum possible instability of the array if you have to remove exactly one element from the array $a$.
-----Examples-----
Input
4
1 3 3 7
Output
2
Input
2
1 100000
Output
0
-----Note-----
In the first example you can remove $7$ then instability of the remaining array will be $3 - 1 = 2$.
In the second example you can remove either $1$ or $100000$ then instability of the remaining array will be $100000 - 100000 = 0$ and $1 - 1 = 0$ correspondingly. | taco |
d = {}
(n, kt) = map(int, input().split())
k = []
for i in range(n):
(a, b) = map(int, input().split())
k.append((a, b))
k.sort(key=lambda x: (x[0], -x[1]), reverse=True)
c = 1
s = 0
rad = 0
for i in range(len(k)):
try:
if k[i] == k[i + 1]:
c += 1
else:
d[s + 1, rad + 1] = c
c = 1
s = rad + 1
except:
d[s + 1, rad + 1] = c
c = 1
s = rad + 1
pass
rad += 1
for i in d.keys():
if i[0] <= kt and kt <= i[1]:
print(d[i])
break
| python | 12 | 0.45733 | 49 | 15.321429 | 28 | Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.
You know the rules of comparing the results of two given teams very well. Let's say that team a solved pa problems with total penalty time ta and team b solved pb problems with total penalty time tb. Team a gets a higher place than team b in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team a gets a higher place than team b in the final results' table if either pa > pb, or pa = pb and ta < tb.
It is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of x teams that solved the same number of problems with the same penalty time. Let's also say that y teams performed better than the teams from this group. In this case all teams from the group share places y + 1, y + 2, ..., y + x. The teams that performed worse than the teams from this group, get their places in the results table starting from the y + x + 1-th place.
Your task is to count what number of teams from the given list shared the k-th place.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 50). Then n lines contain the description of the teams: the i-th line contains two integers pi and ti (1 ≤ pi, ti ≤ 50) — the number of solved problems and the total penalty time of the i-th team, correspondingly. All numbers in the lines are separated by spaces.
Output
In the only line print the sought number of teams that got the k-th place in the final results' table.
Examples
Input
7 2
4 10
4 10
4 10
3 20
2 1
2 1
1 10
Output
3
Input
5 4
3 1
3 1
5 3
3 1
3 1
Output
4
Note
The final results' table for the first sample is:
* 1-3 places — 4 solved problems, the penalty time equals 10
* 4 place — 3 solved problems, the penalty time equals 20
* 5-6 places — 2 solved problems, the penalty time equals 1
* 7 place — 1 solved problem, the penalty time equals 10
The table shows that the second place is shared by the teams that solved 4 problems with penalty time 10. There are 3 such teams.
The final table for the second sample is:
* 1 place — 5 solved problems, the penalty time equals 3
* 2-5 places — 3 solved problems, the penalty time equals 1
The table shows that the fourth place is shared by the teams that solved 3 problems with penalty time 1. There are 4 such teams. | taco |
G = lambda : list(map(int, input().split()))[1:]
n = int(input())
tmp = set(G() + G())
if n > len(tmp):
print('Oh, my keyboard!')
else:
print('I become the guy.')
| python | 13 | 0.563636 | 48 | 22.571429 | 7 | There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game.
Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass and the indices of levels Little Y can pass. Will Little X and Little Y pass the whole game, if they cooperate each other?
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 100).
The next line contains an integer p (0 ≤ p ≤ n) at first, then follows p distinct integers a_1, a_2, ..., a_{p} (1 ≤ a_{i} ≤ n). These integers denote the indices of levels Little X can pass. The next line contains the levels Little Y can pass in the same format. It's assumed that levels are numbered from 1 to n.
-----Output-----
If they can pass all the levels, print "I become the guy.". If it's impossible, print "Oh, my keyboard!" (without the quotes).
-----Examples-----
Input
4
3 1 2 3
2 2 4
Output
I become the guy.
Input
4
3 1 2 3
2 2 3
Output
Oh, my keyboard!
-----Note-----
In the first sample, Little X can pass levels [1 2 3], and Little Y can pass level [2 4], so they can pass all the levels both.
In the second sample, no one can pass level 4. | taco |
count = int(input())
def sum(l, i):
l01 = l[i] + (len(l) - l[-1]) - (i + 1 - l[i])
l10 = i + 1 - l[i] + (l[-1] - l[i])
return min(l01, l10)
for i in range(count):
line = input()
l = [0] * len(line)
for (i, s) in enumerate(line):
if i == 0:
l[0] = 1 if s == '0' else 0
else:
l[i] = l[i - 1] + 1 if s == '0' else l[i - 1]
ar = [sum(l, j) for j in range(len(l))]
print(min(ar))
| python | 14 | 0.469543 | 48 | 23.625 | 16 | Shubham has a binary string $s$. A binary string is a string containing only characters "0" and "1".
He can perform the following operation on the string any amount of times: Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa.
A string is called good if it does not contain "010" or "101" as a subsequence — for instance, "1001" contains "101" as a subsequence, hence it is not a good string, while "1000" doesn't contain neither "010" nor "101" as subsequences, so it is a good string.
What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.
A string $a$ is a subsequence of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters.
-----Input-----
The first line of the input contains a single integer $t$ $(1\le t \le 100)$ — the number of test cases.
Each of the next $t$ lines contains a binary string $s$ $(1 \le |s| \le 1000)$.
-----Output-----
For every string, output the minimum number of operations required to make it good.
-----Example-----
Input
7
001
100
101
010
0
1
001100
Output
0
0
1
1
0
0
2
-----Note-----
In test cases $1$, $2$, $5$, $6$ no operations are required since they are already good strings.
For the $3$rd test case: "001" can be achieved by flipping the first character — and is one of the possible ways to get a good string.
For the $4$th test case: "000" can be achieved by flipping the second character — and is one of the possible ways to get a good string.
For the $7$th test case: "000000" can be achieved by flipping the third and fourth characters — and is one of the possible ways to get a good string. | taco |
s = int(input())
if s <= 5:
print(1)
else:
ost = s // 5
ost2 = s % 5
if ost2 > 0:
print(ost + 1)
else:
print(ost)
| python | 10 | 0.504065 | 16 | 11.3 | 10 | An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order to get to his friend's house.
-----Input-----
The first line of the input contains an integer x (1 ≤ x ≤ 1 000 000) — The coordinate of the friend's house.
-----Output-----
Print the minimum number of steps that elephant needs to make to get from point 0 to point x.
-----Examples-----
Input
5
Output
1
Input
12
Output
3
-----Note-----
In the first sample the elephant needs to make one step of length 5 to reach the point x.
In the second sample the elephant can get to point x if he moves by 3, 5 and 4. There are other ways to get the optimal answer but the elephant cannot reach x in less than three moves. | taco |
import sys
input = sys.stdin.readline
def iinput():
return int(input())
def sinput():
return input().rstrip()
def i0input():
return int(input()) - 1
def linput():
return list(input().split())
def liinput():
return list(map(int, input().split()))
def miinput():
return map(int, input().split())
def li0input():
return list(map(lambda x: int(x) - 1, input().split()))
def mi0input():
return map(lambda x: int(x) - 1, input().split())
INF = 10 ** 20
MOD = 1000000007
t = iinput()
for _ in [0] * t:
(x1, p1) = liinput()
(x2, p2) = liinput()
l1 = len(str(x1)) + p1
l2 = len(str(x2)) + p2
if l1 > l2:
print('>')
elif l1 < l2:
print('<')
else:
l1 = max(0, len(str(x2)) - len(str(x1)))
l2 = max(0, len(str(x1)) - len(str(x2)))
x1 *= 10 ** l1
x2 *= 10 ** l2
if x1 > x2:
print('>')
elif x1 < x2:
print('<')
else:
print('=')
| python | 15 | 0.5625 | 56 | 16.632653 | 49 | Monocarp wrote down two numbers on a whiteboard. Both numbers follow a specific format: a positive integer $x$ with $p$ zeros appended to its end.
Now Monocarp asks you to compare these two numbers. Can you help him?
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of testcases.
The first line of each testcase contains two integers $x_1$ and $p_1$ ($1 \le x_1 \le 10^6; 0 \le p_1 \le 10^6$) — the description of the first number.
The second line of each testcase contains two integers $x_2$ and $p_2$ ($1 \le x_2 \le 10^6; 0 \le p_2 \le 10^6$) — the description of the second number.
-----Output-----
For each testcase print the result of the comparison of the given two numbers. If the first number is smaller than the second one, print '<'. If the first number is greater than the second one, print '>'. If they are equal, print '='.
-----Examples-----
Input
5
2 1
19 0
10 2
100 1
1999 0
2 3
1 0
1 0
99 0
1 2
Output
>
=
<
=
<
-----Note-----
The comparisons in the example are: $20 > 19$, $1000 = 1000$, $1999 < 2000$, $1 = 1$, $99 < 100$. | taco |
for _ in range(int(input())):
(n, k) = list(map(int, input().split()))
flag = False
for i in range(k - 1):
ma = float('-inf')
mi = float('inf')
temp = n
while temp // 10 > 0:
a = temp % 10
ma = max(ma, a)
mi = min(mi, a)
temp = temp // 10
ma = max(ma, temp)
mi = min(mi, temp)
if mi == 0:
break
n = n + mi * ma
print(n)
| python | 13 | 0.495775 | 41 | 18.722222 | 18 | Let's define the following recurrence: $$a_{n+1} = a_{n} + minDigit(a_{n}) \cdot maxDigit(a_{n}).$$
Here $minDigit(x)$ and $maxDigit(x)$ are the minimal and maximal digits in the decimal representation of $x$ without leading zeroes. For examples refer to notes.
Your task is calculate $a_{K}$ for given $a_{1}$ and $K$.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 1000$) — the number of independent test cases.
Each test case consists of a single line containing two integers $a_{1}$ and $K$ ($1 \le a_{1} \le 10^{18}$, $1 \le K \le 10^{16}$) separated by a space.
-----Output-----
For each test case print one integer $a_{K}$ on a separate line.
-----Example-----
Input
8
1 4
487 1
487 2
487 3
487 4
487 5
487 6
487 7
Output
42
487
519
528
544
564
588
628
-----Note-----
$a_{1} = 487$
$a_{2} = a_{1} + minDigit(a_{1}) \cdot maxDigit(a_{1}) = 487 + \min (4, 8, 7) \cdot \max (4, 8, 7) = 487 + 4 \cdot 8 = 519$
$a_{3} = a_{2} + minDigit(a_{2}) \cdot maxDigit(a_{2}) = 519 + \min (5, 1, 9) \cdot \max (5, 1, 9) = 519 + 1 \cdot 9 = 528$
$a_{4} = a_{3} + minDigit(a_{3}) \cdot maxDigit(a_{3}) = 528 + \min (5, 2, 8) \cdot \max (5, 2, 8) = 528 + 2 \cdot 8 = 544$
$a_{5} = a_{4} + minDigit(a_{4}) \cdot maxDigit(a_{4}) = 544 + \min (5, 4, 4) \cdot \max (5, 4, 4) = 544 + 4 \cdot 5 = 564$
$a_{6} = a_{5} + minDigit(a_{5}) \cdot maxDigit(a_{5}) = 564 + \min (5, 6, 4) \cdot \max (5, 6, 4) = 564 + 4 \cdot 6 = 588$
$a_{7} = a_{6} + minDigit(a_{6}) \cdot maxDigit(a_{6}) = 588 + \min (5, 8, 8) \cdot \max (5, 8, 8) = 588 + 5 \cdot 8 = 628$ | taco |
teams = []
n = int(input())
for i in range(n):
teams.append(list(map(int, input().strip().split())))
n_guest = 0
for i in range(n):
matches = list(teams)
matches.pop(i)
for match in matches:
if teams[i][0] == match[1]:
n_guest += 1
print(n_guest)
| python | 16 | 0.617188 | 54 | 20.333333 | 12 | Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as a guest on somebody else's stadium, the players put on the guest uniform. The only exception to that rule is: when the home uniform color of the host team matches the guests' uniform, the host team puts on its guest uniform as well. For each team the color of the home and guest uniform is different.
There are n teams taking part in the national championship. The championship consists of n·(n - 1) games: each team invites each other team to its stadium. At this point Manao wondered: how many times during the championship is a host team going to put on the guest uniform? Note that the order of the games does not affect this number.
You know the colors of the home and guest uniform for each team. For simplicity, the colors are numbered by integers in such a way that no two distinct colors have the same number. Help Manao find the answer to his question.
-----Input-----
The first line contains an integer n (2 ≤ n ≤ 30). Each of the following n lines contains a pair of distinct space-separated integers h_{i}, a_{i} (1 ≤ h_{i}, a_{i} ≤ 100) — the colors of the i-th team's home and guest uniforms, respectively.
-----Output-----
In a single line print the number of games where the host team is going to play in the guest uniform.
-----Examples-----
Input
3
1 2
2 4
3 4
Output
1
Input
4
100 42
42 100
5 42
100 5
Output
5
Input
2
1 2
1 2
Output
0
-----Note-----
In the first test case the championship consists of 6 games. The only game with the event in question is the game between teams 2 and 1 on the stadium of team 2.
In the second test sample the host team will have to wear guest uniform in the games between teams: 1 and 2, 2 and 1, 2 and 3, 3 and 4, 4 and 2 (the host team is written first). | taco |
def solve(s):
ans = []
for ab in s.split('\n'):
(carry, carried) = (0, 0)
for (a, b) in zip(*map(lambda ss: map(int, ss[::-1]), ab.split())):
carried += a + b
carry += carried > 9
carried //= 10
ans.append(carry)
return '\n'.join(('No carry operation' if not c else '%d carry operations' % c for c in ans))
| python | 17 | 0.569231 | 94 | 31.5 | 10 | In elementary arithmetic a "carry" is a digit that is transferred from one column of digits to another column of more significant digits during a calculation algorithm.
This Kata is about determining the number of carries performed during the addition of multi-digit numbers.
You will receive an input string containing a set of pairs of numbers formatted as follows:
```
123 456
555 555
123 594
```
And your output should be a string formatted as follows:
```
No carry operation
1 carry operations
3 carry operations
```
###Some Assumptions
- Assume that numbers can be of any length.
- But both numbers in the pair will be of the same length.
- Although not all the numbers in the set need to be of the same length.
- If a number is shorter, it will be zero-padded.
- The input may contain any arbitrary number of pairs. | taco |
from itertools import groupby
for _ in range(int(input())):
ans = 0
lw = input()
arr = input().strip('.')
l = 0
r = len(arr) - 1
left = 0
right = 0
if len(arr) != 0:
if arr[r] == '*':
right += 1
if arr[0] == '*':
left += 1
while l < r:
if left <= right:
l += 1
if arr[l] == '*':
left += 1
else:
ans += left
else:
r -= 1
if arr[r] == '*':
right += 1
else:
ans += right
print(ans)
else:
print(0)
| python | 15 | 0.449893 | 29 | 14.633333 | 30 | You are playing the game "Arranging The Sheep". The goal of this game is to make the sheep line up. The level in the game is described by a string of length $n$, consisting of the characters '.' (empty space) and '*' (sheep). In one move, you can move any sheep one square to the left or one square to the right, if the corresponding square exists and is empty. The game ends as soon as the sheep are lined up, that is, there should be no empty cells between any sheep.
For example, if $n=6$ and the level is described by the string "**.*..", then the following game scenario is possible:
the sheep at the $4$ position moves to the right, the state of the level: "**..*.";
the sheep at the $2$ position moves to the right, the state of the level: "*.*.*.";
the sheep at the $1$ position moves to the right, the state of the level: ".**.*.";
the sheep at the $3$ position moves to the right, the state of the level: ".*.**.";
the sheep at the $2$ position moves to the right, the state of the level: "..***.";
the sheep are lined up and the game ends.
For a given level, determine the minimum number of moves you need to make to complete the level.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 10^4$). Then $t$ test cases follow.
The first line of each test case contains one integer $n$ ($1 \le n \le 10^6$).
The second line of each test case contains a string of length $n$, consisting of the characters '.' (empty space) and '*' (sheep) — the description of the level.
It is guaranteed that the sum of $n$ over all test cases does not exceed $10^6$.
-----Output-----
For each test case output the minimum number of moves you need to make to complete the level.
-----Examples-----
Input
5
6
**.*..
5
*****
3
.*.
3
...
10
*.*...*.**
Output
1
0
0
0
9
-----Note-----
None | taco |
for _ in range(int(input())):
n = int(input())
check = [i for i in range(n)]
A = list(map(int, input().split()))
count = True
while count:
count = False
for i in range(n):
x = A.index(i + 1)
while x != 0 and x in check and (A[x - 1] > A[x]):
count = True
(A[x], A[x - 1]) = (A[x - 1], A[x])
check.remove(x)
x -= 1
for i in range(n - 1):
print(A[i], end=' ')
print(A[-1])
| python | 14 | 0.504926 | 53 | 22.882353 | 17 | You are given a permutation of length $n$. Recall that the permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2, 3, 1, 5, 4]$ is a permutation, but $[1, 2, 2]$ is not a permutation ($2$ appears twice in the array) and $[1, 3, 4]$ is also not a permutation ($n=3$ but there is $4$ in the array).
You can perform at most $n-1$ operations with the given permutation (it is possible that you don't perform any operations at all). The $i$-th operation allows you to swap elements of the given permutation on positions $i$ and $i+1$. Each operation can be performed at most once. The operations can be performed in arbitrary order.
Your task is to find the lexicographically minimum possible permutation obtained by performing some of the given operations in some order.
You can see the definition of the lexicographical order in the notes section.
You have to answer $q$ independent test cases.
For example, let's consider the permutation $[5, 4, 1, 3, 2]$. The minimum possible permutation we can obtain is $[1, 5, 2, 4, 3]$ and we can do it in the following way:
perform the second operation (swap the second and the third elements) and obtain the permutation $[5, 1, 4, 3, 2]$; perform the fourth operation (swap the fourth and the fifth elements) and obtain the permutation $[5, 1, 4, 2, 3]$; perform the third operation (swap the third and the fourth elements) and obtain the permutation $[5, 1, 2, 4, 3]$. perform the first operation (swap the first and the second elements) and obtain the permutation $[1, 5, 2, 4, 3]$;
Another example is $[1, 2, 4, 3]$. The minimum possible permutation we can obtain is $[1, 2, 3, 4]$ by performing the third operation (swap the third and the fourth elements).
-----Input-----
The first line of the input contains one integer $q$ ($1 \le q \le 100$) — the number of test cases. Then $q$ test cases follow.
The first line of the test case contains one integer $n$ ($1 \le n \le 100$) — the number of elements in the permutation.
The second line of the test case contains $n$ distinct integers from $1$ to $n$ — the given permutation.
-----Output-----
For each test case, print the answer on it — the lexicograhically minimum possible permutation obtained by performing some of the given operations in some order.
-----Example-----
Input
4
5
5 4 1 3 2
4
1 2 4 3
1
1
4
4 3 2 1
Output
1 5 2 4 3
1 2 3 4
1
1 4 3 2
-----Note-----
Recall that the permutation $p$ of length $n$ is lexicographically less than the permutation $q$ of length $n$ if there is such index $i \le n$ that for all $j$ from $1$ to $i - 1$ the condition $p_j = q_j$ is satisfied, and $p_i < q_i$. For example:
$p = [1, 3, 5, 2, 4]$ is less than $q = [1, 3, 5, 4, 2]$ (such $i=4$ exists, that $p_i < q_i$ and for each $j < i$ holds $p_j = q_j$), $p = [1, 2]$ is less than $q = [2, 1]$ (such $i=1$ exists, that $p_i < q_i$ and for each $j < i$ holds $p_j = q_j$). | taco |
import java.util.Scanner;
import static java.lang.Math.ceil;
import static java.lang.Math.sqrt;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int numberOfCases = sc.nextInt();
for (int i = 0; i < numberOfCases; i++) {
long number = sc.nextInt();
long nearestIndex = (long) ceil(sqrt(number));
long nearestValue = (nearestIndex - 1L) * nearestIndex + 1L;
long columnNumber;
long rowNumber;
if (number > nearestValue) {
columnNumber = nearestIndex - (number - nearestValue);
rowNumber = nearestIndex;
} else if (number < nearestValue) {
columnNumber = nearestIndex;
rowNumber = nearestIndex - (nearestValue - number);
} else {
columnNumber = nearestIndex;
rowNumber = nearestIndex;
}
System.out.println(rowNumber + " " + columnNumber);
}
}
} | java | 15 | 0.530706 | 72 | 14.380282 | 71 | C. Infinity Tabletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has found a table having an infinite number of rows and columns. The rows are numbered from $$$1$$$, starting from the topmost one. The columns are numbered from $$$1$$$, starting from the leftmost one.Initially, the table hasn't been filled and Polycarp wants to fix it. He writes integers from $$$1$$$ and so on to the table as follows. The figure shows the placement of the numbers from $$$1$$$ to $$$10$$$. The following actions are denoted by the arrows. The leftmost topmost cell of the table is filled with the number $$$1$$$. Then he writes in the table all positive integers beginning from $$$2$$$ sequentially using the following algorithm.First, Polycarp selects the leftmost non-filled cell in the first row and fills it. Then, while the left neighbor of the last filled cell is filled, he goes down and fills the next cell. So he goes down until the last filled cell has a non-filled neighbor to the left (look at the vertical arrow going down in the figure above).After that, he fills the cells from the right to the left until he stops at the first column (look at the horizontal row in the figure above). Then Polycarp selects the leftmost non-filled cell in the first row, goes down, and so on.A friend of Polycarp has a favorite number $$$k$$$. He wants to know which cell will contain the number. Help him to find the indices of the row and the column, such that the intersection of the row and the column is the cell containing the number $$$k$$$.InputThe first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow.Each test case consists of one line containing one integer $$$k$$$ ($$$1 \le k \le 10^9$$$) which location must be found.OutputFor each test case, output in a separate line two integers $$$r$$$ and $$$c$$$ ($$$r, c \ge 1$$$) separated by spaces — the indices of the row and the column containing the cell filled by the number $$$k$$$, respectively.ExampleInput
7
11
14
5
4
1
2
1000000000
Output
2 4
4 3
1 3
2 1
1 1
1 2
31623 14130 | cf |
import copy
def calprofit(lines_removed, j):
lines_set = copy.deepcopy(differentline[j])
iterator = 0
while iterator < len(lines_set) and lines_removed > 0:
possible = min(lines_set[iterator], lines_removed)
lines_set[iterator] = lines_set[iterator] - possible
lines_removed = lines_removed - possible
iterator = iterator + 1
if lines_removed > 0:
return 0
sum1 = 0
for iterator1 in range(len(lines_set)):
sum1 = sum1 + lines_set[iterator1]
sum2 = 0
temp = [0] * (len(lines_set) + 1)
for iterator2 in range(len(lines_set)):
temp[iterator2] = lines_set[iterator2] * (sum1 - lines_set[iterator2])
sum2 = sum2 + temp[iterator2]
sum2 = sum2 // 2
sum3 = 0
for iterator3 in range(len(lines_set)):
sum3 = sum3 + lines_set[iterator3] * (sum2 - temp[iterator3])
sum3 = sum3 // 3
return sum3
for i in range(int(input())):
(n, c, k) = [int(i) for i in input().split()]
color = []
for i in range(c + 1):
color.append(dict())
for i in range(n):
(a, b, co) = [int(i) for i in input().split()]
if color[co].get(a, 0):
color[co][a] = color[co][a] + 1
else:
color[co][a] = 1
differentline = []
for i in color:
chk = list(i.values())
chk.sort()
differentline.append(chk)
weight = [0] + [int(i) for i in input().split()]
profit = []
dp = []
for i in range(k + 1):
profitdemo = []
dpdemo = []
for j in range(c + 1):
profitdemo.append(-1)
if j == 0:
dpdemo.append(0)
else:
dpdemo.append(10 ** 20 + 7)
profit.append(profitdemo)
dp.append(dpdemo)
for i in range(k + 1):
for j in range(1, c + 1):
removable_item = i // weight[j]
for lines_removed in range(removable_item + 1):
demo = lines_removed * weight[j]
if profit[lines_removed][j] == -1:
profit[lines_removed][j] = calprofit(lines_removed, j)
dp[i][j] = min(dp[i][j], dp[i - demo][j - 1] + profit[lines_removed][j])
print(dp[k][c])
| python | 17 | 0.619022 | 76 | 27.953846 | 65 | After failing to clear his school mathematics examination, infinitepro decided to prepare very hard for his upcoming re-exam, starting with the topic he is weakest at ― computational geometry.
Being an artist, infinitepro has C$C$ pencils (numbered 1$1$ through C$C$); each of them draws with one of C$C$ distinct colours. He draws N$N$ lines (numbered 1$1$ through N$N$) in a 2D Cartesian coordinate system; for each valid i$i$, the i$i$-th line is drawn with the ci$c_i$-th pencil and it is described by the equation y=ai⋅x+bi$y = a_i \cdot x + b_i$.
Now, infinitepro calls a triangle truly-geometric if each of its sides is part of some line he drew and all three sides have the same colour. He wants to count these triangles, but there are too many of them! After a lot of consideration, he decided to erase a subset of the N$N$ lines he drew. He wants to do it with his eraser, which has length K$K$.
Whenever erasing a line with a colour i$i$, the length of the eraser decreases by Vi$V_i$. In other words, when the eraser has length k$k$ and we use it to erase a line with a colour i$i$, the length of the eraser decreases to k−Vi$k-V_i$; if k<Vi$k < V_i$, it is impossible to erase such a line.
Since infinitepro has to study for the re-exam, he wants to minimise the number of truly-geometric triangles. Can you help him find the minimum possible number of truly-geometric triangles which can be obtained by erasing a subset of the N$N$ lines in an optimal way? He promised a grand treat for you if he passes the examination!
-----Input-----
- The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows.
- The first line of the input contains three space-separated integers N$N$, C$C$ and K$K$.
- N$N$ lines follow. For each i$i$ (1≤i≤N$1 \le i \le N$), the i$i$-th of these lines contains three space-separated integers ai$a_i$, bi$b_i$ and ci$c_i$.
- The last line contains C$C$ space-separated integers V1,V2,…,VC$V_1, V_2, \ldots, V_C$.
-----Output-----
For each test case, print a single line containing one integer ― the smallest possible number of truly-geometric triangles after erasing lines.
-----Constraints-----
- 1≤T≤10$1 \le T \le 10$
- 1≤C≤N≤3,000$1 \le C \le N \le 3,000$
- 0≤K≤3,000$0 \le K \le 3,000$
- 0≤ai,bi≤109$0 \le a_i, b_i \le 10^9$ for each valid i$i$
- 1≤ci≤C$1 \le c_i \le C$ for each valid i$i$
- 0≤Vi≤K$0 \le V_i \le K$ for each valid i$i$
- no two lines coincide, regardless of their colours
- no three lines are concurrent
-----Subtasks-----
Subtask #1 (10 points):
- N≤10$N \le 10$
- K≤100$K \le 100$
Subtask 2 (15 points):
- V1=V2=…=VC$V_1 = V_2 = \ldots = V_C$
- no two lines are parallel
Subtask #3 (25 points): no two lines are parallel
Subtask #4 (50 points): original constraints
-----Example Input-----
2
7 2 13
1 10 1
1 14 2
6 4 1
2 2 1
0 12 2
2 11 2
0 6 1
8 10
6 1 20
1 5 1
2 11 1
4 0 1
6 8 1
0 11 1
3 3 1
9
-----Example Output-----
2
4
-----Explanation-----
Example case 1: We can remove exactly one line. Initially, we have 5$5$ truly geometric triangles (see the image below; red is colour 1$1$ and green is colour 2$2$).
- Removing any line with colour 2$2$ brings the total number of truly-geometric triangles down to 4+0=4$4+0=4$.
- Removing any line with colour 1$1$ brings the total number of truly-geometric triangles down to 1+1=2$1+1=2$.
Thus, the smallest number of truly-geometric triangles we can obtain is 2$2$.
Example case 2: We can remove at most 2$2$ lines and removing any 2$2$ lines gives us a total of 4$4$ truly-geometric triangles. | taco |
n = int(input())
data = list(map(int, input().split()))
def cal(data, n):
data.sort()
res = [0] * n
m = n // 2
res[0::2] = data[m:]
res[1::2] = data[:m]
ans = 0
for i in range(1, n, 2):
if i == n - 1:
break
if res[i - 1] > res[i] and res[i] < res[i + 1]:
ans += 1
print(ans)
s = ' '.join(list(map(str, res)))
print(s)
cal(data, n)
| python | 11 | 0.497159 | 49 | 17.526316 | 19 | This is the easy version of the problem. The difference between the versions is that in the easy version all prices $a_i$ are different. You can make hacks if and only if you solved both versions of the problem.
Today is Sage's birthday, and she will go shopping to buy ice spheres. All $n$ ice spheres are placed in a row and they are numbered from $1$ to $n$ from left to right. Each ice sphere has a positive integer price. In this version all prices are different.
An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.
You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered.
-----Input-----
The first line contains a single integer $n$ $(1 \le n \le 10^5)$ — the number of ice spheres in the shop.
The second line contains $n$ different integers $a_1, a_2, \dots, a_n$ $(1 \le a_i \le 10^9)$ — the prices of ice spheres.
-----Output-----
In the first line print the maximum number of ice spheres that Sage can buy.
In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them.
-----Example-----
Input
5
1 2 3 4 5
Output
2
3 1 4 2 5
-----Note-----
In the example it's not possible to place ice spheres in any order so that Sage would buy $3$ of them. If the ice spheres are placed like this $(3, 1, 4, 2, 5)$, then Sage will buy two spheres: one for $1$ and one for $2$, because they are cheap. | taco |
import sys
input = sys.stdin.readline
r = 'QWERTYUIOPASDFGHJKLZXCVBNM'
A = set(list(r))
a = set(list(r.lower()))
n = set(['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'])
c = set(['@', '#', '%', '&', '?'])
for i in range(int(input().strip())):
s = list(input().strip())
if len(s) < 10:
print('NO')
continue
aa = False
AA = False
CC = False
NN = False
if s[0] in a or s[-1] in a:
aa = True
for x in range(1, len(s) - 1):
if s[x] in A:
AA = True
elif s[x] in n:
NN = True
elif s[x] in c:
CC = True
elif s[x] in a:
aa = True
if not AA or not CC or (not NN) or (not aa):
print('NO')
continue
print('YES')
| python | 11 | 0.51944 | 59 | 19.741935 | 31 | Read problems statements in [Hindi], [Mandarin Chinese], [Russian], [Vietnamese], and [Bengali] as well.
Chef is planning to setup a secure password for his Codechef account. For a password to be secure the following conditions should be satisfied:
1) Password must contain at least one lower case letter $[a-z]$;
2) Password must contain at least one upper case letter $[A-Z]$ strictly inside, i.e. not as the first or the last character;
3) Password must contain at least one digit $[0-9]$ strictly inside;
4) Password must contain at least one special character from the set $\{$ '@', '\#', '%', '&', '?' $\}$ strictly inside;
5) Password must be at least $10$ characters in length, but it can be longer.
Chef has generated several strings and now wants you to check whether the passwords are secure based on the above criteria. Please help Chef in doing so.
------ Input ------
First line will contain $T$, number of testcases. Then the testcases follow.
Each testcase contains of a single line of input, string $S$.
------ Output ------
For each testcase, output in a single line "YES" if the password is secure and "NO" if it is not.
------ Constraints ------
$1 ≤ |S| ≤ 20$
All the characters in $S$ are one of the following: lower case letters $[a-z]$, upper case letters $[A-Z]$, digits $[0-9]$, special characters from the set $\{$ '@', '\#', '%', '&', '?' $\}$
Sum of length of strings over all tests is atmost $10^{6}$
----- Sample Input 1 ------
3
#cookOff#P1
U@code4CHEFINA
gR3@tPWD
----- Sample Output 1 ------
NO
YES
NO
----- explanation 1 ------
Example case 1: Condition $3$ is not satisfied, because the only digit is not strictly inside.
Example case 2: All conditions are satisfied.
Example case 3: Condition $5$ is not satisfied, because the length of this string is 8. | taco |
from math import log
from collections import defaultdict, deque
from sys import stdin, stdout
from bisect import bisect_left, bisect_right
from copy import deepcopy
inp = lambda : int(stdin.readline())
sip = lambda : stdin.readline()
mulip = lambda : map(int, stdin.readline().split())
lst = lambda : list(map(int, stdin.readline().split()))
slst = lambda : list(sip())
M = pow(10, 9) + 7
(n, m) = mulip()
A = []
B = [[0] * m for i in range(n)]
for i in range(n):
l = lst()
A.append(l)
k = []
for i in range(1, n):
for j in range(1, m):
if A != B:
if A[i][j] == 1 and A[i - 1][j] == 1 and (A[i - 1][j - 1] == 1) and (A[i][j - 1] == 1):
B[i - 1][j - 1] = 1
B[i - 1][j] = 1
B[i][j - 1] = 1
B[i][j] = 1
k.append([i, j])
if A == B:
if len(k) == 0:
print(0)
else:
print(len(k))
for l in k:
print(*l)
else:
print(-1)
| python | 15 | 0.554642 | 90 | 22.638889 | 36 | You are given two matrices $A$ and $B$. Each matrix contains exactly $n$ rows and $m$ columns. Each element of $A$ is either $0$ or $1$; each element of $B$ is initially $0$.
You may perform some operations with matrix $B$. During each operation, you choose any submatrix of $B$ having size $2 \times 2$, and replace every element in the chosen submatrix with $1$. In other words, you choose two integers $x$ and $y$ such that $1 \le x < n$ and $1 \le y < m$, and then set $B_{x, y}$, $B_{x, y + 1}$, $B_{x + 1, y}$ and $B_{x + 1, y + 1}$ to $1$.
Your goal is to make matrix $B$ equal to matrix $A$. Two matrices $A$ and $B$ are equal if and only if every element of matrix $A$ is equal to the corresponding element of matrix $B$.
Is it possible to make these matrices equal? If it is, you have to come up with a sequence of operations that makes $B$ equal to $A$. Note that you don't have to minimize the number of operations.
-----Input-----
The first line contains two integers $n$ and $m$ ($2 \le n, m \le 50$).
Then $n$ lines follow, each containing $m$ integers. The $j$-th integer in the $i$-th line is $A_{i, j}$. Each integer is either $0$ or $1$.
-----Output-----
If it is impossible to make $B$ equal to $A$, print one integer $-1$.
Otherwise, print any sequence of operations that transforms $B$ into $A$ in the following format: the first line should contain one integer $k$ — the number of operations, and then $k$ lines should follow, each line containing two integers $x$ and $y$ for the corresponding operation (set $B_{x, y}$, $B_{x, y + 1}$, $B_{x + 1, y}$ and $B_{x + 1, y + 1}$ to $1$). The condition $0 \le k \le 2500$ should hold.
-----Examples-----
Input
3 3
1 1 1
1 1 1
0 1 1
Output
3
1 1
1 2
2 2
Input
3 3
1 0 1
1 0 1
0 0 0
Output
-1
Input
3 2
0 0
0 0
0 0
Output
0
-----Note-----
The sequence of operations in the first example: $\begin{matrix} 0 & 0 & 0 & & 1 & 1 & 0 & & 1 & 1 & 1 & & 1 & 1 & 1 \\ 0 & 0 & 0 & \rightarrow & 1 & 1 & 0 & \rightarrow & 1 & 1 & 1 & \rightarrow & 1 & 1 & 1 \\ 0 & 0 & 0 & & 0 & 0 & 0 & & 0 & 0 & 0 & & 0 & 1 & 1 \end{matrix}$ | taco |
def bfs(mst, src):
q = [src]
parent = [None for _ in range(n)]
state = [-1 for _ in range(n)]
state[src] = 2
while q:
u = q.pop()
for (v, w) in mst[u]:
if state[v] == -1:
state[v] = 2
parent[v] = (u, w)
q.insert(0, v)
if v == n - 1:
return (parent, True)
state[u] = 1
return (parent, False)
def find(a, nodes):
if nodes[a][1] == a:
return a
else:
return find(nodes[a][1], nodes)
def union(a, b, nodes):
r1 = find(a, nodes)
r2 = find(b, nodes)
if r1 == r2:
return nodes
elif nodes[r1][0] > nodes[r2][0]:
nodes[r2][1] = r1
elif nodes[r1][0] < nodes[r2][0]:
nodes[r1][1] = r2
else:
nodes[r2][1] = r1
nodes[r1][0] += 1
return nodes
(n, m) = [int(i) for i in input().split()]
nodes = {}
for i in range(n):
nodes[i] = [0, i]
edges = []
for _ in range(m):
(a, b, w) = [int(i) for i in input().split()]
edges.append((a, b, w))
edges.sort(key=lambda x: x[2])
total = 0
mst = {}
for edge in edges:
(u, v, w) = edge
if find(u - 1, nodes) != find(v - 1, nodes):
union(u - 1, v - 1, nodes)
if u - 1 in mst:
mst[u - 1].add((v - 1, w))
else:
mst[u - 1] = {(v - 1, w)}
if v - 1 in mst:
mst[v - 1].add((u - 1, w))
else:
mst[v - 1] = {(u - 1, w)}
(parent, exisits) = bfs(mst, 0)
if exisits:
maxVal = parent[n - 1][1]
val = parent[n - 1][0]
while val != 0:
maxVal = max(maxVal, parent[val][1])
val = parent[val][0]
print(maxVal)
else:
print('NO PATH EXISTS')
| python | 13 | 0.528223 | 46 | 19.797101 | 69 | Jack has just moved to a new city called Rapture. He wants to use the public public transport system. The fare rules are as follows:
1.Each pair of connected stations has a fare assigned to it regardless of direction of travel.
2.If Jack travels from station A to station B, he only has to pay the difference between (the fare from A to B) and (the cumulative fare paid to reach station A), [fare(A,B) - total fare to reach station A]. If the difference is negative, travel is free of cost from A to B.
Jack is low on cash and needs your help to figure out the most cost efficient way to go from the first station to the last station. Given the number of stations $g\text{_}nodes$ (numbered from $\mbox{1}$ to $g\text{_}nodes$), and the fares (weights) between the $g\text{_edges}$ pairs of stations that are connected, determine the lowest fare from station $\mbox{1}$ to station $g\text{_}nodes$.
Example
$g\text{_}nodes=4$
$g_{-}\textit{from}=[1,1,2,3]$
$g_{-}to=[2,3,4,4]$
$g\text{_weight}=[20,5,30,40]$
The graph looks like this:
Travel from station $1\rightarrow2\rightarrow4$ costs $\textbf{20}$ for the first segment ($1\rightarrow2$) then the cost differential, an additional $30-20=10$ for the remainder. The total cost is $30$.
Travel from station $1\rightarrow3\rightarrow4$ costs $5$ for the first segment, then an additional $40-5=35$ for the remainder, a total cost of $\boldsymbol{40}$.
The lower priced option costs $30$.
Function Description
Complete the getCost function in the editor below.
getCost has the following parameters:
int g_nodes: the number of stations in the network
int g_from[g_edges]: end stations of a bidirectional connection
int g_to[g_edges]: $g\text{_from}[i]$ is connected to $g\textrm{_to}[i]$ at cost $g\text{_weight}[i]$
int g_weight[g_edges]: the cost of travel between associated stations
Prints
- int or string: the cost of the lowest priced route from station $\mbox{I}$ to station $g\text{_}nodes$ or NO PATH EXISTS. No return value is expected.
Input Format
The first line contains two space-separated integers, $g\text{_}nodes$ and $g\text{_edges}$, the number of stations and the number of connections between them.
Each of the next $g\text{_edges}$ lines contains three space-separated integers, $g\text{_from},g\text{_to}$ and $g\text{_weight}$, the connected stations and the fare between them.
Constraints
$1\leq g\text{_}nodes\leq50000$
$1\leq g\text{_edges}\leq5000000$
$1\leq g\text{_weight}[i]\leq10^7$ | taco |
def maxXor(l, r):
abin = list(bin(l)[2:])
bbin = list(bin(r)[2:])
abin = (len(bbin) - len(abin)) * ['0'] + abin
a = l
b = r
val = 2 ** (len(bbin) - 1)
maxXor = 0
for i in range(len(bbin)):
if bbin[i] == abin[i]:
if bbin[i] == '0':
if a + val <= r:
abin[i] = '1'
a += val
elif b + val <= r:
bbin[i] = '1'
b += val
elif a - val >= l:
abin[i] = '0'
a -= val
elif b - val >= l:
bbin[i] = '0'
b -= val
if bbin[i] != abin[i]:
maxXor += val
val //= 2
return maxXor
l = int(input())
r = int(input())
print(maxXor(l, r))
| python | 15 | 0.451115 | 46 | 18.433333 | 30 | Given two integers, $\boldsymbol{l}$ and $\textbf{r}$, find the maximal value of $\boldsymbol{a}$ xor $\boldsymbol{b}$, written $a\oplus b$, where $\boldsymbol{a}$ and $\boldsymbol{b}$ satisfy the following condition:
$l\leq a\leq b\leq r$
For example, if $l=11$ and $r=12$, then
$\textbf{11}\oplus11=\textbf{0}$
$\textbf{11}\oplus12=7$
$12\oplus12=0$
Our maximum value is $7$.
Function Description
Complete the maximizingXor function in the editor below. It must return an integer representing the maximum value calculated.
maximizingXor has the following parameter(s):
l: an integer, the lower bound, inclusive
r: an integer, the upper bound, inclusive
Input Format
The first line contains the integer $\boldsymbol{l}$.
The second line contains the integer $\textbf{r}$.
Constraints
$1\leq l\leq r\leq10$^{3}
Output Format
Return the maximal value of the xor operations for all permutations of the integers from $\boldsymbol{l}$ to $\textbf{r}$, inclusive.
Sample Input 0
10
15
Sample Output 0
7
Explanation 0
Here $l=10$ and $r=15$. Testing all pairs:
$10\oplus10=0$
$10\oplus11=1$
$\textbf{10}\oplus12=\textbf{6}$
$\textbf{10}\oplus13=7$
$\textbf{10}\oplus\textbf{14}=4$
$10\oplus15=5$
$\textbf{11}\oplus11=\textbf{0}$
$\textbf{11}\oplus12=7$
$11\oplus13=6$
$11\oplus14=5$
$11\oplus15=4$
$12\oplus12=0$
$12\oplus13=1$
$\textbf{12}\oplus\textbf{14}=2$
$12\oplus15=3$
$13\oplus13=0$
$13\oplus14=3$
$13\oplus15=2$
$14\oplus14=0$
$14\oplus15=1$
$15\oplus15=0$
Two pairs, (10, 13) and (11, 12) have the xor value 7, and this is maximal.
Sample Input 1
11
100
Sample Output 1
127 | taco |
def CalResult(votes):
(upvotes, downvotes, uncertain) = (int(votes[0]), int(votes[1]), int(votes[2]))
partial_result = None
complete_result = None
if upvotes >= downvotes:
if upvotes - downvotes > uncertain:
partial_result = '+'
elif upvotes - downvotes < uncertain:
partial_result = '?'
elif upvotes - downvotes == 0 and uncertain == 0:
partial_result = '0'
elif upvotes - downvotes == uncertain:
partial_result = '?'
elif downvotes - upvotes > uncertain:
partial_result = '-'
elif downvotes - upvotes < uncertain:
partial_result = '?'
elif -upvotes + downvotes == uncertain:
partial_result = '?'
complete_result = partial_result
return complete_result
people = []
x = input()
people = x.split(' ')
result = CalResult(people)
print(result)
| python | 11 | 0.673969 | 80 | 28.846154 | 26 | Nauuo is a girl who loves writing comments.
One day, she posted a comment on Codeforces, wondering whether she would get upvotes or downvotes.
It's known that there were $x$ persons who would upvote, $y$ persons who would downvote, and there were also another $z$ persons who would vote, but you don't know whether they would upvote or downvote. Note that each of the $x+y+z$ people would vote exactly one time.
There are three different results: if there are more people upvote than downvote, the result will be "+"; if there are more people downvote than upvote, the result will be "-"; otherwise the result will be "0".
Because of the $z$ unknown persons, the result may be uncertain (i.e. there are more than one possible results). More formally, the result is uncertain if and only if there exist two different situations of how the $z$ persons vote, that the results are different in the two situations.
Tell Nauuo the result or report that the result is uncertain.
-----Input-----
The only line contains three integers $x$, $y$, $z$ ($0\le x,y,z\le100$), corresponding to the number of persons who would upvote, downvote or unknown.
-----Output-----
If there is only one possible result, print the result : "+", "-" or "0".
Otherwise, print "?" to report that the result is uncertain.
-----Examples-----
Input
3 7 0
Output
-
Input
2 0 1
Output
+
Input
1 1 0
Output
0
Input
0 0 1
Output
?
-----Note-----
In the first example, Nauuo would definitely get three upvotes and seven downvotes, so the only possible result is "-".
In the second example, no matter the person unknown downvotes or upvotes, Nauuo would get more upvotes than downvotes. So the only possible result is "+".
In the third example, Nauuo would definitely get one upvote and one downvote, so the only possible result is "0".
In the fourth example, if the only one person upvoted, the result would be "+", otherwise, the result would be "-". There are two possible results, so the result is uncertain. | taco |
def mi(a):
(a, i, c) = (a + '*', 0, [])
while i < len(a):
b = ''
while a[i] != '*':
b += str(a[i])
i += 1
if a[i] == '*':
c.append(b)
i += 1
return list(map(int, list(filter(lambda a: a != '', c))))
for _ in range(int(input())):
(m, i, j, r, z, p) = (str(input()), 0, '', '', [], 1)
while m[i] != ' ':
j += m[i]
i += 1
for i in range(i + 1, len(m)):
r += m[i]
(y, k) = (mi(r), int(j))
for i in range(0, len(y), 2):
z.append(pow(y[i], y[i + 1], k))
for i in range(len(z)):
p *= z[i]
p = p % k
print(p)
| python | 15 | 0.409259 | 58 | 20.6 | 25 | Read problems statements in Mandarin Chinese and Russian.
Leonid is developing new programming language. The key feature of his language is fast multiplication and raising to a power operations. He is asking you to help with the following task.
You have an expression S and positive integer M. S has the following structure: A_{1}*A_{2}*...*A_{n} where "*" is multiplication operation. Each A_{i} is an expression X_{i}Y_{i} where X_{i} and Y_{i} are non-negative integers and "" is raising X_{i} to power Y_{i} operation.
.
Your task is just to find the value of an expression S modulo M
------ Input ------
The first line of the input contains an integer T denoting the number of test cases. Each of the following T testcases is described by one line which contains one positive integer M and expression S separated by whitespace.
------ Output ------
For each test case, output a single line containing one integer corresponding to value of S modulo M
------ Constraints ------
$1 ≤ T ≤ 20$
$ 1 ≤ M ≤ 10^{18}$
$ 1 ≤ length of S ≤ 10^{4}$
$ 0 ≤ X_{i}, Y_{i} ≤ 10^{9997} $
$It's guaranteed that there will not be 00 expression$
------ Subtasks ------
Subtask #1[30 points]: X_{i}, Y_{i} < 10, M < 10 ^{4}
Subtask #2[40 points]: M < 10^{9}
Subtask #3[30 points]: no additional conditions
------ Example ------
Input:
2
1000 23*31
100000 112*24
Output:
24
1936 | taco |
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
for (int i = 0; i < t; i++) {
BigInteger n = scanner.nextBigInteger();
if (n.remainder(BigInteger.valueOf(2050)).compareTo(BigInteger.valueOf(0)) == 0) {
BigInteger result = n.divide(BigInteger.valueOf(2050));
String digits = result.toString();
int ans = 0;
for (int p = 0; p < digits.length(); p++)
ans += (digits.charAt(p) - '0');
System.out.println(ans);
} else {
System.out.println(-1);
}
}
}
}
| java | 16 | 0.492908 | 94 | 16.625 | 48 | A. Sum of 2050time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA number is called 2050-number if it is $$$2050$$$, $$$20500$$$, ..., ($$$2050 \cdot 10^k$$$ for integer $$$k \ge 0$$$).Given a number $$$n$$$, you are asked to represent $$$n$$$ as the sum of some (not necessarily distinct) 2050-numbers. Compute the minimum number of 2050-numbers required for that.InputThe first line contains a single integer $$$T$$$ ($$$1\le T\leq 1\,000$$$) denoting the number of test cases.The only line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^{18}$$$) denoting the number to be represented.OutputFor each test case, output the minimum number of 2050-numbers in one line. If $$$n$$$ cannot be represented as the sum of 2050-numbers, output $$$-1$$$ instead. ExampleInput
6
205
2050
4100
20500
22550
25308639900
Output
-1
1
2
1
2
36
NoteIn the third case, $$$4100 = 2050 + 2050$$$.In the fifth case, $$$22550 = 20500 + 2050$$$. | cf |
t = int(input())
for _ in range(t):
(n, k, d) = map(int, input().split())
a = list(map(int, input().split()))
total = sum(a)
contests = total // k
if contests <= d:
ans = contests
else:
ans = d
print(ans)
| python | 13 | 0.560185 | 38 | 18.636364 | 11 | Chef wants to host some Division-3 contests. Chef has $N$ setters who are busy creating new problems for him. The $i^{th}$ setter has made $A_i$ problems where $1 \leq i \leq N$.
A Division-3 contest should have exactly $K$ problems. Chef wants to plan for the next $D$ days using the problems that they have currently. But Chef cannot host more than one Division-3 contest in a day.
Given these constraints, can you help Chef find the maximum number of Division-3 contests that can be hosted in these $D$ days?
-----Input:-----
- The first line of input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains three space-separated integers - $N$, $K$ and $D$ respectively.
- The second line of each test case contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$ respectively.
-----Output:-----
For each test case, print a single line containing one integer ― the maximum number of Division-3 contests Chef can host in these $D$ days.
-----Constraints-----
- $1 \leq T \leq 10^3$
- $1 \leq N \leq 10^2$
- $1 \le K \le 10^9$
- $1 \le D \le 10^9$
- $1 \le A_i \le 10^7$ for each valid $i$
-----Subtasks-----
Subtask #1 (40 points):
- $N = 1$
- $1 \le A_1 \le 10^5$
Subtask #2 (60 points): Original constraints
-----Sample Input:-----
5
1 5 31
4
1 10 3
23
2 5 7
20 36
2 5 10
19 2
3 3 300
1 1 1
-----Sample Output:-----
0
2
7
4
1
-----Explanation:-----
-
Example case 1: Chef only has $A_1 = 4$ problems and he needs $K = 5$ problems for a Division-3 contest. So Chef won't be able to host any Division-3 contest in these 31 days. Hence the first output is $0$.
-
Example case 2: Chef has $A_1 = 23$ problems and he needs $K = 10$ problems for a Division-3 contest. Chef can choose any $10+10 = 20$ problems and host $2$ Division-3 contests in these 3 days. Hence the second output is $2$.
-
Example case 3: Chef has $A_1 = 20$ problems from setter-1 and $A_2 = 36$ problems from setter-2, and so has a total of $56$ problems. Chef needs $K = 5$ problems for each Division-3 contest. Hence Chef can prepare $11$ Division-3 contests. But since we are planning only for the next $D = 7$ days and Chef cannot host more than $1$ contest in a day, Chef cannot host more than $7$ contests. Hence the third output is $7$. | taco |
test = int(input())
for _ in range(test):
(x, y) = map(int, input().split())
(a, b) = map(int, input().split())
if x > y:
temp = x
x = y
y = temp
res1 = 0
res2 = 0
res1 = x * a + y * a
temp = y - x
res2 = temp * a + x * b
print(min(res1, res2))
| python | 11 | 0.496154 | 35 | 17.571429 | 14 | You are given two integers $x$ and $y$. You can perform two types of operations: Pay $a$ dollars and increase or decrease any of these integers by $1$. For example, if $x = 0$ and $y = 7$ there are four possible outcomes after this operation: $x = 0$, $y = 6$; $x = 0$, $y = 8$; $x = -1$, $y = 7$; $x = 1$, $y = 7$.
Pay $b$ dollars and increase or decrease both integers by $1$. For example, if $x = 0$ and $y = 7$ there are two possible outcomes after this operation: $x = -1$, $y = 6$; $x = 1$, $y = 8$.
Your goal is to make both given integers equal zero simultaneously, i.e. $x = y = 0$. There are no other requirements. In particular, it is possible to move from $x=1$, $y=0$ to $x=y=0$.
Calculate the minimum amount of dollars you have to spend on it.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 100$) — the number of testcases.
The first line of each test case contains two integers $x$ and $y$ ($0 \le x, y \le 10^9$).
The second line of each test case contains two integers $a$ and $b$ ($1 \le a, b \le 10^9$).
-----Output-----
For each test case print one integer — the minimum amount of dollars you have to spend.
-----Example-----
Input
2
1 3
391 555
0 0
9 4
Output
1337
0
-----Note-----
In the first test case you can perform the following sequence of operations: first, second, first. This way you spend $391 + 555 + 391 = 1337$ dollars.
In the second test case both integers are equal to zero initially, so you dont' have to spend money. | taco |
s = str(input())
final = ''
try:
for i in range(len(s)):
if s[i] == 'h':
final += 'h'
break
for k in range(i + 1, len(s)):
if s[k] == 'e':
final += 'e'
break
for l in range(k + 1, len(s)):
if s[l] == 'l':
final += 'l'
break
for t in range(l + 1, len(s)):
if s[t] == 'l':
final += 'l'
break
for b in range(t + 1, len(s)):
if s[b] == 'o':
final += 'o'
break
if final == 'hello':
print('YES')
else:
print('NO')
except:
print('NO')
| python | 10 | 0.466667 | 31 | 15.551724 | 29 | Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if Vasya types the word "ahhellllloou", it will be considered that he said hello, and if he types "hlelo", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word s.
Input
The first and only line contains the word s, which Vasya typed. This word consisits of small Latin letters, its length is no less that 1 and no more than 100 letters.
Output
If Vasya managed to say hello, print "YES", otherwise print "NO".
Examples
Input
ahhellllloou
Output
YES
Input
hlelo
Output
NO | taco |
def contar(p):
marks = [0] * len(p)
for i in range(1, len(p)):
mark = 0
if p[i] == p[i - 1] and marks[i - 1] != 1:
mark = 1
if i > 1 and p[i] == p[i - 2] and (marks[i - 2] != 1):
mark = 1
marks[i] = mark
return marks.count(1)
n = int(input())
r = ''
for i in range(0, n):
p = input()
r += str(contar(p)) + '\n'
print(r)
| python | 11 | 0.489676 | 56 | 20.1875 | 16 | After his wife's tragic death, Eurydice, Orpheus descended to the realm of death to see her. Reaching its gates was uneasy, but passing through them proved to be even more challenging. Mostly because of Cerberus, the three-headed hound of Hades.
Orpheus, a famous poet, and musician plans to calm Cerberus with his poetry and safely walk past him. He created a very peculiar poem for Cerberus. It consists only of lowercase English letters.
We call a poem's substring a palindrome if and only if it reads the same backwards and forwards. A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deleting several (possibly zero or all) characters from the beginning and several (possibly zero or all) characters from the end.
Unfortunately, Cerberus dislikes palindromes of length greater than $1$. For example in the poem abaa the hound of Hades wouldn't like substrings aba and aa.
Orpheus can only calm Cerberus if the hound likes his poetry. That's why he wants to change his poem so that it does not contain any palindrome substrings of length greater than $1$.
Orpheus can modify the poem by replacing a letter at any position with any lowercase English letter. He can use this operation arbitrarily many times (possibly zero). Since there can be many palindromes in his poem, he may have to make some corrections. But how many, exactly? Given the poem, determine the minimal number of letters that have to be changed so that the poem does not contain any palindromes of length greater than $1$.
-----Input-----
The first line of the input contains a single integer $t$ ($1 \leq t \leq 10^5$) denoting the number of test cases, then $t$ test cases follow.
The first and only line of each test case contains a non-empty string of lowercase English letters, Orpheus' poem.
The sum of the length of Orpheus' poems in all test cases will not exceed $10^5$.
-----Output-----
You should output $t$ lines, $i$-th line should contain a single integer, answer to the $i$-th test case.
-----Examples-----
Input
7
babba
abaac
codeforces
zeroorez
abcdcba
bbbbbbb
a
Output
1
1
0
1
1
4
0
-----Note-----
In the first test case, we can replace the third character with c and obtain a palindrome-less poem bacba.
In the second test case, we can replace the third character with d and obtain a palindrome-less poem abdac.
In the third test case, the initial poem already doesn't contain any palindromes, so Orpheus doesn't need to change anything there. | taco |
def Input():
Str = input('')
List = Str.split(' ')
for i in range(len(List)):
List[i] = int(List[i])
return List
def Freq(List):
Values = []
Freq = [0] * 100
for a in range(0, len(List) - 1):
for b in range(a + 1, len(List)):
Freq[List[a] + List[b] - 1] += 1
Max = max(Freq)
for i in range(len(Freq)):
if Freq[i] == Max:
Values.append(i + 1)
return Values
def Remove(List, Index):
Done = False
for a in range(len(List) - 1):
for b in range(a + 1, len(List)):
if List[a] + List[b] == Index:
Done = True
A = a
B = b
break
if Done == True:
break
if Done == True:
List.pop(A)
List.pop(B - 1)
return List
else:
return False
def Det(List):
Original = list(List)
Values = []
for i in range(2, 101):
Values.append(i)
Counters = [0] * len(Values)
for i in range(len(Values)):
List = Original.copy()
Done = False
Index = Values[i]
Counter = 0
while Done == False:
Result = Remove(List, Index)
if Result != False:
List = Result
Counter = Counter + 1
if Result == False:
Done = True
Counters[i] = Counter
return max(Counters)
trials = int(input(''))
for i in range(trials):
input('')
List = Input()
print(Det(List))
| python | 13 | 0.584641 | 35 | 18.532258 | 62 | There are $n$ people who want to participate in a boat competition. The weight of the $i$-th participant is $w_i$. Only teams consisting of two people can participate in this competition. As an organizer, you think that it's fair to allow only teams with the same total weight.
So, if there are $k$ teams $(a_1, b_1)$, $(a_2, b_2)$, $\dots$, $(a_k, b_k)$, where $a_i$ is the weight of the first participant of the $i$-th team and $b_i$ is the weight of the second participant of the $i$-th team, then the condition $a_1 + b_1 = a_2 + b_2 = \dots = a_k + b_k = s$, where $s$ is the total weight of each team, should be satisfied.
Your task is to choose such $s$ that the number of teams people can create is the maximum possible. Note that each participant can be in no more than one team.
You have to answer $t$ independent test cases.
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 1000$) — the number of test cases. Then $t$ test cases follow.
The first line of the test case contains one integer $n$ ($1 \le n \le 50$) — the number of participants. The second line of the test case contains $n$ integers $w_1, w_2, \dots, w_n$ ($1 \le w_i \le n$), where $w_i$ is the weight of the $i$-th participant.
-----Output-----
For each test case, print one integer $k$: the maximum number of teams people can compose with the total weight $s$, if you choose $s$ optimally.
-----Example-----
Input
5
5
1 2 3 4 5
8
6 6 6 6 6 6 8 8
8
1 2 2 1 2 1 1 2
3
1 3 3
6
1 1 3 4 2 2
Output
2
3
4
1
2
-----Note-----
In the first test case of the example, we can reach the optimal answer for $s=6$. Then the first boat is used by participants $1$ and $5$ and the second boat is used by participants $2$ and $4$ (indices are the same as weights).
In the second test case of the example, we can reach the optimal answer for $s=12$. Then first $6$ participants can form $3$ pairs.
In the third test case of the example, we can reach the optimal answer for $s=3$. The answer is $4$ because we have $4$ participants with weight $1$ and $4$ participants with weight $2$.
In the fourth test case of the example, we can reach the optimal answer for $s=4$ or $s=6$.
In the fifth test case of the example, we can reach the optimal answer for $s=3$. Note that participant with weight $3$ can't use the boat because there is no suitable pair for him in the list. | taco |
t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
c = []
for i in range(1, n - 1):
if a[i] == -1:
if a[i - 1] != -1:
c.append(a[i - 1])
if a[i + 1] != -1:
c.append(a[i + 1])
if a[-1] == -1 and a[-2] != -1:
c.append(a[-2])
if a[0] == -1 and a[1] != -1:
c.append(a[1])
if len(c) == 0:
print(0, 1)
continue
else:
d = (max(c) + min(c)) // 2
b = []
for i in range(n):
if a[i] == -1:
a[i] = d
for i in range(n - 1):
b.append(abs(a[i + 1] - a[i]))
print(max(b), d)
| python | 14 | 0.437269 | 36 | 19.074074 | 27 | Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array $a$ of $n$ non-negative integers.
Dark created that array $1000$ years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer $k$ ($0 \leq k \leq 10^{9}$) and replaces all missing elements in the array $a$ with $k$.
Let $m$ be the maximum absolute difference between all adjacent elements (i.e. the maximum value of $|a_i - a_{i+1}|$ for all $1 \leq i \leq n - 1$) in the array $a$ after Dark replaces all missing elements with $k$.
Dark should choose an integer $k$ so that $m$ is minimized. Can you help him?
-----Input-----
The input consists of multiple test cases. The first line contains a single integer $t$ ($1 \leq t \leq 10^4$) — the number of test cases. The description of the test cases follows.
The first line of each test case contains one integer $n$ ($2 \leq n \leq 10^{5}$) — the size of the array $a$.
The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($-1 \leq a_i \leq 10 ^ {9}$). If $a_i = -1$, then the $i$-th integer is missing. It is guaranteed that at least one integer is missing in every test case.
It is guaranteed, that the sum of $n$ for all test cases does not exceed $4 \cdot 10 ^ {5}$.
-----Output-----
Print the answers for each test case in the following format:
You should print two integers, the minimum possible value of $m$ and an integer $k$ ($0 \leq k \leq 10^{9}$) that makes the maximum absolute difference between adjacent elements in the array $a$ equal to $m$.
Make sure that after replacing all the missing elements with $k$, the maximum absolute difference between adjacent elements becomes $m$.
If there is more than one possible $k$, you can print any of them.
-----Example-----
Input
7
5
-1 10 -1 12 -1
5
-1 40 35 -1 35
6
-1 -1 9 -1 3 -1
2
-1 -1
2
0 -1
4
1 -1 3 -1
7
1 -1 7 5 2 -1 5
Output
1 11
5 35
3 6
0 42
0 0
1 2
3 4
-----Note-----
In the first test case after replacing all missing elements with $11$ the array becomes $[11, 10, 11, 12, 11]$. The absolute difference between any adjacent elements is $1$. It is impossible to choose a value of $k$, such that the absolute difference between any adjacent element will be $\leq 0$. So, the answer is $1$.
In the third test case after replacing all missing elements with $6$ the array becomes $[6, 6, 9, 6, 3, 6]$. $|a_1 - a_2| = |6 - 6| = 0$; $|a_2 - a_3| = |6 - 9| = 3$; $|a_3 - a_4| = |9 - 6| = 3$; $|a_4 - a_5| = |6 - 3| = 3$; $|a_5 - a_6| = |3 - 6| = 3$.
So, the maximum difference between any adjacent elements is $3$. | taco |
s = input().split()
a = int(s[0])
b = int(s[1])
j = 0
c = 1
while b % c == 0:
j += 1
c *= 2
print(j)
| python | 7 | 0.436893 | 19 | 10.444444 | 9 | Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad.
Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step.
The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps.
Please help Chloe to solve the problem!
-----Input-----
The only line contains two integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2^{n} - 1).
-----Output-----
Print single integer — the integer at the k-th position in the obtained sequence.
-----Examples-----
Input
3 2
Output
2
Input
4 8
Output
4
-----Note-----
In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2.
In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4. | taco |
t = int(input())
for _ in range(t):
(n, T) = map(int, input().split())
a = list(map(int, input().split()))
d = [0] * n
for i in range(n):
a[i] = [a[i], i]
a.sort()
r = 0
pp = 0
d[a[0][1]] = 0
for i in range(1, n):
if a[i][0] + a[i - 1][0] > T:
r = 1
d[a[i][1]] = r
elif a[i][0] + a[i - 1][0] == T:
if pp % 2 == 0:
d[a[i][1]] = 1
else:
d[a[i][1]] = 0
pp += 1
else:
d[a[i][1]] = r
for i in range(n):
print(d[i], end=' ')
print()
| python | 16 | 0.411392 | 36 | 17.230769 | 26 | RedDreamer has an array $a$ consisting of $n$ non-negative integers, and an unlucky integer $T$.
Let's denote the misfortune of array $b$ having length $m$ as $f(b)$ — the number of pairs of integers $(i, j)$ such that $1 \le i < j \le m$ and $b_i + b_j = T$. RedDreamer has to paint each element of $a$ into one of two colors, white and black (for each element, the color is chosen independently), and then create two arrays $c$ and $d$ so that all white elements belong to $c$, and all black elements belong to $d$ (it is possible that one of these two arrays becomes empty). RedDreamer wants to paint the elements in such a way that $f(c) + f(d)$ is minimum possible.
For example:
if $n = 6$, $T = 7$ and $a = [1, 2, 3, 4, 5, 6]$, it is possible to paint the $1$-st, the $4$-th and the $5$-th elements white, and all other elements black. So $c = [1, 4, 5]$, $d = [2, 3, 6]$, and $f(c) + f(d) = 0 + 0 = 0$; if $n = 3$, $T = 6$ and $a = [3, 3, 3]$, it is possible to paint the $1$-st element white, and all other elements black. So $c = [3]$, $d = [3, 3]$, and $f(c) + f(d) = 0 + 1 = 1$.
Help RedDreamer to paint the array optimally!
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 1000$) — the number of test cases. Then $t$ test cases follow.
The first line of each test case contains two integers $n$ and $T$ ($1 \le n \le 10^5$, $0 \le T \le 10^9$) — the number of elements in the array and the unlucky integer, respectively.
The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($0 \le a_i \le 10^9$) — the elements of the array.
The sum of $n$ over all test cases does not exceed $10^5$.
-----Output-----
For each test case print $n$ integers: $p_1$, $p_2$, ..., $p_n$ (each $p_i$ is either $0$ or $1$) denoting the colors. If $p_i$ is $0$, then $a_i$ is white and belongs to the array $c$, otherwise it is black and belongs to the array $d$.
If there are multiple answers that minimize the value of $f(c) + f(d)$, print any of them.
-----Example-----
Input
2
6 7
1 2 3 4 5 6
3 6
3 3 3
Output
1 0 0 1 1 0
1 0 0 | taco |
n = int(input())
a = int(input())
b = int(input())
c = int(input())
if n < a and n < b:
print(0)
elif n >= b and b - c <= a:
t = (n - b) // (b - c)
t += 1
n -= t * (b - c)
print(t + n // a)
else:
print(n // a)
| python | 9 | 0.430556 | 27 | 15.615385 | 13 | Kolya Gerasimov loves kefir very much. He lives in year 1984 and knows all the details of buying this delicious drink. One day, as you probably know, he found himself in year 2084, and buying kefir there is much more complicated.
Kolya is hungry, so he went to the nearest milk shop. In 2084 you may buy kefir in a plastic liter bottle, that costs a rubles, or in glass liter bottle, that costs b rubles. Also, you may return empty glass bottle and get c (c < b) rubles back, but you cannot return plastic bottles.
Kolya has n rubles and he is really hungry, so he wants to drink as much kefir as possible. There were no plastic bottles in his 1984, so Kolya doesn't know how to act optimally and asks for your help.
-----Input-----
First line of the input contains a single integer n (1 ≤ n ≤ 10^18) — the number of rubles Kolya has at the beginning.
Then follow three lines containing integers a, b and c (1 ≤ a ≤ 10^18, 1 ≤ c < b ≤ 10^18) — the cost of one plastic liter bottle, the cost of one glass liter bottle and the money one can get back by returning an empty glass bottle, respectively.
-----Output-----
Print the only integer — maximum number of liters of kefir, that Kolya can drink.
-----Examples-----
Input
10
11
9
8
Output
2
Input
10
5
6
1
Output
2
-----Note-----
In the first sample, Kolya can buy one glass bottle, then return it and buy one more glass bottle. Thus he will drink 2 liters of kefir.
In the second sample, Kolya can buy two plastic bottle and get two liters of kefir, or he can buy one liter glass bottle, then return it and buy one plastic bottle. In both cases he will drink two liters of kefir. | taco |
(s, n) = map(int, input().split())
flag = 0
(xl, yl) = ([], [])
for i in range(n):
(x, y) = map(int, input().split())
xl.append(x)
yl.append(y)
xy = list(zip(xl, yl))
xy.sort()
(xl, yl) = ([], [])
for (i, j) in xy:
xl.append(i)
yl.append(j)
for i in range(len(xl)):
if s <= xl[i]:
flag = 1
break
else:
s = s + yl[i]
if flag:
print('NO')
else:
print('YES')
| python | 11 | 0.514825 | 35 | 15.130435 | 23 | Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito's strength equals s.
If Kirito starts duelling with the i-th (1 ≤ i ≤ n) dragon and Kirito's strength is not greater than the dragon's strength xi, then Kirito loses the duel and dies. But if Kirito's strength is greater than the dragon's strength, then he defeats the dragon and gets a bonus strength increase by yi.
Kirito can fight the dragons in any order. Determine whether he can move on to the next level of the game, that is, defeat all dragons without a single loss.
Input
The first line contains two space-separated integers s and n (1 ≤ s ≤ 104, 1 ≤ n ≤ 103). Then n lines follow: the i-th line contains space-separated integers xi and yi (1 ≤ xi ≤ 104, 0 ≤ yi ≤ 104) — the i-th dragon's strength and the bonus for defeating it.
Output
On a single line print "YES" (without the quotes), if Kirito can move on to the next level and print "NO" (without the quotes), if he can't.
Examples
Input
2 2
1 99
100 0
Output
YES
Input
10 1
100 100
Output
NO
Note
In the first sample Kirito's strength initially equals 2. As the first dragon's strength is less than 2, Kirito can fight it and defeat it. After that he gets the bonus and his strength increases to 2 + 99 = 101. Now he can defeat the second dragon and move on to the next level.
In the second sample Kirito's strength is too small to defeat the only dragon and win. | taco |
class Solution:
def minCostConnectPoints(self, points: List[List[int]]) -> int:
if len(points) == 1:
return 0
def distance(p1, p2):
return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
n = len(points)
parents = list(range(n))
def find(x):
if x != parents[x]:
parents[x] = find(parents[x])
return parents[x]
def union(x, y):
(px, py) = (find(x), find(y))
if px != py:
parents[py] = px
return True
return False
ans = 0
count = 0
g = []
for i in range(n):
for j in range(i + 1, n):
cost = distance(points[i], points[j])
g.append([cost, i, j])
for (cost, pt1, pt2) in sorted(g):
if union(pt1, pt2):
ans += cost
count += 1
if count == n - 1:
return ans
| python | 14 | 0.549932 | 64 | 19.885714 | 35 | You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi].
The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: |xi - xj| + |yi - yj|, where |val| denotes the absolute value of val.
Return the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points.
Example 1:
Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
Output: 20
Explanation:
We can connect the points as shown above to get the minimum cost of 20.
Notice that there is a unique path between every pair of points.
Example 2:
Input: points = [[3,12],[-2,5],[-4,1]]
Output: 18
Example 3:
Input: points = [[0,0],[1,1],[1,0],[-1,1]]
Output: 4
Example 4:
Input: points = [[-1000000,-1000000],[1000000,1000000]]
Output: 4000000
Example 5:
Input: points = [[0,0]]
Output: 0
Constraints:
1 <= points.length <= 1000
-106 <= xi, yi <= 106
All pairs (xi, yi) are distinct. | taco |
class Solution:
def countSubarrWithEqualZeroAndOne(self, arr, n):
d = dict()
ans = 0
total = 0
for i in arr:
x = -1 if i == 0 else 1
total += x
if total == 0:
ans += 1
if total in d:
ans += d[total]
d[total] += 1
else:
d[total] = 1
return ans
| python | 13 | 0.534965 | 50 | 15.823529 | 17 | Given an array containing 0s and 1s. Find the number of subarrays having equal number of 0s and 1s.
Example 1:
Input:
n = 7
A[] = {1,0,0,1,0,1,1}
Output: 8
Explanation: The index range for the 8
sub-arrays are: (0, 1), (2, 3), (0, 3), (3, 4),
(4, 5) ,(2, 5), (0, 5), (1, 6)
Example 2:
Input:
n = 5
A[] = {1,1,1,1,0}
Output: 1
Explanation: The index range for the
subarray is (3,4).
Your Task:
You don't need to read input or print anything. Your task is to complete the function countSubarrWithEqualZeroAndOne() which takes the array arr[] and the size of the array as inputs and returns the number of subarrays with equal number of 0s and 1s.
Expected Time Complexity: O(n).
Expected Auxiliary Space: O(n).
Constraints:
1 <= n <= 10^{6}
0 <= A[i] <= 1 | taco |
import sys
input = sys.stdin.readline
for nt in range(int(input())):
n = int(input())
a = [[0, 0]]
for i in range(n):
a.append(list(map(int, input().split())))
a.append([10 ** 10, 0])
curr = 0
i = 1
ans = 0
free = 1
t = 0
prev = 0
changed = 0
target = 0
while i < n + 1:
time_left = a[i + 1][0] - a[i][0]
if a[i][0] >= t:
curr = target
changed = 1
free = 1
if free:
target = a[i][1]
t = abs(a[i][1] - curr) + a[i][0]
free = 0
if not changed:
if target > curr:
curr += a[i][0] - a[i - 1][0]
else:
curr -= a[i][0] - a[i - 1][0]
else:
changed = 0
x = a[i][1]
if abs(x - curr) + abs(x - target) == abs(target - curr) and time_left >= abs(x - curr):
ans += 1
i += 1
print(ans)
| python | 16 | 0.497305 | 90 | 18.526316 | 38 | You have a robot that can move along a number line. At time moment $0$ it stands at point $0$.
You give $n$ commands to the robot: at time $t_i$ seconds you command the robot to go to point $x_i$. Whenever the robot receives a command, it starts moving towards the point $x_i$ with the speed of $1$ unit per second, and he stops when he reaches that point. However, while the robot is moving, it ignores all the other commands that you give him.
For example, suppose you give three commands to the robot: at time $1$ move to point $5$, at time $3$ move to point $0$ and at time $6$ move to point $4$. Then the robot stands at $0$ until time $1$, then starts moving towards $5$, ignores the second command, reaches $5$ at time $6$ and immediately starts moving to $4$ to execute the third command. At time $7$ it reaches $4$ and stops there.
You call the command $i$ successful, if there is a time moment in the range $[t_i, t_{i + 1}]$ (i. e. after you give this command and before you give another one, both bounds inclusive; we consider $t_{n + 1} = +\infty$) when the robot is at point $x_i$. Count the number of successful commands. Note that it is possible that an ignored command is successful.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases. The next lines describe the test cases.
The first line of a test case contains a single integer $n$ ($1 \le n \le 10^5$) — the number of commands.
The next $n$ lines describe the commands. The $i$-th of these lines contains two integers $t_i$ and $x_i$ ($1 \le t_i \le 10^9$, $-10^9 \le x_i \le 10^9$) — the time and the point of the $i$-th command.
The commands are ordered by time, that is, $t_i < t_{i + 1}$ for all possible $i$.
The sum of $n$ over test cases does not exceed $10^5$.
-----Output-----
For each testcase output a single integer — the number of successful commands.
-----Examples-----
Input
8
3
1 5
3 0
6 4
3
1 5
2 4
10 -5
5
2 -5
3 1
4 1
5 1
6 1
4
3 3
5 -3
9 2
12 0
8
1 1
2 -6
7 2
8 3
12 -9
14 2
18 -1
23 9
5
1 -4
4 -7
6 -1
7 -3
8 -7
2
1 2
2 -2
6
3 10
5 5
8 0
12 -4
14 -7
19 -5
Output
1
2
0
2
1
1
0
2
-----Note-----
The movements of the robot in the first test case are described in the problem statement. Only the last command is successful.
In the second test case the second command is successful: the robot passes through target point $4$ at time $5$. Also, the last command is eventually successful.
In the third test case no command is successful, and the robot stops at $-5$ at time moment $7$.
Here are the $0$-indexed sequences of the positions of the robot in each second for each testcase of the example. After the cut all the positions are equal to the last one:
$[0, 0, 1, 2, 3, 4, 5, 4, 4, \dots]$
$[0, 0, 1, 2, 3, 4, 5, 5, 5, 5, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -5, \dots]$
$[0, 0, 0, -1, -2, -3, -4, -5, -5, \dots]$
$[0, 0, 0, 0, 1, 2, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, \dots]$
$[0, 0, 1, 0, -1, -2, -3, -4, -5, -6, -6, -6, -6, -7, -8, -9, -9, -9, -9, -8, -7, -6, -5, -4, -3, -2, -1, -1, \dots]$
$[0, 0, -1, -2, -3, -4, -4, -3, -2, -1, -1, \dots]$
$[0, 0, 1, 2, 2, \dots]$
$[0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -7, \dots]$ | taco |
import sys
input = sys.stdin.readline
n = int(input())
ab = [tuple(map(int, input().split())) for _ in range(n - 1)]
edges = {}
for i in range(1, n + 1):
edges[i] = set()
for tmp in ab:
(a, b) = tmp
edges[a].add(b)
edges[b].add(a)
group = [[], []]
g_flag = 0
next = {1}
while len(next) > 0:
tmp = list(next)
next = set()
for i in tmp:
group[g_flag].append(i)
for j in edges[i]:
next.add(j)
edges[j].remove(i)
g_flag = 1 - g_flag
even_n = len(group[0])
odd_n = len(group[1])
ans = [0] * (n + 1)
if (even_n > n // 3) & (odd_n > n // 3):
g1 = group[0][:(n + 2) // 3]
g2 = group[1][:(n + 1) // 3]
g0 = group[0][(n + 2) // 3:] + group[1][(n + 1) // 3:]
elif even_n <= n // 3:
g0 = group[0] + group[1][:n // 3 - even_n]
g1 = group[1][n // 3 - even_n:n // 3 - even_n + (n + 2) // 3]
g2 = group[1][n // 3 - even_n + (n + 2) // 3:]
else:
g0 = group[1] + group[0][:n // 3 - odd_n]
g1 = group[0][n // 3 - odd_n:n // 3 - odd_n + (n + 2) // 3]
g2 = group[0][n // 3 - odd_n + (n + 2) // 3:]
for i in range((n + 2) // 3):
ans[g1[i]] = i * 3 + 1
for i in range((n + 1) // 3):
ans[g2[i]] = i * 3 + 2
for (i, val) in enumerate(g0):
ans[val] = (i + 1) * 3
print(' '.join(map(str, ans[1:])))
| python | 12 | 0.480033 | 62 | 25.711111 | 45 | We have a tree with N vertices. The vertices are numbered 1 to N, and the i-th edge connects Vertex a_i and Vertex b_i.
Takahashi loves the number 3. He is seeking a permutation p_1, p_2, \ldots , p_N of integers from 1 to N satisfying the following condition:
* For every pair of vertices (i, j), if the distance between Vertex i and Vertex j is 3, the sum or product of p_i and p_j is a multiple of 3.
Here the distance between Vertex i and Vertex j is the number of edges contained in the shortest path from Vertex i to Vertex j.
Help Takahashi by finding a permutation that satisfies the condition.
Constraints
* 2\leq N\leq 2\times 10^5
* 1\leq a_i, b_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
\vdots
a_{N-1} b_{N-1}
Output
If no permutation satisfies the condition, print `-1`.
Otherwise, print a permutation satisfying the condition, with space in between. If there are multiple solutions, you can print any of them.
Example
Input
5
1 2
1 3
3 4
3 5
Output
1 2 5 4 3 | taco |
def solve(p, qlist):
for [a, b, c, d] in qlist:
if c % p == 0:
if d % p == 0:
print(a + b)
else:
print('wala')
elif d % p == 0:
print('wala')
else:
toprint = (a + b) * p
for x in range(1, p):
for y in range(1, p):
if pow(c, x, p) == pow(d, y, p):
toprint = min(a * x + b * y, toprint)
print(toprint)
t = int(input())
for _ in range(t):
[p, n] = list(map(int, input().split(' ')))
qlist = []
for __ in range(n):
var = list(map(int, input().split(' ')))
qlist.append(var)
solve(p, qlist)
| python | 20 | 0.49262 | 44 | 21.583333 | 24 | Gru wanted to upgrade the quality of his minions' despicableness through his new base, The Volcano. Dave, desperately wanting the Minion of the Year award, rushed to The Volcano only to find out that he needs to solve a series of questions before he can unlock the gate and enter.
Dave is given a prime $\mbox{P}$, and $N$ questions.
In each question/query, Dave is given four integers $(A,B,C,D)$, and Dave needs to find the minimum possible value of $Ax+By$ among all positive integer pairs $(x,y)$ such that $\mbox{P}$ divides $|C^x-D^y|$.
Unfortunately, the gate has a strict time limit, and if Dave is unable to answer all questions quickly and correctly, then a hidden freeze ray will zap him and he won't be able to move. Please help Dave answer all the questions so he can enter The Volcano and win the Minion of the Year award!
Input Format
The first line of input consists of an integer, $\mathbf{T}$, which is the number of test cases.
The first line of each test case consists of two integers separated by a space, $\mbox{P}$ and $N$. The following $N$ lines contain the queries, each in a line. Each question consists of four integers separated by single spaces: $\mbox{A}$, $\mbox{B}$, $\mbox{C}$ and $\mbox{D}$.
Output Format
For each query, output a single line containing the minimum value of $Ax+By$, or output wala if no such pairs $(x,y)$ exist.
Constraints
$1\leq T\leq3$
$1\leq N\leq6000$
$2\leq P\leq10^{8}$
$0\leq A,B,C,D\leq10^8$
$\mbox{P}$ is prime
Sample Input
2
7 2
1 1 1 5
7 8 8 7
11 5
1 1 1 1
0 1 2 3
3 2 1 0
9 8 7 6
0 0 1 1
Sample Output
7
wala
2
1
wala
33
0
Explanation
For the first query, $P=7$, $(A,B,C,D)=(1,1,1,5)$, the minimum $1x+1y$ is $7$, which occurs at $(x,y)=(1,6)$ ($7$ divides $\left|1^1-5^6\right|=15624=7\cdot2232$).
For the second query, no matter what $(x,y)$ you choose, $|8^x-7^y|$ will not by divisible by $7$, so the answer is wala. | taco |
n = list(input())
t1 = n.count('4')
t2 = n.count('7')
r = list(str(t1 + t2))
if len(r) == r.count('4') + r.count('7'):
print('YES')
else:
print('NO')
| python | 8 | 0.519737 | 41 | 18 | 8 | Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky digits in it is a lucky number. He wonders whether number n is a nearly lucky number.
Input
The only line contains an integer n (1 ≤ n ≤ 1018).
Please do not use the %lld specificator to read or write 64-bit numbers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Output
Print on the single line "YES" if n is a nearly lucky number. Otherwise, print "NO" (without the quotes).
Examples
Input
40047
Output
NO
Input
7747774
Output
YES
Input
1000000000000000000
Output
NO
Note
In the first sample there are 3 lucky digits (first one and last two), so the answer is "NO".
In the second sample there are 7 lucky digits, 7 is lucky number, so the answer is "YES".
In the third sample there are no lucky digits, so the answer is "NO". | taco |
s = input()
t = input()
cnt = 0
for (i, c) in enumerate(s):
if c != t[i]:
cnt += 1
print(cnt)
| python | 7 | 0.515464 | 27 | 12.857143 | 7 | Given are strings S and T. Consider changing S to T by repeating the operation below. Find the minimum number of operations required to do so.
Operation: Choose one character of S and replace it with a different character.
-----Constraints-----
- S and T have lengths between 1 and 2\times 10^5 (inclusive).
- S and T consists of lowercase English letters.
- S and T have equal lengths.
-----Input-----
Input is given from Standard Input in the following format:
S
T
-----Output-----
Print the answer.
-----Sample Input-----
cupofcoffee
cupofhottea
-----Sample Output-----
4
We can achieve the objective in four operations, such as the following:
- First, replace the sixth character c with h.
- Second, replace the eighth character f with t.
- Third, replace the ninth character f with t.
- Fourth, replace the eleventh character e with a. | taco |
w = 'codeforces'
n = int(input())
for _ in range(n):
l = input()
if l in w:
print('YES')
else:
print('NO')
| python | 10 | 0.54386 | 18 | 13.25 | 8 | Given a lowercase Latin character (letter), check if it appears in the string ${codeforces}$.
-----Input-----
The first line of the input contains an integer $t$ ($1 \leq t \leq 26$) — the number of test cases.
The only line of each test case contains a character $c$ — a single lowercase Latin character (letter).
-----Output-----
For each test case, output "YES" (without quotes) if $c$ satisfies the condition, and "NO" (without quotes) otherwise.
You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).
-----Examples-----
Input
10
a
b
c
d
e
f
g
h
i
j
Output
NO
NO
YES
YES
YES
YES
NO
NO
NO
NO
-----Note-----
None | taco |
y = input()
x = input()
list = []
for letter in x:
list.append(letter)
a = list.count('x')
b = list.count('X')
count = 0
if a > b:
i = 0
while a > b:
if list[i] != 'X':
list[i] = 'X'
count += 1
i += 1
a = list.count('x')
b = list.count('X')
if a < b:
i = 0
while a < b:
if list[i] != 'x':
list[i] = 'x'
count += 1
i += 1
a = list.count('x')
b = list.count('X')
string = ''
for item in list:
string = string + item
print(count)
print(string)
| python | 10 | 0.509474 | 23 | 14.322581 | 31 | Pasha has many hamsters and he makes them work out. Today, n hamsters (n is even) came to work out. The hamsters lined up and each hamster either sat down or stood up.
For another exercise, Pasha needs exactly $\frac{n}{2}$ hamsters to stand up and the other hamsters to sit down. In one minute, Pasha can make some hamster ether sit down or stand up. How many minutes will he need to get what he wants if he acts optimally well?
-----Input-----
The first line contains integer n (2 ≤ n ≤ 200; n is even). The next line contains n characters without spaces. These characters describe the hamsters' position: the i-th character equals 'X', if the i-th hamster in the row is standing, and 'x', if he is sitting.
-----Output-----
In the first line, print a single integer — the minimum required number of minutes. In the second line, print a string that describes the hamsters' position after Pasha makes the required changes. If there are multiple optimal positions, print any of them.
-----Examples-----
Input
4
xxXx
Output
1
XxXx
Input
2
XX
Output
1
xX
Input
6
xXXxXx
Output
0
xXXxXx | taco |
for tc in range(int(eval(input()))):
n=eval(input())
esum,osum,count=0,1,0
while n!=1:
if n%2==0:
esum+=n
n=n//2
else:
osum+=n
n=3*n+1
count+=1
if esum%count>osum%count:
print('Even Rules')
elif esum%count<osum%count:
print('Odd Rules')
else:
print('Tie')
#print(esum,osum,count)
| python | 12 | 0.602564 | 36 | 16.333333 | 18 | Many of us are familiar with collatz sequence. Know the problem is, There is a fight going between the students of the class they have splitted up into two groups the odd rulers and the even rulers. To resolve this fight sir will randomly pick up the numbers and are written on the board. Teacher stated that if the total sum of all even numbers occuring in the collatz sequence for a number when it is divided by the total no of steps to reach 1 remainder is named as odd remainder will be compared with the even remainder i.e., sum of all odd numbers in sequence divided with steps the resulting remainder. If the odd remainder is greater than even then odd rulers win, if even remainder is more than odd remainder then even rulers win. if both are same then there is a tie.
INPUT:
First line contains number of test cases T.
Next T line contains a number N for each line
OUTPUT:
for every respective N print either "Even Rules" or "Odd Rules" or "Tie" according to the problem.
Explanation:
for n=4, steps followed are 4->2->1 no of steps is 2 and even sum is 6 and odd sum is 1 since 6%2 < 1%2 so Odd Rules
SAMPLE INPUT
2
3
4
SAMPLE OUTPUT
Even Rules
Odd Rules | taco |
n = int(input())
a = [0] * (n + 3)
p = [0] * (n + 3)
for i in range(n):
(t1, t2) = map(int, input().split())
a[i] = t1
p[i] = t2
pmin = p[0]
kq = p[0] * a[0]
for i in range(1, n):
pmin = min(pmin, p[i])
kq += pmin * a[i]
print(kq)
| python | 11 | 0.466102 | 37 | 17.153846 | 13 | Duff is addicted to meat! Malek wants to keep her happy for n days. In order to be happy in i-th day, she needs to eat exactly a_{i} kilograms of meat. [Image]
There is a big shop uptown and Malek wants to buy meat for her from there. In i-th day, they sell meat for p_{i} dollars per kilogram. Malek knows all numbers a_1, ..., a_{n} and p_1, ..., p_{n}. In each day, he can buy arbitrary amount of meat, also he can keep some meat he has for the future.
Malek is a little tired from cooking meat, so he asked for your help. Help him to minimize the total money he spends to keep Duff happy for n days.
-----Input-----
The first line of input contains integer n (1 ≤ n ≤ 10^5), the number of days.
In the next n lines, i-th line contains two integers a_{i} and p_{i} (1 ≤ a_{i}, p_{i} ≤ 100), the amount of meat Duff needs and the cost of meat in that day.
-----Output-----
Print the minimum money needed to keep Duff happy for n days, in one line.
-----Examples-----
Input
3
1 3
2 2
3 1
Output
10
Input
3
1 3
2 1
3 2
Output
8
-----Note-----
In the first sample case: An optimal way would be to buy 1 kg on the first day, 2 kg on the second day and 3 kg on the third day.
In the second sample case: An optimal way would be to buy 1 kg on the first day and 5 kg (needed meat for the second and third day) on the second day. | taco |
def divisible_by(numbers, divisor):
liste = []
for i in range(0, len(numbers)):
if numbers[i] % divisor == 0:
liste.append(numbers[i])
i += 1
return liste
| python | 11 | 0.63253 | 35 | 22.714286 | 7 | Complete the function which takes two arguments and returns all numbers which are divisible by the given divisor. First argument is an array of `numbers` and the second is the `divisor`.
## Example
```python
divisible_by([1, 2, 3, 4, 5, 6], 2) == [2, 4, 6]
``` | taco |
t = int(input())
for _ in range(t):
(n, m) = map(int, input().split())
a = []
for i in range(n):
l = input()
l = list(l)
a.append(l)
cnt = 0
l = []
for i in range(n - 1):
for j in range(m - 1):
v1 = int(a[i][j])
v2 = int(a[i][j + 1])
v3 = int(a[i + 1][j])
v4 = int(a[i + 1][j + 1])
if v1 + v2 + v3 + v4 == 3:
cnt += 1
if v2 == 0:
l.append([i + 1, j + 1, i + 2, j + 1, i + 2, j + 2])
a[i][j] = '0'
a[i + 1][j] = '0'
a[i + 1][j + 1] = '0'
elif v1 == 0:
l.append([i + 1, j + 2, i + 2, j + 1, i + 2, j + 2])
a[i][j + 1] = '0'
a[i + 1][j] = '0'
a[i + 1][j + 1] = '0'
elif v3 == 0:
l.append([i + 1, j + 1, i + 1, j + 2, i + 2, j + 2])
a[i][j] = '0'
a[i][j + 1] = '0'
a[i + 1][j + 1] = '0'
else:
l.append([i + 1, j + 1, i + 1, j + 2, i + 2, j + 1])
a[i][j] = '0'
a[i + 1][j] = '0'
a[i][j + 1] = '0'
if v1 + v2 + v3 + v4 == 2:
cnt += 2
if v1 == 0 and v2 == 0:
l.append([i + 2, j + 1, i + 1, j + 1, i + 1, j + 2])
l.append([i + 1, j + 1, i + 1, j + 2, i + 2, j + 2])
a[i + 1][j] = '0'
a[i + 1][j + 1] = '0'
if v1 == 0 and v3 == 0:
l.append([i + 1, j + 2, i + 1, j + 1, i + 2, j + 1])
l.append([i + 1, j + 1, i + 2, j + 1, i + 2, j + 2])
a[i][j + 1] = '0'
a[i + 1][j + 1] = '0'
if v1 == 0 and v4 == 0:
l.append([i + 1, j + 2, i + 1, j + 1, i + 2, j + 2])
l.append([i + 1, j + 1, i + 2, j + 1, i + 2, j + 2])
a[i + 1][j] = '0'
a[i][j + 1] = '0'
if v2 == 0 and v3 == 0:
l.append([i + 2, j + 1, i + 1, j + 1, i + 1, j + 2])
l.append([i + 1, j + 2, i + 2, j + 1, i + 2, j + 2])
a[i][j] = '0'
a[i + 1][j + 1] = '0'
if v2 == 0 and v4 == 0:
l.append([i + 1, j + 2, i + 1, j + 1, i + 2, j + 2])
l.append([i + 2, j + 1, i + 1, j + 2, i + 2, j + 2])
a[i][j] = '0'
a[i + 1][j] = '0'
if v3 == 0 and v4 == 0:
l.append([i + 2, j + 1, i + 1, j + 1, i + 2, j + 2])
l.append([i + 1, j + 2, i + 2, j + 1, i + 2, j + 2])
a[i][j] = '0'
a[i][j + 1] = '0'
if v1 + v2 + v3 + v4 == 1:
cnt += 3
if v1 == 1:
l.append([i + 1, j + 1, i + 1, j + 2, i + 2, j + 2])
l.append([i + 1, j + 2, i + 1, j + 1, i + 2, j + 1])
l.append([i + 1, j + 1, i + 2, j + 1, i + 2, j + 2])
a[i][j] = '0'
if v2 == 1:
l.append([i + 1, j + 1, i + 1, j + 2, i + 2, j + 2])
l.append([i + 1, j + 2, i + 1, j + 1, i + 2, j + 1])
l.append([i + 1, j + 2, i + 2, j + 1, i + 2, j + 2])
a[i][j + 1] = '0'
if v3 == 1:
l.append([i + 2, j + 1, i + 1, j + 1, i + 2, j + 2])
l.append([i + 1, j + 2, i + 1, j + 1, i + 2, j + 1])
l.append([i + 1, j + 2, i + 2, j + 1, i + 2, j + 2])
a[i + 1][j] = '0'
if v4 == 1:
l.append([i + 1, j + 1, i + 1, j + 2, i + 2, j + 2])
l.append([i + 2, j + 2, i + 1, j + 1, i + 2, j + 1])
l.append([i + 1, j + 2, i + 2, j + 1, i + 2, j + 2])
a[i + 1][j + 1] = '0'
if v1 + v2 + v3 + v4 == 4:
cnt += 4
l.append([i + 1, j + 1, i + 1, j + 2, i + 2, j + 2])
l.append([i + 2, j + 1, i + 1, j + 1, i + 2, j + 2])
l.append([i + 1, j + 2, i + 1, j + 1, i + 2, j + 1])
l.append([i + 1, j + 2, i + 2, j + 1, i + 2, j + 2])
a[i][j] = '0'
a[i][j + 1] = '0'
a[i + 1][j] = '0'
a[i + 1][j + 1] = '0'
print(cnt)
for i in range(len(l)):
print(*l[i])
| python | 17 | 0.324047 | 57 | 31.47619 | 105 | This is the easy version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem.
You are given a binary table of size n × m. This table consists of symbols 0 and 1.
You can make such operation: select 3 different cells that belong to one 2 × 2 square and change the symbols in these cells (change 0 to 1 and 1 to 0).
Your task is to make all symbols in the table equal to 0. You are allowed to make at most 3nm operations. You don't need to minimize the number of operations.
It can be proved that it is always possible.
Input
The first line contains a single integer t (1 ≤ t ≤ 5000) — the number of test cases. The next lines contain descriptions of test cases.
The first line of the description of each test case contains two integers n, m (2 ≤ n, m ≤ 100).
Each of the next n lines contains a binary string of length m, describing the symbols of the next row of the table.
It is guaranteed that the sum of nm for all test cases does not exceed 20000.
Output
For each test case print the integer k (0 ≤ k ≤ 3nm) — the number of operations.
In the each of the next k lines print 6 integers x_1, y_1, x_2, y_2, x_3, y_3 (1 ≤ x_1, x_2, x_3 ≤ n, 1 ≤ y_1, y_2, y_3 ≤ m) describing the next operation. This operation will be made with three cells (x_1, y_1), (x_2, y_2), (x_3, y_3). These three cells should be different. These three cells should belong into some 2 × 2 square.
Example
Input
5
2 2
10
11
3 3
011
101
110
4 4
1111
0110
0110
1111
5 5
01011
11001
00010
11011
10000
2 3
011
101
Output
1
1 1 2 1 2 2
2
2 1 3 1 3 2
1 2 1 3 2 3
4
1 1 1 2 2 2
1 3 1 4 2 3
3 2 4 1 4 2
3 3 4 3 4 4
4
1 2 2 1 2 2
1 4 1 5 2 5
4 1 4 2 5 1
4 4 4 5 3 4
2
1 3 2 2 2 3
1 2 2 1 2 2
Note
In the first test case, it is possible to make only one operation with cells (1, 1), (2, 1), (2, 2). After that, all symbols will be equal to 0.
In the second test case:
* operation with cells (2, 1), (3, 1), (3, 2). After it the table will be:
011
001
000
* operation with cells (1, 2), (1, 3), (2, 3). After it the table will be:
000
000
000
In the fifth test case:
* operation with cells (1, 3), (2, 2), (2, 3). After it the table will be:
010
110
* operation with cells (1, 2), (2, 1), (2, 2). After it the table will be:
000
000 | taco |
n = int(input())
s = input()
if s.count('b') == n or s.count('r') == n:
print(n // 2)
else:
s_r_count_r = 0
s_r_count_b = 0
s_b_count_r = 0
s_b_count_b = 0
for i in range(n):
if i % 2 == 0 and s[i] == 'r' or (i % 2 == 1 and s[i] == 'b'):
if i % 2 == 0:
s_b_count_b += 1
else:
s_b_count_r += 1
elif i % 2 == 0:
s_r_count_r += 1
else:
s_r_count_b += 1
print(min(max(s_r_count_r, s_r_count_b), max(s_b_count_r, s_b_count_b)))
| python | 13 | 0.47807 | 73 | 21.8 | 20 | Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room.
Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to alternate. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color.
Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.
-----Input-----
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of cockroaches.
The second line contains a string of length n, consisting of characters 'b' and 'r' that denote black cockroach and red cockroach respectively.
-----Output-----
Print one integer — the minimum number of moves Anatoly has to perform in order to make the colors of cockroaches in the line to alternate.
-----Examples-----
Input
5
rbbrr
Output
1
Input
5
bbbbb
Output
2
Input
3
rbr
Output
0
-----Note-----
In the first sample, Anatoly has to swap third and fourth cockroaches. He needs 1 turn to do this.
In the second sample, the optimum answer is to paint the second and the fourth cockroaches red. This requires 2 turns.
In the third sample, the colors of cockroaches in the line are alternating already, thus the answer is 0. | taco |
def check(a, k, m):
s = 0
for (i, v) in enumerate(a):
s += max(0, a[i] - i // k)
return s >= m
def main():
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
a.sort(reverse=True)
(left, right, ret) = (1, n, n + 1)
while left <= right:
mid = (left + right) // 2
if check(a, mid, m):
right = mid - 1
ret = mid
else:
left = mid + 1
print(ret if ret <= n else -1)
main()
| python | 13 | 0.516908 | 36 | 19.7 | 20 | The only difference between easy and hard versions is the constraints.
Polycarp has to write a coursework. The coursework consists of $m$ pages.
Polycarp also has $n$ cups of coffee. The coffee in the $i$-th cup Polycarp has $a_i$ caffeine in it. Polycarp can drink some cups of coffee (each one no more than once). He can drink cups in any order. Polycarp drinks each cup instantly and completely (i.e. he cannot split any cup into several days).
Surely, courseworks are not being written in a single day (in a perfect world of Berland, at least).
Let's consider some day of Polycarp's work. Consider Polycarp drinks $k$ cups of coffee during this day and caffeine dosages of cups Polycarp drink during this day are $a_{i_1}, a_{i_2}, \dots, a_{i_k}$. Then the first cup he drinks gives him energy to write $a_{i_1}$ pages of coursework, the second cup gives him energy to write $max(0, a_{i_2} - 1)$ pages, the third cup gives him energy to write $max(0, a_{i_3} - 2)$ pages, ..., the $k$-th cup gives him energy to write $max(0, a_{i_k} - k + 1)$ pages.
If Polycarp doesn't drink coffee during some day, he cannot write coursework at all that day.
Polycarp has to finish his coursework as soon as possible (spend the minimum number of days to do it). Your task is to find out this number of days or say that it is impossible.
-----Input-----
The first line of the input contains two integers $n$ and $m$ ($1 \le n \le 2 \cdot 10^5$, $1 \le m \le 10^9$) — the number of cups of coffee and the number of pages in the coursework.
The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$), where $a_i$ is the caffeine dosage of coffee in the $i$-th cup.
-----Output-----
If it is impossible to write the coursework, print -1. Otherwise print the minimum number of days Polycarp needs to do it.
-----Examples-----
Input
5 8
2 3 1 1 2
Output
4
Input
7 10
1 3 4 2 1 4 2
Output
2
Input
5 15
5 5 5 5 5
Output
1
Input
5 16
5 5 5 5 5
Output
2
Input
5 26
5 5 5 5 5
Output
-1
-----Note-----
In the first example Polycarp can drink fourth cup during first day (and write $1$ page), first and second cups during second day (and write $2 + (3 - 1) = 4$ pages), fifth cup during the third day (and write $2$ pages) and third cup during the fourth day (and write $1$ page) so the answer is $4$. It is obvious that there is no way to write the coursework in three or less days.
In the second example Polycarp can drink third, fourth and second cups during first day (and write $4 + (2 - 1) + (3 - 2) = 6$ pages) and sixth cup during second day (and write $4$ pages) so the answer is $2$. It is obvious that Polycarp cannot write the whole coursework in one day in this test.
In the third example Polycarp can drink all cups of coffee during first day and write $5 + (5 - 1) + (5 - 2) + (5 - 3) + (5 - 4) = 15$ pages of coursework.
In the fourth example Polycarp cannot drink all cups during first day and should drink one of them during the second day. So during first day he will write $5 + (5 - 1) + (5 - 2) + (5 - 3) = 14$ pages of coursework and during second day he will write $5$ pages of coursework. This is enough to complete it.
In the fifth example Polycarp cannot write the whole coursework at all, even if he will drink one cup of coffee during each day, so the answer is -1. | taco |
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define ld long double
#define fi first
#define se second
#define pb push_back
#define bip __builtin_popcountll
#define bic __builtin_ctzll
#pragma GCC optimize("O3,unroll-loops,Ofast")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
//#define int long long
#define pi pair<int,int>
#define pii pair<pair<int,int>,int>
const int MOD=1e9+7,MOD2=998244353,M=1009,N=1e6+9,BIG_PRIME=2305843009213693951;int n,m,k,ans,otv,x,z,l,r,q,mid,tt,kol,tek,tk,lst=-1,sm,y,in;bool ok;string s,t;char c;
// *************************************************************************************************
struct build
{
int v[10] = {0,0,0,0,0,0,0,0,0,0};
};
int A[10][N/5], sz[M];
auto cmp = [](build a, build b)
{
for (int i=0;i<n;i++)
{
if (a.v[i] < b.v[i]) return 1;
if (a.v[i] > b.v[i]) return 0;
}
};
auto cmp2 = [](build a, build b)
{
int sa=0,sb=0;
for (int i=0;i<n;i++) sa += A[i][a.v[i]], sb += A[i][b.v[i]];
if (sa > sb) return 1;
if (sa < sb) return 0;
return cmp(a, b);
};
set<build, decltype(cmp)> rejected(cmp);
build res;
set<build, decltype(cmp2)> maximal(cmp2);
void make()
{
build b;
while (1)
{
b = *maximal.begin();
maximal.erase(b);
if (rejected.find(b) == rejected.end())
{
for (int i=0;i<n;i++) cout << b.v[i] + 1 << " ";
return;
}
build nb;
for (int i=0;i<n;i++) nb.v[i] = b.v[i];
for (int i=0;i<n;i++)
{
if (!nb.v[i]) continue;
nb.v[i]--;
maximal.insert(nb);
nb.v[i]++;
}
}
}
// ************************************************************************************************
signed main()
{
cin.tie(0);cout.tie(0);ios_base::sync_with_stdio(0);
//*************************************************************************************************************************************************************************************************************************************
//freopen("input.txt", "r", stdin);
cin >> n;
for (int i=0;i<n;i++)
{
cin >> sz[i];
for (int j=0;j<sz[i];j++) cin >> A[i][j];
}
cin >> m;
for (int i=0;i<m;i++)
{
build b;
for (int j=0;j<n;j++)
{
cin >> x;
x--;
b.v[j] = x;
}
rejected.insert(b);
}
build big;
for (int i=0;i<n;i++) big.v[i] = sz[i] - 1;
maximal.insert(big);
make();
return 0;
}
| c++ | 14 | 0.401779 | 235 | 13.2 | 190 | D. The Strongest Buildtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIvan is playing yet another roguelike computer game. He controls a single hero in the game. The hero has $$$n$$$ equipment slots. There is a list of $$$c_i$$$ items for the $$$i$$$-th slot, the $$$j$$$-th of them increases the hero strength by $$$a_{i,j}$$$. The items for each slot are pairwise distinct and are listed in the increasing order of their strength increase. So, $$$a_{i,1} < a_{i,2} < \dots < a_{i,c_i}$$$.For each slot Ivan chooses exactly one item. Let the chosen item for the $$$i$$$-th slot be the $$$b_i$$$-th item in the corresponding list. The sequence of choices $$$[b_1, b_2, \dots, b_n]$$$ is called a build.The strength of a build is the sum of the strength increases of the items in it. Some builds are banned from the game. There is a list of $$$m$$$ pairwise distinct banned builds. It's guaranteed that there's at least one build that's not banned.What is the build with the maximum strength that is not banned from the game? If there are multiple builds with maximum strength, print any of them.InputThe first line contains a single integer $$$n$$$ ($$$1 \le n \le 10$$$) — the number of equipment slots.The $$$i$$$-th of the next $$$n$$$ lines contains the description of the items for the $$$i$$$-th slot. First, one integer $$$c_i$$$ ($$$1 \le c_i \le 2 \cdot 10^5$$$) — the number of items for the $$$i$$$-th slot. Then $$$c_i$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,c_i}$$$ ($$$1 \le a_{i,1} < a_{i,2} < \dots < a_{i,c_i} \le 10^8$$$).The sum of $$$c_i$$$ doesn't exceed $$$2 \cdot 10^5$$$.The next line contains a single integer $$$m$$$ ($$$0 \le m \le 10^5$$$) — the number of banned builds.Each of the next $$$m$$$ lines contains a description of a banned build — a sequence of $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le c_i$$$).The builds are pairwise distinct, and there's at least one build that's not banned.OutputPrint the build with the maximum strength that is not banned from the game. If there are multiple builds with maximum strength, print any of them.ExamplesInput
3
3 1 2 3
2 1 5
3 2 4 6
2
3 2 3
3 2 2
Output
2 2 3
Input
3
3 1 2 3
2 1 5
3 2 4 6
2
3 2 3
2 2 3
Output
1 2 3
Input
3
3 1 2 3
2 1 5
3 2 4 6
2
3 2 3
2 2 3
Output
3 2 2
Input
4
1 10
1 4
1 7
1 3
0
Output
1 1 1 1 | cf |
class Solution:
def maximumMeetings(self, n, start, end):
jobs = []
ans = 0
for i in range(n):
jobs.append([start[i], end[i], i])
jobs.sort(key=lambda x: x[1])
curr_job = jobs[0]
ans += 1
for i in range(1, n):
if curr_job[1] < jobs[i][0]:
ans += 1
curr_job = jobs[i]
return ans
| python | 12 | 0.564516 | 42 | 19.666667 | 15 | There is one meeting room in a firm. There are N meetings in the form of (start[i], end[i]) where start[i] is start time of meeting i and end[i] is finish time of meeting i.
What is the maximum number of meetings that can be accommodated in the meeting room when only one meeting can be held in the meeting room at a particular time?
Note: Start time of one chosen meeting can't be equal to the end time of the other chosen meeting.
Example 1:
Input:
N = 6
start[] = {1,3,0,5,8,5}
end[] = {2,4,6,7,9,9}
Output:
4
Explanation:
Maximum four meetings can be held with
given start and end timings.
The meetings are - (1, 2),(3, 4), (5,7) and (8,9)
Example 2:
Input:
N = 3
start[] = {10, 12, 20}
end[] = {20, 25, 30}
Output:
1
Explanation:
Only one meetings can be held
with given start and end timings.
Your Task :
You don't need to read inputs or print anything. Complete the function maxMeetings() that takes two arrays start[] and end[] along with their size N as input parameters and returns the maximum number of meetings that can be held in the meeting room.
Expected Time Complexity : O(N*LogN)
Expected Auxilliary Space : O(N)
Constraints:
1 ≤ N ≤ 10^{5}
0 ≤ start[i] < end[i] ≤ 10^{5} | taco |
End of preview. Expand
in Dataset Viewer.
This dataset contains deduplicated data from TACO dataset, and additional 107k CodeForces solutions in Python, Java, C++ from this link.
Filtering strategy:
- AST parsability: we extracted only the AST parsable codes
- AST Depth: only samples with depth from 2.0 to 31.0
- Maximum Line Length: only samples with a maximum of 12.0 to 400.0 characters
- Average Line Length: only samples with 5.0 to 140.0 characters on average
- Alphanumeric Fraction of samples greater than 0.2 and less than 0.75
- Number of Lines: from 6.0 to 300.0
- Language Filter: samples whose docstring scores an English language confidence greater than 99% by the
lingua
language detector - Deduplication: samples MinHash deduplicated using a shingle size of 8 and a similarity threshold of 0.8
- Downloads last month
- 32