Muennighoff/xP3x-sample huggingface dataset:
inputs: I found an interesting problem on https://www.codechef.com/SIC2016/problems/SANTA:
It's Christmas time and Santa is in town. There are N children each having a bag with a mission to fill in as many toffees as possible. They are accompanied by a teacher whose ulterior motive is to test their counting skills. The toffees are of different brands (denoted by lowercase letters a-z). Santa picks up a child numbered m and gives n toffees of brand p to the child.

The teacher wishes to ask the children to calculate the number of toffees there are of a particular brand amongst a given range of children. Formally, there are 2 queries:

Input:

First line consists of Q queries.

Each line follows and consists of four space separated values:

Type 1: It is of the form 1 m x p

1 is the type no,"m" is the child to which "x" toffees of a brand "p" are given

Type 2: It is of the form 2 m n p
where m - n is the range of children (inclusive) being queried for brand p

Output:

Report the sum of toffees of brand p within the given range m - n for each query of type 2

Constraints:

1 <= Q <= 10^5

1 <= N <= 10^6

1 <= m <= n <= 10^6

1 <= x <= 10^6

all brand of toffees are lowercase letters

Subtask 1: (30 points)

1 <= Q <= 10^3

1 <= m <= n <= 10^3

1 <= x <= 10^3

Subtask 2: (70 points)

Original Constraints

Sample Input:

5

1 3 4 a

1 5 8 a

1 1 7 x

2 1 6 a

2 3 6 y

Sample Output:

12

0

In first case, there are two children between 3 and 5 between 0 - 6  having sum (4 + 8)

There's no toffee for y in given range

I tried it in Python, but could not do it. Can you solve it?
targets: import numpy as np

N=10**6+1
t=eval(input())
inp = ()

t1=ord('z')
#bag=[[0  for _ in xrange(t1)] for _ in xrange(N+1)]
bag=np.zeros((N+1,t1),dtype=np.int)
#print bag
while t:
 t-=1
 inp=input().split()
 t2=ord(inp[3]) - ord('a')
 t3=int(inp[1])
 t4=int(inp[2]) + 1
 if inp[0]=="1":
  #print "enter"
  bag[t3][t2]+=int(inp[2])


 if inp[0]=="2":
  sum=0
  for i in range(t3,t4):
   sum+=bag[i][t2]
  print(sum)

#
# for j in range(ord('z')-ord('a')):
#     for i in range(N+1):
#         if bag[i][j]!=0:
#             print bag[i][j] ,i,j
inputs: Solve in Python:
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K(odd) to form a new pattern. Help the chef to code this pattern problem.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow. 
- Each test case contains a single line of input, one integer $K$. 

-----Output:-----
For each test case, output as the pattern.

-----Constraints-----
- $1 \leq T \leq 50$
- $1 \leq K \leq 50$

-----Sample Input:-----
4
1
3
5
7

-----Sample Output:-----
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*

-----EXPLANATION:-----
No need, else pattern can be decode easily.
targets: t=int(input())
while(t):
    n=int(input())
    p=int(n/2)
    p=p+1
    for i in range(0,p):
        for j in range(0,i):
            if(j>=0):
                print(end=" ")
        print("*")
    p=p-2
    for i in range(p,0,-1):
        for j in range(0,i):
            print(end=" ")
        print("*")
    
    if(n>1):
        print("*")
    t=t-1
inputs: I found an interesting problem on https://www.codewars.com/kata/59841e5084533834d6000025:
Iahub got bored, so he invented a game to be played on paper.
 He writes n integers a1, a2, ..., an. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≤ i ≤ j ≤ n) and flips all values ak for which their positions are in range [i, j] (that is i ≤ k ≤ j). Flip the value of x means to apply operation x = 1 - x.
 The goal of the game is that after exactly one move to obtain the maximum number of ones. Write a program to solve the little game of Iahub.
```
@param {Array} line of the input there are n integers: a1, a2, ..., an. 1 ≤ n ≤ 100. It is guaranteed that each of those n values is either 0 or 1
@return {Integer} the maximal number of 1s that can be obtained after exactly one move
```
Examples :
```
[1, 0, 0, 1, 0, 0]  =>  5
[1, 0, 0, 1]  =>  4

```
Note:
 In the first case, flip the segment from 2 to 6 (i = 2, j = 6). That flip changes the sequence, it becomes: [1 1 1 0 1 1]. So, it contains four ones. There is no way to make the whole sequence equal to [1 1 1 1 1 1].
 In the second case, flipping only the second and the third element (i = 2, j = 3) will turn all numbers into 1.

(c)ll931110 & fchirica

I tried it in Python, but could not do it. Can you solve it?
targets: def flipping_game(num):
    all_pairs = ((i, j) for i in range(len(num)) for j in range(i + 1, len(num) + 1))
    ones = (sum(num[:i]) + j - i - sum(num[i:j]) + sum(num[j:]) for i, j in all_pairs)
    return max(ones)
inputs: Solve in Python:
For this problem you must create a program that says who ate the last cookie. If the input is a string then "Zach" ate the cookie. If the input is a float or an int then "Monica" ate the cookie. If the input is anything else "the dog" ate the cookie. The way to return the statement is:
"Who ate the last cookie? It was (name)!"

Ex: Input = "hi" --> Output = "Who ate the last cookie? It was Zach!
(The reason you return Zach is because the input is a string)

Note: Make sure you return the correct message with correct spaces and punctuation.

Please leave feedback for this kata.
Cheers!
targets: def cookie(x):
    if isinstance(x, bool): return "Who ate the last cookie? It was the dog!"
    if isinstance(x, str): return "Who ate the last cookie? It was Zach!"
    if isinstance(x, (int,float)): return "Who ate the last cookie? It was Monica!"
    return "Who ate the last cookie? It was the dog!"
inputs: Solve in Python:
Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store. 

Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group.

Jzzhu wonders how to get the maximum possible number of groups. Can you help him?


-----Input-----

A single integer n (1 ≤ n ≤ 10^5), the number of the apples.


-----Output-----

The first line must contain a single integer m, representing the maximum number of groups he can get. Each of the next m lines must contain two integers — the numbers of apples in the current group.

If there are several optimal answers you can print any of them.


-----Examples-----
Input
6

Output
2
6 3
2 4

Input
9

Output
3
9 3
2 4
6 8

Input
2

Output
0
targets: """
Codeforces Round 257 Div 1 Problem C

Author  : chaotic_iak
Language: Python 3.3.4
"""

def read(mode=2):
    # 0: String
    # 1: List of strings
    # 2: List of integers
    inputs = input().strip()
    if mode == 0:
        return inputs
    if mode == 1:
        return inputs.split()
    if mode == 2:
        return [int(x) for x in inputs.split()]

def write(s="\n"):
    if isinstance(s, list): s = " ".join(map(str,s))
    s = str(s)
    print(s, end="")

################################################### SOLUTION

# croft algorithm to generate primes
# from pyprimes library, not built-in, just google it
from itertools import compress
import itertools
def croft():
    """Yield prime integers using the Croft Spiral sieve.

    This is a variant of wheel factorisation modulo 30.
    """
    # Implementation is based on erat3 from here:
    #   http://stackoverflow.com/q/2211990
    # and this website:
    #   http://www.primesdemystified.com/
    # Memory usage increases roughly linearly with the number of primes seen.
    # dict ``roots`` stores an entry x:p for every prime p.
    for p in (2, 3, 5):
        yield p
    roots = {9: 3, 25: 5}  # Map d**2 -> d.
    primeroots = frozenset((1, 7, 11, 13, 17, 19, 23, 29))
    selectors = (1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0)
    for q in compress(
            # Iterate over prime candidates 7, 9, 11, 13, ...
            itertools.islice(itertools.count(7), 0, None, 2),
            # Mask out those that can't possibly be prime.
            itertools.cycle(selectors)
            ):
        # Using dict membership testing instead of pop gives a
        # 5-10% speedup over the first three million primes.
        if q in roots:
            p = roots[q]
            del roots[q]
            x = q + 2*p
            while x in roots or (x % 30) not in primeroots:
                x += 2*p
            roots[x] = p
        else:
            roots[q*q] = q
            yield q

n, = read()
cr = croft()
primes = []
for i in cr:
    if i < n:
       ...
inputs: I found an interesting problem on https://codeforces.com/problemset/problem/572/B:
In this task you need to process a set of stock exchange orders and use them to create order book.

An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number i has price p_{i}, direction d_{i} — buy or sell, and integer q_{i}. This means that the participant is ready to buy or sell q_{i} stocks at price p_{i} for one stock. A value q_{i} is also known as a volume of an order.

All orders with the same price p and direction d are merged into one aggregated order with price p and direction d. The volume of such order is a sum of volumes of the initial orders.

An order book is a list of aggregated orders, the first part of which contains sell orders sorted by price in descending order, the second contains buy orders also sorted by price in descending order.

An order book of depth s contains s best aggregated orders for each direction. A buy order is better if it has higher price and a sell order is better if it has lower price. If there are less than s aggregated orders for some direction then all of them will be in the final order book.

You are given n stock exhange orders. Your task is to print order book of depth s for these orders.


-----Input-----

The input starts with two positive integers n and s (1 ≤ n ≤ 1000, 1 ≤ s ≤ 50), the number of orders and the book depth.

Next n lines contains a letter d_{i} (either 'B' or 'S'), an integer p_{i} (0 ≤ p_{i} ≤ 10^5) and an integer q_{i} (1 ≤ q_{i} ≤ 10^4) — direction, price and volume respectively. The letter 'B' means buy, 'S' means sell. The price of any sell order is higher than the price of any buy order.


-----Output-----

Print no more than 2s lines with aggregated orders from order book of depth s. The output format for orders should be the same as in input.


-----Examples-----
Input
6 2
B 10 3
S 50 2
S 40 1
S 50 6
B 20 4
B 25 10

Output
S 50 8
S 40 1
B 25 10
B 20 4



-----Note-----

Denote (x, y) an order with price x and volume y. There are 3 aggregated buy orders (10, 3), (20, 4), (25, 10) and two...

I tried it in Python, but could not do it. Can you solve it?
targets: s = input()
n, d = int(s.split()[0]), int(s.split()[1])
b, s = {}, {}
wb, ws = [], []
for i in range(0, n):
	st = input().split()
	st[1] = int(st[1])
	st[2] = int(st[2])
	if st[0] == 'B':
		if st[1] not in b:
			b[st[1]] = st[2]
		else:
			b[st[1]] += st[2];
		if st[1] not in wb:
			wb.append(st[1]);
	else:
		if st[1] not in s:
			s[st[1]] = st[2]
		else:
			s[st[1]] += st[2];
		if st[1] not in ws:
			ws.append(st[1]);
ws.sort()#[:d]#.sort(reverse=True)
wb.sort(reverse=True)#[:d]
ws = ws[:d]
wb = wb[:d]
ws.sort(reverse=True)
for i in ws:
	print('S %s %s' %(i, s[i]))
for i in wb:
	print('B %s %s' %(i, b[i]))
inputs: I found an interesting problem on https://codeforces.com/problemset/problem/1336/A:
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.

[Image] 

There are $n$ cities and $n-1$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $1$ to $n$, and the city $1$ is the capital of the kingdom. So, the kingdom has a tree structure.

As the queen, Linova plans to choose exactly $k$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.

A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).

Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.

In order to be a queen loved by people, Linova wants to choose $k$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?


-----Input-----

The first line contains two integers $n$ and $k$ ($2\le n\le 2 \cdot 10^5$, $1\le k< n$)  — the number of cities and industry cities respectively.

Each of the next $n-1$ lines contains two integers $u$ and $v$ ($1\le u,v\le n$), denoting there is a road connecting city $u$ and city $v$.

It is guaranteed that from any city, you can reach any other city by the roads.


-----Output-----

Print the only line containing a single integer  — the maximum possible sum of happinesses of all envoys.


-----Examples-----
Input
7 4
1 2
1 3
1 4
3 5
3 6
4 7

Output
7
Input
4 1
1 2
1 3
2 4

Output
2
Input
8 5
7 5
1 7
6 1
3 7
8 3
2 1
4 5

Output
9


-----Note-----

[Image]

In the first example, Linova can choose cities $2$, $5$, $6$, $7$ to develop industry, then the happiness of the envoy from city $2$ is...

I tried it in Python, but could not do it. Can you solve it?
targets: import sys
input = sys.stdin.readline

n, k = list(map(int, input().split()))

begin = [-1] * n
end = [-1] * n
hurt = [-1] * n

adj = [[] for i in range(n)]
for _ in range(n-1):
    u ,v = list(map(int, input().split()))
    adj[u-1].append(v-1)
    adj[v-1].append(u-1)

hurt[0] = 1
begin[0] = 0
stack = [0]
curr = 1
while stack:
    nex = stack[-1]
    if adj[nex]:
        v = adj[nex].pop()
        if begin[v] == -1:
            begin[v] = curr
            curr += 1
            stack.append(v)
            hurt[v] = len(stack)
    else:
        end[nex] = curr
        stack.pop()

desc = [end[i] - begin[i]-hurt[i] for i in range(n)]
desc.sort(reverse = True)
out = 0
for i in range(n - k):
    out += desc[i]
print(out)
inputs: Solve in Python:
Write a function called `LCS` that accepts two sequences and returns the longest subsequence common to the passed in sequences.

### Subsequence
A subsequence is different from a substring. The terms of a subsequence need not be consecutive terms of the original sequence.

### Example subsequence
Subsequences of `"abc"` = `"a"`, `"b"`, `"c"`, `"ab"`, `"ac"`, `"bc"` and `"abc"`.

### LCS examples
```python
lcs( "abcdef" , "abc" ) => returns "abc"
lcs( "abcdef" , "acf" ) => returns "acf"
lcs( "132535365" , "123456789" ) => returns "12356"
```

### Notes
* Both arguments will be strings
* Return value must be a string
* Return an empty string if there exists no common subsequence
* Both arguments will have one or more characters (in JavaScript)
* All tests will only have a single longest common subsequence. Don't worry about cases such as `LCS( "1234", "3412" )`, which would have two possible longest common subsequences: `"12"` and `"34"`.

Note that the Haskell variant will use randomized testing, but any longest common subsequence will be valid.

Note that the OCaml variant is using generic lists instead of strings, and will also have randomized tests (any longest common subsequence will be valid).

### Tips

Wikipedia has an explanation of the two properties that can be used to solve the problem:

- [First property](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#First_property)
- [Second property](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Second_property)
targets: def lcs(x, y):
    if not x or not y: return ""
    if x[0] == y[0]: return x[0] + lcs(x[1:], y[1:])
    
    return max(lcs(x[1:], y), lcs(x, y[1:]), key=len)
inputs: I found an interesting problem on https://codeforces.com/problemset/problem/250/E:
Joe has been hurt on the Internet. Now he is storming around the house, destroying everything in his path.

Joe's house has n floors, each floor is a segment of m cells. Each cell either contains nothing (it is an empty cell), or has a brick or a concrete wall (always something one of three). It is believed that each floor is surrounded by a concrete wall on the left and on the right.

Now Joe is on the n-th floor and in the first cell, counting from left to right. At each moment of time, Joe has the direction of his gaze, to the right or to the left (always one direction of the two). Initially, Joe looks to the right.

Joe moves by a particular algorithm. Every second he makes one of the following actions:   If the cell directly under Joe is empty, then Joe falls down. That is, he moves to this cell, the gaze direction is preserved.  Otherwise consider the next cell in the current direction of the gaze.   If the cell is empty, then Joe moves into it, the gaze direction is preserved.  If this cell has bricks, then Joe breaks them with his forehead (the cell becomes empty), and changes the direction of his gaze to the opposite.  If this cell has a concrete wall, then Joe just changes the direction of his gaze to the opposite (concrete can withstand any number of forehead hits).  

Joe calms down as soon as he reaches any cell of the first floor.

The figure below shows an example Joe's movements around the house.

 [Image] 

Determine how many seconds Joe will need to calm down.


-----Input-----

The first line contains two integers n and m (2 ≤ n ≤ 100, 1 ≤ m ≤ 10^4).

Next n lines contain the description of Joe's house. The i-th of these lines contains the description of the (n - i + 1)-th floor of the house — a line that consists of m characters: "." means an empty cell, "+" means bricks and "#" means a concrete wall.

It is guaranteed that the first cell of the n-th floor is empty.


-----Output-----

Print a single number — the number of seconds Joe needs to reach the first floor; or else, print word...

I tried it in Python, but could not do it. Can you solve it?
targets: n, m = [int(i) for i in input().split()]
current_floor = list(input())

x, t, direction = 0, 0, 1

for i in range(n-1):
    floor = list(input())
    l, r = x, x
    wall = 0
    while True:
        t += 1
        if floor[x] == '.':
            break
        if (x + direction == m) or (x + direction < 0) or (current_floor[x+direction] == '#'):
            wall += 1
            direction = -direction
            if wall == 2:
                print("Never")
                return
        elif current_floor[x+direction] == '+':
            wall = 0
            current_floor[x+direction] = '.'
            direction = -direction
        elif l <= x+direction and x+direction <= r:
            if direction == 1:
                t += r-x-1
                x = r
            else:
                t += x-l-1
                x = l
        else:
            x += direction
            r = max(r, x)
            l = min(l, x)
    current_floor, floor = floor, current_floor
print(t)
inputs: Solve in Python:
We often go to supermarkets to buy some fruits or vegetables, and on the tag there prints the price for a kilo. But in some supermarkets, when asked how much the items are, the clerk will say that $a$ yuan for $b$ kilos (You don't need to care about what "yuan" is), the same as $a/b$ yuan for a kilo.

Now imagine you'd like to buy $m$ kilos of apples. You've asked $n$ supermarkets and got the prices. Find the minimum cost for those apples.

You can assume that there are enough apples in all supermarkets.


-----Input-----

The first line contains two positive integers $n$ and $m$ ($1 \leq n \leq 5\,000$, $1 \leq m \leq 100$), denoting that there are $n$ supermarkets and you want to buy $m$ kilos of apples.

The following $n$ lines describe the information of the supermarkets. Each line contains two positive integers $a, b$ ($1 \leq a, b \leq 100$), denoting that in this supermarket, you are supposed to pay $a$ yuan for $b$ kilos of apples.


-----Output-----

The only line, denoting the minimum cost for $m$ kilos of apples. Please make sure that the absolute or relative error between your answer and the correct answer won't exceed $10^{-6}$.

Formally, let your answer be $x$, and the jury's answer be $y$. Your answer is considered correct if $\frac{|x - y|}{\max{(1, |y|)}} \le 10^{-6}$.


-----Examples-----
Input
3 5
1 2
3 4
1 3

Output
1.66666667

Input
2 1
99 100
98 99

Output
0.98989899



-----Note-----

In the first sample, you are supposed to buy $5$ kilos of apples in supermarket $3$. The cost is $5/3$ yuan.

In the second sample, you are supposed to buy $1$ kilo of apples in supermarket $2$. The cost is $98/99$ yuan.
targets: n, m = [int(i) for i in input().split()]
ans = 10 ** 9
for i in range(n):
    a1, a2 = [int(i) for i in input().split()]
    ans = min(ans, a1 * m / a2)
print(ans)
inputs: Solve in Python:
An army of n droids is lined up in one row. Each droid is described by m integers a_1, a_2, ..., a_{m}, where a_{i} is the number of details of the i-th type in this droid's mechanism. R2-D2 wants to destroy the sequence of consecutive droids of maximum length. He has m weapons, the i-th weapon can affect all the droids in the army by destroying one detail of the i-th type (if the droid doesn't have details of this type, nothing happens to it). 

A droid is considered to be destroyed when all of its details are destroyed. R2-D2 can make at most k shots. How many shots from the weapon of what type should R2-D2 make to destroy the sequence of consecutive droids of maximum length?


-----Input-----

The first line contains three integers n, m, k (1 ≤ n ≤ 10^5, 1 ≤ m ≤ 5, 0 ≤ k ≤ 10^9) — the number of droids, the number of detail types and the number of available shots, respectively.

Next n lines follow describing the droids. Each line contains m integers a_1, a_2, ..., a_{m} (0 ≤ a_{i} ≤ 10^8), where a_{i} is the number of details of the i-th type for the respective robot.


-----Output-----

Print m space-separated integers, where the i-th number is the number of shots from the weapon of the i-th type that the robot should make to destroy the subsequence of consecutive droids of the maximum length.

If there are multiple optimal solutions, print any of them. 

It is not necessary to make exactly k shots, the number of shots can be less.


-----Examples-----
Input
5 2 4
4 0
1 2
2 1
0 2
1 3

Output
2 2

Input
3 2 4
1 2
1 3
2 2

Output
1 3



-----Note-----

In the first test the second, third and fourth droids will be destroyed. 

In the second test the first and second droids will be destroyed.
targets: from heapq import heappush, heappop
from sys import setrecursionlimit
from sys import stdin
from collections import defaultdict
setrecursionlimit(1000000007)
_data = iter(stdin.read().split('\n'))
def input():
    return next(_data)

n, m, k = [int(x) for x in input().split()]
a = tuple(tuple(-int(x) for x in input().split()) for i in range(n))
heaps = tuple([0] for _ in range(m))
removed = tuple(defaultdict(int) for _ in range(m))

rv = -1
rt = (0,) * m
t = [0] * m
p = 0
for i in range(n):
    ai = a[i]
    for j, v, heap in zip(range(m), ai, heaps):
        heappush(heap, v)
        t[j] = heap[0]
    while -sum(t) > k:
        ap = a[p]
        for j, v, heap, remd in zip(range(m), ap, heaps, removed):
            remd[v] += 1
            while heap[0] in remd:
                top = heappop(heap)
                if remd[top] == 1:
                   del remd[top]
                else:
                    remd[top] -= 1
            t[j] = heap[0]
        p += 1
    if rv < (i + 1) - p:
        rv = (i + 1) - p
        rt = tuple(t)
print(*map(lambda x: -x, rt))
inputs: Solve in Python:
Kefa decided to celebrate his first big salary by going to the restaurant. 

He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.

The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. 

Your task is to help Kefa count the number of restaurants where he can go.


-----Input-----

The first line contains two integers, n and m (2 ≤ n ≤ 10^5, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa.

The second line contains n integers a_1, a_2, ..., a_{n}, where each a_{i} either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat).

Next n - 1 lines contains the edges of the tree in the format "x_{i} y_{i}" (without the quotes) (1 ≤ x_{i}, y_{i} ≤ n, x_{i} ≠ y_{i}), where x_{i} and y_{i} are the vertices of the tree, connected by an edge. 

It is guaranteed that the given set of edges specifies a tree.


-----Output-----

A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats.


-----Examples-----
Input
4 1
1 1 0 0
1 2
1 3
1 4

Output
2

Input
7 1
1 0 1 1 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7

Output
2



-----Note-----

Let us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.

Note to the first sample test:...
targets: n, m = input().split()
n, m = int(n), int(m)
a = list( map( int , input().split() ) )
v = [ [] for _ in range( n ) ]
for i in range( n - 1 ):
  x = list( map( int , input().split() ) )
  x[ 0 ], x[ 1 ] = int(x[ 0 ]) - 1, int(x[ 1 ]) - 1
  v[ x[ 0 ] ].append( x[ 1 ] )
  v[ x[ 1 ] ].append( x[ 0 ] )
tag = [False] * n
con = [0] * n
from collections import deque as dq
d = dq()
d.append( 0 )
con[ 0 ] = a[ 0 ]
tag[ 0 ] = True
ans = 0
while len(d) > 0:
  x, chd = d.popleft(), 0
  #  print( ( x , con[ x ] ) )
  if con[ x ] > m: continue
  for y in v[x]:
    if not tag[ y ]:
      con[ y ] = con[ x ] + a[ y ] if a[ y ] == 1 else 0
      tag[ y ] = True
      chd += 1
      d.append( y )
  if chd == 0 and con[ x ] <= m:
    ans += 1
print( ans )
inputs: Solve in Python:
# Task
 The string is called `prime` if it cannot be constructed by concatenating some (more than one) equal strings together.

 For example, "abac" is prime, but "xyxy" is not("xyxy"="xy"+"xy").
 
 Given a string determine if it is prime or not.

# Input/Output


 - `[input]` string `s`

  string containing only lowercase English letters

 - `[output]` a boolean value

  `true` if the string is prime, `false` otherwise
targets: def prime_string(s):
    return (s + s).find(s, 1) == len(s)
inputs: I found an interesting problem on https://www.codewars.com/kata/57f7796697d62fc93d0001b8:
Given an array of integers (x), and a target (t), you must find out if any two consecutive numbers in the array sum to t. If so, remove the second number.

Example:

x = [1, 2, 3, 4, 5]
t = 3 

1+2 = t, so remove 2. No other pairs = t, so rest of array remains:

[1, 3, 4, 5]

Work through the array from left to right.

Return the resulting array.

I tried it in Python, but could not do it. Can you solve it?
targets: from functools import reduce

def trouble(x, t):
    return reduce(lambda a, u: a + ([u] if not a or a[-1] + u != t else []), x[1:], x[0:1])
inputs: Solve in Python:
Appleman and Toastman play a game. Initially Appleman gives one group of n numbers to the Toastman, then they start to complete the following tasks:  Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman.  Each time Appleman gets a group consisting of a single number, he throws this group out. Each time Appleman gets a group consisting of more than one number, he splits the group into two non-empty groups (he can do it in any way) and gives each of them to Toastman. 

After guys complete all the tasks they look at the score value. What is the maximum possible value of score they can get?


-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 3·10^5). The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^6) — the initial group that is given to Toastman.


-----Output-----

Print a single integer — the largest possible score.


-----Examples-----
Input
3
3 1 5

Output
26

Input
1
10

Output
10



-----Note-----

Consider the following situation in the first example. Initially Toastman gets group [3, 1, 5] and adds 9 to the score, then he give the group to Appleman. Appleman splits group [3, 1, 5] into two groups: [3, 5] and [1]. Both of them should be given to Toastman. When Toastman receives group [1], he adds 1 to score and gives the group to Appleman (he will throw it out). When Toastman receives group [3, 5], he adds 8 to the score and gives the group to Appleman. Appleman splits [3, 5] in the only possible way: [5] and [3]. Then he gives both groups to Toastman. When Toastman receives [5], he adds 5 to the score and gives the group to Appleman (he will throws it out). When Toastman receives [3], he adds 3 to the score and gives the group to Appleman (he will throws it out). Finally Toastman have added 9 + 1 + 8 + 5 + 3 = 26 to the score. This is the optimal sequence of actions.
targets: n = int(input())
a = list(map(int, input().split()))

a.sort(reverse=True)
s = sum(a)

res = s

while len(a) > 1:
    res += s
    s -= a.pop()

print(res)
inputs: Solve in Python:
You've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer c_{i}.

Let's consider all vertices of the graph, that are painted some color k. Let's denote a set of such as V(k). Let's denote the value of the neighbouring color diversity for color k as the cardinality of the set Q(k) = {c_{u} :  c_{u} ≠ k and there is vertex v belonging to set V(k) such that nodes v and u are connected by an edge of the graph}.

Your task is to find such color k, which makes the cardinality of set Q(k) maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color k, that the graph has at least one vertex with such color.


-----Input-----

The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 10^5) — the number of vertices end edges of the graph, correspondingly. The second line contains a sequence of integers c_1, c_2, ..., c_{n} (1 ≤ c_{i} ≤ 10^5) — the colors of the graph vertices. The numbers on the line are separated by spaces.

Next m lines contain the description of the edges: the i-th line contains two space-separated integers a_{i}, b_{i} (1 ≤ a_{i}, b_{i} ≤ n; a_{i} ≠ b_{i}) — the numbers of the vertices, connected by the i-th edge. 

It is guaranteed that the given graph has no self-loops or multiple edges.


-----Output-----

Print the number of the color which has the set of neighbours with the maximum cardinality. It there are multiple optimal colors, print the color with the minimum number. Please note, that you want to find such color, that the graph has at least one vertex with such color.


-----Examples-----
Input
6 6
1 1 2 3 5 8
1 2
3 2
1 4
4 3
4 5
4 6

Output
3

Input
5 6
4 2 5 2 4
1 2
2 3
3 1
5 3
5 4
3 4

Output
2
targets: from collections import defaultdict
n,m = map(int,input().split())
g = defaultdict(set)
c = list(map(int,input().split()))
for _ in range(m):
    x,y = map(int,input().split())
    if(c[x-1]!=c[y-1]):g[c[x-1]].add(c[y-1])
    if(c[y-1]!=c[x-1]):g[c[y-1]].add(c[x-1])
ma = 0
co = 10**5 + 1      
f = 0   
for i in g:
    ma = max(ma,len(g[i]))
for i in g:
    if(len(g[i])==ma):
        f+=1
        co = min(co,i)
if(f==0):
    co = min(c)
print(co)
inputs: I found an interesting problem on https://codeforces.com/problemset/problem/853/A:
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.

Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.

All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.

Helen knows that each minute of delay of the i-th flight costs airport c_{i} burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.


-----Input-----

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart.

The second line contains n integers c_1, c_2, ..., c_{n} (1 ≤ c_{i} ≤ 10^7), here c_{i} is the cost of delaying the i-th flight for one minute.


-----Output-----

The first line must contain the minimum possible total cost of delaying the flights.

The second line must contain n different integers t_1, t_2, ..., t_{n} (k + 1 ≤ t_{i} ≤ k + n), here t_{i} is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.


-----Example-----
Input
5 2
4 2 1 10 2

Output
20
3 6 7 4 5 



-----Note-----

Let us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 +...

I tried it in Python, but could not do it. Can you solve it?
targets: from heapq import heappush,heappop,heapify
n,k=list(map(int,input().split()))
*l,=list(map(int,input().split()))
q=[(-l[i],i)for i in range(k)]
heapify(q)
a=[0]*n
s=0
for i in range(k,n) :
    heappush(q,(-l[i],i))
    x,j=heappop(q)
    s-=x*(i-j)
    a[j]=i+1
for i in range(n,n+k) :
    x,j=heappop(q)
    s-=x*(i-j)
    a[j]=i+1
print(s)
print(' '.join(map(str,a)))
inputs: I found an interesting problem on https://codeforces.com/problemset/problem/1107/A:
You are given a sequence $s$ consisting of $n$ digits from $1$ to $9$.

You have to divide it into at least two segments (segment — is a consecutive sequence of elements) (in other words, you have to place separators between some digits of the sequence) in such a way that each element belongs to exactly one segment and if the resulting division will be represented as an integer numbers sequence then each next element of this sequence will be strictly greater than the previous one.

More formally: if the resulting division of the sequence is $t_1, t_2, \dots, t_k$, where $k$ is the number of element in a division, then for each $i$ from $1$ to $k-1$ the condition $t_{i} < t_{i + 1}$ (using numerical comparing, it means that the integer representations of strings are compared) should be satisfied.

For example, if $s=654$ then you can divide it into parts $[6, 54]$ and it will be suitable division. But if you will divide it into parts $[65, 4]$ then it will be bad division because $65 > 4$. If $s=123$ then you can divide it into parts $[1, 23]$, $[1, 2, 3]$ but not into parts $[12, 3]$.

Your task is to find any suitable division for each of the $q$ independent queries.


-----Input-----

The first line of the input contains one integer $q$ ($1 \le q \le 300$) — the number of queries.

The first line of the $i$-th query contains one integer number $n_i$ ($2 \le n_i \le 300$) — the number of digits in the $i$-th query.

The second line of the $i$-th query contains one string $s_i$ of length $n_i$ consisting only of digits from $1$ to $9$.


-----Output-----

If the sequence of digits in the $i$-th query cannot be divided into at least two parts in a way described in the problem statement, print the single line "NO" for this query.

Otherwise in the first line of the answer to this query print "YES", on the second line print $k_i$ — the number of parts in your division of the $i$-th query sequence and in the third line print $k_i$ strings $t_{i, 1}, t_{i, 2}, \dots, t_{i, k_i}$ — your division. Parts should be...

I tried it in Python, but could not do it. Can you solve it?
targets: q = int(input())

for _ in range(q):
    n = int(input())
    s = input()
    if n > 2:
        print('YES')
        print(2)
        print(s[0],s[1:])
    else:
        if int(s[0]) >= int(s[1]):
            print('NO')
        else:
            print('YES')
            print(2)
            print(s[0],s[1])
inputs: I found an interesting problem on https://codeforces.com/problemset/problem/1372/C:
Patrick likes to play baseball, but sometimes he will spend so many hours hitting home runs that his mind starts to get foggy! Patrick is sure that his scores across $n$ sessions follow the identity permutation (ie. in the first game he scores $1$ point, in the second game he scores $2$ points and so on). However, when he checks back to his record, he sees that all the numbers are mixed up! 

Define a special exchange as the following: choose any subarray of the scores and permute elements such that no element of subarray gets to the same position as it was before the exchange. For example, performing a special exchange on $[1,2,3]$ can yield $[3,1,2]$ but it cannot yield $[3,2,1]$ since the $2$ is in the same position. 

Given a permutation of $n$ integers, please help Patrick find the minimum number of special exchanges needed to make the permutation sorted! It can be proved that under given constraints this number doesn't exceed $10^{18}$.

An array $a$ is a subarray of an array $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.


-----Input-----

Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 100$). Description of the test cases follows.

The first line of each test case contains integer $n$ ($1 \leq n \leq 2 \cdot 10^5$)  — the length of the given permutation.

The second line of each test case contains $n$ integers $a_{1},a_{2},...,a_{n}$ ($1 \leq a_{i} \leq n$)  — the initial permutation.

It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$.


-----Output-----

For each test case, output one integer: the minimum number of special exchanges needed to sort the permutation.


-----Example-----
Input
2
5
1 2 3 4 5
7
3 2 4 5 1 6 7

Output
0
2



-----Note-----

In the first permutation, it is already sorted so no exchanges are needed.

It can be shown that you need at least $2$ exchanges to sort...

I tried it in Python, but could not do it. Can you solve it?
targets: from collections import defaultdict as dd
from collections import deque
import bisect
import heapq

def ri():
    return int(input())

def rl():
    return list(map(int, input().split()))


def solve():
    n = ri()
    A = rl()

    first_wrong = -1
    first_break = -1
    skip = False

    for i, a in enumerate(A):
        if i + 1 == a:
            if first_wrong != -1 and first_break == -1:
                first_break = i
        else:
            if first_wrong == -1:
                first_wrong = i
            elif first_break != -1:
                skip = True

    if first_wrong == -1:
        print(0)
    elif not skip:
        print(1)
    else:
        print(2)






mode = 'T'

if mode == 'T':
    t = ri()
    for i in range(t):
        solve()
else:
    solve()
inputs: Solve in Python:
Gennady owns a small hotel in the countryside where he lives a peaceful life. He loves to take long walks, watch sunsets and play cards with tourists staying in his hotel. His favorite game is called "Mau-Mau".

To play Mau-Mau, you need a pack of $52$ cards. Each card has a suit (Diamonds — D, Clubs — C, Spades — S, or Hearts — H), and a rank (2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K, or A).

At the start of the game, there is one card on the table and you have five cards in your hand. You can play a card from your hand if and only if it has the same rank or the same suit as the card on the table.

In order to check if you'd be a good playing partner, Gennady has prepared a task for you. Given the card on the table and five cards in your hand, check if you can play at least one card.


-----Input-----

The first line of the input contains one string which describes the card on the table. The second line contains five strings which describe the cards in your hand.

Each string is two characters long. The first character denotes the rank and belongs to the set $\{{\tt 2}, {\tt 3}, {\tt 4}, {\tt 5}, {\tt 6}, {\tt 7}, {\tt 8}, {\tt 9}, {\tt T}, {\tt J}, {\tt Q}, {\tt K}, {\tt A}\}$. The second character denotes the suit and belongs to the set $\{{\tt D}, {\tt C}, {\tt S}, {\tt H}\}$.

All the cards in the input are different.


-----Output-----

If it is possible to play a card from your hand, print one word "YES". Otherwise, print "NO".

You can print each letter in any case (upper or lower).


-----Examples-----
Input
AS
2H 4C TH JH AD

Output
YES

Input
2H
3D 4C AC KD AS

Output
NO

Input
4D
AS AC AD AH 5H

Output
YES



-----Note-----

In the first example, there is an Ace of Spades (AS) on the table. You can play an Ace of Diamonds (AD) because both of them are Aces.

In the second example, you cannot play any card.

In the third example, you can play an Ace of Diamonds (AD) because it has the same suit as a Four of Diamonds (4D), which lies on the table.
targets: s1 = input()
ls = input().split()
print('YES' if any(any(s1[i] == ls[j][i] for i in range(2)) for j in range(5)) else 'NO')
inputs: I found an interesting problem on https://leetcode.com/problems/contains-duplicate/:
Given an array of integers, find if the array contains any duplicates.

Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

Example 1:


Input: [1,2,3,1]
Output: true

Example 2:


Input: [1,2,3,4]
Output: false

Example 3:


Input: [1,1,1,3,3,4,3,2,4,2]
Output: true

I tried it in Python, but could not do it. Can you solve it?
targets: class Solution:
     def containsDuplicate(self, nums):
         """
         :type nums: List[int]
         :rtype: bool
         """
         
         diction = {}
         flag = 0
         for number in nums:
             if number not in diction:
                 diction[number] = 1
             else:
                 flag = 1
                 break
         if flag == 1:
             return True
         else:
             return False
inputs: Solve in Python:
We have a chocolate bar partitioned into H horizontal rows and W vertical columns of squares.
The square (i, j) at the i-th row from the top and the j-th column from the left is dark if S_{i,j} is 0, and white if S_{i,j} is 1.
We will cut the bar some number of times to divide it into some number of blocks. In each cut, we cut the whole bar by a line running along some boundaries of squares from end to end of the bar.
How many times do we need to cut the bar so that every block after the cuts has K or less white squares?

-----Constraints-----
 - 1 \leq H \leq 10
 - 1 \leq W \leq 1000
 - 1 \leq K \leq H \times W
 - S_{i,j} is 0 or 1.

-----Input-----
Input is given from Standard Input in the following format:
H W K
S_{1,1}S_{1,2}...S_{1,W}
:
S_{H,1}S_{H,2}...S_{H,W}

-----Output-----
Print the number of minimum times the bar needs to be cut so that every block after the cuts has K or less white squares.

-----Sample Input-----
3 5 4
11100
10001
00111

-----Sample Output-----
2

For example, cutting between the 1-st and 2-nd rows and between the 3-rd and 4-th columns - as shown in the figure to the left - works.
Note that we cannot cut the bar in the ways shown in the two figures to the right.
targets: # E - Dividing Chocolate
import numpy as np

H, W, K = list(map(int, input().split()))
S = np.zeros((H, W), dtype=np.int64)

ans = H+W

for i in range(H):
    S[i] = list(str(input()))

for m in range(2**(H-1)):
    wp = np.zeros((H, W), dtype=np.int64)
    wq = np.zeros((H, ), dtype=np.int64)
    wp[0] = S[0]
    cut = 0
    for n in range(H-1):
        if m>>n&1:
            cut += 1
        wp[cut] += S[n+1]

    if cut >= ans or np.count_nonzero(wp > K):
        continue

    for j in range(W):
        wq += wp[:,j]
        if np.count_nonzero(wq > K):
            cut += 1
            wq = wp[:,j]
    ans = min(ans, cut)

print(ans)
inputs: I found an interesting problem on https://atcoder.jp/contests/abc113/tasks/abc113_b:
A country decides to build a palace.
In this country, the average temperature of a point at an elevation of x meters is T-x \times 0.006 degrees Celsius.
There are N places proposed for the place. The elevation of Place i is H_i meters.
Among them, Princess Joisino orders you to select the place whose average temperature is the closest to A degrees Celsius, and build the palace there.
Print the index of the place where the palace should be built.
It is guaranteed that the solution is unique.

-----Constraints-----
 - 1 \leq N \leq 1000
 - 0 \leq T \leq 50
 - -60 \leq A \leq T
 - 0 \leq H_i \leq 10^5
 - All values in input are integers.
 - The solution is unique.

-----Input-----
Input is given from Standard Input in the following format:
N
T A
H_1 H_2 ... H_N

-----Output-----
Print the index of the place where the palace should be built.

-----Sample Input-----
2
12 5
1000 2000

-----Sample Output-----
1

 - The average temperature of Place 1 is 12-1000 \times 0.006=6 degrees Celsius.
 - The average temperature of Place 2 is 12-2000 \times 0.006=0 degrees Celsius.
Thus, the palace should be built at Place 1.

I tried it in Python, but could not do it. Can you solve it?
targets: from typing import List


def answer(n: int, t: int, a: int, hs: List[int]) -> int:
    import sys
    
    result = 0
    temperature_difference = sys.maxsize
    
    for i, h in enumerate(hs, start=1):
        temp = abs(a - (t - h * 0.006))
        if temp < temperature_difference:
            temperature_difference = temp
            result = i

    return result


def main():
    n = int(input())
    t, a = map(int, input().split())
    hs = list(map(int, input().split()))
    print(answer(n, t, a, hs))


def __starting_point():
    main()
__starting_point()