context
stringlengths
88
7.54k
groundtruth
stringlengths
9
28.8k
groundtruth_language
stringclasses
3 values
type
stringclasses
2 values
code_test_cases
listlengths
1
565
dataset
stringclasses
6 values
code_language
stringclasses
1 value
difficulty
float64
0
1
mid
stringlengths
32
32
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning: a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence? Input The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105). Output If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it. Examples Input 2 2 1 Output 1 Input 3 1 3 2 Output -1 Input 2 1 2 Output 0 Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
def us_num(nums): where = None for idx, (a, na) in enumerate(zip(nums[:-1], nums[1:])): if a > na: if where is None: where = idx else: return -1 if where is None: return 0 elif nums[-1] > nums[0]: return -1 return len(nums) - 1 - where n = int(input()) nums = list(map(int, input().split())) print(us_num(nums))
python
code_algorithm
[ { "input": "3\n1 3 2\n", "output": "-1\n" }, { "input": "2\n1 2\n", "output": "0\n" }, { "input": "2\n2 1\n", "output": "1\n" }, { "input": "6\n5 6 7 5 5 5\n", "output": "3\n" }, { "input": "5\n1 1 2 1 1\n", "output": "2\n" }, { "input": "7\n2 3 4 1 2 ...
code_contests
python
0.5
b26977e1cd9d8a4eae5daed81e8afdc4
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and Billy are great fans of even numbers, that's why they want to divide the watermelon in such a way that each of the two parts weighs even number of kilos, at the same time it is not obligatory that the parts are equal. The boys are extremely tired and want to start their meal as soon as possible, that's why you should help them and find out, if they can divide the watermelon in the way they want. For sure, each of them should get a part of positive weight. Input The first (and the only) input line contains integer number w (1 ≤ w ≤ 100) — the weight of the watermelon bought by the boys. Output Print YES, if the boys can divide the watermelon into two parts, each of them weighing even number of kilos; and NO in the opposite case. Examples Input 8 Output YES Note For example, the boys can divide the watermelon into two parts of 2 and 6 kilos respectively (another variant — two parts of 4 and 4 kilos). Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
x=int(input()) y=x-2 if y%2==0 and y!=0: print("YES") else : print("NO")
python
code_algorithm
[ { "input": "8\n", "output": "YES\n" }, { "input": "3\n", "output": "NO\n" }, { "input": "98\n", "output": "YES\n" }, { "input": "7\n", "output": "NO\n" }, { "input": "90\n", "output": "YES\n" }, { "input": "67\n", "output": "NO\n" }, { "inp...
code_contests
python
0.4
8203a469d9921ed6166cb8286ad286d6
You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order). Input The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters. Output Print "YES" (without the quotes), if string s contains two non-overlapping substrings "AB" and "BA", and "NO" otherwise. Examples Input ABA Output NO Input BACFAB Output YES Input AXBYBXA Output NO Note In the first sample test, despite the fact that there are substrings "AB" and "BA", their occurrences overlap, so the answer is "NO". In the second sample test there are the following occurrences of the substrings: BACFAB. In the third sample test there is no substring "AB" nor substring "BA". Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
a = input() b = a f1=0 f2=0 if(a.find('AB')!=-1): a = a.replace('AB', 'C', 1) if(a.find('BA')!=-1): f1=1 if(b.find('BA')!=-1): b = b.replace('BA', 'C', 1) if(b.find('AB')!=-1): f2=1 if(f1==0 and f2==0): print("NO") else: print("YES")
python
code_algorithm
[ { "input": "ABA\n", "output": "NO\n" }, { "input": "AXBYBXA\n", "output": "NO\n" }, { "input": "BACFAB\n", "output": "YES\n" }, { "input": "BAAA\n", "output": "NO\n" }, { "input": "BAA\n", "output": "NO\n" }, { "input": "ABABA\n", "output": "YES\n"...
code_contests
python
0.2
d2a64e9fa4cfd553fdd3b3f6ac1af7d6
You are given a sequence of numbers a1, a2, ..., an, and a number m. Check if it is possible to choose a non-empty subsequence aij such that the sum of numbers in this subsequence is divisible by m. Input The first line contains two numbers, n and m (1 ≤ n ≤ 106, 2 ≤ m ≤ 103) — the size of the original sequence and the number such that sum should be divisible by it. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109). Output In the single line print either "YES" (without the quotes) if there exists the sought subsequence, or "NO" (without the quotes), if such subsequence doesn't exist. Examples Input 3 5 1 2 3 Output YES Input 1 6 5 Output NO Input 4 6 3 1 1 3 Output YES Input 6 6 5 5 5 5 5 5 Output YES Note In the first sample test you can choose numbers 2 and 3, the sum of which is divisible by 5. In the second sample test the single non-empty subsequence of numbers is a single number 5. Number 5 is not divisible by 6, that is, the sought subsequence doesn't exist. In the third sample test you need to choose two numbers 3 on the ends. In the fourth sample test you can take the whole subsequence. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
n,x=map(int,input().split()) a=set() for i in input().split(): i=int(i) b=set() for j in a: b.add((i+j)%x) a|=b a.add(i%x) if 0 in a: print("YES") break else: print("NO")
python
code_algorithm
[ { "input": "4 6\n3 1 1 3\n", "output": "YES\n" }, { "input": "1 6\n5\n", "output": "NO\n" }, { "input": "6 6\n5 5 5 5 5 5\n", "output": "YES\n" }, { "input": "3 5\n1 2 3\n", "output": "YES\n" }, { "input": "100 951\n950 949 949 949 949 950 950 949 949 950 950 949 ...
code_contests
python
0.1
570c8ac6b27439167d011cf567e22a78
Little Petya has recently started attending a programming club. Naturally he is facing the problem of choosing a programming language. After long considerations he realized that Java is the best choice. The main argument in favor of choosing Java was that it has a very large integer data type, called BigInteger. But having attended several classes of the club, Petya realized that not all tasks require using the BigInteger type. It turned out that in some tasks it is much easier to use small data types. That's why a question arises: "Which integer type to use if one wants to store a positive integer n?" Petya knows only 5 integer types: 1) byte occupies 1 byte and allows you to store numbers from - 128 to 127 2) short occupies 2 bytes and allows you to store numbers from - 32768 to 32767 3) int occupies 4 bytes and allows you to store numbers from - 2147483648 to 2147483647 4) long occupies 8 bytes and allows you to store numbers from - 9223372036854775808 to 9223372036854775807 5) BigInteger can store any integer number, but at that it is not a primitive type, and operations with it are much slower. For all the types given above the boundary values are included in the value range. From this list, Petya wants to choose the smallest type that can store a positive integer n. Since BigInteger works much slower, Peter regards it last. Help him. Input The first line contains a positive number n. It consists of no more than 100 digits and doesn't contain any leading zeros. The number n can't be represented as an empty string. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). Output Print the first type from the list "byte, short, int, long, BigInteger", that can store the natural number n, in accordance with the data given above. Examples Input 127 Output byte Input 130 Output short Input 123456789101112131415161718192021222324 Output BigInteger Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
n= int(input()) if(n<=127): print("byte") elif(n<=32767): print("short") elif(n<=2147483647): print("int") elif(n<=9223372036854775807): print("long") else: print("BigInteger")
python
code_algorithm
[ { "input": "123456789101112131415161718192021222324\n", "output": "BigInteger\n" }, { "input": "127\n", "output": "byte\n" }, { "input": "130\n", "output": "short\n" }, { "input": "73301058161399915972677875815320924081350034292596169552397613159508055212649940212428739793091...
code_contests
python
0.5
3af36abdfc5f69d1ce7bdf8c158640b2
Heidi has finally found the mythical Tree of Life – a legendary combinatorial structure which is said to contain a prophecy crucially needed to defeat the undead armies. On the surface, the Tree of Life is just a regular undirected tree well-known from computer science. This means that it is a collection of n points (called vertices), some of which are connected using n - 1 line segments (edges) so that each pair of vertices is connected by a path (a sequence of one or more edges). To decipher the prophecy, Heidi needs to perform a number of steps. The first is counting the number of lifelines in the tree – these are paths of length 2, i.e., consisting of two edges. Help her! Input The first line of the input contains a single integer n – the number of vertices in the tree (1 ≤ n ≤ 10000). The vertices are labeled with the numbers from 1 to n. Then n - 1 lines follow, each describing one edge using two space-separated numbers a b – the labels of the vertices connected by the edge (1 ≤ a < b ≤ n). It is guaranteed that the input represents a tree. Output Print one integer – the number of lifelines in the tree. Examples Input 4 1 2 1 3 1 4 Output 3 Input 5 1 2 2 3 3 4 3 5 Output 4 Note In the second sample, there are four lifelines: paths between vertices 1 and 3, 2 and 4, 2 and 5, and 4 and 5. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
n = int(input()) a = [0]*(n+1) for _ in range(n-1): x, y = input().split(' ') x, y = [int(x), int(y)] a[x] += 1 a[y] += 1 too = 0 for x in a: too += (x * (x-1))//2 print(too)
python
code_algorithm
[ { "input": "4\n1 2\n1 3\n1 4\n", "output": "3\n" }, { "input": "5\n1 2\n2 3\n3 4\n3 5\n", "output": "4\n" }, { "input": "2\n1 2\n", "output": "0\n" }, { "input": "3\n2 1\n3 2\n", "output": "1\n" }, { "input": "10\n5 1\n1 2\n9 3\n10 5\n6 3\n8 5\n2 7\n2 3\n9 4\n", ...
code_contests
python
1
eb43966a8926282f134e5e2bf46c7150
Ostap already settled down in Rio de Janiero suburb and started to grow a tree in his garden. Recall that a tree is a connected undirected acyclic graph. Ostap's tree now has n vertices. He wants to paint some vertices of the tree black such that from any vertex u there is at least one black vertex v at distance no more than k. Distance between two vertices of the tree is the minimum possible number of edges of the path between them. As this number of ways to paint the tree can be large, Ostap wants you to compute it modulo 109 + 7. Two ways to paint the tree are considered different if there exists a vertex that is painted black in one way and is not painted in the other one. Input The first line of the input contains two integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ min(20, n - 1)) — the number of vertices in Ostap's tree and the maximum allowed distance to the nearest black vertex. Don't miss the unusual constraint for k. Each of the next n - 1 lines contain two integers ui and vi (1 ≤ ui, vi ≤ n) — indices of vertices, connected by the i-th edge. It's guaranteed that given graph is a tree. Output Print one integer — the remainder of division of the number of ways to paint the tree by 1 000 000 007 (109 + 7). Examples Input 2 0 1 2 Output 1 Input 2 1 1 2 Output 3 Input 4 1 1 2 2 3 3 4 Output 9 Input 7 2 1 2 2 3 1 4 4 5 1 6 6 7 Output 91 Note In the first sample, Ostap has to paint both vertices black. In the second sample, it is enough to paint only one of two vertices, thus the answer is 3: Ostap can paint only vertex 1, only vertex 2, vertices 1 and 2 both. In the third sample, the valid ways to paint vertices are: {1, 3}, {1, 4}, {2, 3}, {2, 4}, {1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}, {1, 2, 3, 4}. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
def main(): n, k = map(int, input().split()) cnt = [[[0] * 21 for _ in (0, 1)] for _ in range(n + 1)] edges, mod = [[] for _ in range(n + 1)], 1000000007 for _ in range(n - 1): u, v = map(int, input().split()) edges[u].append(v) edges[v].append(u) def dfs(u, f): cnt[u][0][0] = cnt[u][1][k] = 1 for v in edges[u]: if v != f: dfs(v, u) tmp0, tmp1 = [0] * 21, [0] * 21 for i in range(k + 1): for j in range(k + 1): if i != k: tmp0[j if i < j else i + 1] += cnt[u][0][j] * cnt[v][0][i] if i < j: tmp1[j] += cnt[u][1][j] * cnt[v][0][i] elif i != k: tmp0[i + 1] += cnt[u][1][j] * cnt[v][0][i] if i > j: tmp1[i - 1] += cnt[u][0][j] * cnt[v][1][i] else: tmp0[j] += cnt[u][0][j] * cnt[v][1][i] tmp1[max(i - 1, j)] += cnt[u][1][j] * cnt[v][1][i] for i in range(21): tmp0[i] %= mod tmp1[i] %= mod cnt[u][0] = tmp0 cnt[u][1] = tmp1 dfs(1, 1) print(sum(cnt[1][1][j] for j in range(k + 1)) % mod) if __name__ == '__main__': main()
python
code_algorithm
[ { "input": "7 2\n1 2\n2 3\n1 4\n4 5\n1 6\n6 7\n", "output": "91\n" }, { "input": "4 1\n1 2\n2 3\n3 4\n", "output": "9\n" }, { "input": "2 0\n1 2\n", "output": "1\n" }, { "input": "2 1\n1 2\n", "output": "3\n" }, { "input": "10 1\n6 3\n1 5\n10 7\n4 10\n2 4\n5 9\n8 ...
code_contests
python
0
90b79d03b24efa117cb5a7aff676dd2c
Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters. Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: 1. the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", 2. or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name. Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. Input The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of clubs in the league. Each of the next n lines contains two words — the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. Output It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. Examples Input 2 DINAMO BYTECITY FOOTBALL MOSCOW Output YES DIN FOO Input 2 DINAMO BYTECITY DINAMO BITECITY Output NO Input 3 PLAYFOOTBALL MOSCOW PLAYVOLLEYBALL SPB GOGO TECHNOCUP Output YES PLM PLS GOG Input 3 ABC DEF ABC EFG ABD OOO Output YES ABD ABE ABO Note In the first sample Innokenty can choose first option for both clubs. In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs. In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club. In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
from collections import defaultdict names = int(input()) inp = [input().split() for x in range(names)] choice = [] res = defaultdict(lambda: []) for x, word in enumerate(inp): choice.append(False) res[word[0][:3]].append(x) while True: changes = [] for key in res.keys(): if len(res[key]) > 1: # All choice = False options must be changed remove = [] for i, index in enumerate(res[key]): if choice[index]: continue remove.append(i) choice[index] = True changes.append((inp[index][0][:2] + inp[index][1][0], index)) for i in remove[::-1]: del res[key][i] if len(changes) == 0: break for word, i in changes: res[word].append(i) bad = False for key in res.keys(): if len(res[key]) > 1: bad = True if bad: print("NO") else: print("YES") for i in range(names): if choice[i]: print(inp[i][0][:2] + inp[i][1][0]) else: print(inp[i][0][:3])
python
code_algorithm
[ { "input": "3\nABC DEF\nABC EFG\nABD OOO\n", "output": "YES\nABD\nABE\nABO\n" }, { "input": "2\nDINAMO BYTECITY\nFOOTBALL MOSCOW\n", "output": "YES\nDIN\nFOO\n" }, { "input": "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP\n", "output": "YES\nPLM\nPLS\nGOG\n" }, { ...
code_contests
python
0
bb8e12eacea1677f579848f9d1c2afc4
A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends. There are n schools numerated from 1 to n. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools i and j costs <image> and can be used multiple times. Help Sajjad to find the minimum cost he needs to pay for tickets to visit all schools. He can start and finish in any school. Input The first line contains a single integer n (1 ≤ n ≤ 105) — the number of schools. Output Print single integer: the minimum cost of tickets needed to visit all schools. Examples Input 2 Output 0 Input 10 Output 4 Note In the first example we can buy a ticket between the schools that costs <image>. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
n = int(input()) print(int((n + 1) / 2) - 1)
python
code_algorithm
[ { "input": "10\n", "output": "4\n" }, { "input": "2\n", "output": "0\n" }, { "input": "60397\n", "output": "30198\n" }, { "input": "53022\n", "output": "26510\n" }, { "input": "32866\n", "output": "16432\n" }, { "input": "40873\n", "output": "20436...
code_contests
python
0.5
cc3d4c932cfcff678a133c260e7a65ee
Alice and Bob begin their day with a quick game. They first choose a starting number X0 ≥ 3 and try to reach one million by the process described below. Alice goes first and then they take alternating turns. In the i-th turn, the player whose turn it is selects a prime number smaller than the current number, and announces the smallest multiple of this prime number that is not smaller than the current number. Formally, he or she selects a prime p < Xi - 1 and then finds the minimum Xi ≥ Xi - 1 such that p divides Xi. Note that if the selected prime p already divides Xi - 1, then the number does not change. Eve has witnessed the state of the game after two turns. Given X2, help her determine what is the smallest possible starting number X0. Note that the players don't necessarily play optimally. You should consider all possible game evolutions. Input The input contains a single integer X2 (4 ≤ X2 ≤ 106). It is guaranteed that the integer X2 is composite, that is, is not prime. Output Output a single integer — the minimum possible X0. Examples Input 14 Output 6 Input 20 Output 15 Input 8192 Output 8191 Note In the first test, the smallest possible starting number is X0 = 6. One possible course of the game is as follows: * Alice picks prime 5 and announces X1 = 10 * Bob picks prime 7 and announces X2 = 14. In the second case, let X0 = 15. * Alice picks prime 2 and announces X1 = 16 * Bob picks prime 5 and announces X2 = 20. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
import math,sys,bisect,heapq from collections import defaultdict,Counter,deque from itertools import groupby,accumulate #sys.setrecursionlimit(200000000) int1 = lambda x: int(x) - 1 input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__ ilele = lambda: map(int,input().split()) alele = lambda: list(map(int, input().split())) ilelec = lambda: map(int1,input().split()) alelec = lambda: list(map(int1, input().split())) def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] #MOD = 1000000000 + 7 def Y(c): print(["NO","YES"][c]) def y(c): print(["no","yes"][c]) def Yy(c): print(["No","Yes"][c]) N = int(input()) P = [0 for _ in range(1000010)] for i in range(2, N): if P[i] == 0: for j in range(2*i, N+1, i): P[j] = i ans = 1000010 for i in range(N-P[N]+1, N+1): ans = min(ans, i-P[i]+1) print(ans)
python
code_algorithm
[ { "input": "8192\n", "output": "8191\n" }, { "input": "20\n", "output": "15\n" }, { "input": "14\n", "output": "6\n" }, { "input": "12\n", "output": "6\n" }, { "input": "908209\n", "output": "453632\n" }, { "input": "999958\n", "output": "250008\n"...
code_contests
python
0
31635fa6c218bad54a657ac09cedf17c
You might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy. Lara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D environment. The dungeon can be represented as a rectangle matrix of n rows and m columns. Cell (x, y) is the cell in the x-th row in the y-th column. Lara can move between the neighbouring by side cells in all four directions. Moreover, she has even chosen the path for herself to avoid all the traps. She enters the dungeon in cell (1, 1), that is top left corner of the matrix. Then she goes down all the way to cell (n, 1) — the bottom left corner. Then she starts moving in the snake fashion — all the way to the right, one cell up, then to the left to the cell in 2-nd column, one cell up. She moves until she runs out of non-visited cells. n and m given are such that she always end up in cell (1, 2). Lara has already moved to a neighbouring cell k times. Can you determine her current position? Input The only line contains three integers n, m and k (2 ≤ n, m ≤ 109, n is always even, 0 ≤ k < n·m). Note that k doesn't fit into 32-bit integer type! Output Print the cell (the row and the column where the cell is situated) where Lara ends up after she moves k times. Examples Input 4 3 0 Output 1 1 Input 4 3 11 Output 1 2 Input 4 3 7 Output 3 2 Note Here is her path on matrix 4 by 3: <image> Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
import sys n,m,k=map(int,input().split()) if(k<n): print(k+1,1) sys.exit() k-=n x=n-(k)//(m-1) if(x%2==0): y=k%(m-1)+2 else: y=m-k%(m-1) print(x,y)
python
code_algorithm
[ { "input": "4 3 0\n", "output": "1 1\n" }, { "input": "4 3 7\n", "output": "3 2\n" }, { "input": "4 3 11\n", "output": "1 2\n" }, { "input": "9213788 21936127 8761236\n", "output": "8761237 1\n" }, { "input": "2182 23967 52288026\n", "output": "1 7969\n" }, ...
code_contests
python
0
4adf07184def5795c5d8632ce76140b5
Recently Vasya found a golden ticket — a sequence which consists of n digits a_1a_2... a_n. Vasya considers a ticket to be lucky if it can be divided into two or more non-intersecting segments with equal sums. For example, ticket 350178 is lucky since it can be divided into three segments 350, 17 and 8: 3+5+0=1+7=8. Note that each digit of sequence should belong to exactly one segment. Help Vasya! Tell him if the golden ticket he found is lucky or not. Input The first line contains one integer n (2 ≤ n ≤ 100) — the number of digits in the ticket. The second line contains n digits a_1 a_2 ... a_n (0 ≤ a_i ≤ 9) — the golden ticket. Digits are printed without spaces. Output If the golden ticket is lucky then print "YES", otherwise print "NO" (both case insensitive). Examples Input 5 73452 Output YES Input 4 1248 Output NO Note In the first example the ticket can be divided into 7, 34 and 52: 7=3+4=5+2. In the second example it is impossible to divide ticket into segments with equal sum. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
n = int(input()) s = input() arr = list() arr.append(int(s[0])) summ = arr[0] bigflg = False for i in range(1,len(s)): arr.append(int(s[i])) summ+=arr[i] for i in range(2,len(s)+1): if summ % i == 0: amount = summ / i sm = 0 flg = True for j in range(len(arr)): sm += arr[j] if (sm > amount): flg = False break if (sm == amount): sm = 0 if sm==0 and flg: bigflg = True print('YES') break if not bigflg: print('NO')
python
code_algorithm
[ { "input": "4\n1248\n", "output": "NO\n" }, { "input": "5\n73452\n", "output": "YES\n" }, { "input": "7\n5541514\n", "output": "YES\n" }, { "input": "20\n69325921242281090228\n", "output": "NO\n" }, { "input": "3\n222\n", "output": "YES\n" }, { "input"...
code_contests
python
0.4
db2f3897a9a3d45bbb9591cfab740099
Today, Mezo is playing a game. Zoma, a character in that game, is initially at position x = 0. Mezo starts sending n commands to Zoma. There are two possible commands: * 'L' (Left) sets the position x: =x - 1; * 'R' (Right) sets the position x: =x + 1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position x doesn't change and Mezo simply proceeds to the next command. For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully): * "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 0; * "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 0 as well; * "LRLR" — Zoma moves to the left, then to the left again and ends up in position -2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at. Input The first line contains n (1 ≤ n ≤ 10^5) — the number of commands Mezo sends. The second line contains a string s of n commands, each either 'L' (Left) or 'R' (Right). Output Print one integer — the number of different positions Zoma may end up at. Example Input 4 LRLR Output 5 Note In the example, Zoma may end up anywhere between -2 and 2. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
def func(n): x = input() ans = 0 l_counter = x.count('L') r_counter = x.count('R') y = 0 - l_counter z = 0 + r_counter for i in range(y,z+1): ans += 1 print(ans) n = int(input()) func(n)
python
code_algorithm
[ { "input": "4\nLRLR\n", "output": "5\n" }, { "input": "12\nLLLLLLLLLLLL\n", "output": "13\n" }, { "input": "2\nLR\n", "output": "3\n" }, { "input": "1\nR\n", "output": "2\n" }, { "input": "13\nLRLLLLRRLLRLR\n", "output": "14\n" }, { "input": "1\nL\n", ...
code_contests
python
0.9
9aa45e0939896c25d8f257c8ad842659
A permutation of length n 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). For a positive integer n, we call a permutation p of length n good if the following condition holds for every pair i and j (1 ≤ i ≤ j ≤ n) — * (p_i OR p_{i+1} OR … OR p_{j-1} OR p_{j}) ≥ j-i+1, where OR denotes the [bitwise OR operation.](https://en.wikipedia.org/wiki/Bitwise_operation#OR) In other words, a permutation p is good if for every subarray of p, the OR of all elements in it is not less than the number of elements in that subarray. Given a positive integer n, output any good permutation of length n. We can show that for the given constraints such a permutation always exists. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 100). Description of the test cases follows. The first and only line of every test case contains a single integer n (1 ≤ n ≤ 100). Output For every test, output any good permutation of length n on a separate line. Example Input 3 1 3 7 Output 1 3 1 2 4 3 5 2 7 1 6 Note For n = 3, [3,1,2] is a good permutation. Some of the subarrays are listed below. * 3 OR 1 = 3 ≥ 2 (i = 1,j = 2) * 3 OR 1 OR 2 = 3 ≥ 3 (i = 1,j = 3) * 1 OR 2 = 3 ≥ 2 (i = 2,j = 3) * 1 ≥ 1 (i = 2,j = 2) Similarly, you can verify that [4,3,5,2,7,1,6] is also good. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
import sys input = sys.stdin.readline from collections import * for _ in range(int(input())): n = int(input()) print(*[i for i in range(1, n+1)])
python
code_algorithm
[ { "input": "3\n1\n3\n7\n", "output": "1\n1 2 3\n1 2 3 4 5 6 7\n" }, { "input": "1\n77\n", "output": "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 ...
code_contests
python
0
662b50e8191597219b6fd97f824fbc5a
One day little Vasya found mom's pocket book. The book had n names of her friends and unusually enough, each name was exactly m letters long. Let's number the names from 1 to n in the order in which they are written. As mom wasn't home, Vasya decided to play with names: he chose three integers i, j, k (1 ≤ i < j ≤ n, 1 ≤ k ≤ m), then he took names number i and j and swapped their prefixes of length k. For example, if we take names "CBDAD" and "AABRD" and swap their prefixes with the length of 3, the result will be names "AABAD" and "CBDRD". You wonder how many different names Vasya can write instead of name number 1, if Vasya is allowed to perform any number of the described actions. As Vasya performs each action, he chooses numbers i, j, k independently from the previous moves and his choice is based entirely on his will. The sought number can be very large, so you should only find it modulo 1000000007 (109 + 7). Input The first input line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of names and the length of each name, correspondingly. Then n lines contain names, each name consists of exactly m uppercase Latin letters. Output Print the single number — the number of different names that could end up in position number 1 in the pocket book after the applying the procedures described above. Print the number modulo 1000000007 (109 + 7). Examples Input 2 3 AAB BAA Output 4 Input 4 5 ABABA BCGDG AAAAA YABSA Output 216 Note In the first sample Vasya can get the following names in the position number 1: "AAB", "AAA", "BAA" and "BAB". Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
mod=10**9+7 n,m=map(int,input().split()) mat=[] for _ in range(n): s=input() mat.append(s) b=ord("A") s=[False]*255 res=1 for j in range(m): for i in range(b,b+26): s[i]=False for i in range(n): s[ord(mat[i][j])]=True r=0 for i in range(b,b+26): if(s[i]):r+=1 res*=r print(res%mod)
python
code_algorithm
[ { "input": "2 3\nAAB\nBAA\n", "output": "4\n" }, { "input": "4 5\nABABA\nBCGDG\nAAAAA\nYABSA\n", "output": "216\n" }, { "input": "100 1\nA\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM\nN\nA\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM\nN\nA\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM\nN\nA\nB\nC\nD\nE\nF\nG\nH\nI...
code_contests
python
0.9
9a208a9dd693293a689761984dd56b0c
Vasya studies divisibility rules at school. Here are some of them: * Divisibility by 2. A number is divisible by 2 if and only if its last digit is divisible by 2 or in other words, is even. * Divisibility by 3. A number is divisible by 3 if and only if the sum of its digits is divisible by 3. * Divisibility by 4. A number is divisible by 4 if and only if its last two digits form a number that is divisible by 4. * Divisibility by 5. A number is divisible by 5 if and only if its last digit equals 5 or 0. * Divisibility by 6. A number is divisible by 6 if and only if it is divisible by 2 and 3 simultaneously (that is, if the last digit is even and the sum of all digits is divisible by 3). * Divisibility by 7. Vasya doesn't know such divisibility rule. * Divisibility by 8. A number is divisible by 8 if and only if its last three digits form a number that is divisible by 8. * Divisibility by 9. A number is divisible by 9 if and only if the sum of its digits is divisible by 9. * Divisibility by 10. A number is divisible by 10 if and only if its last digit is a zero. * Divisibility by 11. A number is divisible by 11 if and only if the sum of digits on its odd positions either equals to the sum of digits on the even positions, or they differ in a number that is divisible by 11. Vasya got interested by the fact that some divisibility rules resemble each other. In fact, to check a number's divisibility by 2, 4, 5, 8 and 10 it is enough to check fulfiling some condition for one or several last digits. Vasya calls such rules the 2-type rules. If checking divisibility means finding a sum of digits and checking whether the sum is divisible by the given number, then Vasya calls this rule the 3-type rule (because it works for numbers 3 and 9). If we need to find the difference between the sum of digits on odd and even positions and check whether the difference is divisible by the given divisor, this rule is called the 11-type rule (it works for number 11). In some cases we should divide the divisor into several factors and check whether rules of different types (2-type, 3-type or 11-type) work there. For example, for number 6 we check 2-type and 3-type rules, for number 66 we check all three types. Such mixed divisibility rules are called 6-type rules. And finally, there are some numbers for which no rule works: neither 2-type, nor 3-type, nor 11-type, nor 6-type. The least such number is number 7, so we'll say that in such cases the mysterious 7-type rule works, the one that Vasya hasn't discovered yet. Vasya's dream is finding divisibility rules for all possible numbers. He isn't going to stop on the decimal numbers only. As there are quite many numbers, ha can't do it all by himself. Vasya asked you to write a program that determines the divisibility rule type in the b-based notation for the given divisor d. Input The first input line contains two integers b and d (2 ≤ b, d ≤ 100) — the notation system base and the divisor. Both numbers are given in the decimal notation. Output On the first output line print the type of the rule in the b-based notation system, where the divisor is d: "2-type", "3-type", "11-type", "6-type" or "7-type". If there are several such types, print the one that goes earlier in the given sequence. If a number belongs to the 2-type, print on the second line the least number of the last b-based digits that we will need to use to check the divisibility. Examples Input 10 10 Output 2-type 1 Input 2 3 Output 11-type Note The divisibility rule for number 3 in binary notation looks as follows: "A number is divisible by 3 if and only if the sum of its digits that occupy the even places differs from the sum of digits that occupy the odd places, in a number that is divisible by 3". That's an 11-type rule. For example, 2110 = 101012. For it the sum of digits on odd positions equals 1 + 1 + 1 = 3, an on even positions — 0 + 0 = 0. The rule works and the number is divisible by 3. In some notations a number can fit into the 3-type rule and the 11-type rule. In this case the correct answer is "3-type". Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
b, d = map(int, input().split()) for i in range(1, 10): if (b**i) % d == 0: print("2-type") print(i) exit() if (b-1) % d == 0: print("3-type") exit() if (b+1) % d == 0: print("11-type") exit() for i in range(2, d+1): if d % i == 0: x = 1 while d % i == 0: d /= i x *= i if (b**10) % x != 0 and (b+1) % x != 0 and (b-1) % x != 0: print("7-type") break else: print("6-type")
python
code_algorithm
[ { "input": "2 3\n", "output": "11-type\n" }, { "input": "10 10\n", "output": "2-type\n1\n" }, { "input": "5 2\n", "output": "3-type\n" }, { "input": "2 5\n", "output": "7-type\n" }, { "input": "8 5\n", "output": "7-type\n" }, { "input": "2 32\n", "...
code_contests
python
0
8f1900ffd6f27935606c7ef9a0987a4c
The Tower of Hanoi is a well-known mathematical puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: 1. Only one disk can be moved at a time. 2. Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. 3. No disk may be placed on top of a smaller disk. With three disks, the puzzle can be solved in seven moves. The minimum number of moves required to solve a Tower of Hanoi puzzle is 2n - 1, where n is the number of disks. (c) Wikipedia. SmallY's puzzle is very similar to the famous Tower of Hanoi. In the Tower of Hanoi puzzle you need to solve a puzzle in minimum number of moves, in SmallY's puzzle each move costs some money and you need to solve the same puzzle but for minimal cost. At the beginning of SmallY's puzzle all n disks are on the first rod. Moving a disk from rod i to rod j (1 ≤ i, j ≤ 3) costs tij units of money. The goal of the puzzle is to move all the disks to the third rod. In the problem you are given matrix t and an integer n. You need to count the minimal cost of solving SmallY's puzzle, consisting of n disks. Input Each of the first three lines contains three integers — matrix t. The j-th integer in the i-th line is tij (1 ≤ tij ≤ 10000; i ≠ j). The following line contains a single integer n (1 ≤ n ≤ 40) — the number of disks. It is guaranteed that for all i (1 ≤ i ≤ 3), tii = 0. Output Print a single integer — the minimum cost of solving SmallY's puzzle. Examples Input 0 1 1 1 0 1 1 1 0 3 Output 7 Input 0 2 2 1 0 100 1 2 0 3 Output 19 Input 0 2 1 1 0 100 1 2 0 5 Output 87 Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
def play(price, n): # dp[i][j][k] - naimen'shaya stoimost' peremeshcheniya i blinov so sterzhnya j => k # U nas vsegda est' dva varianta dejstviya: # 1. Peremeshchaem i - 1 blin na mesto 2. Dalee, peremeshchaem i - yj blin na mesto 3. I nakonec peremeshchaem i - 1 blin na mesto 3. # 2. Peremeshchaem i - 1 blin na mesto 3. Zatem i - yj na mesto 2, zatem i - 1 blin na mesto 1, dalee i -yj na 3-e mesto i nakonec i - 1 blin na 3 mesto # t.e, dp[i][j][k] = min(dp[i - 1][j][k ^ j] + Price[j][k] + dp[i - 1][k ^ j][k], # dp[i - 1][j][k] + Price[j][k ^ j] + dp[i - 1][k][j] + Price[j ^ k][k] + dp[i - 1][j][k]) dp = [[[0 for k in range(0, 4)] for j in range(0, 4)] for i in range(0, n + 1)] for i in range(1, n + 1): for j in range(1, 4): for k in range(1, 4): dp[i][j][k] = min(dp[i - 1][j][k ^ j] + price[j][k] + dp[i - 1][k ^ j][k], 2 * dp[i - 1][j][k] + price[j][k ^ j] + dp[i - 1][k][j] + price[j ^ k][k]) return dp[n][1][3] def main(): matrix = [[0 for j in range(0, 4)] for i in range(0, 4)] i = 1 while i < 4: row = list(map(int, input().split())) for j in range(1, 4): matrix[i][j] = row[j - 1] i += 1 n = int(input()) print(play(matrix, n)) main() #print(play([[0, 0, 0, 0], [0, 0, 1, 1],[0, 1, 0, 1],[0, 1, 1, 0]], 3))
python
code_algorithm
[ { "input": "0 2 1\n1 0 100\n1 2 0\n5\n", "output": "87\n" }, { "input": "0 2 2\n1 0 100\n1 2 0\n3\n", "output": "19\n" }, { "input": "0 1 1\n1 0 1\n1 1 0\n3\n", "output": "7\n" }, { "input": "0 9628 4599\n6755 0 5302\n5753 1995 0\n39\n", "output": "2894220024221629\n" }...
code_contests
python
0
9ca324b2007c64df718e0a5ed76f16ed
Have you ever played Hanabi? If not, then you've got to try it out! This problem deals with a simplified version of the game. Overall, the game has 25 types of cards (5 distinct colors and 5 distinct values). Borya is holding n cards. The game is somewhat complicated by the fact that everybody sees Borya's cards except for Borya himself. Borya knows which cards he has but he knows nothing about the order they lie in. Note that Borya can have multiple identical cards (and for each of the 25 types of cards he knows exactly how many cards of this type he has). The aim of the other players is to achieve the state when Borya knows the color and number value of each of his cards. For that, other players can give him hints. The hints can be of two types: color hints and value hints. A color hint goes like that: a player names some color and points at all the cards of this color. Similarly goes the value hint. A player names some value and points at all the cards that contain the value. Determine what minimum number of hints the other players should make for Borya to be certain about each card's color and value. Input The first line contains integer n (1 ≤ n ≤ 100) — the number of Borya's cards. The next line contains the descriptions of n cards. The description of each card consists of exactly two characters. The first character shows the color (overall this position can contain five distinct letters — R, G, B, Y, W). The second character shows the card's value (a digit from 1 to 5). Borya doesn't know exact order of the cards they lie in. Output Print a single integer — the minimum number of hints that the other players should make. Examples Input 2 G3 G3 Output 0 Input 4 G4 R4 R3 B3 Output 2 Input 5 B1 Y1 W1 G1 R1 Output 4 Note In the first sample Borya already knows for each card that it is a green three. In the second sample we can show all fours and all red cards. In the third sample you need to make hints about any four colors. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
input() p = {(1 << 'RGBYW'.index(c)) + (1 << int(k) + 4) for c, k in input().split()} print(min(bin(t).count('1') for t in range(1024) if len({t & q for q in p}) == len(p))) # Made By Mostafa_Khaled
python
code_algorithm
[ { "input": "5\nB1 Y1 W1 G1 R1\n", "output": "4\n" }, { "input": "4\nG4 R4 R3 B3\n", "output": "2\n" }, { "input": "2\nG3 G3\n", "output": "0\n" }, { "input": "35\nG2 Y1 Y1 R4 G5 B5 R2 G4 G2 G3 W4 W1 B3 W5 R2 Y5 R4 R4 B5 Y2 B4 B1 R3 G4 Y3 G2 R4 G3 B2 G2 R3 B2 R1 W2 B4\n", ...
code_contests
python
0
972efc7a67f582cef3f13f245266eab7
Giga Tower is the tallest and deepest building in Cyberland. There are 17 777 777 777 floors, numbered from - 8 888 888 888 to 8 888 888 888. In particular, there is floor 0 between floor - 1 and floor 1. Every day, thousands of tourists come to this place to enjoy the wonderful view. In Cyberland, it is believed that the number "8" is a lucky number (that's why Giga Tower has 8 888 888 888 floors above the ground), and, an integer is lucky, if and only if its decimal notation contains at least one digit "8". For example, 8, - 180, 808 are all lucky while 42, - 10 are not. In the Giga Tower, if you write code at a floor with lucky floor number, good luck will always be with you (Well, this round is #278, also lucky, huh?). Tourist Henry goes to the tower to seek good luck. Now he is at the floor numbered a. He wants to find the minimum positive integer b, such that, if he walks b floors higher, he will arrive at a floor with a lucky number. Input The only line of input contains an integer a ( - 109 ≤ a ≤ 109). Output Print the minimum b in a line. Examples Input 179 Output 1 Input -1 Output 9 Input 18 Output 10 Note For the first sample, he has to arrive at the floor numbered 180. For the second sample, he will arrive at 8. Note that b should be positive, so the answer for the third sample is 10, not 0. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
n = int(input())+1 nword = str(n) count = 1 while("8" not in nword): n+=1 nword = str(n) count += 1 print(count)
python
code_algorithm
[ { "input": "18\n", "output": "10\n" }, { "input": "179\n", "output": "1\n" }, { "input": "-1\n", "output": "9\n" }, { "input": "-1000000000\n", "output": "2\n" }, { "input": "-19\n", "output": "1\n" }, { "input": "-8\n", "output": "16\n" }, { ...
code_contests
python
0.9
fb6d96e504e68a38a2491ded72add9aa
Karafs is some kind of vegetable in shape of an 1 × h rectangle. Tavaspolis people love Karafs and they use Karafs in almost any kind of food. Tavas, himself, is crazy about Karafs. <image> Each Karafs has a positive integer height. Tavas has an infinite 1-based sequence of Karafses. The height of the i-th Karafs is si = A + (i - 1) × B. For a given m, let's define an m-bite operation as decreasing the height of at most m distinct not eaten Karafses by 1. Karafs is considered as eaten when its height becomes zero. Now SaDDas asks you n queries. In each query he gives you numbers l, t and m and you should find the largest number r such that l ≤ r and sequence sl, sl + 1, ..., sr can be eaten by performing m-bite no more than t times or print -1 if there is no such number r. Input The first line of input contains three integers A, B and n (1 ≤ A, B ≤ 106, 1 ≤ n ≤ 105). Next n lines contain information about queries. i-th line contains integers l, t, m (1 ≤ l, t, m ≤ 106) for i-th query. Output For each query, print its answer in a single line. Examples Input 2 1 4 1 5 3 3 3 10 7 10 2 6 4 8 Output 4 -1 8 -1 Input 1 5 2 1 5 10 2 7 4 Output 1 2 Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
#------------------------template--------------------------# import os import sys from math import * from collections import * # from fractions import * # from heapq import* from bisect import * from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") ALPHA='abcdefghijklmnopqrstuvwxyz/' M=998244353 EPS=1e-6 def Ceil(a,b): return a//b+int(a%b>0) def value():return tuple(map(int,input().split())) def array():return [int(i) for i in input().split()] def Int():return int(input()) def Str():return input() def arrayS():return [i for i in input().split()] #-------------------------code---------------------------# # vsInput() def possible(r): n=r-l+1 s=n*a+ n*(n-1)*B//2 # print(m,s,n,a) return s<=m*t and a+B*(n-1)<=t A,B,n=value() for _ in range(n): l,t,m=value() a=A+(l-1)*B low=l high=10**10 ans=-1 while(low<=high): mid=low+(high-low)//2 # print(low,mid,high) if(possible(mid)): ans=mid low=mid+1 else: high=mid-1 print(ans)
python
code_algorithm
[ { "input": "1 5 2\n1 5 10\n2 7 4\n", "output": "1\n2\n" }, { "input": "2 1 4\n1 5 3\n3 3 10\n7 10 2\n6 4 8\n", "output": "4\n-1\n8\n-1\n" }, { "input": "1 5000 1\n1 1000000 1000000\n", "output": "200\n" }, { "input": "999999 1000000 1\n1 1000000 1000000\n", "output": "1\n...
code_contests
python
0
120c9b7e35abe69616928f61424f9fe6
In the spirit of the holidays, Saitama has given Genos two grid paths of length n (a weird gift even by Saitama's standards). A grid path is an ordered sequence of neighbouring squares in an infinite grid. Two squares are neighbouring if they share a side. One example of a grid path is (0, 0) → (0, 1) → (0, 2) → (1, 2) → (1, 1) → (0, 1) → ( - 1, 1). Note that squares in this sequence might be repeated, i.e. path has self intersections. Movement within a grid path is restricted to adjacent squares within the sequence. That is, from the i-th square, one can only move to the (i - 1)-th or (i + 1)-th squares of this path. Note that there is only a single valid move from the first and last squares of a grid path. Also note, that even if there is some j-th square of the path that coincides with the i-th square, only moves to (i - 1)-th and (i + 1)-th squares are available. For example, from the second square in the above sequence, one can only move to either the first or third squares. To ensure that movement is not ambiguous, the two grid paths will not have an alternating sequence of three squares. For example, a contiguous subsequence (0, 0) → (0, 1) → (0, 0) cannot occur in a valid grid path. One marble is placed on the first square of each grid path. Genos wants to get both marbles to the last square of each grid path. However, there is a catch. Whenever he moves one marble, the other marble will copy its movement if possible. For instance, if one marble moves east, then the other marble will try and move east as well. By try, we mean if moving east is a valid move, then the marble will move east. Moving north increases the second coordinate by 1, while moving south decreases it by 1. Similarly, moving east increases first coordinate by 1, while moving west decreases it. Given these two valid grid paths, Genos wants to know if it is possible to move both marbles to the ends of their respective paths. That is, if it is possible to move the marbles such that both marbles rest on the last square of their respective paths. Input The first line of the input contains a single integer n (2 ≤ n ≤ 1 000 000) — the length of the paths. The second line of the input contains a string consisting of n - 1 characters (each of which is either 'N', 'E', 'S', or 'W') — the first grid path. The characters can be thought of as the sequence of moves needed to traverse the grid path. For example, the example path in the problem statement can be expressed by the string "NNESWW". The third line of the input contains a string of n - 1 characters (each of which is either 'N', 'E', 'S', or 'W') — the second grid path. Output Print "YES" (without quotes) if it is possible for both marbles to be at the end position at the same time. Print "NO" (without quotes) otherwise. In both cases, the answer is case-insensitive. Examples Input 7 NNESWW SWSWSW Output YES Input 3 NN SS Output NO Note In the first sample, the first grid path is the one described in the statement. Moreover, the following sequence of moves will get both marbles to the end: NNESWWSWSW. In the second sample, no sequence of moves can get both marbles to the end. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
def prefix(s): v = [0]*len(s) for i in range(1,len(s)): k = v[i-1] while k > 0 and s[k] != s[i]: k = v[k-1] if s[k] == s[i]: k = k + 1 v[i] = k return v n = int(input()) n-=1 s1 = input() s2 = input() opos = {'W':'E', 'E':'W', 'N':'S', 'S':'N'} s3 = '' for elem in s2: s3 += opos[elem] s3 = s3[::-1] s = s3 + '$' + s1 a = prefix(s)[2 * n] if a == 0: print('YES') else: print('NO')
python
code_algorithm
[ { "input": "3\nNN\nSS\n", "output": "NO\n" }, { "input": "7\nNNESWW\nSWSWSW\n", "output": "YES\n" }, { "input": "200\nNESENEESEESWWWNWWSWSWNWNNWNNESWSWNNWNWNENESENNESSWSESWWSSSEEEESSENNNESSWWSSSSESWSWWNNEESSWWNNWSWSSWWNWNNEENNENWWNESSSENWNESWNESWNESEESSWNESSSSSESESSWNNENENESSWWNNWWSWWNES...
code_contests
python
0
21deffc5f5fd580a54515d8931b0b684
<image> You can preview the image in better quality by the link: [http://assets.codeforces.com/files/656/without-text.png](//assets.codeforces.com/files/656/without-text.png) Input The only line of the input is a string (between 1 and 50 characters long, inclusive). Each character will be an alphanumeric character or a full stop ".". Output Output the required answer. Examples Input Codeforces Output -87 Input APRIL.1st Output 17 Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
s = input() alpha = "abcdefghijklmnopqrstuvwxyz.0123456789" res = 0 for c in s: x1 = int('@' < c and '[' > c) x2 = alpha.index(c.lower()) + 1 x3 = int('`' < c and '{' > c) x4 = x1 * x2 x5 = x2 * x3 x6 = x4 - x5 res += x6 print(res)
python
code_algorithm
[ { "input": "APRIL.1st\n", "output": "17\n" }, { "input": "Codeforces\n", "output": "-87\n" }, { "input": "K3n5JwuWoJdFUVq8H5QldFqDD2B9yCUDFY1TTMN10\n", "output": "118\n" }, { "input": "F646Pj3RlX5iZ9ei8oCh.IDjGCcvPQofAPCpNRwkBa6uido8w\n", "output": "-44\n" }, { "i...
code_contests
python
0
ea5962a9630636afe6e7bd9ff5f5916b
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower. Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r. If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower. Input The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order. Output Print minimal r so that each city will be covered by cellular network. Examples Input 3 2 -2 2 4 -3 0 Output 4 Input 5 3 1 5 10 14 17 4 11 15 Output 3 Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
import bisect import sys EPS = sys.float_info.epsilon LENGTH = 10 matrix = [[] for i in range(LENGTH)] array = [0] * LENGTH if __name__ == "__main__": n, m = map(int, sys.stdin.readline().split()) a = list(map(int, sys.stdin.readline().split())) b = list(map(int, sys.stdin.readline().split())) answer = 0 for val in a: index_l = bisect.bisect_left(b, val) index_r = bisect.bisect_left(b, val) ans1 = 10000000000000 ans2 = 10000000000000 if index_l > 0: ans1 = abs(val - b[index_l - 1]) if index_l <= len(b) - 1: ans2 = abs(b[index_l] - val) answer1 = min(ans1, ans2) ans1 = 10000000000000 ans2 = 10000000000000 if index_r > 0: ans1 = abs(val - b[index_r - 1]) if index_r <= len(b) - 1: ans2 = abs(b[index_r] - val) answer2 = min(ans1, ans2) answer = max(answer, min(answer1, answer2)) print(answer)
python
code_algorithm
[ { "input": "3 2\n-2 2 4\n-3 0\n", "output": "4\n" }, { "input": "5 3\n1 5 10 14 17\n4 11 15\n", "output": "3\n" }, { "input": "10 10\n2 52 280 401 416 499 721 791 841 943\n246 348 447 486 507 566 568 633 953 986\n", "output": "244\n" }, { "input": "2 1\n4 8\n-1\n", "outpu...
code_contests
python
0.1
1691b5d985b071cdacae8313becbe8c4
Innokentiy likes tea very much and today he wants to drink exactly n cups of tea. He would be happy to drink more but he had exactly n tea bags, a of them are green and b are black. Innokentiy doesn't like to drink the same tea (green or black) more than k times in a row. Your task is to determine the order of brewing tea bags so that Innokentiy will be able to drink n cups of tea, without drinking the same tea more than k times in a row, or to inform that it is impossible. Each tea bag has to be used exactly once. Input The first line contains four integers n, k, a and b (1 ≤ k ≤ n ≤ 105, 0 ≤ a, b ≤ n) — the number of cups of tea Innokentiy wants to drink, the maximum number of cups of same tea he can drink in a row, the number of tea bags of green and black tea. It is guaranteed that a + b = n. Output If it is impossible to drink n cups of tea, print "NO" (without quotes). Otherwise, print the string of the length n, which consists of characters 'G' and 'B'. If some character equals 'G', then the corresponding cup of tea should be green. If some character equals 'B', then the corresponding cup of tea should be black. If there are multiple answers, print any of them. Examples Input 5 1 3 2 Output GBGBG Input 7 2 2 5 Output BBGBGBB Input 4 3 4 0 Output NO Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
n,k,a,b = [int(i) for i in input().split()] check = False if (a>b): a,b = b,a check = True res = "" cr = 1 cA = True while (a > 0 or b > 0): if (a==b): break #print(a,b) if (cr==1): if a <= b: u = min(k, b - a) b -= u res += u * '1' else: if (b==0): cA = False break else: b -= 1 res += '1' cr = 0 else: if a >= b: u = min(k, a - b) a -= u res += u * '0' else: if (a==0): cA = False break else: a -= 1 res += '0' cr = 1 if (a==b): if (len(res)>0): if (res[len(res)-1] =='0'): res += '10' * a else: res += '01' * a else: res += '01' * a if (b==0 and a > k): cA = False if (a==0 and b > k): cA = False if cA == False: print("NO") else: if (check): for i in res: if i == '1': print('G', end ='') else: print('B', end ='') else: for i in res: if i == '1': print('B', end ='') else: print('G', end ='')
python
code_algorithm
[ { "input": "5 1 3 2\n", "output": "GBGBG" }, { "input": "7 2 2 5\n", "output": "BBGBBGB" }, { "input": "4 3 4 0\n", "output": "NO\n" }, { "input": "99999 3580 66665 33334\n", "output": "GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG...
code_contests
python
0
a157ccb403f288b1f59e69aaf1d86219
Vasya has the sequence consisting of n integers. Vasya consider the pair of integers x and y k-interesting, if their binary representation differs from each other exactly in k bits. For example, if k = 2, the pair of integers x = 5 and y = 3 is k-interesting, because their binary representation x=101 and y=011 differs exactly in two bits. Vasya wants to know how many pairs of indexes (i, j) are in his sequence so that i < j and the pair of integers ai and aj is k-interesting. Your task is to help Vasya and determine this number. Input The first line contains two integers n and k (2 ≤ n ≤ 105, 0 ≤ k ≤ 14) — the number of integers in Vasya's sequence and the number of bits in which integers in k-interesting pair should differ. The second line contains the sequence a1, a2, ..., an (0 ≤ ai ≤ 104), which Vasya has. Output Print the number of pairs (i, j) so that i < j and the pair of integers ai and aj is k-interesting. Examples Input 4 1 0 3 2 1 Output 4 Input 6 0 200 100 100 100 200 200 Output 6 Note In the first test there are 4 k-interesting pairs: * (1, 3), * (1, 4), * (2, 3), * (2, 4). In the second test k = 0. Consequently, integers in any k-interesting pair should be equal to themselves. Thus, for the second test there are 6 k-interesting pairs: * (1, 5), * (1, 6), * (2, 3), * (2, 4), * (3, 4), * (5, 6). Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
from collections import defaultdict n, k = [int(i) for i in input().split()] A = [int(i) for i in input().split()] A_dict = defaultdict(int) for i in A: A_dict[i] += 1 def bitCount(x): cur = 0 while x > 0: if x % 2: cur += 1 x //= 2 return cur mask = [] for i in range(2**15): if bitCount(i) == k: mask.append(i) ans = 0 for i in A_dict: for j in mask: if i^j in A_dict: if i^j == i: ans += A_dict[i] * (A_dict[i]-1) else: ans += A_dict[i] * A_dict[i^j] print(ans//2)
python
code_algorithm
[ { "input": "6 0\n200 100 100 100 200 200\n", "output": "6\n" }, { "input": "4 1\n0 3 2 1\n", "output": "4\n" }, { "input": "2 1\n0 1\n", "output": "1\n" }, { "input": "2 0\n1 1\n", "output": "1\n" }, { "input": "3 2\n0 3 3\n", "output": "2\n" }, { "inp...
code_contests
python
0.5
37973198e1286cc4a05223081702826f
Bankopolis is an incredible city in which all the n crossroads are located on a straight line and numbered from 1 to n along it. On each crossroad there is a bank office. The crossroads are connected with m oriented bicycle lanes (the i-th lane goes from crossroad ui to crossroad vi), the difficulty of each of the lanes is known. Oleg the bank client wants to gift happiness and joy to the bank employees. He wants to visit exactly k offices, in each of them he wants to gift presents to the employees. The problem is that Oleg don't want to see the reaction on his gifts, so he can't use a bicycle lane which passes near the office in which he has already presented his gifts (formally, the i-th lane passes near the office on the x-th crossroad if and only if min(ui, vi) < x < max(ui, vi))). Of course, in each of the offices Oleg can present gifts exactly once. Oleg is going to use exactly k - 1 bicycle lane to move between offices. Oleg can start his path from any office and finish it in any office. Oleg wants to choose such a path among possible ones that the total difficulty of the lanes he will use is minimum possible. Find this minimum possible total difficulty. Input The first line contains two integers n and k (1 ≤ n, k ≤ 80) — the number of crossroads (and offices) and the number of offices Oleg wants to visit. The second line contains single integer m (0 ≤ m ≤ 2000) — the number of bicycle lanes in Bankopolis. The next m lines contain information about the lanes. The i-th of these lines contains three integers ui, vi and ci (1 ≤ ui, vi ≤ n, 1 ≤ ci ≤ 1000), denoting the crossroads connected by the i-th road and its difficulty. Output In the only line print the minimum possible total difficulty of the lanes in a valid path, or -1 if there are no valid paths. Examples Input 7 4 4 1 6 2 6 2 2 2 4 2 2 7 1 Output 6 Input 4 3 4 2 1 2 1 3 2 3 4 2 4 1 1 Output 3 Note In the first example Oleg visiting banks by path 1 → 6 → 2 → 4. Path 1 → 6 → 2 → 7 with smaller difficulity is incorrect because crossroad 2 → 7 passes near already visited office on the crossroad 6. In the second example Oleg can visit banks by path 4 → 1 → 3. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
import sys from functools import lru_cache input = sys.stdin.readline # sys.setrecursionlimit(2 * 10**6) def inpl(): return list(map(int, input().split())) @lru_cache(maxsize=None) def recur(v, s, e, k): """ vから初めて[s, e]の都市をk個まわる最小値は? """ if k == 0: return 0 elif k > e - s + 1: return INF ret = INF # print(v, k) for nv in edge[v]: if not(s <= nv <= e): continue tmp = [0] * 2 if v < nv: tmp[0] = recur(nv, max(s, v + 1), nv - 1, k - 1) tmp[1] = recur(nv, nv + 1, e, k - 1) else: tmp[0] = recur(nv, s, nv - 1, k - 1) tmp[1] = recur(nv, nv + 1, min(v - 1, e), k - 1) # print(v, nv, tmp) if min(tmp) + cost[(v, nv)] < ret: ret = min(tmp) + cost[(v, nv)] return ret def main(): M = int(input()) U, V, C = [], [], [] for _ in range(M): u, v, c = inpl() U.append(u) V.append(v) C.append(c) for u, v, c in zip(U, V, C): if (u, v) in cost: cost[(u, v)] = min(cost[(u, v)], c) else: edge[u].append(v) cost[(u, v)] = c # print(cost) ans = INF for v in range(N + 1): for nv in edge[v]: tmp = [float('inf')] * 2 if v < nv: tmp[0] = recur(nv, nv + 1, N, K - 2) tmp[1] = recur(nv, v + 1, nv - 1, K - 2) else: tmp[0] = recur(nv, 1, nv - 1, K - 2) tmp[1] = recur(nv, nv + 1, v - 1, K - 2) if min(tmp) + cost[(v, nv)] < ans: ans = min(tmp) + cost[(v, nv)] if ans == INF: print(-1) else: print(ans) if __name__ == '__main__': INF = float('inf') N, K = inpl() if K < 2: print(0) exit() edge = [[] for _ in range(N + 1)] cost = {} main()
python
code_algorithm
[ { "input": "7 4\n4\n1 6 2\n6 2 2\n2 4 2\n2 7 1\n", "output": "6\n" }, { "input": "4 3\n4\n2 1 2\n1 3 2\n3 4 2\n4 1 1\n", "output": "3\n" }, { "input": "5 5\n10\n2 4 420\n4 5 974\n5 1 910\n1 3 726\n1 2 471\n5 2 94\n3 2 307\n2 5 982\n5 4 848\n3 5 404\n", "output": "-1\n" }, { "...
code_contests
python
0
9f26bd6070ab9b9b8a68b01180cbf2f2
Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical. Valera absolutely accidentally got a piece of ancient parchment on which an array of numbers was written. He immediately thought that the numbers in this array were not random. As a result of extensive research Valera worked out a wonderful property that a magical array should have: an array is defined as magic if its minimum and maximum coincide. He decided to share this outstanding discovery with you, but he asks you for help in return. Despite the tremendous intelligence and wit, Valera counts very badly and so you will have to complete his work. All you have to do is count the number of magical subarrays of the original array of numbers, written on the parchment. Subarray is defined as non-empty sequence of consecutive elements. Input The first line of the input data contains an integer n (1 ≤ n ≤ 105). The second line contains an array of original integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). Output Print on the single line the answer to the problem: the amount of subarrays, which are magical. Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is recommended to use cin, cout streams (you can also use the %I64d specificator). Examples Input 4 2 1 1 4 Output 5 Input 5 -2 -2 -2 0 1 Output 8 Note Notes to sample tests: Magical subarrays are shown with pairs of indices [a;b] of the beginning and the end. In the first sample: [1;1], [2;2], [3;3], [4;4], [2;3]. In the second sample: [1;1], [2;2], [3;3], [4;4], [5;5], [1;2], [2;3], [1;3]. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
from collections import defaultdict n = int(input()) arr = list(map(int,input().split())) cur = arr[0] cnt = 1 d = defaultdict(int) for i in range(1,n): if arr[i]==cur: cnt+=1 else: d[cnt]+=1 cur = arr[i] cnt = 1 if cnt!=0: d[cnt]+=1 ans = 0 for i in d: freq = d[i] cnt = (i*(i+1))//2 cnt = cnt*freq ans+=cnt print(ans)
python
code_algorithm
[ { "input": "5\n-2 -2 -2 0 1\n", "output": "8\n" }, { "input": "4\n2 1 1 4\n", "output": "5\n" }, { "input": "1\n10\n", "output": "1\n" }, { "input": "100\n0 -18 -9 -15 3 16 -28 0 -28 0 28 -20 -9 9 -11 0 18 -15 -18 -26 0 -27 -25 -22 6 -5 8 14 -17 24 20 3 -6 24 -27 1 -23 0 4 12...
code_contests
python
0.5
a20eda1216c79ff3280f2a05e1d890c7
Vlad likes to eat in cafes very much. During his life, he has visited cafes n times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research. First of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes he visited in a row, in order of visiting them. Now, Vlad wants to find such a cafe that his last visit to that cafe was before his last visits to every other cafe. In other words, he wants to find such a cafe that he hasn't been there for as long as possible. Help Vlad to find that cafe. Input In first line there is one integer n (1 ≤ n ≤ 2·105) — number of cafes indices written by Vlad. In second line, n numbers a1, a2, ..., an (0 ≤ ai ≤ 2·105) are written — indices of cafes in order of being visited by Vlad. Vlad could visit some cafes more than once. Note that in numeration, some indices could be omitted. Output Print one integer — index of the cafe that Vlad hasn't visited for as long as possible. Examples Input 5 1 3 2 1 2 Output 3 Input 6 2 1 2 2 4 1 Output 2 Note In first test, there are three cafes, and the last visits to cafes with indices 1 and 2 were after the last visit to cafe with index 3; so this cafe is the answer. In second test case, there are also three cafes, but with indices 1, 2 and 4. Cafes with indices 1 and 4 were visited after the last visit of cafe with index 2, so the answer is 2. Note that Vlad could omit some numbers while numerating the cafes. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
from sys import stdin as fin # fin = open("tc173b.in", "r") n = int(fin.readline()) # n, k = map(int, fin.readline().split()) arr = list(map(int, fin.readline().split())) # s = fin.readline().rstrip() s = dict() for i in range(n): x = arr[i] s[x] = (i, x) # print(tuple(s.items())) print(min(s.items(), key=lambda x: x[1])[0]) # print()
python
code_algorithm
[ { "input": "6\n2 1 2 2 4 1\n", "output": "2\n" }, { "input": "5\n1 3 2 1 2\n", "output": "3\n" }, { "input": "2\n2018 2017\n", "output": "2018\n" }, { "input": "11\n1 1 1 1 1 1 1 1 1 1 1\n", "output": "1\n" }, { "input": "5\n100 1000 1000 1000 1000\n", "output...
code_contests
python
1
432ae70ad8b0bffa92cce53a9d7e4487
You are given an integer N. Consider all possible segments on the coordinate axis with endpoints at integer points with coordinates between 0 and N, inclusive; there will be <image> of them. You want to draw these segments in several layers so that in each layer the segments don't overlap (they might touch at the endpoints though). You can not move the segments to a different location on the coordinate axis. Find the minimal number of layers you have to use for the given N. Input The only input line contains a single integer N (1 ≤ N ≤ 100). Output Output a single integer - the minimal number of layers required to draw the segments for the given N. Examples Input 2 Output 2 Input 3 Output 4 Input 4 Output 6 Note As an example, here are the segments and their optimal arrangement into layers for N = 4. <image> Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
n=int(input()) print(((n//2)+1)*(n-(n//2)))
python
code_algorithm
[ { "input": "3\n", "output": "4\n" }, { "input": "2\n", "output": "2\n" }, { "input": "4\n", "output": "6\n" }, { "input": "31\n", "output": "256\n" }, { "input": "68\n", "output": "1190\n" }, { "input": "75\n", "output": "1444\n" }, { "inpu...
code_contests
python
0
785c90506a381cfffa93ab4193600c4d
Polycarp is going to participate in the contest. It starts at h_1:m_1 and ends at h_2:m_2. It is guaranteed that the contest lasts an even number of minutes (i.e. m_1 \% 2 = m_2 \% 2, where x \% y is x modulo y). It is also guaranteed that the entire contest is held during a single day. And finally it is guaranteed that the contest lasts at least two minutes. Polycarp wants to know the time of the midpoint of the contest. For example, if the contest lasts from 10:00 to 11:00 then the answer is 10:30, if the contest lasts from 11:10 to 11:12 then the answer is 11:11. Input The first line of the input contains two integers h_1 and m_1 in the format hh:mm. The second line of the input contains two integers h_2 and m_2 in the same format (hh:mm). It is guaranteed that 0 ≤ h_1, h_2 ≤ 23 and 0 ≤ m_1, m_2 ≤ 59. It is guaranteed that the contest lasts an even number of minutes (i.e. m_1 \% 2 = m_2 \% 2, where x \% y is x modulo y). It is also guaranteed that the entire contest is held during a single day. And finally it is guaranteed that the contest lasts at least two minutes. Output Print two integers h_3 and m_3 (0 ≤ h_3 ≤ 23, 0 ≤ m_3 ≤ 59) corresponding to the midpoint of the contest in the format hh:mm. Print each number as exactly two digits (prepend a number with leading zero if needed), separate them with ':'. Examples Input 10:00 11:00 Output 10:30 Input 11:10 11:12 Output 11:11 Input 01:02 03:02 Output 02:02 Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
s=input() h1=int(s[:2]) m1=int(s[3:]) s=input() h2=int(s[:2]) m2=int(s[3:]) #print(h1,m1,h2,m2) m=(m2-m1)+(h2-h1)*60; ma=(m1+m/2)%60; ha=(h1+(m1+m/2)/60); print('0'*(2-len(str(int(ha))))+str(int(ha))+':'+'0'*(2-len(str(int(ma))))+str(int(ma)))
python
code_algorithm
[ { "input": "01:02\n03:02\n", "output": "02:02\n" }, { "input": "11:10\n11:12\n", "output": "11:11\n" }, { "input": "10:00\n11:00\n", "output": "10:30\n" }, { "input": "09:10\n09:12\n", "output": "09:11\n" }, { "input": "00:01\n23:59\n", "output": "12:00\n" }...
code_contests
python
0.7
59182cbdf2dc625f1a5c42299ca10699
Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 ≤ ti ≤ 10). Of course, one number can be assigned to any number of customers. "Perfect Matching" wants to advertise its services and publish the number of opposite couples, that is, the couples who have opposite values of t. Each couple consists of exactly two clients. The customer can be included in a couple an arbitrary number of times. Help the agency and write the program that will find the sought number by the given sequence t1, t2, ..., tn. For example, if t = (1, - 1, 1, - 1), then any two elements ti and tj form a couple if i and j have different parity. Consequently, in this case the sought number equals 4. Of course, a client can't form a couple with him/herself. Input The first line of the input data contains an integer n (1 ≤ n ≤ 105) which represents the number of registered clients of the "Couple Matching". The second line contains a sequence of integers t1, t2, ..., tn ( - 10 ≤ ti ≤ 10), ti — is the parameter of the i-th customer that has been assigned to the customer by the result of the analysis of his interests. Output Print the number of couples of customs with opposite t. The opposite number for x is number - x (0 is opposite to itself). Couples that only differ in the clients' order are considered the same. Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator. Examples Input 5 -3 3 0 0 3 Output 3 Input 3 0 0 0 Output 3 Note In the first sample the couples of opposite clients are: (1,2), (1,5) и (3,4). In the second sample any couple of clients is opposite. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
c=[0]*50 n=int(input()) a=[0]*2000001 a=[int(i) for i in input().split()] for i in range(n): c[int(a[i]+10)]+=1; r=0 for i in range(10): r+=int(c[int(i)]*c[int(20-i)]) r+=(c[10]*(c[10]-1))//2; r=int(r) print(r)
python
code_algorithm
[ { "input": "5\n-3 3 0 0 3\n", "output": "3\n" }, { "input": "3\n0 0 0\n", "output": "3\n" }, { "input": "2\n0 0\n", "output": "1\n" }, { "input": "10\n1 -1 2 -2 3 -3 4 -4 0 0\n", "output": "5\n" }, { "input": "4\n1 -1 1 -1\n", "output": "4\n" }, { "inp...
code_contests
python
0.1
c9ab0e4eca7e72b1c6ec1e367ece822c
You have a tree of n vertices. You are going to convert this tree into n rubber bands on infinitely large plane. Conversion rule follows: * For every pair of vertices a and b, rubber bands a and b should intersect if and only if there is an edge exists between a and b in the tree. * Shape of rubber bands must be a simple loop. In other words, rubber band is a loop which doesn't self-intersect. Now let's define following things: * Rubber band a includes rubber band b, if and only if rubber band b is in rubber band a's area, and they don't intersect each other. * Sequence of rubber bands a_{1}, a_{2}, …, a_{k} (k ≥ 2) are nested, if and only if for all i (2 ≤ i ≤ k), a_{i-1} includes a_{i}. <image> This is an example of conversion. Note that rubber bands 5 and 6 are nested. It can be proved that is it possible to make a conversion and sequence of nested rubber bands under given constraints. What is the maximum length of sequence of nested rubber bands can be obtained from given tree? Find and print it. Input The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in tree. The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices. Output Print the answer. Examples Input 6 1 3 2 3 3 4 4 5 4 6 Output 4 Input 4 1 2 2 3 3 4 Output 2 Note In the first sample, you can obtain a nested sequence of 4 rubber bands(1, 2, 5, and 6) by the conversion shown below. Of course, there are other conversions exist to make a nested sequence of 4 rubber bands. However, you cannot make sequence of 5 or more nested rubber bands with given tree. <image> You can see one of the possible conversions for the second sample below. <image> Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
import os import sys input = sys.stdin.buffer.readline #sys.setrecursionlimit(int(3e5)) from collections import deque from queue import PriorityQueue import math import copy # list(map(int, input().split())) ##################################################################################### class CF(object): def __init__(self): self.n = int(input()) self.g = [[] for _ in range(self.n)] self.v = [[] for _ in range(self.n)] self.r = [] # last order path self.f = [-1] * self.n self.vis = [0] * self.n for _ in range(self.n-1): x, y = list(map(int, input().split())) x-=1 y-=1 self.v[x].append(y) self.v[y].append(x) pass self.g = copy.deepcopy(self.v) self.dp = [[0,0] for _ in range(self.n)] self.leaf = [0] * self.n for i in range(self.n): if(len(self.g[i]) == 1): self.leaf[i] = True pass def dfs(self, root=0): # last order path s = [root] v = [self.g[root]] self.vis[root] = 1 while(len(s)> 0): if(v[-1] == []): v.pop() self.r.append(s.pop()) else: now = v[-1].pop() if(not self.vis[now]): self.vis[now] = 1 self.f[now] = s[-1] s.append(now) v.append(self.g[now]) pass def update(self, temp, x): temp.append(x) for i in range(len(temp)-1)[::-1]: if(temp[i+1]> temp[i]): temp[i+1], temp[i] = temp[i], temp[i+1] pass return temp[:2] def main(self): self.dfs() ans = 0 for now in self.r: if(self.leaf[now]): self.dp[now][1] = 1 self.dp[now][0] = 0 else: temp = [] t2 = [] for to in self.v[now]: if(to != self.f[now]): #temp = max(temp, self.dp[to][0]) temp = self.update(temp, self.dp[to][0]) t2 = self.update(t2, max(self.dp[to][1], self.dp[to][0])) #t2 = max(t2, max(self.dp[to][1], self.dp[to][0])) pass self.dp[now][1] = temp[0] + 1 self.dp[now][0] = t2[0] + len(self.v[now])-1-1 ans = max(ans, 1+sum(temp)) ans = max(ans, len(self.v[now]) - len(t2) + sum(t2)) pass ar = [] for to in self.v[0]: ar.append(self.dp[to][0]) ar.sort() if(len(ar)>=2): ans = max(ans, 1+ar[-1]+ar[-2]) else: ans = max(ans, 1+ar[-1]) ar = [] for to in self.v[0]: ar.append(max(self.dp[to][1], self.dp[to][0])) ar.sort() for i in range(len(ar)-2): ar[i] = 1 ans = max(ans, sum(ar)) print(ans) pass # print(self.dp) # print(self.leaf) # print(self.r) # print(self.f) if __name__ == "__main__": cf = CF() cf.main() pass
python
code_algorithm
[ { "input": "6\n1 3\n2 3\n3 4\n4 5\n4 6\n", "output": "4\n" }, { "input": "4\n1 2\n2 3\n3 4\n", "output": "2\n" }, { "input": "28\n2 24\n2 4\n2 3\n1 2\n1 17\n1 21\n1 22\n10 22\n22 23\n22 26\n25 26\n16 25\n7 26\n5 7\n5 8\n5 15\n5 14\n5 12\n5 20\n11 25\n9 25\n6 9\n9 19\n9 28\n13 28\n18 28\n...
code_contests
python
0
64e98588da9e4eb9c29d7b201acf69bf
There are n warriors in a row. The power of the i-th warrior is a_i. All powers are pairwise distinct. You have two types of spells which you may cast: 1. Fireball: you spend x mana and destroy exactly k consecutive warriors; 2. Berserk: you spend y mana, choose two consecutive warriors, and the warrior with greater power destroys the warrior with smaller power. For example, let the powers of warriors be [2, 3, 7, 8, 11, 5, 4], and k = 3. If you cast Berserk on warriors with powers 8 and 11, the resulting sequence of powers becomes [2, 3, 7, 11, 5, 4]. Then, for example, if you cast Fireball on consecutive warriors with powers [7, 11, 5], the resulting sequence of powers becomes [2, 3, 4]. You want to turn the current sequence of warriors powers a_1, a_2, ..., a_n into b_1, b_2, ..., b_m. Calculate the minimum amount of mana you need to spend on it. Input The first line contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the length of sequence a and the length of sequence b respectively. The second line contains three integers x, k, y (1 ≤ x, y, ≤ 10^9; 1 ≤ k ≤ n) — the cost of fireball, the range of fireball and the cost of berserk respectively. The third line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n). It is guaranteed that all integers a_i are pairwise distinct. The fourth line contains m integers b_1, b_2, ..., b_m (1 ≤ b_i ≤ n). It is guaranteed that all integers b_i are pairwise distinct. Output Print the minimum amount of mana for turning the sequnce a_1, a_2, ..., a_n into b_1, b_2, ..., b_m, or -1 if it is impossible. Examples Input 5 2 5 2 3 3 1 4 5 2 3 5 Output 8 Input 4 4 5 1 4 4 3 1 2 2 4 3 1 Output -1 Input 4 4 2 1 11 1 3 2 4 1 3 2 4 Output 0 Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------------------ def RL(): return map(int, sys.stdin.readline().rstrip().split()) def RLL(): return list(map(int, sys.stdin.readline().rstrip().split())) def N(): return int(input()) def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0 def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0 def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2) mod = 998244353 INF = float('inf') from math import factorial from collections import Counter, defaultdict, deque from heapq import heapify, heappop, heappush # ------------------------------ # f = open('../input.txt') # sys.stdin = f def main(): n, m = RL() x, k, y = RL() arra = RLL() arrb = RLL() arra+=[arrb[-1]]; arrb+=[arrb[-1]] m+=1; n+=1 pn, pm = 0, 0 res = 0 while pn<n and pm<m: nma = nmi = 0 ma = max(arrb[pm], arrb[max(pm-1, 0)]) while pn<n and arra[pn]!=arrb[pm]: if arra[pn]>ma: nma+=1 else: nmi+=1 pn+=1 if pn >= n: break num = nma+nmi tms = num//k ots = num%k if nma != 0: if num - k < 0: break if x<y*k: res+=tms*x + ots*y else: if nma!=0: res+=(num-k)*y + x else: res+=num*y pn+=1 pm+=1 print(res if pm==m and pn==n else -1) if __name__ == "__main__": main()
python
code_algorithm
[ { "input": "5 2\n5 2 3\n3 1 4 5 2\n3 5\n", "output": "8\n" }, { "input": "4 4\n2 1 11\n1 3 2 4\n1 3 2 4\n", "output": "0\n" }, { "input": "4 4\n5 1 4\n4 3 1 2\n2 4 3 1\n", "output": "-1\n" }, { "input": "4 4\n10 1 5\n1 2 3 4\n1 3 2 4\n", "output": "-1\n" }, { "inp...
code_contests
python
0
f1d85476039ebc552d227f426d0a6922
You've gotten an n × m sheet of squared paper. Some of its squares are painted. Let's mark the set of all painted squares as A. Set A is connected. Your task is to find the minimum number of squares that we can delete from set A to make it not connected. A set of painted squares is called connected, if for every two squares a and b from this set there is a sequence of squares from the set, beginning in a and ending in b, such that in this sequence any square, except for the last one, shares a common side with the square that follows next in the sequence. An empty set and a set consisting of exactly one square are connected by definition. Input The first input line contains two space-separated integers n and m (1 ≤ n, m ≤ 50) — the sizes of the sheet of paper. Each of the next n lines contains m characters — the description of the sheet of paper: the j-th character of the i-th line equals either "#", if the corresponding square is painted (belongs to set A), or equals "." if the corresponding square is not painted (does not belong to set A). It is guaranteed that the set of all painted squares A is connected and isn't empty. Output On the first line print the minimum number of squares that need to be deleted to make set A not connected. If it is impossible, print -1. Examples Input 5 4 #### #..# #..# #..# #### Output 2 Input 5 5 ##### #...# ##### #...# ##### Output 2 Note In the first sample you can delete any two squares that do not share a side. After that the set of painted squares is not connected anymore. The note to the second sample is shown on the figure below. To the left there is a picture of the initial set of squares. To the right there is a set with deleted squares. The deleted squares are marked with crosses. <image> Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
def add(vertex,neighbour): if vertex in graph: graph[vertex].append(neighbour) else: graph[vertex]=[neighbour] if neighbour in graph: #####for undirected part remove to get directed graph[neighbour].append(vertex) else: graph[neighbour]=[vertex] def dfs(graph,n,currnode): visited=[False for x in range(n+1)] stack=[currnode] ans=[] while stack: currnode=stack[-1] if visited[currnode]==False: visited[currnode]=True ans.append(currnode) if currnode in graph1: for neighbour in graph[currnode]: if visited[neighbour]==False: visited[neighbour]=True stack.append(neighbour) ans.append(neighbour) break #####if we remove break it becomes bfs else: stack.pop() ####we are backtracking to previous node which is in our stack else: stack.pop() return ans n,m=[int(x) for x in input().split()] nodes=n*m arr=[None for i in range(nodes)] for i in range(n): s=input() for j in range(m): arr[i*m+j]=s[j] graph={} for i in range(m,nodes): if i%m!=0 and arr[i]=="#": if arr[i-1]=="#": add(i,i-1) r=i//m;c=i%m if arr[(r-1)*m+c]=="#": add(i,(r-1)*m+c) elif i%m==0 and arr[i]=="#": #if arr[i+1]=="#": #add(i,i+1) r=i//m if arr[(r-1)*m]=="#": add((r-1)*m,i) for i in range(1,m): if arr[i]=="#" and arr[i-1]=="#": add(i,i-1) for i in range(nodes): if arr[i]=="#" and i not in graph: graph[i]=[] graph1=graph.copy() if len(graph)<3: print(-1) else: found=False firstnode=[];secondnnode=[] for key,val in graph.items(): if len(firstnode)==0: firstnode=[key,val] d=len(dfs(graph,nodes,firstnode[0])) elif len(secondnnode)==0: secondnnode=[key,val] else: del graph1[key] if len(dfs(graph1,nodes,firstnode[0]))-1!=d-1: found=True break graph1[key]=val else: del graph1[firstnode[0]] if len(dfs(graph1,nodes,secondnnode[0]))-1!=d-1: found=True graph1[firstnode[0]]=firstnode[1] del graph1[secondnnode[0]] if len(dfs(graph1,nodes,firstnode[0]))-1!=d-1: found=True graph1[secondnnode[0]]=secondnnode[1] if found==True: print(1) else: print(2)
python
code_algorithm
[ { "input": "5 4\n####\n#..#\n#..#\n#..#\n####\n", "output": "2\n" }, { "input": "5 5\n#####\n#...#\n#####\n#...#\n#####\n", "output": "2\n" }, { "input": "10 10\n..........\n.#####....\n.#........\n.#.###....\n.#.###....\n.#.###....\n.#..##....\n.#####....\n..........\n..........\n", ...
code_contests
python
0.3
3e90f0389d26a4d04aea0a6b5a173bbf
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created. We assume that Bajtek can only heap up snow drifts at integer coordinates. Input The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift. Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct. Output Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one. Examples Input 2 2 1 1 2 Output 1 Input 2 2 1 4 1 Output 0 Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
n = int(input()) g = [] for i in range(n): t = input().split() g.append([ int(t[0]), int(t[1]), False ]) def visita(i): g[i][2] = True for j in range(n): if g[j][2] == False and (g[i][0] == g[j][0] or g[i][1] == g[j][1]): visita(j) cnt = -1 for i in range(n): if g[i][2] == False: cnt += 1 visita(i) print(cnt)
python
code_algorithm
[ { "input": "2\n2 1\n1 2\n", "output": "1\n" }, { "input": "2\n2 1\n4 1\n", "output": "0\n" }, { "input": "55\n1 1\n1 14\n2 2\n2 19\n3 1\n3 3\n3 8\n3 14\n3 23\n4 1\n4 4\n5 5\n5 8\n5 15\n6 2\n6 3\n6 4\n6 6\n7 7\n8 8\n8 21\n9 9\n10 1\n10 10\n11 9\n11 11\n12 12\n13 13\n14 14\n15 15\n15 24\n1...
code_contests
python
0.4
25ad2fdbe8dee1f207928b04c60170e3
Squirrel Liss is interested in sequences. She also has preferences of integers. She thinks n integers a1, a2, ..., an are good. Now she is interested in good sequences. A sequence x1, x2, ..., xk is called good if it satisfies the following three conditions: * The sequence is strictly increasing, i.e. xi < xi + 1 for each i (1 ≤ i ≤ k - 1). * No two adjacent elements are coprime, i.e. gcd(xi, xi + 1) > 1 for each i (1 ≤ i ≤ k - 1) (where gcd(p, q) denotes the greatest common divisor of the integers p and q). * All elements of the sequence are good integers. Find the length of the longest good sequence. Input The input consists of two lines. The first line contains a single integer n (1 ≤ n ≤ 105) — the number of good integers. The second line contains a single-space separated list of good integers a1, a2, ..., an in strictly increasing order (1 ≤ ai ≤ 105; ai < ai + 1). Output Print a single integer — the length of the longest good sequence. Examples Input 5 2 3 4 6 9 Output 4 Input 9 1 2 3 5 6 7 8 9 10 Output 4 Note In the first example, the following sequences are examples of good sequences: [2; 4; 6; 9], [2; 4; 6], [3; 9], [6]. The length of the longest good sequence is 4. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
# Legends Always Come Up with Solution # Author: Manvir Singh import os import sys from io import BytesIO, IOBase from collections import Counter def seieve_prime_factorisation(n): p, i = [1] * (n + 1), 2 while i * i <= n: if p[i] == 1: for j in range(i * i, n + 1, i): p[j] = i i += 1 return p def prime_factorisation_by_seive(p, x): c = Counter() while p[x] != 1: c[p[x]] += 1 x = x // p[x] c[x] += 1 return c def main(): n=int(input()) a=list(map(int,input().split())) p=seieve_prime_factorisation(max(a)) dp=[1]*n b=Counter() for i in range(n-1,-1,-1): z=prime_factorisation_by_seive(p,a[i]) ma=0 for j in z: ma=max(ma,b[j]) dp[i]+=ma for j in z: b[j]=max(b[j],dp[i]) print(max(dp)) # (region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == "__main__": main()
python
code_algorithm
[ { "input": "9\n1 2 3 5 6 7 8 9 10\n", "output": "4\n" }, { "input": "5\n2 3 4 6 9\n", "output": "4\n" }, { "input": "2\n1009 2018\n", "output": "2\n" }, { "input": "7\n1 2 3 4 7 9 10\n", "output": "3\n" }, { "input": "2\n601 1202\n", "output": "2\n" }, { ...
code_contests
python
0.6
30d2aa766fea0453a9b6a9d4d6400b23
Little penguin Polo loves his home village. The village has n houses, indexed by integers from 1 to n. Each house has a plaque containing an integer, the i-th house has a plaque containing integer pi (1 ≤ pi ≤ n). Little penguin Polo loves walking around this village. The walk looks like that. First he stands by a house number x. Then he goes to the house whose number is written on the plaque of house x (that is, to house px), then he goes to the house whose number is written on the plaque of house px (that is, to house ppx), and so on. We know that: 1. When the penguin starts walking from any house indexed from 1 to k, inclusive, he can walk to house number 1. 2. When the penguin starts walking from any house indexed from k + 1 to n, inclusive, he definitely cannot walk to house number 1. 3. When the penguin starts walking from house number 1, he can get back to house number 1 after some non-zero number of walks from a house to a house. You need to find the number of ways you may write the numbers on the houses' plaques so as to fulfill the three above described conditions. Print the remainder after dividing this number by 1000000007 (109 + 7). Input The single line contains two space-separated integers n and k (1 ≤ n ≤ 1000, 1 ≤ k ≤ min(8, n)) — the number of the houses and the number k from the statement. Output In a single line print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 5 2 Output 54 Input 7 4 Output 1728 Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
MOD = 10 ** 9 + 7 n, k = map(int, input().split()) ans = pow(n - k, n - k, MOD) * pow(k, k - 1, MOD) print(ans % MOD)
python
code_algorithm
[ { "input": "5 2\n", "output": "54\n" }, { "input": "7 4\n", "output": "1728\n" }, { "input": "475 5\n", "output": "449471303\n" }, { "input": "10 7\n", "output": "3176523\n" }, { "input": "685 7\n", "output": "840866481\n" }, { "input": "8 5\n", "o...
code_contests
python
0.2
63d97818e4ccb7b4ec88b37e8bca0d47
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddly shaped, interlocking and tessellating pieces). The shop assistant told the teacher that there are m puzzles in the shop, but they might differ in difficulty and size. Specifically, the first jigsaw puzzle consists of f1 pieces, the second one consists of f2 pieces and so on. Ms. Manana doesn't want to upset the children, so she decided that the difference between the numbers of pieces in her presents must be as small as possible. Let A be the number of pieces in the largest puzzle that the teacher buys and B be the number of pieces in the smallest such puzzle. She wants to choose such n puzzles that A - B is minimum possible. Help the teacher and find the least possible value of A - B. Input The first line contains space-separated integers n and m (2 ≤ n ≤ m ≤ 50). The second line contains m space-separated integers f1, f2, ..., fm (4 ≤ fi ≤ 1000) — the quantities of pieces in the puzzles sold in the shop. Output Print a single integer — the least possible difference the teacher can obtain. Examples Input 4 6 10 12 10 7 5 22 Output 5 Note Sample 1. The class has 4 students. The shop sells 6 puzzles. If Ms. Manana buys the first four puzzles consisting of 10, 12, 10 and 7 pieces correspondingly, then the difference between the sizes of the largest and the smallest puzzle will be equal to 5. It is impossible to obtain a smaller difference. Note that the teacher can also buy puzzles 1, 3, 4 and 5 to obtain the difference 5. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
n,m = map(int,input().split()) f = list(map(int,input().split())) f.sort() a = [] for i in range(m-n+1): a.append(f[i+n-1]-f[i]) print(min(a))
python
code_algorithm
[ { "input": "4 6\n10 12 10 7 5 22\n", "output": "5\n" }, { "input": "2 2\n1000 4\n", "output": "996\n" }, { "input": "2 3\n4 502 1000\n", "output": "498\n" }, { "input": "40 50\n17 20 43 26 41 37 14 8 30 35 30 24 43 8 42 9 41 50 41 35 27 32 35 43 28 36 31 16 5 7 23 16 14 29 8 ...
code_contests
python
0.8
63f54f44e840190e13f26d990bd024b6
Iahub helps his grandfather at the farm. Today he must milk the cows. There are n cows sitting in a row, numbered from 1 to n from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of milk that they can give. A cow facing left sees all the cows with lower indices than her index, and a cow facing right sees all the cows with higher indices than her index. A cow that got scared once can get scared again (and lose one more unit of milk). A cow that has been milked once cannot get scared and lose any more milk. You can assume that a cow never loses all the milk she can give (a cow gives an infinitely amount of milk). Iahub can decide the order in which he milks the cows. But he must milk each cow exactly once. Iahub wants to lose as little milk as possible. Print the minimum amount of milk that is lost. Input The first line contains an integer n (1 ≤ n ≤ 200000). The second line contains n integers a1, a2, ..., an, where ai is 0 if the cow number i is facing left, and 1 if it is facing right. Output Print a single integer, the minimum amount of lost milk. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 4 0 0 1 0 Output 1 Input 5 1 0 1 0 1 Output 3 Note In the first sample Iahub milks the cows in the following order: cow 3, cow 4, cow 2, cow 1. When he milks cow 3, cow 4 loses 1 unit of milk. After that, no more milk is lost. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
#! usr/bin/env python3 # coding:UTF-8 # wdnmd UKE # wcnm UKE ans = 0 cnt = 0 N = input() t = input().split() for i in t: if(int(i) == 1): cnt += 1 else: ans += cnt print(ans)
python
code_algorithm
[ { "input": "5\n1 0 1 0 1\n", "output": "3\n" }, { "input": "4\n0 0 1 0\n", "output": "1\n" }, { "input": "4\n1 1 1 1\n", "output": "0\n" }, { "input": "1\n0\n", "output": "0\n" }, { "input": "2\n1 0\n", "output": "1\n" }, { "input": "2\n0 0\n", "ou...
code_contests
python
0.3
d337837decce25296e2788db031d814b
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone. In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules of the game, Jury must use this second to touch the corresponding strip to make the square go away. As Jury is both smart and lazy, he counted that he wastes exactly ai calories on touching the i-th strip. You've got a string s, describing the process of the game and numbers a1, a2, a3, a4. Calculate how many calories Jury needs to destroy all the squares? Input The first line contains four space-separated integers a1, a2, a3, a4 (0 ≤ a1, a2, a3, a4 ≤ 104). The second line contains string s (1 ≤ |s| ≤ 105), where the і-th character of the string equals "1", if on the i-th second of the game the square appears on the first strip, "2", if it appears on the second strip, "3", if it appears on the third strip, "4", if it appears on the fourth strip. Output Print a single integer — the total number of calories that Jury wastes. Examples Input 1 2 3 4 123214 Output 13 Input 1 5 3 2 11221 Output 13 Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
#!/usr/bin/env python3 a=list(map(int,input().split())) s=input() print(a[0]*s.count('1') + a[1]*s.count('2') + a[2]*s.count('3') + a[3]*s.count('4'))
python
code_algorithm
[ { "input": "1 2 3 4\n123214\n", "output": "13\n" }, { "input": "1 5 3 2\n11221\n", "output": "13\n" }, { "input": "1 2 3 4\n11111111111111111111111111111111111111111111111111\n", "output": "50\n" }, { "input": "5651 6882 6954 4733\n2442313421\n", "output": "60055\n" }, ...
code_contests
python
1
781d3442ff7c817e7fc2db550e2a9941
Dreamoon wants to climb up a stair of n steps. He can climb 1 or 2 steps at each move. Dreamoon wants the number of moves to be a multiple of an integer m. What is the minimal number of moves making him climb to the top of the stairs that satisfies his condition? Input The single line contains two space separated integers n, m (0 < n ≤ 10000, 1 < m ≤ 10). Output Print a single integer — the minimal number of moves being a multiple of m. If there is no way he can climb satisfying condition print - 1 instead. Examples Input 10 2 Output 6 Input 3 5 Output -1 Note For the first sample, Dreamoon could climb in 6 moves with following sequence of steps: {2, 2, 2, 2, 1, 1}. For the second sample, there are only three valid sequence of steps {2, 1}, {1, 2}, {1, 1, 1} with 2, 2, and 3 steps respectively. All these numbers are not multiples of 5. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
n,m = map(int, input().split()) if n < m: print(-1) else: if n % 2 == 0: b = n//2 else: b = (n//2)+1 while b % m != 0: b = b + 1 print(b)
python
code_algorithm
[ { "input": "10 2\n", "output": "6\n" }, { "input": "3 5\n", "output": "-1\n" }, { "input": "3979 2\n", "output": "1990\n" }, { "input": "18 10\n", "output": "10\n" }, { "input": "3832 6\n", "output": "1920\n" }, { "input": "8 2\n", "output": "4\n" ...
code_contests
python
0.4
bdbe1f78c9c50bdc7572ddbde98ef252
Vasya studies positional numeral systems. Unfortunately, he often forgets to write the base of notation in which the expression is written. Once he saw a note in his notebook saying a + b = ?, and that the base of the positional notation wasn’t written anywhere. Now Vasya has to choose a base p and regard the expression as written in the base p positional notation. Vasya understood that he can get different results with different bases, and some bases are even invalid. For example, expression 78 + 87 in the base 16 positional notation is equal to FF16, in the base 15 positional notation it is equal to 11015, in the base 10 one — to 16510, in the base 9 one — to 1769, and in the base 8 or lesser-based positional notations the expression is invalid as all the numbers should be strictly less than the positional notation base. Vasya got interested in what is the length of the longest possible expression value. Help him to find this length. The length of a number should be understood as the number of numeric characters in it. For example, the length of the longest answer for 78 + 87 = ? is 3. It is calculated like that in the base 15 (11015), base 10 (16510), base 9 (1769) positional notations, for example, and in some other ones. Input The first letter contains two space-separated numbers a and b (1 ≤ a, b ≤ 1000) which represent the given summands. Output Print a single number — the length of the longest answer. Examples Input 78 87 Output 3 Input 1 1 Output 2 Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
a,b=list(map(int,input().split())) k=int(max(str(a)+str(b)))+1 carry=0 l=max(len(str(a)),len(str(b))) for itr in range(l): if a%10+b%10+carry<k: carry=0 else: carry=1 a//=10 b//=10 #print(a,b) if carry: print(l+1) else: print(l)
python
code_algorithm
[ { "input": "78 87\n", "output": "3\n" }, { "input": "1 1\n", "output": "2\n" }, { "input": "208 997\n", "output": "4\n" }, { "input": "12 34\n", "output": "3\n" }, { "input": "104 938\n", "output": "4\n" }, { "input": "1000 539\n", "output": "4\n" ...
code_contests
python
0
4a55d6843fe826a04913e23095194da4
A social network for dogs called DH (DogHouse) has k special servers to recompress uploaded videos of cute cats. After each video is uploaded, it should be recompressed on one (any) of the servers, and only after that it can be saved in the social network. We know that each server takes one second to recompress a one minute fragment. Thus, any server takes m seconds to recompress a m minute video. We know the time when each of the n videos were uploaded to the network (in seconds starting from the moment all servers started working). All videos appear at different moments of time and they are recompressed in the order they appear. If some video appeared at time s, then its recompressing can start at that very moment, immediately. Some videos can await recompressing when all the servers are busy. In this case, as soon as a server is available, it immediately starts recompressing another video. The videos that await recompressing go in a queue. If by the moment the videos started being recompressed some servers are available, then any of them starts recompressing the video. For each video find the moment it stops being recompressed. Input The first line of the input contains integers n and k (1 ≤ n, k ≤ 5·105) — the number of videos and servers, respectively. Next n lines contain the descriptions of the videos as pairs of integers si, mi (1 ≤ si, mi ≤ 109), where si is the time in seconds when the i-th video appeared and mi is its duration in minutes. It is guaranteed that all the si's are distinct and the videos are given in the chronological order of upload, that is in the order of increasing si. Output Print n numbers e1, e2, ..., en, where ei is the time in seconds after the servers start working, when the i-th video will be recompressed. Examples Input 3 2 1 5 2 5 3 5 Output 6 7 11 Input 6 1 1 1000000000 2 1000000000 3 1000000000 4 1000000000 5 1000000000 6 3 Output 1000000001 2000000001 3000000001 4000000001 5000000001 5000000004 Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
import atexit import io import sys _INPUT_LINES = sys.stdin.read().splitlines() input = iter(_INPUT_LINES).__next__ _OUTPUT_BUFFER = io.StringIO() sys.stdout = _OUTPUT_BUFFER @atexit.register def write(): sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) def main(): import heapq n, k = [int(i) for i in input().split()] s, m = [0] * n, [0] * n for i in range(n): s[i], m[i] = [int(i) for i in input().split()] current_time = 0 event = [] ans = [0] * n i = 0 while len(event) or i < n: if (len(event) == 0): current_time = max(current_time, s[i]) heapq.heappush(event, (current_time + m[i], i)) i += 1 continue e_time, e_id = event[0] if e_time == current_time or i == n: current_time = max(current_time, e_time) ans[e_id] = e_time heapq.heappop(event) continue if s[i] < e_time and len(event) < k: current_time = max(current_time, s[i]) heapq.heappush(event, (current_time + m[i], i)) i += 1 continue else: current_time = ans[e_id] = e_time heapq.heappop(event) continue print("\n".join([str(i) for i in ans])) main()
python
code_algorithm
[ { "input": "6 1\n1 1000000000\n2 1000000000\n3 1000000000\n4 1000000000\n5 1000000000\n6 3\n", "output": "1000000001\n2000000001\n3000000001\n4000000001\n5000000001\n5000000004\n" }, { "input": "3 2\n1 5\n2 5\n3 5\n", "output": "6\n7\n11\n" }, { "input": "10 2\n1 5650\n2 4753\n3 7632\n4 ...
code_contests
python
0.7
2e966bc7462a3ee7d5118ea4e4a81ed8
The Hedgehog recently remembered one of his favorite childhood activities, — solving puzzles, and got into it with new vigor. He would sit day in, day out with his friend buried into thousands of tiny pieces of the picture, looking for the required items one by one. Soon the Hedgehog came up with a brilliant idea: instead of buying ready-made puzzles, one can take his own large piece of paper with some picture and cut it into many small rectangular pieces, then mix them and solve the resulting puzzle, trying to piece together the picture. The resulting task is even more challenging than the classic puzzle: now all the fragments have the same rectangular shape, and one can assemble the puzzle only relying on the picture drawn on the pieces. All puzzle pieces turn out to be of the same size X × Y, because the picture is cut first by horizontal cuts with the pitch of X, then with vertical cuts with the pitch of Y. If we denote the initial size of the picture as A × B, then A must be divisible by X and B must be divisible by Y (X and Y are integer numbers). However, not every such cutting of the picture will result in a good puzzle. The Hedgehog finds a puzzle good if no two pieces in it are the same (It is allowed to rotate the pieces when comparing them, but it is forbidden to turn them over). Your task is to count for a given picture the number of good puzzles that you can make from it, and also to find the puzzle with the minimal piece size. Input The first line contains two numbers A and B which are the sizes of the picture. They are positive integers not exceeding 20. Then follow A lines containing B symbols each, describing the actual picture. The lines only contain uppercase English letters. Output In the first line print the number of possible good puzzles (in other words, the number of pairs (X, Y) such that the puzzle with the corresponding element sizes will be good). This number should always be positive, because the whole picture is a good puzzle itself. In the second line print two numbers — the sizes X and Y of the smallest possible element among all good puzzles. The comparison is made firstly by the area XY of one element and secondly — by the length X. Examples Input 2 4 ABDC ABDC Output 3 2 1 Input 2 6 ABCCBA ABCCBA Output 1 2 6 Note The picture in the first sample test has the following good puzzles: (2, 1), (2, 2), (2, 4). Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
def rotate(puzzle): n_puzzle = [] for y in range(len(puzzle) - 1, -1, -1): n_puzzle.append(puzzle[y]) result = [] for x in range(len(puzzle[0])): col = [] for y in range(len(puzzle)): col.append(n_puzzle[y][x]) result.append(col) return result def puzzle_match(p1, p2): r1 = p2 r2 = rotate(p2) r3 = rotate(r2) r4 = rotate(r3) variants = [r1, r2, r3, r4] return p1 in variants def make_puzzles(puzzle, x_cuts, y_cuts, a, b): x_size = a // x_cuts y_size = b // y_cuts result = [] for x in range(x_cuts): for y in range(y_cuts): p = [] for i in range(x_size): row = [] for j in range(y_size): row.append(puzzle[x * x_size + i][y * y_size + j]) p.append(row) result.append(p) return result class CodeforcesTask54BSolution: def __init__(self): self.result = '' self.a_b = [] self.puzzle = [] def read_input(self): self.a_b = [int(x) for x in input().split(" ")] for x in range(self.a_b[0]): self.puzzle.append(list(input())) def process_task(self): x_cuts = [x for x in range(1, self.a_b[0] + 1) if not self.a_b[0] % x][::-1] y_cuts = [x for x in range(1, self.a_b[1] + 1) if not self.a_b[1] % x][::-1] variants = 0 varianted = [] for x in x_cuts: for y in y_cuts: puzzles = make_puzzles(self.puzzle, x, y, self.a_b[0], self.a_b[1]) rotated = [] valid = True for p in puzzles: r1 = p r2 = rotate(r1) r3 = rotate(r2) r4 = rotate(r3) for r in (r1, r2, r3, r4): if r in rotated: valid = False break if not valid: break rotated += [r1, r2, r3, r4] if valid: variants += 1 varianted.append((self.a_b[0] // x, self.a_b[1] // y)) varianted.sort(key=lambda x: x[0]*x[1]) self.result = "{0}\n{1} {2}".format(variants, varianted[0][0], varianted[0][1]) def get_result(self): return self.result if __name__ == "__main__": Solution = CodeforcesTask54BSolution() Solution.read_input() Solution.process_task() print(Solution.get_result())
python
code_algorithm
[ { "input": "2 4\nABDC\nABDC\n", "output": "3\n2 1\n" }, { "input": "2 6\nABCCBA\nABCCBA\n", "output": "1\n2 6\n" }, { "input": "12 18\nCBBCAACABACCACABBC\nABCAACABAABCBCBCCC\nBCAACCCBBBABBACBBA\nACCBCBBBAABACCACCC\nCAABCCCACACCBACACC\nBBBCBCACCABCCBCBBB\nBAABBCACAAAAACCBCB\nBAABAABACBCAB...
code_contests
python
0
024816636e966647a2b153b0644927de
Today Patrick waits for a visit from his friend Spongebob. To prepare for the visit, Patrick needs to buy some goodies in two stores located near his house. There is a d1 meter long road between his house and the first shop and a d2 meter long road between his house and the second shop. Also, there is a road of length d3 directly connecting these two shops to each other. Help Patrick calculate the minimum distance that he needs to walk in order to go to both shops and return to his house. <image> Patrick always starts at his house. He should visit both shops moving only along the three existing roads and return back to his house. He doesn't mind visiting the same shop or passing the same road multiple times. The only goal is to minimize the total distance traveled. Input The first line of the input contains three integers d1, d2, d3 (1 ≤ d1, d2, d3 ≤ 108) — the lengths of the paths. * d1 is the length of the path connecting Patrick's house and the first shop; * d2 is the length of the path connecting Patrick's house and the second shop; * d3 is the length of the path connecting both shops. Output Print the minimum distance that Patrick will have to walk in order to visit both shops and return to his house. Examples Input 10 20 30 Output 60 Input 1 1 5 Output 4 Note The first sample is shown on the picture in the problem statement. One of the optimal routes is: house <image> first shop <image> second shop <image> house. In the second sample one of the optimal routes is: house <image> first shop <image> house <image> second shop <image> house. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
d=list(map(int,input().split())) d.sort() print(min(d[0]*2+d[1]*2,d[0]+d[1]+d[2]))
python
code_algorithm
[ { "input": "10 20 30\n", "output": "60\n" }, { "input": "1 1 5\n", "output": "4\n" }, { "input": "318476 318476 318476\n", "output": "955428\n" }, { "input": "1 100000000 1\n", "output": "4\n" }, { "input": "12 34 56\n", "output": "92\n" }, { "input": ...
code_contests
python
0
45cc667036dff65b6bce42ed7214c64b
Heidi the Cow is aghast: cracks in the northern Wall? Zombies gathering outside, forming groups, preparing their assault? This must not happen! Quickly, she fetches her HC2 (Handbook of Crazy Constructions) and looks for the right chapter: How to build a wall: 1. Take a set of bricks. 2. Select one of the possible wall designs. Computing the number of possible designs is left as an exercise to the reader. 3. Place bricks on top of each other, according to the chosen design. This seems easy enough. But Heidi is a Coding Cow, not a Constructing Cow. Her mind keeps coming back to point 2b. Despite the imminent danger of a zombie onslaught, she wonders just how many possible walls she could build with up to n bricks. A wall is a set of wall segments as defined in the easy version. How many different walls can be constructed such that the wall consists of at least 1 and at most n bricks? Two walls are different if there exist a column c and a row r such that one wall has a brick in this spot, and the other does not. Along with n, you will be given C, the width of the wall (as defined in the easy version). Return the number of different walls modulo 106 + 3. Input The first line contains two space-separated integers n and C, 1 ≤ n ≤ 500000, 1 ≤ C ≤ 200000. Output Print the number of different walls that Heidi could build, modulo 106 + 3. Examples Input 5 1 Output 5 Input 2 2 Output 5 Input 3 2 Output 9 Input 11 5 Output 4367 Input 37 63 Output 230574 Note The number 106 + 3 is prime. In the second sample case, the five walls are: B B B., .B, BB, B., and .B In the third sample case, the nine walls are the five as in the second sample case and in addition the following four: B B B B B B B., .B, BB, and BB Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
result=0 mod=10**6 +3 n,C=map(int,input().split()) #recibimos la entrada #calc n! def fact(n): fact=1 for i in range(1,n+1): #1*2*3*...*n = n*(n-1)*(n-2)...*1 fact=(fact*i)%mod # return fact def pow(a,b): #Algoritmo de Exponenciacion binaria exp=1 # Caso base a^1=a x=a % mod b=b%(mod-1) while b > 0: if b % 2 == 1:# En caso que b sea impar exp=(exp*x)%mod # En caso que b sea impar x=(x*x)%mod b=b//2 return exp #cacl (n+C)!/(n!*C!) , usamos el pequenno teorema de Fermat a^{p-1}congruente 1(p) a^{p-2}congruente a^{-1}(p) # de esta forma en vez de 1/n! y 1/C! usamos n!**p-2 C!**p-2 en este caso p=mod result=fact(n+C)*pow(fact(n),mod-2)*pow(fact(C),mod-2)-1 # C(n+C,C)= n+C! print(int(result%mod))
python
code_algorithm
[ { "input": "37 63\n", "output": "230574\n" }, { "input": "11 5\n", "output": "4367\n" }, { "input": "3 2\n", "output": "9\n" }, { "input": "2 2\n", "output": "5\n" }, { "input": "5 1\n", "output": "5\n" }, { "input": "350000 180000\n", "output": "7...
code_contests
python
0.1
0f0deb8b8f8c9ef4eef4f0448eb07fe3
On the way to Rio de Janeiro Ostap kills time playing with a grasshopper he took with him in a special box. Ostap builds a line of length n such that some cells of this line are empty and some contain obstacles. Then, he places his grasshopper to one of the empty cells and a small insect in another empty cell. The grasshopper wants to eat the insect. Ostap knows that grasshopper is able to jump to any empty cell that is exactly k cells away from the current (to the left or to the right). Note that it doesn't matter whether intermediate cells are empty or not as the grasshopper makes a jump over them. For example, if k = 1 the grasshopper can jump to a neighboring cell only, and if k = 2 the grasshopper can jump over a single cell. Your goal is to determine whether there is a sequence of jumps such that grasshopper will get from his initial position to the cell with an insect. Input The first line of the input contains two integers n and k (2 ≤ n ≤ 100, 1 ≤ k ≤ n - 1) — the number of cells in the line and the length of one grasshopper's jump. The second line contains a string of length n consisting of characters '.', '#', 'G' and 'T'. Character '.' means that the corresponding cell is empty, character '#' means that the corresponding cell contains an obstacle and grasshopper can't jump there. Character 'G' means that the grasshopper starts at this position and, finally, 'T' means that the target insect is located at this cell. It's guaranteed that characters 'G' and 'T' appear in this line exactly once. Output If there exists a sequence of jumps (each jump of length k), such that the grasshopper can get from his initial position to the cell with the insect, print "YES" (without quotes) in the only line of the input. Otherwise, print "NO" (without quotes). Examples Input 5 2 #G#T# Output YES Input 6 1 T....G Output YES Input 7 3 T..#..G Output NO Input 6 2 ..GT.. Output NO Note In the first sample, the grasshopper can make one jump to the right in order to get from cell 2 to cell 4. In the second sample, the grasshopper is only able to jump to neighboring cells but the way to the insect is free — he can get there by jumping left 5 times. In the third sample, the grasshopper can't make a single jump. In the fourth sample, the grasshopper can only jump to the cells with odd indices, thus he won't be able to reach the insect. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
n,k=[int(x) for x in input().split()] s=input() if s.index('G')>s.index('T'):s=s[::-1] x=s.index('G') for i in range(x,n): x+=k if x>n-1 or s[x]=='#':print("NO");break elif s[x]=='T':print("YES");break
python
code_algorithm
[ { "input": "6 1\nT....G\n", "output": "YES\n" }, { "input": "6 2\n..GT..\n", "output": "NO\n" }, { "input": "7 3\nT..#..G\n", "output": "NO\n" }, { "input": "5 2\n#G#T#\n", "output": "YES\n" }, { "input": "100 1\nG.....................................................
code_contests
python
0.3
452671b47ee966055d5f920b120974b9
Can you imagine our life if we removed all zeros from it? For sure we will have many problems. In this problem we will have a simple example if we removed all zeros from our life, it's the addition operation. Let's assume you are given this equation a + b = c, where a and b are positive integers, and c is the sum of a and b. Now let's remove all zeros from this equation. Will the equation remain correct after removing all zeros? For example if the equation is 101 + 102 = 203, if we removed all zeros it will be 11 + 12 = 23 which is still a correct equation. But if the equation is 105 + 106 = 211, if we removed all zeros it will be 15 + 16 = 211 which is not a correct equation. Input The input will consist of two lines, the first line will contain the integer a, and the second line will contain the integer b which are in the equation as described above (1 ≤ a, b ≤ 109). There won't be any leading zeros in both. The value of c should be calculated as c = a + b. Output The output will be just one line, you should print "YES" if the equation will remain correct after removing all zeros, and print "NO" otherwise. Examples Input 101 102 Output YES Input 105 106 Output NO Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
a = input () b = input () c = str (int (a) + int (b)) a = a.replace ("0", "") b = b.replace ("0", "") c = c.replace ("0", "") if int (a) + int (b) == int (c): print ("YES") else: print ("NO")
python
code_algorithm
[ { "input": "105\n106\n", "output": "NO\n" }, { "input": "101\n102\n", "output": "YES\n" }, { "input": "5\n4\n", "output": "YES\n" }, { "input": "341781108\n784147010\n", "output": "NO\n" }, { "input": "501871728\n725074574\n", "output": "NO\n" }, { "in...
code_contests
python
0.9
dec21533d4cad8a1fda365c14e959da7
Have you ever tasted Martian food? Well, you should. Their signature dish is served on a completely black plate with the radius of R, flat as a pancake. First, they put a perfectly circular portion of the Golden Honduras on the plate. It has the radius of r and is located as close to the edge of the plate as possible staying entirely within the plate. I. e. Golden Honduras touches the edge of the plate from the inside. It is believed that the proximity of the portion of the Golden Honduras to the edge of a plate demonstrates the neatness and exactness of the Martians. Then a perfectly round portion of Pink Guadeloupe is put on the plate. The Guadeloupe should not overlap with Honduras, should not go beyond the border of the plate, but should have the maximum radius. I. e. Pink Guadeloupe should touch the edge of the plate from the inside, and touch Golden Honduras from the outside. For it is the size of the Rose Guadeloupe that shows the generosity and the hospitality of the Martians. Further, the first portion (of the same perfectly round shape) of Green Bull Terrier is put on the plate. It should come in contact with Honduras and Guadeloupe, should not go beyond the border of the plate and should have maximum radius. Each of the following portions of the Green Bull Terrier must necessarily touch the Golden Honduras, the previous portion of the Green Bull Terrier and touch the edge of a plate, but should not go beyond the border. To determine whether a stranger is worthy to touch the food, the Martians ask him to find the radius of the k-th portion of the Green Bull Terrier knowing the radii of a plate and a portion of the Golden Honduras. And are you worthy? Input The first line contains integer t (1 ≤ t ≤ 104) — amount of testcases. Each of the following t lines contain three positive integers: the radii of the plate and a portion of the Golden Honduras R and r (1 ≤ r < R ≤ 104) and the number k (1 ≤ k ≤ 104). In the pretests 1 ≤ k ≤ 2. Output Print t lines — the radius of the k-th portion of the Green Bull Terrier for each test. The absolute or relative error of the answer should not exceed 10 - 6. Examples Input 2 4 3 1 4 2 2 Output 0.9230769231 0.6666666667 Note Dish from the first sample looks like this: <image> Dish from the second sample looks like this: <image> Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
#!/usr/bin/env python3 def solve(R,r,k): # Thanks to Numberphile's "Epic circles" video # Use the formula for radii of circles in Pappus chain r = r / R n = k answer = ((1-r)*r)/(2*((n**2)*((1-r)**2)+r)) # Note that in a Pappus chain the diameter of the circle is 1, so we need to scale up: answer = 2*R * answer print("%.10f" % answer) t = int(input()) for i in range(t): R,r,k = map(int, input().split()) solve(R,r,k)
python
code_algorithm
[ { "input": "2\n4 3 1\n4 2 2\n", "output": "0.9230769231\n0.6666666667\n" }, { "input": "1\n4 2 2\n", "output": "0.6666666667\n" }, { "input": "1\n1000 999 1\n", "output": "0.9999989990\n" }, { "input": "1\n7 2 1\n", "output": "1.7948717949\n" }, { "input": "1\n100...
code_contests
python
0
4e73c84b4ed43f4931fd026d34418dd6
The main city magazine offers its readers an opportunity to publish their ads. The format of the ad should be like this: There are space-separated non-empty words of lowercase and uppercase Latin letters. There are hyphen characters '-' in some words, their positions set word wrapping points. Word can include more than one hyphen. It is guaranteed that there are no adjacent spaces and no adjacent hyphens. No hyphen is adjacent to space. There are no spaces and no hyphens before the first word and after the last word. When the word is wrapped, the part of the word before hyphen and the hyphen itself stay on current line and the next part of the word is put on the next line. You can also put line break between two words, in that case the space stays on current line. Check notes for better understanding. The ad can occupy no more that k lines and should have minimal width. The width of the ad is the maximal length of string (letters, spaces and hyphens are counted) in it. You should write a program that will find minimal width of the ad. Input The first line contains number k (1 ≤ k ≤ 105). The second line contains the text of the ad — non-empty space-separated words of lowercase and uppercase Latin letters and hyphens. Total length of the ad don't exceed 106 characters. Output Output minimal width of the ad. Examples Input 4 garage for sa-le Output 7 Input 4 Edu-ca-tion-al Ro-unds are so fun Output 10 Note Here all spaces are replaced with dots. In the first example one of possible results after all word wraps looks like this: garage. for. sa- le The second example: Edu-ca- tion-al. Ro-unds. are.so.fun Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
def f(r): prev, ofs = -1, -1 s = list() while True: try: ofs = r.index(' ', ofs + 1) except ValueError: s.append(len(r) - 1 - prev) return s s.append(ofs - prev) prev = ofs n = int(input()) s = f(input().replace('-', ' ')) def can(w): cnt, cur = 0, 0 for l in s: if l > w: return False ln = cur + l <= w cur = cur * ln + l cnt += not ln return cnt < n def bsearch(lo, hi): while lo < hi: mid = (lo + hi) // 2 if can(mid): hi = mid else: lo = mid + 1 return lo print(bsearch(0, sum(s)))
python
code_algorithm
[ { "input": "4\nEdu-ca-tion-al Ro-unds are so fun\n", "output": "10\n" }, { "input": "4\ngarage for sa-le\n", "output": "7\n" }, { "input": "4\nasd asd asd asdf\n", "output": "4\n" }, { "input": "1\nrHPBSGKzxoSLerxkDVxJG PfUqVrdSdOgJBySsRHYryfLKOvIcU\n", "output": "51\n" ...
code_contests
python
0
e490c21f104e68747ad4b16b37183829
Ann and Borya have n piles with candies and n is even number. There are ai candies in pile with number i. Ann likes numbers which are square of some integer and Borya doesn't like numbers which are square of any integer. During one move guys can select some pile with candies and add one candy to it (this candy is new and doesn't belong to any other pile) or remove one candy (if there is at least one candy in this pile). Find out minimal number of moves that is required to make exactly n / 2 piles contain number of candies that is a square of some integer and exactly n / 2 piles contain number of candies that is not a square of any integer. Input First line contains one even integer n (2 ≤ n ≤ 200 000) — number of piles with candies. Second line contains sequence of integers a1, a2, ..., an (0 ≤ ai ≤ 109) — amounts of candies in each pile. Output Output minimal number of steps required to make exactly n / 2 piles contain number of candies that is a square of some integer and exactly n / 2 piles contain number of candies that is not a square of any integer. If condition is already satisfied output 0. Examples Input 4 12 14 30 4 Output 2 Input 6 0 0 0 0 0 0 Output 6 Input 6 120 110 23 34 25 45 Output 3 Input 10 121 56 78 81 45 100 1 0 54 78 Output 0 Note In first example you can satisfy condition in two moves. During each move you should add one candy to second pile. After it size of second pile becomes 16. After that Borya and Ann will have two piles with number of candies which is a square of integer (second and fourth pile) and two piles with number of candies which is not a square of any integer (first and third pile). In second example you should add two candies to any three piles. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
n=int(input()) p=[] m=list(map(int,input().split())) from math import floor,ceil for i in m: if i**0.5%1==0: p.append(0) else: p.append(min(i-floor(i**0.5)**2,ceil(i**0.5)**2-i)) a=p.count(0) am=m.count(0) if n//2<=a: x=a-n//2 dif=a-am if dif >= x: print(x) else: print(dif+(x-dif)*2) else: p.sort() k=a-n//2 x=a ans=0 for i in range(a,n//2): ans+=p[i] print(ans)
python
code_algorithm
[ { "input": "6\n0 0 0 0 0 0\n", "output": "6\n" }, { "input": "6\n120 110 23 34 25 45\n", "output": "3\n" }, { "input": "10\n121 56 78 81 45 100 1 0 54 78\n", "output": "0\n" }, { "input": "4\n12 14 30 4\n", "output": "2\n" }, { "input": "2\n2 0\n", "output": "...
code_contests
python
0
b92ae049a71ed7424acdc17e994b4cdd
Ivar the Boneless is a great leader. He is trying to capture Kattegat from Lagertha. The war has begun and wave after wave Ivar's warriors are falling in battle. Ivar has n warriors, he places them on a straight line in front of the main gate, in a way that the i-th warrior stands right after (i-1)-th warrior. The first warrior leads the attack. Each attacker can take up to a_i arrows before he falls to the ground, where a_i is the i-th warrior's strength. Lagertha orders her warriors to shoot k_i arrows during the i-th minute, the arrows one by one hit the first still standing warrior. After all Ivar's warriors fall and all the currently flying arrows fly by, Thor smashes his hammer and all Ivar's warriors get their previous strengths back and stand up to fight again. In other words, if all warriors die in minute t, they will all be standing to fight at the end of minute t. The battle will last for q minutes, after each minute you should tell Ivar what is the number of his standing warriors. Input The first line contains two integers n and q (1 ≤ n, q ≤ 200 000) — the number of warriors and the number of minutes in the battle. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) that represent the warriors' strengths. The third line contains q integers k_1, k_2, …, k_q (1 ≤ k_i ≤ 10^{14}), the i-th of them represents Lagertha's order at the i-th minute: k_i arrows will attack the warriors. Output Output q lines, the i-th of them is the number of standing warriors after the i-th minute. Examples Input 5 5 1 2 1 2 1 3 10 1 1 1 Output 3 5 4 4 3 Input 4 4 1 2 3 4 9 1 10 6 Output 1 4 4 1 Note In the first example: * after the 1-st minute, the 1-st and 2-nd warriors die. * after the 2-nd minute all warriors die (and all arrows left over are wasted), then they will be revived thus answer is 5 — all warriors are alive. * after the 3-rd minute, the 1-st warrior dies. * after the 4-th minute, the 2-nd warrior takes a hit and his strength decreases by 1. * after the 5-th minute, the 2-nd warrior dies. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
import bisect n,q=map(int,input().split()) a=list(map(int,input().split())) s=[0,] for i in a: s.append(s[-1]+i) k=list(map(int,input().split())) tb=0 for i in range(q): tb+=k[i] if tb>=s[-1]: tb=0 print(n) else: ans=bisect.bisect_right(s,tb) print(n-ans+1)
python
code_algorithm
[ { "input": "4 4\n1 2 3 4\n9 1 10 6\n", "output": "1\n4\n4\n1\n" }, { "input": "5 5\n1 2 1 2 1\n3 10 1 1 1\n", "output": "3\n5\n4\n4\n3\n" }, { "input": "10 3\n1 1 1 1 1 1 1 1 1 1\n10 10 5\n", "output": "10\n10\n5\n" }, { "input": "1 1\n56563128\n897699770\n", "output": "1...
code_contests
python
0.1
cce84143a4d595e0f70cc338799a40ec
Allen is hosting a formal dinner party. 2n people come to the event in n pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The 2n people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the picture more aesthetic. Help Allen find the minimum number of swaps of adjacent positions he must perform to make it so that each couple occupies adjacent positions in the line. Input The first line contains a single integer n (1 ≤ n ≤ 100), the number of pairs of people. The second line contains 2n integers a_1, a_2, ..., a_{2n}. For each i with 1 ≤ i ≤ n, i appears exactly twice. If a_j = a_k = i, that means that the j-th and k-th people in the line form a couple. Output Output a single integer, representing the minimum number of adjacent swaps needed to line the people up so that each pair occupies adjacent positions. Examples Input 4 1 1 2 3 3 2 4 4 Output 2 Input 3 1 1 2 2 3 3 Output 0 Input 3 3 1 2 3 1 2 Output 3 Note In the first sample case, we can transform 1 1 2 3 3 2 4 4 → 1 1 2 3 2 3 4 4 → 1 1 2 2 3 3 4 4 in two steps. Note that the sequence 1 1 2 3 3 2 4 4 → 1 1 3 2 3 2 4 4 → 1 1 3 3 2 2 4 4 also works in the same number of steps. The second sample case already satisfies the constraints; therefore we need 0 swaps. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
input() a=list(map(int,input().split())) cnt=0 while a: i=a.index(a.pop(0)) cnt+=i a.pop(i) print(cnt)
python
code_algorithm
[ { "input": "4\n1 1 2 3 3 2 4 4\n", "output": "2\n" }, { "input": "3\n1 1 2 2 3 3\n", "output": "0\n" }, { "input": "3\n3 1 2 3 1 2\n", "output": "3\n" }, { "input": "1\n1 1\n", "output": "0\n" }, { "input": "19\n15 19 18 8 12 2 11 7 5 2 1 1 9 9 3 3 16 6 15 17 13 1...
code_contests
python
0
cedfab60d30656c830b86b9675070267
The king's birthday dinner was attended by k guests. The dinner was quite a success: every person has eaten several dishes (though the number of dishes was the same for every person) and every dish was served alongside with a new set of kitchen utensils. All types of utensils in the kingdom are numbered from 1 to 100. It is known that every set of utensils is the same and consist of different types of utensils, although every particular type may appear in the set at most once. For example, a valid set of utensils can be composed of one fork, one spoon and one knife. After the dinner was over and the guests were dismissed, the king wondered what minimum possible number of utensils could be stolen. Unfortunately, the king has forgotten how many dishes have been served for every guest but he knows the list of all the utensils left after the dinner. Your task is to find the minimum possible number of stolen utensils. Input The first line contains two integer numbers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 100) — the number of kitchen utensils remaining after the dinner and the number of guests correspondingly. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 100) — the types of the utensils remaining. Equal values stand for identical utensils while different values stand for different utensils. Output Output a single value — the minimum number of utensils that could be stolen by the guests. Examples Input 5 2 1 2 2 1 3 Output 1 Input 10 3 1 3 3 1 3 5 5 5 5 100 Output 14 Note In the first example it is clear that at least one utensil of type 3 has been stolen, since there are two guests and only one such utensil. But it is also possible that every person received only one dish and there were only six utensils in total, when every person got a set (1, 2, 3) of utensils. Therefore, the answer is 1. One can show that in the second example at least 2 dishes should have been served for every guest, so the number of utensils should be at least 24: every set contains 4 utensils and every one of the 3 guests gets two such sets. Therefore, at least 14 objects have been stolen. Please note that utensils of some types (for example, of types 2 and 4 in this example) may be not present in the set served for dishes. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
import math n, k = map(int, input().split()) a = [int(t) for t in input().split()] d = {} for i in a: if d.get(i) is None: d[i] = 0 d[i] += 1 print(math.ceil(max(d.values()) / k) * len(d.keys()) * k - n)
python
code_algorithm
[ { "input": "10 3\n1 3 3 1 3 5 5 5 5 100\n", "output": "14\n" }, { "input": "5 2\n1 2 2 1 3\n", "output": "1\n" }, { "input": "100 1\n17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17...
code_contests
python
0.3
6525f66e507e4da2f77b308ad56e21b8
From "ftying rats" to urban saniwation workers - can synthetic biology tronsform how we think of pigeons? The upiquitous pigeon has long been viewed as vermin - spleading disease, scavenging through trush, and defecating in populous urban spases. Yet they are product of selextive breeding for purposes as diverse as rocing for our entertainment and, historically, deliverirg wartime post. Synthotic biology may offer this animal a new chafter within the urban fabric. Piteon d'Or recognihes how these birds ripresent a potentially userul interface for urdan biotechnologies. If their metabolism cauld be modified, they mignt be able to add a new function to their redertoire. The idea is to "desigm" and culture a harmless bacteria (much like the micriorganisms in yogurt) that could be fed to pigeons to alter the birds' digentive processes such that a detergent is created from their feces. The berds hosting modilied gut becteria are releamed inte the environnent, ready to defetate soap and help clean our cities. Input The first line of input data contains a single integer n (5 ≤ n ≤ 10). The second line of input data contains n space-separated integers a_i (1 ≤ a_i ≤ 32). Output Output a single integer. Example Input 5 1 2 3 4 5 Output 4 Note We did not proofread this statement at all. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
n = int(input()) a = list(map(int, input().split())) print(2+(min(a)^a[2]))
python
code_algorithm
[ { "input": "5\n1 2 3 4 5\n", "output": "4\n" }, { "input": "7\n24 10 8 26 25 5 16\n", "output": "15\n" }, { "input": "7\n18 29 23 23 1 14 5\n", "output": "24\n" }, { "input": "9\n23 1 2 26 9 11 23 10 26\n", "output": "5\n" }, { "input": "7\n4 13 8 20 31 17 3\n", ...
code_contests
python
0
9fa83559efbeb87252229e9110e2fc38
The legend of the foundation of Vectorland talks of two integers x and y. Centuries ago, the array king placed two markers at points |x| and |y| on the number line and conquered all the land in between (including the endpoints), which he declared to be Arrayland. Many years later, the vector king placed markers at points |x - y| and |x + y| and conquered all the land in between (including the endpoints), which he declared to be Vectorland. He did so in such a way that the land of Arrayland was completely inside (including the endpoints) the land of Vectorland. Here |z| denotes the absolute value of z. Now, Jose is stuck on a question of his history exam: "What are the values of x and y?" Jose doesn't know the answer, but he believes he has narrowed the possible answers down to n integers a_1, a_2, ..., a_n. Now, he wants to know the number of unordered pairs formed by two different elements from these n integers such that the legend could be true if x and y were equal to these two values. Note that it is possible that Jose is wrong, and that no pairs could possibly make the legend true. Input The first line contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of choices. The second line contains n pairwise distinct integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9) — the choices Jose is considering. Output Print a single integer number — the number of unordered pairs \\{x, y\} formed by different numbers from Jose's choices that could make the legend true. Examples Input 3 2 5 -3 Output 2 Input 2 3 6 Output 1 Note Consider the first sample. For the pair \{2, 5\}, the situation looks as follows, with the Arrayland markers at |2| = 2 and |5| = 5, while the Vectorland markers are located at |2 - 5| = 3 and |2 + 5| = 7: <image> The legend is not true in this case, because the interval [2, 3] is not conquered by Vectorland. For the pair \{5, -3\} the situation looks as follows, with Arrayland consisting of the interval [3, 5] and Vectorland consisting of the interval [2, 8]: <image> As Vectorland completely contains Arrayland, the legend is true. It can also be shown that the legend is true for the pair \{2, -3\}, for a total of two pairs. In the second sample, the only pair is \{3, 6\}, and the situation looks as follows: <image> Note that even though Arrayland and Vectorland share 3 as endpoint, we still consider Arrayland to be completely inside of Vectorland. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
num = int(input()) data = [abs(int(i)) for i in input().split()] data.sort() def bins(a, b, n): if a == b: if data[a] <= n: return a+1 else: return a else: m = (a+b)//2 if data[m] <= n: return bins(m+1,b,n) else: return bins(a, m, n) sum = 0 #prev = 0 ind = 0 for i in range(num): while ind < num and data[ind] <= 2*data[i]: ind += 1 #prev = bins(prev, num-1, 2*data[i]) - 1 sum += ind - i - 1 #print(2*data[i] ,bins(i, num-1, 2*data[i]), bins(i, num-1, 2*data[i]) - i - 1) print(sum) #data = [1,2,3, 4,5,6,7,23] #print(bins(1,6,3))
python
code_algorithm
[ { "input": "2\n3 6\n", "output": "1\n" }, { "input": "3\n2 5 -3\n", "output": "2\n" }, { "input": "3\n0 1000000000 -1000000000\n", "output": "1\n" }, { "input": "10\n9 1 2 3 5 7 4 10 6 8\n", "output": "25\n" }, { "input": "20\n55 -14 -28 13 -67 -23 58 2 -87 92 -80...
code_contests
python
0.7
2d9c6c6b4a9a63d53bbd3ba63aff3e7d
Polycarp decided to relax on his weekend and visited to the performance of famous ropewalkers: Agafon, Boniface and Konrad. The rope is straight and infinite in both directions. At the beginning of the performance, Agafon, Boniface and Konrad are located in positions a, b and c respectively. At the end of the performance, the distance between each pair of ropewalkers was at least d. Ropewalkers can walk on the rope. In one second, only one ropewalker can change his position. Every ropewalker can change his position exactly by 1 (i. e. shift by 1 to the left or right direction on the rope). Agafon, Boniface and Konrad can not move at the same time (Only one of them can move at each moment). Ropewalkers can be at the same positions at the same time and can "walk past each other". You should find the minimum duration (in seconds) of the performance. In other words, find the minimum number of seconds needed so that the distance between each pair of ropewalkers can be greater or equal to d. Ropewalkers can walk to negative coordinates, due to the rope is infinite to both sides. Input The only line of the input contains four integers a, b, c, d (1 ≤ a, b, c, d ≤ 10^9). It is possible that any two (or all three) ropewalkers are in the same position at the beginning of the performance. Output Output one integer — the minimum duration (in seconds) of the performance. Examples Input 5 2 6 3 Output 2 Input 3 1 5 6 Output 8 Input 8 3 3 2 Output 2 Input 2 3 10 4 Output 3 Note In the first example: in the first two seconds Konrad moves for 2 positions to the right (to the position 8), while Agafon and Boniface stay at their positions. Thus, the distance between Agafon and Boniface will be |5 - 2| = 3, the distance between Boniface and Konrad will be |2 - 8| = 6 and the distance between Agafon and Konrad will be |5 - 8| = 3. Therefore, all three pairwise distances will be at least d=3, so the performance could be finished within 2 seconds. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
a, b, c, d = map(int, input().split()) a, b, c = sorted([a, b, c]) def solve1(a, b, c): r1 = max(0, d-(b-a)) b += r1 r2 = max(0, d-(c-b)) return r1+r2 def solve2(a, b, c): r1 = max(0, d-(c-b)) r2 = max(0, d-(b-a)) return r1+r2 def solve3(a, b, c): r1 = max(0, d-(c-b)) b -= r1 r2 = max(0, d-(b-a)) return r1+r2 r1 = solve1(a, b, c) r2 = solve2(a, b, c) r3 = solve3(a, b, c) print(min(r1, r2, r3))
python
code_algorithm
[ { "input": "5 2 6 3\n", "output": "2\n" }, { "input": "2 3 10 4\n", "output": "3\n" }, { "input": "3 1 5 6\n", "output": "8\n" }, { "input": "8 3 3 2\n", "output": "2\n" }, { "input": "1 1 1 1\n", "output": "2\n" }, { "input": "1 2 1 1\n", "output"...
code_contests
python
0.8
0d80cfb2a887fb99c2d2355dfd5018c2
There are n boxers, the weight of the i-th boxer is a_i. Each of them can change the weight by no more than 1 before the competition (the weight cannot become equal to zero, that is, it must remain positive). Weight is always an integer number. It is necessary to choose the largest boxing team in terms of the number of people, that all the boxers' weights in the team are different (i.e. unique). Write a program that for given current values ​a_i will find the maximum possible number of boxers in a team. It is possible that after some change the weight of some boxer is 150001 (but no more). Input The first line contains an integer n (1 ≤ n ≤ 150000) — the number of boxers. The next line contains n integers a_1, a_2, ..., a_n, where a_i (1 ≤ a_i ≤ 150000) is the weight of the i-th boxer. Output Print a single integer — the maximum possible number of people in a team. Examples Input 4 3 2 4 1 Output 4 Input 6 1 1 1 4 4 4 Output 5 Note In the first example, boxers should not change their weights — you can just make a team out of all of them. In the second example, one boxer with a weight of 1 can be increased by one (get the weight of 2), one boxer with a weight of 4 can be reduced by one, and the other can be increased by one (resulting the boxers with a weight of 3 and 5, respectively). Thus, you can get a team consisting of boxers with weights of 5, 4, 3, 2, 1. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
N = int(input()) A = sorted([int(a) for a in input().split()]) k = 0 ans = 0 for i in range(N): if k > A[i]: pass elif k >= A[i] - 1: ans += 1 k += 1 else: ans += 1 k = A[i] - 1 print(ans)
python
code_algorithm
[ { "input": "6\n1 1 1 4 4 4\n", "output": "5\n" }, { "input": "4\n3 2 4 1\n", "output": "4\n" }, { "input": "10\n8 9 4 9 6 10 8 2 7 1\n", "output": "10\n" }, { "input": "125\n8 85 125 177 140 158 2 152 67 102 9 61 29 188 102 193 112 194 15 7 133 134 145 7 89 193 130 149 134 51...
code_contests
python
0.1
a5d72153fc2fb0b78c6987a17865dc79
Mike and Ann are sitting in the classroom. The lesson is boring, so they decided to play an interesting game. Fortunately, all they need to play this game is a string s and a number k (0 ≤ k < |s|). At the beginning of the game, players are given a substring of s with left border l and right border r, both equal to k (i.e. initially l=r=k). Then players start to make moves one by one, according to the following rules: * A player chooses l^{\prime} and r^{\prime} so that l^{\prime} ≤ l, r^{\prime} ≥ r and s[l^{\prime}, r^{\prime}] is lexicographically less than s[l, r]. Then the player changes l and r in this way: l := l^{\prime}, r := r^{\prime}. * Ann moves first. * The player, that can't make a move loses. Recall that a substring s[l, r] (l ≤ r) of a string s is a continuous segment of letters from s that starts at position l and ends at position r. For example, "ehn" is a substring (s[3, 5]) of "aaaehnsvz" and "ahz" is not. Mike and Ann were playing so enthusiastically that they did not notice the teacher approached them. Surprisingly, the teacher didn't scold them, instead of that he said, that he can figure out the winner of the game before it starts, even if he knows only s and k. Unfortunately, Mike and Ann are not so keen in the game theory, so they ask you to write a program, that takes s and determines the winner for all possible k. Input The first line of the input contains a single string s (1 ≤ |s| ≤ 5 ⋅ 10^5) consisting of lowercase English letters. Output Print |s| lines. In the line i write the name of the winner (print Mike or Ann) in the game with string s and k = i, if both play optimally Examples Input abba Output Mike Ann Ann Mike Input cba Output Mike Mike Mike Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
s = input().rstrip() minimum = "z" for ch in s: if ch > minimum: print("Ann") else: print("Mike") minimum = ch
python
code_algorithm
[ { "input": "abba\n", "output": "Mike\nAnn\nAnn\nMike\n" }, { "input": "cba\n", "output": "Mike\nMike\nMike\n" }, { "input": "dyqyq\n", "output": "Mike\nAnn\nAnn\nAnn\nAnn\n" }, { "input": "pefrpnmnlfxihesbjxybgvxdvvbliljvqoxxzvhlpfxcucqurvzeygbnpghxkgaethtkgjvlctneuuqzfwypkaj...
code_contests
python
0
49930fbd91b9597c7a3b03740cc77369
After battling Shikamaru, Tayuya decided that her flute is too predictable, and replaced it with a guitar. The guitar has 6 strings and an infinite number of frets numbered from 1. Fretting the fret number j on the i-th string produces the note a_{i} + j. Tayuya wants to play a melody of n notes. Each note can be played on different string-fret combination. The easiness of performance depends on the difference between the maximal and the minimal indices of used frets. The less this difference is, the easier it is to perform the technique. Please determine the minimal possible difference. For example, if a = [1, 1, 2, 2, 3, 3], and the sequence of notes is 4, 11, 11, 12, 12, 13, 13 (corresponding to the second example), we can play the first note on the first string, and all the other notes on the sixth string. Then the maximal fret will be 10, the minimal one will be 3, and the answer is 10 - 3 = 7, as shown on the picture. <image> Input The first line contains 6 space-separated numbers a_{1}, a_{2}, ..., a_{6} (1 ≤ a_{i} ≤ 10^{9}) which describe the Tayuya's strings. The second line contains the only integer n (1 ≤ n ≤ 100 000) standing for the number of notes in the melody. The third line consists of n integers b_{1}, b_{2}, ..., b_{n} (1 ≤ b_{i} ≤ 10^{9}), separated by space. They describe the notes to be played. It's guaranteed that b_i > a_j for all 1≤ i≤ n and 1≤ j≤ 6, in other words, you can play each note on any string. Output Print the minimal possible difference of the maximal and the minimal indices of used frets. Examples Input 1 4 100 10 30 5 6 101 104 105 110 130 200 Output 0 Input 1 1 2 2 3 3 7 13 4 11 12 11 13 12 Output 7 Note In the first sample test it is optimal to play the first note on the first string, the second note on the second string, the third note on the sixth string, the fourth note on the fourth string, the fifth note on the fifth string, and the sixth note on the third string. In this case the 100-th fret is used each time, so the difference is 100 - 100 = 0. <image> In the second test it's optimal, for example, to play the second note on the first string, and all the other notes on the sixth string. Then the maximal fret will be 10, the minimal one will be 3, and the answer is 10 - 3 = 7. <image> Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline() # ------------------------------ def RL(): return map(int, sys.stdin.readline().split()) def RLL(): return list(map(int, sys.stdin.readline().split())) def N(): return int(input()) def print_list(l): print(' '.join(map(str,l))) # sys.setrecursionlimit(300000) from heapq import * # from collections import deque as dq # from math import ceil,floor,sqrt,pow # import bisect as bs # from collections import Counter # from collections import defaultdict as dc # from functools import lru_cache a = RLL() a.sort(reverse=True) n = N() b = RLL() res = float('inf') heap = [(b[i]-a[0],i) for i in range(n)] heapify(heap) m = max(b)-a[0] count = [0]*n while 1: v,i = heap[0] res = min(res,m-v) count[i]+=1 if count[i]==6: break t = b[i]-a[count[i]] m = max(m,t) heapreplace(heap,(t,i)) print(res)
python
code_algorithm
[ { "input": "1 4 100 10 30 5\n6\n101 104 105 110 130 200\n", "output": "0\n" }, { "input": "1 1 2 2 3 3\n7\n13 4 11 12 11 13 12\n", "output": "7\n" }, { "input": "5 4 7 6 4 1\n10\n19 16 18 12 16 15 16 20 16 14\n", "output": "2\n" }, { "input": "158260522 877914575 602436426 24...
code_contests
python
0.2
e1a2016d31f8c679f0f5275adc45466d
The Little Elephant loves to play with color cards. He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered). Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny. Input The first line contains a single integer n (1 ≤ n ≤ 105) — the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 — colors of both sides. The first number in a line is the color of the front of the card, the second one — of the back. The color of the front of the card may coincide with the color of the back of the card. The numbers in the lines are separated by single spaces. Output On a single line print a single integer — the sought minimum number of moves. If it is impossible to make the set funny, print -1. Examples Input 3 4 7 4 7 7 4 Output 0 Input 5 4 7 7 4 2 11 9 7 1 1 Output 2 Note In the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0. In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
def solve(): n = int(input()) cards = [] cnt = {} for i in range(n): card = tuple(map(int, input().split(' '))) cards.append(card) cnt[card[0]] = [0, 0] cnt[card[1]] = [0, 0] for card in cards: if card[0] != card[1]: cnt[card[0]][0] += 1 cnt[card[1]][1] += 1 else: cnt[card[0]][0] += 1 border = (len(cards) + 1) // 2 best = float('inf') for num in cnt.keys(): count = cnt[num] if sum(count) >= border: # try to flip down -> top or vice versa needTop = max(0, border - count[0]) best = min(best, needTop) if best == float('inf'): print(-1) else: print(best) solve()
python
code_algorithm
[ { "input": "3\n4 7\n4 7\n7 4\n", "output": "0\n" }, { "input": "5\n4 7\n7 4\n2 11\n9 7\n1 1\n", "output": "2\n" }, { "input": "1\n1 2\n", "output": "0\n" }, { "input": "2\n1 1\n1 1\n", "output": "0\n" }, { "input": "5\n1 2\n1 3\n4 1\n5 1\n6 7\n", "output": "1\...
code_contests
python
0
1a5cd31e7a2181d660972ec20c037372
Little Vitaly loves different algorithms. Today he has invented a new algorithm just for you. Vitaly's algorithm works with string s, consisting of characters "x" and "y", and uses two following operations at runtime: 1. Find two consecutive characters in the string, such that the first of them equals "y", and the second one equals "x" and swap them. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string. 2. Find in the string two consecutive characters, such that the first of them equals "x" and the second one equals "y". Remove these characters from the string. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string. The input for the new algorithm is string s, and the algorithm works as follows: 1. If you can apply at least one of the described operations to the string, go to step 2 of the algorithm. Otherwise, stop executing the algorithm and print the current string. 2. If you can apply operation 1, then apply it. Otherwise, apply operation 2. After you apply the operation, go to step 1 of the algorithm. Now Vitaly wonders, what is going to be printed as the result of the algorithm's work, if the input receives string s. Input The first line contains a non-empty string s. It is guaranteed that the string only consists of characters "x" and "y". It is guaranteed that the string consists of at most 106 characters. It is guaranteed that as the result of the algorithm's execution won't be an empty string. Output In the only line print the string that is printed as the result of the algorithm's work, if the input of the algorithm input receives string s. Examples Input x Output x Input yxyxy Output y Input xxxxxy Output xxxx Note In the first test the algorithm will end after the first step of the algorithm, as it is impossible to apply any operation. Thus, the string won't change. In the second test the transformation will be like this: 1. string "yxyxy" transforms into string "xyyxy"; 2. string "xyyxy" transforms into string "xyxyy"; 3. string "xyxyy" transforms into string "xxyyy"; 4. string "xxyyy" transforms into string "xyy"; 5. string "xyy" transforms into string "y". As a result, we've got string "y". In the third test case only one transformation will take place: string "xxxxxy" transforms into string "xxxx". Thus, the answer will be string "xxxx". Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
from sys import stdin,stdout import bisect as bs nmbr = lambda: int(stdin.readline()) lst = lambda: list(map(int,stdin.readline().split())) for _ in range(1):#nmbr()): s=input() n=len(s) x=s.count('x') y=n-x if y>=x: for i in range(y-x): stdout.write('y') else: for i in range(x-y): stdout.write('x')
python
code_algorithm
[ { "input": "x\n", "output": "x" }, { "input": "yxyxy\n", "output": "y" }, { "input": "xxxxxy\n", "output": "xxxx" }, { "input": "xxxyx\n", "output": "xxx" }, { "input": "xxxxxxxxxxxyxyyxxxxyxxxxxyxxxxxyxxxxxxxxyx\n", "output": "xxxxxxxxxxxxxxxxxxxxxxxxxxxx" ...
code_contests
python
0.1
faf4423cf67113f73432ffeff56db744
When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the i-th book. Valera decided to choose an arbitrary book with number i and read the books one by one, starting from this book. In other words, he will first read book number i, then book number i + 1, then book number i + 2 and so on. He continues the process until he either runs out of the free time or finishes reading the n-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it. Print the maximum number of books Valera can read. Input The first line contains two integers n and t (1 ≤ n ≤ 105; 1 ≤ t ≤ 109) — the number of books and the number of free minutes Valera's got. The second line contains a sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 104), where number ai shows the number of minutes that the boy needs to read the i-th book. Output Print a single integer — the maximum number of books Valera can read. Examples Input 4 5 3 1 2 1 Output 3 Input 3 3 2 2 3 Output 1 Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
import bisect n,t=list(map(int,input().split())) a=list(map(int,input().rstrip().split())) b=[0] sol=0 for i in range(n): b.append(b[-1]+a[i]) b.pop(0) for i in range(n): sol=max(sol,bisect.bisect_right(b,t)-i) t+=a[i] print(sol)
python
code_algorithm
[ { "input": "4 5\n3 1 2 1\n", "output": "3\n" }, { "input": "3 3\n2 2 3\n", "output": "1\n" }, { "input": "20 30\n8 1 2 6 9 4 1 9 9 10 4 7 8 9 5 7 1 8 7 4\n", "output": "6\n" }, { "input": "2 10\n6 4\n", "output": "2\n" }, { "input": "100 100\n75 92 18 6 81 67 7 92...
code_contests
python
1
91e72be95de90b2f38066ce61eced907
Yaroslav has an array, consisting of (2·n - 1) integers. In a single operation Yaroslav can change the sign of exactly n elements in the array. In other words, in one operation Yaroslav can select exactly n array elements, and multiply each of them by -1. Yaroslav is now wondering: what maximum sum of array elements can be obtained if it is allowed to perform any number of described operations? Help Yaroslav. Input The first line contains an integer n (2 ≤ n ≤ 100). The second line contains (2·n - 1) integers — the array elements. The array elements do not exceed 1000 in their absolute value. Output In a single line print the answer to the problem — the maximum sum that Yaroslav can get. Examples Input 2 50 50 50 Output 150 Input 2 -1 -100 -1 Output 100 Note In the first sample you do not need to change anything. The sum of elements equals 150. In the second sample you need to change the sign of the first two elements. Then we get the sum of the elements equal to 100. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
#!/usr/bin/python3 n = int(input()) data = list(map(int, input().split())) negative, zero, positive = 0, 0, 0 for element in data: if element < 0: negative += 1 elif element == 0: zero += 1 else: positive += 1 seen = {} min_negative = negative def go(negative, positive): global min_negative if (negative, positive) in seen: return seen[(negative, positive)] = True min_negative = min(min_negative, negative) for i in range(min(n, negative)+1): for j in range(min(n-i, zero)+1): k = n - i - j if k <= positive: go(negative-i+k, positive-k+i) go(negative, positive) values = sorted(list(map(abs, data))) for i in range(min_negative): values[i] *= -1 print(sum(values))
python
code_algorithm
[ { "input": "2\n-1 -100 -1\n", "output": "100\n" }, { "input": "2\n50 50 50\n", "output": "150\n" }, { "input": "5\n270 -181 957 -509 -6 937 -175 434 -625\n", "output": "4094\n" }, { "input": "6\n-403 901 -847 -708 -624 413 -293 709 886 445 716\n", "output": "6359\n" }, ...
code_contests
python
0.1
4aef6d73638c6af34100d25cc69e0b5f
Cucumber boy is fan of Kyubeat, a famous music game. Kyubeat has 16 panels for playing arranged in 4 × 4 table. When a panel lights up, he has to press that panel. Each panel has a timing to press (the preffered time when a player should press it), and Cucumber boy is able to press at most k panels in a time with his one hand. Cucumber boy is trying to press all panels in perfect timing, that is he wants to press each panel exactly in its preffered time. If he cannot press the panels with his two hands in perfect timing, his challenge to press all the panels in perfect timing will fail. You are given one scene of Kyubeat's panel from the music Cucumber boy is trying. Tell him is he able to press all the panels in perfect timing. Input The first line contains a single integer k (1 ≤ k ≤ 5) — the number of panels Cucumber boy can press with his one hand. Next 4 lines contain 4 characters each (digits from 1 to 9, or period) — table of panels. If a digit i was written on the panel, it means the boy has to press that panel in time i. If period was written on the panel, he doesn't have to press that panel. Output Output "YES" (without quotes), if he is able to press all the panels in perfect timing. If not, output "NO" (without quotes). Examples Input 1 .135 1247 3468 5789 Output YES Input 5 ..1. 1111 ..1. ..1. Output YES Input 1 .... 12.1 .2.. .2.. Output NO Note In the third sample boy cannot press all panels in perfect timing. He can press all the panels in timing in time 1, but he cannot press the panels in time 2 in timing with his two hands. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
n = int(input()) memo = {} for _ in range(4): s = input() for i in s: if i != '.': if i not in memo: memo[i] = 1 else: memo[i] += 1 res = True for k, v in memo.items(): if v > n*2: res = False if res: print("YES") else: print("NO")
python
code_algorithm
[ { "input": "5\n..1.\n1111\n..1.\n..1.\n", "output": "YES\n" }, { "input": "1\n.135\n1247\n3468\n5789\n", "output": "YES\n" }, { "input": "1\n....\n12.1\n.2..\n.2..\n", "output": "NO\n" }, { "input": "4\n7777\n..7.\n.7..\n7...\n", "output": "YES\n" }, { "input": "2...
code_contests
python
1
f7e08186392f3ba38877233c8d35a58d
You've got array a[1], a[2], ..., a[n], consisting of n integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same. More formally, you need to find the number of such pairs of indices i, j (2 ≤ i ≤ j ≤ n - 1), that <image>. Input The first line contains integer n (1 ≤ n ≤ 5·105), showing how many numbers are in the array. The second line contains n integers a[1], a[2], ..., a[n] (|a[i]| ≤ 109) — the elements of array a. Output Print a single integer — the number of ways to split the array into three parts with the same sum. Examples Input 5 1 2 3 0 3 Output 2 Input 4 0 1 -1 0 Output 1 Input 2 4 1 Output 0 Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
def NoW(xs): if sum(xs) % 3 != 0: return 0 else: part = sum(xs) // 3 ci = ret = 0 acum = xs[0] for i, x in enumerate(xs[1:]): if acum == 2*part: # print("2. x=",x) ret += ci if acum == part: # print("1. x=",x) ci += 1 acum += x return ret input() xs = list(map(int, input().split())) print(NoW(xs))
python
code_algorithm
[ { "input": "2\n4 1\n", "output": "0\n" }, { "input": "4\n0 1 -1 0\n", "output": "1\n" }, { "input": "5\n1 2 3 0 3\n", "output": "2\n" }, { "input": "5\n1 1 1 1 1\n", "output": "0\n" }, { "input": "4\n0 2 -1 2\n", "output": "0\n" }, { "input": "9\n0 0 0...
code_contests
python
0.2
ae35b7bd5c7a0bab2f4f217350ae5713
Uncle Fyodor, Matroskin the Cat and Sharic the Dog live their simple but happy lives in Prostokvashino. Sometimes they receive parcels from Uncle Fyodor’s parents and sometimes from anonymous benefactors, in which case it is hard to determine to which one of them the package has been sent. A photographic rifle is obviously for Sharic who loves hunting and fish is for Matroskin, but for whom was a new video game console meant? Every one of the three friends claimed that the present is for him and nearly quarreled. Uncle Fyodor had an idea how to solve the problem justly: they should suppose that the console was sent to all three of them and play it in turns. Everybody got relieved but then yet another burning problem popped up — who will play first? This time Matroskin came up with a brilliant solution, suggesting the most fair way to find it out: play rock-paper-scissors together. The rules of the game are very simple. On the count of three every player shows a combination with his hand (or paw). The combination corresponds to one of three things: a rock, scissors or paper. Some of the gestures win over some other ones according to well-known rules: the rock breaks the scissors, the scissors cut the paper, and the paper gets wrapped over the stone. Usually there are two players. Yet there are three friends, that’s why they decided to choose the winner like that: If someone shows the gesture that wins over the other two players, then that player wins. Otherwise, another game round is required. Write a program that will determine the winner by the gestures they have shown. Input The first input line contains the name of the gesture that Uncle Fyodor showed, the second line shows which gesture Matroskin showed and the third line shows Sharic’s gesture. Output Print "F" (without quotes) if Uncle Fyodor wins. Print "M" if Matroskin wins and "S" if Sharic wins. If it is impossible to find the winner, print "?". Examples Input rock rock rock Output ? Input paper rock rock Output F Input scissors rock rock Output ? Input scissors paper rock Output ? Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
I = lambda: int(input()) IL = lambda: list(map(int, input().split())) L = [input()[0] for i in '123'] gt = {'r': 'rp', 'p': 'ps', 's': 'sr'} print('F' if L[1] not in gt[L[0]] and L[2] not in gt[L[0]] else 'M' if L[0] not in gt[L[1]] and L[2] not in gt[L[1]] else 'S' if L[0] not in gt[L[2]] and L[1] not in gt[L[2]] else '?')
python
code_algorithm
[ { "input": "scissors\nrock\nrock\n", "output": "?\n" }, { "input": "scissors\npaper\nrock\n", "output": "?\n" }, { "input": "rock\nrock\nrock\n", "output": "?\n" }, { "input": "paper\nrock\nrock\n", "output": "F\n" }, { "input": "rock\npaper\nrock\n", "output"...
code_contests
python
0.6
f3d88af07986145b5eb78ff60e6a0336
All cities of Lineland are located on the Ox coordinate axis. Thus, each city is associated with its position xi — a coordinate on the Ox axis. No two cities are located at a single point. Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (because if they live in the same city, then it is easier to drop in). Strange but true, the cost of sending the letter is exactly equal to the distance between the sender's city and the recipient's city. For each city calculate two values ​​mini and maxi, where mini is the minimum cost of sending a letter from the i-th city to some other city, and maxi is the the maximum cost of sending a letter from the i-th city to some other city Input The first line of the input contains integer n (2 ≤ n ≤ 105) — the number of cities in Lineland. The second line contains the sequence of n distinct integers x1, x2, ..., xn ( - 109 ≤ xi ≤ 109), where xi is the x-coordinate of the i-th city. All the xi's are distinct and follow in ascending order. Output Print n lines, the i-th line must contain two integers mini, maxi, separated by a space, where mini is the minimum cost of sending a letter from the i-th city, and maxi is the maximum cost of sending a letter from the i-th city. Examples Input 4 -5 -2 2 7 Output 3 12 3 9 4 7 5 12 Input 2 -1 1 Output 2 2 2 2 Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
n = int(input()) a = [int(i) for i in input().split()] for i in range(n): print(min(abs(a[i]-a[(i+1)%n]), abs(a[i]-a[i-1])), max(abs(a[i]-a[0]), abs(a[i]-a[-1])))
python
code_algorithm
[ { "input": "2\n-1 1\n", "output": "2 2\n2 2\n" }, { "input": "4\n-5 -2 2 7\n", "output": "3 12\n3 9\n4 7\n5 12\n" }, { "input": "3\n-1000000000 0 1000000000\n", "output": "1000000000 2000000000\n1000000000 1000000000\n1000000000 2000000000\n" }, { "input": "5\n-2 -1 0 1 2\n",...
code_contests
python
0.8
6363bae5d8be0f9b3928910084fedecc
Recently, Duff has been practicing weight lifting. As a hard practice, Malek gave her a task. He gave her a sequence of weights. Weight of i-th of them is 2wi pounds. In each step, Duff can lift some of the remaining weights and throw them away. She does this until there's no more weight left. Malek asked her to minimize the number of steps. <image> Duff is a competitive programming fan. That's why in each step, she can only lift and throw away a sequence of weights 2a1, ..., 2ak if and only if there exists a non-negative integer x such that 2a1 + 2a2 + ... + 2ak = 2x, i. e. the sum of those numbers is a power of two. Duff is a competitive programming fan, but not a programmer. That's why she asked for your help. Help her minimize the number of steps. Input The first line of input contains integer n (1 ≤ n ≤ 106), the number of weights. The second line contains n integers w1, ..., wn separated by spaces (0 ≤ wi ≤ 106 for each 1 ≤ i ≤ n), the powers of two forming the weights values. Output Print the minimum number of steps in a single line. Examples Input 5 1 1 2 3 3 Output 2 Input 4 0 1 2 3 Output 4 Note In the first sample case: One optimal way would be to throw away the first three in the first step and the rest in the second step. Also, it's not possible to do it in one step because their sum is not a power of two. In the second sample case: The only optimal way is to throw away one weight in each step. It's not possible to do it in less than 4 steps because there's no subset of weights with more than one weight and sum equal to a power of two. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
from collections import * import sys import math from functools import reduce def factors(n): return set(reduce(list.__add__,([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))) def li():return [int(i) for i in input().rstrip('\n').split(' ')] def st():return input().rstrip('\n') def val():return int(input()) def stli():return [int(i) for i in input().rstrip('\n')] def persquare(x): return 1 if x**0.5 == int(x**0.5) else 0 n = val() l = sorted(li()) currlist = [0 for i in range(10**6 + 22)] for i in l: currlist[i] += 1 tot = 0 # print(currlist[:10]) for i in range(10**6 + 21): while currlist[i]>1: temp = 2**int(math.log2(currlist[i])) currlist[i] -= temp currlist[i + 1] += temp//2 # print(currlist[:10]) print(sum(currlist))
python
code_algorithm
[ { "input": "5\n1 1 2 3 3\n", "output": "2\n" }, { "input": "4\n0 1 2 3\n", "output": "4\n" }, { "input": "13\n92 194 580495 0 10855 41704 13 96429 33 213 0 92 140599\n", "output": "11\n" }, { "input": "1\n120287\n", "output": "1\n" }, { "input": "35\n130212 3176 7...
code_contests
python
0.1
91916225290388c310f56a118427d7b1
Sasha lives in a big happy family. At the Man's Day all the men of the family gather to celebrate it following their own traditions. There are n men in Sasha's family, so let's number them with integers from 1 to n. Each man has at most one father but may have arbitrary number of sons. Man number A is considered to be the ancestor of the man number B if at least one of the following conditions is satisfied: * A = B; * the man number A is the father of the man number B; * there is a man number C, such that the man number A is his ancestor and the man number C is the father of the man number B. Of course, if the man number A is an ancestor of the man number B and A ≠ B, then the man number B is not an ancestor of the man number A. The tradition of the Sasha's family is to give gifts at the Man's Day. Because giving gifts in a normal way is boring, each year the following happens. 1. A list of candidates is prepared, containing some (possibly all) of the n men in some order. 2. Each of the n men decides to give a gift. 3. In order to choose a person to give a gift to, man A looks through the list and picks the first man B in the list, such that B is an ancestor of A and gives him a gift. Note that according to definition it may happen that a person gives a gift to himself. 4. If there is no ancestor of a person in the list, he becomes sad and leaves the celebration without giving a gift to anyone. This year you have decided to help in organizing celebration and asked each of the n men, who do they want to give presents to (this person is chosen only among ancestors). Are you able to make a list of candidates, such that all the wishes will be satisfied if they give gifts according to the process described above? Input In the first line of the input two integers n and m (0 ≤ m < n ≤ 100 000) are given — the number of the men in the Sasha's family and the number of family relations in it respectively. The next m lines describe family relations: the (i + 1)th line consists of pair of integers pi and qi (1 ≤ pi, qi ≤ n, pi ≠ qi) meaning that the man numbered pi is the father of the man numbered qi. It is guaranteed that every pair of numbers appears at most once, that among every pair of two different men at least one of them is not an ancestor of another and that every man has at most one father. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n), ith of which means that the man numbered i wants to give a gift to the man numbered ai. It is guaranteed that for every 1 ≤ i ≤ n the man numbered ai is an ancestor of the man numbered i. Output Print an integer k (1 ≤ k ≤ n) — the number of the men in the list of candidates, in the first line. Print then k pairwise different positive integers not exceeding n — the numbers of the men in the list in an order satisfying every of the men's wishes, one per line. If there are more than one appropriate lists, print any of them. If there is no appropriate list print - 1 in the only line. Examples Input 3 2 1 2 2 3 1 2 1 Output -1 Input 4 2 1 2 3 4 1 2 3 3 Output 3 2 1 3 Note The first sample explanation: * if there would be no 1 in the list then the first and the third man's wishes would not be satisfied (a1 = a3 = 1); * if there would be no 2 in the list then the second man wish would not be satisfied (a2 = 2); * if 1 would stay before 2 in the answer then the second man would have to give his gift to the first man, but he wants to give it to himself (a2 = 2). * if, at the other hand, the man numbered 2 would stay before the man numbered 1, then the third man would have to give his gift to the second man, but not to the first (a3 = 1). Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
# [https://codeforces.com/contest/681/submission/37694242 <- https://codeforces.com/contest/681/status/D <- https://codeforces.com/contest/681 <- https://codeforces.com/blog/entry/45425 <- https://codeforces.com/problemset/problem/681/D <- https://algoprog.ru/material/pc681pD] (n, m) = map(int, input().split()) adj = [[] for _ in range(n)] cp = [-1] * n for i in range(m): p, c = map(int, input().split()) adj[p - 1].append(c - 1) cp[c - 1] = p - 1 pres = [i - 1 for i in map(int, input().split())] level = [0] * n from collections import deque def bfs(v): q = deque([v]) while q: v = q.pop() if cp[v] >= 0: level[v] = level[cp[v]] + 1 for nv in adj[v]: q.append(nv) for i in range(n): if cp[i] == -1: bfs(i) for i in range(n): if level[i] > 0: par = cp[i] if pres[i] != pres[par] and level[pres[i]] <= level[par]: print(-1) exit() pres = list(set(pres)) pres = sorted(pres, key = lambda i : level[i], reverse = True) print(len(pres)) pres = [i + 1 for i in pres] print("\n".join(map(str, pres)))
python
code_algorithm
[ { "input": "3 2\n1 2\n2 3\n1 2 1\n", "output": "-1\n" }, { "input": "4 2\n1 2\n3 4\n1 2 3 3\n", "output": "3\n2\n1\n3\n" }, { "input": "1 0\n1\n", "output": "1\n1\n" }, { "input": "4 3\n4 3\n3 2\n2 1\n3 4 4 4\n", "output": "-1\n" }, { "input": "4 3\n1 2\n2 3\n3 4\...
code_contests
python
0
c84be37da7ab107286c63d32ca17cbb4
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures). There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves. Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z. For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well. Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes. Input The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, <image>) — the number of members and the number of pairs of members that are friends. The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input. Output If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes). Examples Input 4 3 1 3 3 4 1 4 Output YES Input 4 4 3 1 2 3 3 4 1 2 Output NO Input 10 4 4 3 5 10 8 9 1 2 Output YES Input 3 2 1 2 2 3 Output NO Note The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not. <image> Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
n,m = map(int,input().split()) dic = {} edges = [] from collections import Counter def find(node): tmp = node while node!=dic[node]: node = dic[node] while tmp!=dic[tmp]: dic[tmp],tmp=node,dic[tmp] return node for _ in range(m): p1,p2 = map(int,input().split()) dic.setdefault(p1,p1) dic.setdefault(p2,p2) edges.append(p1) lp = find(p1) rp = find(p2) if lp!=rp: dic[rp] = lp for k in dic: find(k) def judge(): counter = Counter([dic[i] for i in edges]) s = Counter(dic.values()) for k in counter: en,nn = counter[k],s[k] if (nn**2-nn)//2!=en: return False return True if judge(): print("YES") else: print("NO")
python
code_algorithm
[ { "input": "10 4\n4 3\n5 10\n8 9\n1 2\n", "output": "YES\n" }, { "input": "4 4\n3 1\n2 3\n3 4\n1 2\n", "output": "NO\n" }, { "input": "3 2\n1 2\n2 3\n", "output": "NO\n" }, { "input": "4 3\n1 3\n3 4\n1 4\n", "output": "YES\n" }, { "input": "4 5\n1 2\n1 3\n1 4\n2 3...
code_contests
python
0.9
0f9fbb7c21b25ff919ad665d9dd330ff
Leha somehow found an array consisting of n integers. Looking at it, he came up with a task. Two players play the game on the array. Players move one by one. The first player can choose for his move a subsegment of non-zero length with an odd sum of numbers and remove it from the array, after that the remaining parts are glued together into one array and the game continues. The second player can choose a subsegment of non-zero length with an even sum and remove it. Loses the one who can not make a move. Who will win if both play optimally? Input First line of input data contains single integer n (1 ≤ n ≤ 106) — length of the array. Next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109). Output Output answer in single line. "First", if first player wins, and "Second" otherwise (without quotes). Examples Input 4 1 3 2 3 Output First Input 2 2 2 Output Second Note In first sample first player remove whole array in one move and win. In second sample first player can't make a move and lose. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
input() for t in input().split(): if int(t) % 2: print("First") break else: print("Second")
python
code_algorithm
[ { "input": "4\n1 3 2 3\n", "output": "First\n" }, { "input": "2\n2 2\n", "output": "Second\n" }, { "input": "6\n2 2 1 1 4 2\n", "output": "First\n" }, { "input": "3\n1 2 2\n", "output": "First\n" }, { "input": "5\n1 1 1 1 1\n", "output": "First\n" }, { ...
code_contests
python
0.5
d885c80ab15a677595e25b1f9e63d990
You are given an array a. Some element of this array ai is a local minimum iff it is strictly less than both of its neighbours (that is, ai < ai - 1 and ai < ai + 1). Also the element can be called local maximum iff it is strictly greater than its neighbours (that is, ai > ai - 1 and ai > ai + 1). Since a1 and an have only one neighbour each, they are neither local minima nor local maxima. An element is called a local extremum iff it is either local maximum or local minimum. Your task is to calculate the number of local extrema in the given array. Input The first line contains one integer n (1 ≤ n ≤ 1000) — the number of elements in array a. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000) — the elements of array a. Output Print the number of local extrema in the given array. Examples Input 3 1 2 3 Output 0 Input 4 1 5 2 5 Output 2 Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
n = int(input()) arr = [int(x) for x in input().split()] cnt = 0 for i in range(1,n-1): if arr[i]< arr[i-1] and arr[i] < arr[i+1]:cnt += 1 else: if arr[i]> arr[i-1] and arr[i] > arr[i+ 1]: cnt += 1 print(cnt)
python
code_algorithm
[ { "input": "3\n1 2 3\n", "output": "0\n" }, { "input": "4\n1 5 2 5\n", "output": "2\n" }, { "input": "3\n3 2 3\n", "output": "1\n" }, { "input": "1\n548\n", "output": "0\n" }, { "input": "3\n1 2 1\n", "output": "1\n" }, { "input": "1\n1\n", "output...
code_contests
python
1
c155081cf67ccab72bad513836a90af1
Ehab is interested in the bitwise-xor operation and the special graphs. Mahmoud gave him a problem that combines both. He has a complete graph consisting of n vertices numbered from 0 to n - 1. For all 0 ≤ u < v < n, vertex u and vertex v are connected with an undirected edge that has weight <image> (where <image> is the [bitwise-xor operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)). Can you find the weight of the minimum spanning tree of that graph? You can read about complete graphs in <https://en.wikipedia.org/wiki/Complete_graph> You can read about the minimum spanning tree in <https://en.wikipedia.org/wiki/Minimum_spanning_tree> The weight of the minimum spanning tree is the sum of the weights on the edges included in it. Input The only line contains an integer n (2 ≤ n ≤ 1012), the number of vertices in the graph. Output The only line contains an integer x, the weight of the graph's minimum spanning tree. Example Input 4 Output 4 Note In the first sample: <image> The weight of the minimum spanning tree is 1+2+1=4. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
import math n = int(input()) ans = 0 cur = 1 while cur < n: cnt = math.ceil((n-cur)/(cur << 1)) ans += cnt*cur cur <<= 1 print(ans)
python
code_algorithm
[ { "input": "4\n", "output": "4\n" }, { "input": "2\n", "output": "1\n" }, { "input": "7\n", "output": "11\n" }, { "input": "536870913\n", "output": "8321499136\n" }, { "input": "1048576\n", "output": "10485760\n" }, { "input": "1024\n", "output": "...
code_contests
python
0.2
48ad452f827841985d183e07fc90f0d5
You are given a set of size m with integer elements between 0 and 2^{n}-1 inclusive. Let's build an undirected graph on these integers in the following way: connect two integers x and y with an edge if and only if x \& y = 0. Here \& is the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Count the number of connected components in that graph. Input In the first line of input there are two integers n and m (0 ≤ n ≤ 22, 1 ≤ m ≤ 2^{n}). In the second line there are m integers a_1, a_2, …, a_m (0 ≤ a_{i} < 2^{n}) — the elements of the set. All a_{i} are distinct. Output Print the number of connected components. Examples Input 2 3 1 2 3 Output 2 Input 5 5 5 19 10 20 12 Output 2 Note Graph from first sample: <image> Graph from second sample: <image> Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
n, m = map(int, input().split()) a = set(map(int, input().split())) y = 2 ** n mk = [0] * (2 * y) cur = 0 for x in a: if mk[x]: continue mk[x] = 1 st = [x] def push(v): if not mk[v]: mk[v] = 1; st.append(v) while st: u = st.pop() if u < y: push(y + u) else: for b in range(n): v = u | 1 << b push(v) v = y - 1 - (u - y) if v in a: push(v) cur += 1 print(cur)
python
code_algorithm
[ { "input": "2 3\n1 2 3\n", "output": "2\n" }, { "input": "5 5\n5 19 10 20 12\n", "output": "2\n" }, { "input": "6 19\n15 23 27 29 30 31 43 46 47 51 53 55 57 58 59 60 61 62 63\n", "output": "19\n" }, { "input": "3 5\n3 5 0 6 7\n", "output": "1\n" }, { "input": "0 1...
code_contests
python
1
9a0a458ae9e8984522dd9c75cfb33ac7
There is a rectangular grid of size n × m. Each cell has a number written on it; the number on the cell (i, j) is a_{i, j}. Your task is to calculate the number of paths from the upper-left cell (1, 1) to the bottom-right cell (n, m) meeting the following constraints: * You can move to the right or to the bottom only. Formally, from the cell (i, j) you may move to the cell (i, j + 1) or to the cell (i + 1, j). The target cell can't be outside of the grid. * The xor of all the numbers on the path from the cell (1, 1) to the cell (n, m) must be equal to k (xor operation is the bitwise exclusive OR, it is represented as '^' in Java or C++ and "xor" in Pascal). Find the number of such paths in the given grid. Input The first line of the input contains three integers n, m and k (1 ≤ n, m ≤ 20, 0 ≤ k ≤ 10^{18}) — the height and the width of the grid, and the number k. The next n lines contain m integers each, the j-th element in the i-th line is a_{i, j} (0 ≤ a_{i, j} ≤ 10^{18}). Output Print one integer — the number of paths from (1, 1) to (n, m) with xor sum equal to k. Examples Input 3 3 11 2 1 5 7 10 0 12 6 4 Output 3 Input 3 4 2 1 3 3 3 0 3 3 2 3 0 1 1 Output 5 Input 3 4 1000000000000000000 1 3 3 3 0 3 3 2 3 0 1 1 Output 0 Note All the paths from the first example: * (1, 1) → (2, 1) → (3, 1) → (3, 2) → (3, 3); * (1, 1) → (2, 1) → (2, 2) → (2, 3) → (3, 3); * (1, 1) → (1, 2) → (2, 2) → (3, 2) → (3, 3). All the paths from the second example: * (1, 1) → (2, 1) → (3, 1) → (3, 2) → (3, 3) → (3, 4); * (1, 1) → (2, 1) → (2, 2) → (3, 2) → (3, 3) → (3, 4); * (1, 1) → (2, 1) → (2, 2) → (2, 3) → (2, 4) → (3, 4); * (1, 1) → (1, 2) → (2, 2) → (2, 3) → (3, 3) → (3, 4); * (1, 1) → (1, 2) → (1, 3) → (2, 3) → (3, 3) → (3, 4). Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
from collections import* n, m, k = map(int, input().split()) b = [[int(v) for v in input().split()] for _ in range(n)] if m < n: a = [[b[j][i] for j in range(n)] for i in range(m)] b = a m, n = n, m cntrs = [Counter() for _ in range(n)] d = (n + m-1) // 2 for i in range(1<<d): ones = bin(i).count('1') z = d - ones if ones >= n or z >= m: continue xor = b[0][0] x, y = 0, 0 for j in range(d): if i&(1<<j): x += 1 else: y += 1 xor ^= b[x][y] cntrs[x][xor] += 1 sm = 0 sleft = n + m - 2 - d for i in range(1<<sleft): ones = bin(i).count('1') z = sleft - ones if ones >= n or z >= m: continue xor = b[n-1][m-1] x, y = n-1, m-1 for j in range(sleft): if i&(1<<j): x -= 1 else: y -= 1 xor ^= b[x][y] xor ^= b[x][y] ^ k sm += cntrs[x][xor] print(sm)
python
code_algorithm
[ { "input": "3 4 1000000000000000000\n1 3 3 3\n0 3 3 2\n3 0 1 1\n", "output": "0\n" }, { "input": "3 3 11\n2 1 5\n7 10 0\n12 6 4\n", "output": "3\n" }, { "input": "3 4 2\n1 3 3 3\n0 3 3 2\n3 0 1 1\n", "output": "5\n" }, { "input": "1 1 982347923479\n1\n", "output": "0\n" ...
code_contests
python
0.4
1fe1d3c01ae05cf05fa5310fb3ab14a1
You are given an undirected graph consisting of n vertices. A number is written on each vertex; the number on vertex i is a_i. Initially there are no edges in the graph. You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices x and y is a_x + a_y coins. There are also m special offers, each of them is denoted by three numbers x, y and w, and means that you can add an edge connecting vertices x and y and pay w coins for it. You don't have to use special offers: if there is a pair of vertices x and y that has a special offer associated with it, you still may connect these two vertices paying a_x + a_y coins for it. What is the minimum number of coins you have to spend to make the graph connected? Recall that a graph is connected if it's possible to get from any vertex to any other vertex using only the edges belonging to this graph. Input The first line contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of special offers, respectively. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{12}) — the numbers written on the vertices. Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^{12}, x ≠ y) denoting a special offer: you may add an edge connecting vertex x and vertex y, and this edge will cost w coins. Output Print one integer — the minimum number of coins you have to pay to make the graph connected. Examples Input 3 2 1 3 3 2 3 5 2 1 1 Output 5 Input 4 0 1 3 3 7 Output 16 Input 5 4 1 2 3 4 5 1 2 8 1 3 10 1 4 7 1 5 15 Output 18 Note In the first example it is possible to connect 1 to 2 using special offer 2, and then 1 to 3 without using any offers. In next two examples the optimal answer may be achieved without using special offers. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
n, m = map(int, input().split()) a = list(map(int, input().split())) e = [] for _ in range(m) : u, v, w = map(int, input().split()) e.append((u-1, v-1, w)) a = sorted(zip(a, range(n)), key = lambda x : x[0]) for i in range(1, n) : e.append((a[0][1], a[i][1], a[0][0] + a[i][0])) fa = list(range(n)) rk = [0] * n def find(x) : while fa[x] != x : fa[x] = fa[fa[x]] x = fa[x] return x def unite(u, v) : u, v = map(find, (u, v)) if u == v : return False if rk[u] < rk[v] : u, v = v, u fa[v] = u if rk[u] == rk[v] : rk[u] += 1 return True e.sort(key = lambda x : x[2]) ans = 0 cnt = 1 for ee in e : if cnt == n : break if unite(ee[0], ee[1]) : ans += ee[2] cnt += 1 print(ans)
python
code_algorithm
[ { "input": "5 4\n1 2 3 4 5\n1 2 8\n1 3 10\n1 4 7\n1 5 15\n", "output": "18\n" }, { "input": "3 2\n1 3 3\n2 3 5\n2 1 1\n", "output": "5\n" }, { "input": "4 0\n1 3 3 7\n", "output": "16\n" }, { "input": "1 0\n4\n", "output": "0\n" }, { "input": "10 0\n9 9 5 2 2 5 8 ...
code_contests
python
0.9
16a5c3e6386ee0b44dd180f6525a8556
You are given array a_1, a_2, ..., a_n. Find the subsegment a_l, a_{l+1}, ..., a_r (1 ≤ l ≤ r ≤ n) with maximum arithmetic mean (1)/(r - l + 1)∑_{i=l}^{r}{a_i} (in floating-point numbers, i.e. without any rounding). If there are many such subsegments find the longest one. Input The first line contains single integer n (1 ≤ n ≤ 10^5) — length of the array a. The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9) — the array a. Output Print the single integer — the length of the longest subsegment with maximum possible arithmetic mean. Example Input 5 6 1 6 6 0 Output 2 Note The subsegment [3, 4] is the longest among all subsegments with maximum arithmetic mean. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
n=int(input()) s=[int(x) for x in input().split()] el=max(s) pos1=-1 pos2=-1 c=0 ans=0 for i in range(0,len(s)): if(s[i]==el): c=c+1 else: ans=max(ans,c) c=0 ans=max(ans,c) print(ans)
python
code_algorithm
[ { "input": "5\n6 1 6 6 0\n", "output": "2\n" }, { "input": "2\n1 5\n", "output": "1\n" }, { "input": "5\n1 0 0 0 0\n", "output": "1\n" }, { "input": "15\n2 2 1 2 2 2 2 1 2 2 2 1 2 2 3\n", "output": "1\n" }, { "input": "2\n1 2\n", "output": "1\n" }, { "...
code_contests
python
0.3
d2080d820e558ff117f19aa3e5a24682
This problem is same as the next one, but has smaller constraints. It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system consisting of many chimneys, electric poles, and wires. Since they are cats, they found those things gigantic. At the entrance of the station, there is a map describing the complicated wiring system. Selena is the best at math among three friends. He decided to draw the map on the Cartesian plane. Each pole is now a point at some coordinates (x_i, y_i). Since every pole is different, all of the points representing these poles are distinct. Also, every two poles are connected with each other by wires. A wire is a straight line on the plane infinite in both directions. If there are more than two poles lying on the same line, they are connected by a single common wire. Selena thinks, that whenever two different electric wires intersect, they may interfere with each other and cause damage. So he wonders, how many pairs are intersecting? Could you help him with this problem? Input The first line contains a single integer n (2 ≤ n ≤ 50) — the number of electric poles. Each of the following n lines contains two integers x_i, y_i (-10^4 ≤ x_i, y_i ≤ 10^4) — the coordinates of the poles. It is guaranteed that all of these n points are distinct. Output Print a single integer — the number of pairs of wires that are intersecting. Examples Input 4 0 0 1 1 0 3 1 2 Output 14 Input 4 0 0 0 2 0 4 2 0 Output 6 Input 3 -1 -1 1 0 3 1 Output 0 Note In the first example: <image> In the second example: <image> Note that the three poles (0, 0), (0, 2) and (0, 4) are connected by a single wire. In the third example: <image> Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
import sys import collections import math import heapq from operator import itemgetter def getint(): return int(input()) def getints(): return [int(x) for x in input().split(' ')] n = getint() points = [tuple(getints()) for _ in range(n)] result = 0 slopes = collections.defaultdict(set) for i in range(n - 1): for j in range(i + 1, n): x1, y1, x2, y2 = points[i][0], points[i][1], points[j][0], points[j][1] a, b = y1 - y2, x1 - x2 d = math.gcd(a, b) a, b = a // d, b // d if a < 0 or (a == 0 and b < 0): a, b = -a, -b c = a * x1 - b * y1 slope = (a, b) slopes[slope].add(c) slopeGroups = [(ab[0], ab[1], len(cs)) for ab, cs in slopes.items()] m = len(slopeGroups) for i in range(m - 1): intersects = 0 for j in range(i + 1, m): intersects += slopeGroups[j][2] result += slopeGroups[i][2] * intersects print(str(result))
python
code_algorithm
[ { "input": "4\n0 0\n1 1\n0 3\n1 2\n", "output": "14\n" }, { "input": "4\n0 0\n0 2\n0 4\n2 0\n", "output": "6\n" }, { "input": "3\n-1 -1\n1 0\n3 1\n", "output": "0\n" }, { "input": "2\n10000 10000\n-10000 -10000\n", "output": "0\n" }, { "input": "5\n-8893 8986\n-36...
code_contests
python
0.1
9e2cb5b99abe2a30b0aea5e914e4f148
Melody Pond was stolen from her parents as a newborn baby by Madame Kovarian, to become a weapon of the Silence in their crusade against the Doctor. Madame Kovarian changed Melody's name to River Song, giving her a new identity that allowed her to kill the Eleventh Doctor. Heidi figured out that Madame Kovarian uses a very complicated hashing function in order to change the names of the babies she steals. In order to prevent this from happening to future Doctors, Heidi decided to prepare herself by learning some basic hashing techniques. The first hashing function she designed is as follows. Given two positive integers (x, y) she defines H(x,y):=x^2+2xy+x+1. Now, Heidi wonders if the function is reversible. That is, given a positive integer r, can you find a pair (x, y) (of positive integers) such that H(x, y) = r? If multiple such pairs exist, output the one with smallest possible x. If there is no such pair, output "NO". Input The first and only line contains an integer r (1 ≤ r ≤ 10^{12}). Output Output integers x, y such that H(x,y) = r and x is smallest possible, or "NO" if no such pair exists. Examples Input 19 Output 1 8 Input 16 Output NO Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
from math import sqrt def get_int(): from sys import stdin return int(stdin.readline().replace('\n', '')) def is_even(n): return n%2 == 0 def heidi_hash(r): k = r-1 rt = int(sqrt(k)) for x in range(1, rt+2): if k % x == 0: temp = k/x -x -1 if temp > 0 and is_even(temp): return x,int(temp/2) return 'NO' r = get_int() res = heidi_hash(r) print(res[0],res[1]) if type(res) != type('') else print(res)
python
code_algorithm
[ { "input": "19\n", "output": "1 8\n" }, { "input": "16\n", "output": "NO\n" }, { "input": "768407398177\n", "output": "1 384203699087\n" }, { "input": "7\n", "output": "1 2\n" }, { "input": "156231653273\n", "output": "1 78115826635\n" }, { "input": "4...
code_contests
python
0.5
0aa25f9c504d68aa3d283d3679e3de0f
You are on the island which can be represented as a n × m table. The rows are numbered from 1 to n and the columns are numbered from 1 to m. There are k treasures on the island, the i-th of them is located at the position (r_i, c_i). Initially you stand at the lower left corner of the island, at the position (1, 1). If at any moment you are at the cell with a treasure, you can pick it up without any extra time. In one move you can move up (from (r, c) to (r+1, c)), left (from (r, c) to (r, c-1)), or right (from position (r, c) to (r, c+1)). Because of the traps, you can't move down. However, moving up is also risky. You can move up only if you are in a safe column. There are q safe columns: b_1, b_2, …, b_q. You want to collect all the treasures as fast as possible. Count the minimum number of moves required to collect all the treasures. Input The first line contains integers n, m, k and q (2 ≤ n, m, k, q ≤ 2 ⋅ 10^5, q ≤ m) — the number of rows, the number of columns, the number of treasures in the island and the number of safe columns. Each of the next k lines contains two integers r_i, c_i, (1 ≤ r_i ≤ n, 1 ≤ c_i ≤ m) — the coordinates of the cell with a treasure. All treasures are located in distinct cells. The last line contains q distinct integers b_1, b_2, …, b_q (1 ≤ b_i ≤ m) — the indices of safe columns. Output Print the minimum number of moves required to collect all the treasures. Examples Input 3 3 3 2 1 1 2 1 3 1 2 3 Output 6 Input 3 5 3 2 1 2 2 3 3 1 1 5 Output 8 Input 3 6 3 2 1 6 2 2 3 4 1 6 Output 15 Note In the first example you should use the second column to go up, collecting in each row treasures from the first column. <image> In the second example, it is optimal to use the first column to go up. <image> In the third example, it is optimal to collect the treasure at cell (1;6), go up to row 2 at column 6, then collect the treasure at cell (2;2), go up to the top row at column 1 and collect the last treasure at cell (3;4). That's a total of 15 moves. <image> Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
from sys import stdin from bisect import bisect_left input=stdin.readline n,m,k,q=map(int,input().split(' ')) x=sorted(list(map(int,input().split(' ')))for i in range(k)) y=sorted(list(map(int,input().split(' ')))) def rr(c0,c1,c2): return abs(c2-c0)+abs(c1-c2) def tm(c0,c1): t=bisect_left(y,c0) tt=[] if (t>0): tt.append(rr(c0,c1,y[t-1])) if (t<q): tt.append(rr(c0,c1,y[t])) return min(tt) # thực hiện tìm xem trong một hàng, kho báu nằm từ khoảng nào đến khoảng nào. z=[] for r,c in x: if z and z[-1][0]==r: z[-1][2]=c else: z.append([r,c,c]) v1,v2,r0,c01,c02=0,0,1,1,1 for r1,c11,c12 in z: d=c12-c11+r1-r0 # bình thường if(r1>r0): d01=tm(c01,c11) d02=tm(c01,c12) d11=tm(c02,c11) d12=tm(c02,c12) v2,v1=d+min(v1+d01,v2+d11),d +min(v1+d02,v2+d12) #nếu có kho báu ở hàng 1 else: v1,v2=d+c12-c02,d+c11-c01 c01,c02,r0=c11,c12,r1 ans=min(v1,v2) print(ans)
python
code_algorithm
[ { "input": "3 6 3 2\n1 6\n2 2\n3 4\n1 6\n", "output": "15\n" }, { "input": "3 3 3 2\n1 1\n2 1\n3 1\n2 3\n", "output": "6\n" }, { "input": "3 5 3 2\n1 2\n2 3\n3 1\n1 5\n", "output": "8\n" }, { "input": "2 11 7 6\n1 1\n1 5\n1 2\n1 4\n1 11\n1 8\n1 3\n3 6 5 10 2 7\n", "output...
code_contests
python
0
36022c7f8e498e8adffe4a043bb10a7f
Ujan has been lazy lately, but now has decided to bring his yard to good shape. First, he decided to paint the path from his house to the gate. The path consists of n consecutive tiles, numbered from 1 to n. Ujan will paint each tile in some color. He will consider the path aesthetic if for any two different tiles with numbers i and j, such that |j - i| is a divisor of n greater than 1, they have the same color. Formally, the colors of two tiles with numbers i and j should be the same if |i-j| > 1 and n mod |i-j| = 0 (where x mod y is the remainder when dividing x by y). Ujan wants to brighten up space. What is the maximum number of different colors that Ujan can use, so that the path is aesthetic? Input The first line of input contains a single integer n (1 ≤ n ≤ 10^{12}), the length of the path. Output Output a single integer, the maximum possible number of colors that the path can be painted in. Examples Input 4 Output 2 Input 5 Output 5 Note In the first sample, two colors is the maximum number. Tiles 1 and 3 should have the same color since 4 mod |3-1| = 0. Also, tiles 2 and 4 should have the same color since 4 mod |4-2| = 0. In the second sample, all five colors can be used. <image> Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
def prime_factor(n): ass = [] for i in range(2,int(n**0.5)+1): while n % i==0: ass.append(i) n = n//i if n != 1: ass.append(n) return ass n = int(input()) p = list(set(prime_factor(n))) if len(p) == 1: print(p[0]) else: print(1)
python
code_algorithm
[ { "input": "5\n", "output": "5\n" }, { "input": "4\n", "output": "2\n" }, { "input": "2\n", "output": "2\n" }, { "input": "54241012609\n", "output": "1\n" }, { "input": "4294967318\n", "output": "1\n" }, { "input": "370758709373\n", "output": "1\n"...
code_contests
python
0
0d82584d023ddedece665ba1d1e04255
You are given two positive integers a and b. In one move you can increase a by 1 (replace a with a+1). Your task is to find the minimum number of moves you need to do in order to make a divisible by b. It is possible, that you have to make 0 moves, as a is already divisible by b. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The only line of the test case contains two integers a and b (1 ≤ a, b ≤ 10^9). Output For each test case print the answer — the minimum number of moves you need to do in order to make a divisible by b. Example Input 5 10 4 13 9 100 13 123 456 92 46 Output 2 5 4 333 0 Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
t=int(input()) for i in range(0,t): a,b=input().split() a=int(a) b=int(b) print((b-a%b)%b)
python
code_algorithm
[ { "input": "5\n10 4\n13 9\n100 13\n123 456\n92 46\n", "output": "2\n5\n4\n333\n0\n" }, { "input": "1\n515151 2\n", "output": "1\n" }, { "input": "21\n1 3218\n28 10924\n908802 141084\n82149 9274\n893257 10248\n2750048 802705\n2857 142\n980 209385\n1 3218\n28 10924\n908802 141084\n82149 92...
code_contests
python
1
cb9263badd242860dea59f687ae071cb
Phoenix has n coins with weights 2^1, 2^2, ..., 2^n. He knows that n is even. He wants to split the coins into two piles such that each pile has exactly n/2 coins and the difference of weights between the two piles is minimized. Formally, let a denote the sum of weights in the first pile, and b denote the sum of weights in the second pile. Help Phoenix minimize |a-b|, the absolute value of a-b. Input The input consists of multiple test cases. The first line contains an integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains an integer n (2 ≤ n ≤ 30; n is even) — the number of coins that Phoenix has. Output For each test case, output one integer — the minimum possible difference of weights between the two piles. Example Input 2 2 4 Output 2 6 Note In the first test case, Phoenix has two coins with weights 2 and 4. No matter how he divides the coins, the difference will be 4-2=2. In the second test case, Phoenix has four coins of weight 2, 4, 8, and 16. It is optimal for Phoenix to place coins with weights 2 and 16 in one pile, and coins with weights 4 and 8 in another pile. The difference is (2+16)-(4+8)=6. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
t=eval(input()) for j in range(t): n=eval(input()) if n==2 : print(2) else: sum=2 for i in range(1,n//2): sum=sum+2**(i+1) print(sum)
python
code_algorithm
[ { "input": "2\n2\n4\n", "output": "2\n6\n" }, { "input": "100\n2\n4\n6\n8\n10\n12\n14\n16\n18\n20\n22\n24\n26\n28\n30\n30\n30\n30\n20\n30\n30\n18\n14\n16\n30\n24\n30\n30\n10\n20\n30\n10\n2\n18\n30\n30\n12\n24\n30\n24\n18\n28\n30\n16\n30\n30\n30\n30\n22\n26\n30\n30\n30\n10\n14\n6\n18\n30\n16\n30\n30\...
code_contests
python
0
9f92cfc23ad3afccdf1708eac56effd2
Each of you probably has your personal experience of riding public transportation and buying tickets. After a person buys a ticket (which traditionally has an even number of digits), he usually checks whether the ticket is lucky. Let us remind you that a ticket is lucky if the sum of digits in its first half matches the sum of digits in its second half. But of course, not every ticket can be lucky. Far from it! Moreover, sometimes one look at a ticket can be enough to say right away that the ticket is not lucky. So, let's consider the following unluckiness criterion that can definitely determine an unlucky ticket. We'll say that a ticket is definitely unlucky if each digit from the first half corresponds to some digit from the second half so that each digit from the first half is strictly less than the corresponding digit from the second one or each digit from the first half is strictly more than the corresponding digit from the second one. Each digit should be used exactly once in the comparisons. In other words, there is such bijective correspondence between the digits of the first and the second half of the ticket, that either each digit of the first half turns out strictly less than the corresponding digit of the second half or each digit of the first half turns out strictly more than the corresponding digit from the second half. For example, ticket 2421 meets the following unluckiness criterion and will not be considered lucky (the sought correspondence is 2 > 1 and 4 > 2), ticket 0135 also meets the criterion (the sought correspondence is 0 < 3 and 1 < 5), and ticket 3754 does not meet the criterion. You have a ticket in your hands, it contains 2n digits. Your task is to check whether it meets the unluckiness criterion. Input The first line contains an integer n (1 ≤ n ≤ 100). The second line contains a string that consists of 2n digits and defines your ticket. Output In the first line print "YES" if the ticket meets the unluckiness criterion. Otherwise, print "NO" (without the quotes). Examples Input 2 2421 Output YES Input 2 0135 Output YES Input 2 3754 Output NO Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
number_of_testcases = 1 #int(input()) for _ in range(number_of_testcases): number_of_digits = int(input()) ticket_number = input() ticket_number = list(ticket_number) first_half = ticket_number[:number_of_digits] second_half = ticket_number[number_of_digits:] #print(first_half) first_half.sort() second_half.sort() flag = 1 if first_half[0] > second_half[0]: for i in range(number_of_digits): if first_half[i] <= second_half[i]: flag = 0 #print("NO") else: for i in range(number_of_digits): if first_half[i] >= second_half[i]: flag = 0 #print("NO") if flag==1: print("YES") else: print("NO")
python
code_algorithm
[ { "input": "2\n3754\n", "output": "NO\n" }, { "input": "2\n0135\n", "output": "YES\n" }, { "input": "2\n2421\n", "output": "YES\n" }, { "input": "20\n7405800505032736115894335199688161431589\n", "output": "YES\n" }, { "input": "100\n0200210221001101010012012020022...
code_contests
python
1
f0b5da292109218123e3de893db45021
There are n piles of stones of sizes a1, a2, ..., an lying on the table in front of you. During one move you can take one pile and add it to the other. As you add pile i to pile j, the size of pile j increases by the current size of pile i, and pile i stops existing. The cost of the adding operation equals the size of the added pile. Your task is to determine the minimum cost at which you can gather all stones in one pile. To add some challenge, the stone piles built up conspiracy and decided that each pile will let you add to it not more than k times (after that it can only be added to another pile). Moreover, the piles decided to puzzle you completely and told you q variants (not necessarily distinct) of what k might equal. Your task is to find the minimum cost for each of q variants. Input The first line contains integer n (1 ≤ n ≤ 105) — the number of stone piles. The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 109) — the initial sizes of the stone piles. The third line contains integer q (1 ≤ q ≤ 105) — the number of queries. The last line contains q space-separated integers k1, k2, ..., kq (1 ≤ ki ≤ 105) — the values of number k for distinct queries. Note that numbers ki can repeat. Output Print q whitespace-separated integers — the answers to the queries in the order, in which the queries are given in the input. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 5 2 3 4 1 1 2 2 3 Output 9 8 Note In the first sample one way to get the optimal answer goes like this: we add in turns the 4-th and the 5-th piles to the 2-nd one; then we add the 1-st pile to the 3-rd one; we add the 2-nd pile to the 3-rd one. The first two operations cost 1 each; the third one costs 2, the fourth one costs 5 (the size of the 2-nd pile after the first two operations is not 3, it already is 5). In the second sample you can add the 2-nd pile to the 3-rd one (the operations costs 3); then the 1-st one to the 3-th one (the cost is 2); then the 5-th one to the 4-th one (the costs is 1); and at last, the 4-th one to the 3-rd one (the cost is 2). Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
n = int(input()) stones = list(map(lambda t : int(t), input().split())) q = int(input()) queries = list(map(lambda t : int(t), input().split())) stones.sort() added_stones = [] added_stones.append(stones[0]) for i in range(1, n, 1): added_stones.append(stones[i] + added_stones[i - 1]) computed_queries = {} for qidx, qq in enumerate(queries): if qq in computed_queries: queries[qidx] = computed_queries[qq] continue i = n - 2 multiplier = 1 cost = 0 while i >= 0: pp = pow(qq, multiplier) nexti = i - pp if nexti < 0: cost += added_stones[i] * multiplier break cost += (added_stones[i] - added_stones[nexti]) * multiplier multiplier += 1 i = nexti queries[qidx] = cost computed_queries[qq] = cost print(*queries, sep=' ')
python
code_algorithm
[ { "input": "5\n2 3 4 1 1\n2\n2 3\n", "output": "9 8\n" }, { "input": "3\n1 6 8\n1\n6\n", "output": "7\n" }, { "input": "1\n10\n5\n5 3 7 7 1\n", "output": "0 0 0 0 0\n" }, { "input": "4\n7 4 1 7\n3\n6 8 3\n", "output": "12 12 12\n" }, { "input": "1\n1\n3\n2 1 10\n"...
code_contests
python
0
bbfcc7bffc0c697a5172c70c83db4793
Little Petya likes permutations a lot. Recently his mom has presented him permutation q1, q2, ..., qn of length n. A permutation a of length n is a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ n), all integers there are distinct. There is only one thing Petya likes more than permutations: playing with little Masha. As it turns out, Masha also has a permutation of length n. Petya decided to get the same permutation, whatever the cost may be. For that, he devised a game with the following rules: * Before the beginning of the game Petya writes permutation 1, 2, ..., n on the blackboard. After that Petya makes exactly k moves, which are described below. * During a move Petya tosses a coin. If the coin shows heads, he performs point 1, if the coin shows tails, he performs point 2. 1. Let's assume that the board contains permutation p1, p2, ..., pn at the given moment. Then Petya removes the written permutation p from the board and writes another one instead: pq1, pq2, ..., pqn. In other words, Petya applies permutation q (which he has got from his mother) to permutation p. 2. All actions are similar to point 1, except that Petya writes permutation t on the board, such that: tqi = pi for all i from 1 to n. In other words, Petya applies a permutation that is inverse to q to permutation p. We know that after the k-th move the board contained Masha's permutation s1, s2, ..., sn. Besides, we know that throughout the game process Masha's permutation never occurred on the board before the k-th move. Note that the game has exactly k moves, that is, throughout the game the coin was tossed exactly k times. Your task is to determine whether the described situation is possible or else state that Petya was mistaken somewhere. See samples and notes to them for a better understanding. Input The first line contains two integers n and k (1 ≤ n, k ≤ 100). The second line contains n space-separated integers q1, q2, ..., qn (1 ≤ qi ≤ n) — the permutation that Petya's got as a present. The third line contains Masha's permutation s, in the similar format. It is guaranteed that the given sequences q and s are correct permutations. Output If the situation that is described in the statement is possible, print "YES" (without the quotes), otherwise print "NO" (without the quotes). Examples Input 4 1 2 3 4 1 1 2 3 4 Output NO Input 4 1 4 3 1 2 3 4 2 1 Output YES Input 4 3 4 3 1 2 3 4 2 1 Output YES Input 4 2 4 3 1 2 2 1 4 3 Output YES Input 4 1 4 3 1 2 2 1 4 3 Output NO Note In the first sample Masha's permutation coincides with the permutation that was written on the board before the beginning of the game. Consequently, that violates the condition that Masha's permutation never occurred on the board before k moves were performed. In the second sample the described situation is possible, in case if after we toss a coin, we get tails. In the third sample the possible coin tossing sequence is: heads-tails-tails. In the fourth sample the possible coin tossing sequence is: heads-heads. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
n,k=map(int,input().strip().split()) a=list(map(int,input().strip().split())) b=list(map(int,input().strip().split())) ups = [[i+1 for i in range(n)]] downs = [[i+1 for i in range(n)]] def apply(arr): out = [0]*n for i in range(n): out[i] = arr[a[i]-1] return out def unapply(arr): out = [0]*n for i in range(n): out[a[i]-1] = arr[i] return out for i in range(k): ups.append(apply(ups[i])) for i in range(k): downs.append(unapply(downs[i])) earliest = [None, None] earliestPossible = [None, None] for i in range(k,-1,-1): if ups[i] == b: earliest[0] = i if downs[i] == b: earliest[1] = i # print("YES") # exit(0) for i in range(k,-1,-2): if ups[i] == b: earliestPossible[0] = i if downs[i] == b: earliestPossible[1] = i if (not earliestPossible[0]) and (not earliestPossible[1]): print("NO") exit(0) if ((not earliestPossible[0]) or earliest[0] < earliestPossible[0]) and ((not earliestPossible[1]) or earliest[1] < earliestPossible[1]): print("NO") exit(0) if ups[0] == b or (ups[1] == b and downs[1] == b and k > 1): print("NO") exit(0) print("YES") # tem = [i+1 for i in range(n)] # for i in range(k): # tem = apply(tem) # for i in range(k): # tem = unapply(tem) # print(tem)
python
code_algorithm
[ { "input": "4 1\n4 3 1 2\n3 4 2 1\n", "output": "YES\n" }, { "input": "4 1\n4 3 1 2\n2 1 4 3\n", "output": "NO\n" }, { "input": "4 3\n4 3 1 2\n3 4 2 1\n", "output": "YES\n" }, { "input": "4 1\n2 3 4 1\n1 2 3 4\n", "output": "NO\n" }, { "input": "4 2\n4 3 1 2\n2 1 ...
code_contests
python
0
07e833a312366f0558dffebf48ede084
The little girl loves the problems on array queries very much. One day she came across a rather well-known problem: you've got an array of n elements (the elements of the array are indexed starting from 1); also, there are q queries, each one is defined by a pair of integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n). You need to find for each query the sum of elements of the array with indexes from l_i to r_i, inclusive. The little girl found the problem rather boring. She decided to reorder the array elements before replying to the queries in a way that makes the sum of query replies maximum possible. Your task is to find the value of this maximum sum. Input The first line contains two space-separated integers n (1 ≤ n ≤ 2⋅10^5) and q (1 ≤ q ≤ 2⋅10^5) — the number of elements in the array and the number of queries, correspondingly. The next line contains n space-separated integers a_i (1 ≤ a_i ≤ 2⋅10^5) — the array elements. Each of the following q lines contains two space-separated integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the i-th query. Output In a single line print, a single integer — the maximum sum of query replies after the array elements are reordered. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 3 3 5 3 2 1 2 2 3 1 3 Output 25 Input 5 3 5 2 4 1 3 1 5 2 3 2 3 Output 33 Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
n,m = map(int,input().split()) a = list(map(int,input().split())) l = [0]*(n+2) for i in range(m): x,y=map(int,input().split()) l[x] += 1 l[y+1] -= 1 for i in range(2, n+2): l[i] += l[i-1] l.sort(reverse=True) a.sort(reverse=True) # print(l, a) ans=0 for i in range(n): ans += l[i]*a[i] print(ans)
python
code_algorithm
[ { "input": "5 3\n5 2 4 1 3\n1 5\n2 3\n2 3\n", "output": "33\n" }, { "input": "3 3\n5 3 2\n1 2\n2 3\n1 3\n", "output": "25\n" }, { "input": "31 48\n45 19 16 42 38 18 50 7 28 40 39 25 45 14 36 18 27 30 16 4 22 6 1 23 16 47 14 35 27 47 2\n6 16\n11 28\n4 30\n25 26\n11 30\n5 9\n4 17\n15 17\n1...
code_contests
python
0.8
4a905d242c7ea515049ee7acc043ddc9
Fox Ciel has a robot on a 2D plane. Initially it is located in (0, 0). Fox Ciel code a command to it. The command was represented by string s. Each character of s is one move operation. There are four move operations at all: * 'U': go up, (x, y) → (x, y+1); * 'D': go down, (x, y) → (x, y-1); * 'L': go left, (x, y) → (x-1, y); * 'R': go right, (x, y) → (x+1, y). The robot will do the operations in s from left to right, and repeat it infinite times. Help Fox Ciel to determine if after some steps the robot will located in (a, b). Input The first line contains two integers a and b, ( - 109 ≤ a, b ≤ 109). The second line contains a string s (1 ≤ |s| ≤ 100, s only contains characters 'U', 'D', 'L', 'R') — the command. Output Print "Yes" if the robot will be located at (a, b), and "No" otherwise. Examples Input 2 2 RU Output Yes Input 1 2 RU Output No Input -1 1000000000 LRRLU Output Yes Input 0 0 D Output Yes Note In the first and second test case, command string is "RU", so the robot will go right, then go up, then right, and then up and so on. The locations of its moves are (0, 0) → (1, 0) → (1, 1) → (2, 1) → (2, 2) → ... So it can reach (2, 2) but not (1, 2). Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
target = tuple(map(int, input().split())) s = input() #print(target) #print(s) ok = False pos = (0, 0) for c in s: if c == 'L': pos = (pos[0]-1, pos[1]) if c == 'R': pos = (pos[0]+1, pos[1]) if c == 'U': pos = (pos[0], pos[1]+1) if c == 'D': pos = (pos[0], pos[1]-1) if pos == target: ok = True if pos == (0, 0): #termin pe pozitia din care am pornit if ok: print('Yes') else: print('No') exit() if pos[0] == 0: if target[1] * pos[1] < 0: raport = 0 else: raport = target[1] // pos[1] else: if target[0] * pos[0] < 0: raport = 0 else: raport = target[0] // pos[0] if raport > 0: raport = max(0, raport - 1000) if raport < 0: raport = min(0, raport + 1000) #print('Ajung in (%i, %i) dupa o executie, si raport = %i' %(pos[0], pos[1], raport)) coord = (pos[0] * raport, pos[1]*raport) for rep in range(0, 10**4): if coord == target: ok = True for c in s: if c == 'L': coord = (coord[0]-1, coord[1]) if c == 'R': coord = (coord[0]+1, coord[1]) if c == 'U': coord = (coord[0], coord[1]+1) if c == 'D': coord = (coord[0], coord[1]-1) if coord == target: ok = True if ok: print('Yes') else: print('No')
python
code_algorithm
[ { "input": "0 0\nD\n", "output": "Yes\n" }, { "input": "-1 1000000000\nLRRLU\n", "output": "Yes\n" }, { "input": "2 2\nRU\n", "output": "Yes\n" }, { "input": "1 2\nRU\n", "output": "No\n" }, { "input": "999999999 -999999999\nRRRRRRRRRRRRRRRRRRRRRRRRRDDDDDDDDDDDDDD...
code_contests
python
0
e00d702d3d0e3904e2c8e47e6c0181c8
You want to arrange n integers a1, a2, ..., an in some order in a row. Let's define the value of an arrangement as the sum of differences between all pairs of adjacent integers. More formally, let's denote some arrangement as a sequence of integers x1, x2, ..., xn, where sequence x is a permutation of sequence a. The value of such an arrangement is (x1 - x2) + (x2 - x3) + ... + (xn - 1 - xn). Find the largest possible value of an arrangement. Then, output the lexicographically smallest sequence x that corresponds to an arrangement of the largest possible value. Input The first line of the input contains integer n (2 ≤ n ≤ 100). The second line contains n space-separated integers a1, a2, ..., an (|ai| ≤ 1000). Output Print the required sequence x1, x2, ..., xn. Sequence x should be the lexicographically smallest permutation of a that corresponds to an arrangement of the largest possible value. Examples Input 5 100 -100 50 0 -50 Output 100 -50 0 50 -100 Note In the sample test case, the value of the output arrangement is (100 - ( - 50)) + (( - 50) - 0) + (0 - 50) + (50 - ( - 100)) = 200. No other arrangement has a larger value, and among all arrangements with the value of 200, the output arrangement is the lexicographically smallest one. Sequence x1, x2, ... , xp is lexicographically smaller than sequence y1, y2, ... , yp if there exists an integer r (0 ≤ r < p) such that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
# t=int(input()) # import math # for _ in range(t): # n,k=list(map(int,input().split())) # s=input() # a=[] # summer=0 # for i in range(len(s)): # if(s[i]=='1'): # a.append(i) # i=0 # while(i<len(a)-1): # dist=a[i+1]-k-1-(a[i]+k+1)+1 # # print(a,dist) # if(dist>0): # # summer+=(dist//k) # summer+=(math.ceil(dist/(k+1))) # i+=1 # if(len(a)>0): # dist=a[0]-k # if(dist>0): # summer+=(math.ceil(dist/(k+1))) # dist=n-1-a[-1]-k # if(dist>0): # summer+=(math.ceil(dist/(k+1))) # else: # summer+=(math.ceil(n/(k+1))) # print(summer) n=int(input()) s=list(map(int,input().split())) s.sort() print(s[n-1],end=" ") for a in s[1:-1]: print(a,end =" ") print(s[0])
python
code_algorithm
[ { "input": "5\n100 -100 50 0 -50\n", "output": "100 -50 0 50 -100\n" }, { "input": "50\n-262 -377 -261 903 547 759 -800 -53 670 92 758 109 547 877 152 -901 -318 -527 -388 24 139 -227 413 -135 811 -886 -22 -526 -643 -431 284 609 -745 -62 323 -441 743 -800 86 862 587 -513 -468 -651 -760 197 141 -414 -...
code_contests
python
0
023f4a03feb28558dd65db88f92645fc
Fox Ciel is playing a mobile puzzle game called "Two Dots". The basic levels are played on a board of size n × m cells, like this: <image> Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors. The key of this game is to find a cycle that contain dots of same color. Consider 4 blue dots on the picture forming a circle as an example. Formally, we call a sequence of dots d1, d2, ..., dk a cycle if and only if it meets the following condition: 1. These k dots are different: if i ≠ j then di is different from dj. 2. k is at least 4. 3. All dots belong to the same color. 4. For all 1 ≤ i ≤ k - 1: di and di + 1 are adjacent. Also, dk and d1 should also be adjacent. Cells x and y are called adjacent if they share an edge. Determine if there exists a cycle on the field. Input The first line contains two integers n and m (2 ≤ n, m ≤ 50): the number of rows and columns of the board. Then n lines follow, each line contains a string consisting of m characters, expressing colors of dots in each line. Each character is an uppercase Latin letter. Output Output "Yes" if there exists a cycle, and "No" otherwise. Examples Input 3 4 AAAA ABCA AAAA Output Yes Input 3 4 AAAA ABCA AADA Output No Input 4 4 YYYR BYBY BBBY BBBY Output Yes Input 7 6 AAAAAB ABBBAB ABAAAB ABABBB ABAAAB ABBBAB AAAAAB Output Yes Input 2 13 ABCDEFGHIJKLM NOPQRSTUVWXYZ Output No Note In first sample test all 'A' form a cycle. In second sample there is no such cycle. The third sample is displayed on the picture above ('Y' = Yellow, 'B' = Blue, 'R' = Red). Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
''' Zijian He 1429876 ''' # Import from sys import setrecursionlimit setrecursionlimit(10**6) # Function from class class Graph: def __init__ (self): self._alist = {} def add_vertex (self, vertex): if vertex not in self._alist: self._alist[vertex] = set() def add_edge (self, source, destination): self.add_vertex(source) self.add_vertex(destination) self._alist[source].add(destination) def is_edge (self, source, destination): return (self.is_vertex(source) and destination in self._alist[source]) def is_vertex (self, vertex): return vertex in self._alist def neighbours (self, vertex): return self._alist[vertex] def vertices (self): return self._alist.keys() class UndirectedGraph (Graph): def add_edge (self, a, b): super().add_edge (a, b) super().add_edge (b, a) def depth_first_search(g, v): reached = {} def do_dfs(curr, prev): if curr in reached: return reached[curr] = prev for succ in g.neighbours(curr): do_dfs(succ, curr) do_dfs(v, v) return reached #----------------------------------------------------------------------- # Declaire the variables for checking the cycle Detect = False vertex = {} def dfs_v2(g, curr, prev): global Detect global vertex if Detect: return vertex[curr] = True for succ in g.neighbours(curr): if vertex[succ] and succ != prev: Detect = True return if not vertex[succ]: dfs_v2(g, succ, curr) def cycle(g): global Detect global vertex # Initialize all the node as unmarked for i in g.vertices(): vertex[i] = False # Check throughout the node for j in g.vertices(): if not vertex[j]: dfs_v2(g, j, j) if Detect: break return # ---------------------------------------------------------------------- # Process the input row, col = map(int, input().split(" ")) rows = [] for i in range(row): rows.append(input()) # Set node as a dictionary node = {} for i in range(row): for j in range(col): node[i * col + j] = rows[i][j] # Set up the graph result_Graph = UndirectedGraph() # Connecting the node with same color for i in range(row * col): result_Graph.add_vertex(i) try: if node[i] == node[i + 1] and (i % col) != (col - 1): result_Graph.add_edge(i, i + 1) if node[i] == node[i + col]: result_Graph.add_edge(i, i + col) except: continue # Main function cycle(result_Graph) if Detect: print("Yes") else: print("No")
python
code_algorithm
[ { "input": "2 13\nABCDEFGHIJKLM\nNOPQRSTUVWXYZ\n", "output": "No\n" }, { "input": "7 6\nAAAAAB\nABBBAB\nABAAAB\nABABBB\nABAAAB\nABBBAB\nAAAAAB\n", "output": "Yes\n" }, { "input": "3 4\nAAAA\nABCA\nAAAA\n", "output": "Yes\n" }, { "input": "3 4\nAAAA\nABCA\nAADA\n", "output...
code_contests
python
0.8
cfbefff03bc55f8686ad940b0127d814
Karafs is some kind of vegetable in shape of an 1 × h rectangle. Tavaspolis people love Karafs and they use Karafs in almost any kind of food. Tavas, himself, is crazy about Karafs. <image> Each Karafs has a positive integer height. Tavas has an infinite 1-based sequence of Karafses. The height of the i-th Karafs is si = A + (i - 1) × B. For a given m, let's define an m-bite operation as decreasing the height of at most m distinct not eaten Karafses by 1. Karafs is considered as eaten when its height becomes zero. Now SaDDas asks you n queries. In each query he gives you numbers l, t and m and you should find the largest number r such that l ≤ r and sequence sl, sl + 1, ..., sr can be eaten by performing m-bite no more than t times or print -1 if there is no such number r. Input The first line of input contains three integers A, B and n (1 ≤ A, B ≤ 106, 1 ≤ n ≤ 105). Next n lines contain information about queries. i-th line contains integers l, t, m (1 ≤ l, t, m ≤ 106) for i-th query. Output For each query, print its answer in a single line. Examples Input 2 1 4 1 5 3 3 3 10 7 10 2 6 4 8 Output 4 -1 8 -1 Input 1 5 2 1 5 10 2 7 4 Output 1 2 Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
a,b,n=map(int,input().split()) for _ in range(n): l,t,m=map(int,input().split()) lo=l hi=100000000 while lo<hi: mid=(lo+hi)//2 count=(mid-l)+1 first=a+(l-1)*b last=a+(mid-1)*b if last<=t and (count*(first+last))//2<=m*t: lo=mid+1 else: hi=mid if mid!=lo: print(mid) else: count=(mid-1-l)+1 first=a+(l-1)*b last=a+(mid-1-1)*b if last<=t and (count*(first+last))//2<=m*t and mid-1>=l: print(mid-1) else: print(-1)
python
code_algorithm
[ { "input": "1 5 2\n1 5 10\n2 7 4\n", "output": "1\n2\n" }, { "input": "2 1 4\n1 5 3\n3 3 10\n7 10 2\n6 4 8\n", "output": "4\n-1\n8\n-1\n" }, { "input": "1 1 1\n1 1000000 1000000\n", "output": "1000000\n" }, { "input": "447 74474 4\n47 777474 747\n74 744744 74477\n477 477447 7...
code_contests
python
0
120c9b7e35abe69616928f61424f9fe6
Alena has successfully passed the entrance exams to the university and is now looking forward to start studying. One two-hour lesson at the Russian university is traditionally called a pair, it lasts for two academic hours (an academic hour is equal to 45 minutes). The University works in such a way that every day it holds exactly n lessons. Depending on the schedule of a particular group of students, on a given day, some pairs may actually contain classes, but some may be empty (such pairs are called breaks). The official website of the university has already published the schedule for tomorrow for Alena's group. Thus, for each of the n pairs she knows if there will be a class at that time or not. Alena's House is far from the university, so if there are breaks, she doesn't always go home. Alena has time to go home only if the break consists of at least two free pairs in a row, otherwise she waits for the next pair at the university. Of course, Alena does not want to be sleepy during pairs, so she will sleep as long as possible, and will only come to the first pair that is presented in her schedule. Similarly, if there are no more pairs, then Alena immediately goes home. Alena appreciates the time spent at home, so she always goes home when it is possible, and returns to the university only at the beginning of the next pair. Help Alena determine for how many pairs she will stay at the university. Note that during some pairs Alena may be at the university waiting for the upcoming pair. Input The first line of the input contains a positive integer n (1 ≤ n ≤ 100) — the number of lessons at the university. The second line contains n numbers ai (0 ≤ ai ≤ 1). Number ai equals 0, if Alena doesn't have the i-th pairs, otherwise it is equal to 1. Numbers a1, a2, ..., an are separated by spaces. Output Print a single number — the number of pairs during which Alena stays at the university. Examples Input 5 0 1 0 1 1 Output 4 Input 7 1 0 1 0 0 1 0 Output 4 Input 1 0 Output 0 Note In the first sample Alena stays at the university from the second to the fifth pair, inclusive, during the third pair she will be it the university waiting for the next pair. In the last sample Alena doesn't have a single pair, so she spends all the time at home. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
n = int(input()) a = list(map(int, input().split())) + [0] home = True ans = 0 for i in range(n): if a[i]: ans += 1 home = False elif not a[i + 1] and not home: home = True elif not home: ans += 1 print(ans)
python
code_algorithm
[ { "input": "5\n0 1 0 1 1\n", "output": "4\n" }, { "input": "7\n1 0 1 0 0 1 0\n", "output": "4\n" }, { "input": "1\n0\n", "output": "0\n" }, { "input": "95\n1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ...
code_contests
python
0
88c08865e1188a3451597a0ab0d807c4
Genos needs your help. He was asked to solve the following programming problem by Saitama: The length of some string s is denoted |s|. The Hamming distance between two strings s and t of equal length is defined as <image>, where si is the i-th character of s and ti is the i-th character of t. For example, the Hamming distance between string "0011" and string "0110" is |0 - 0| + |0 - 1| + |1 - 1| + |1 - 0| = 0 + 1 + 0 + 1 = 2. Given two binary strings a and b, find the sum of the Hamming distances between a and all contiguous substrings of b of length |a|. Input The first line of the input contains binary string a (1 ≤ |a| ≤ 200 000). The second line of the input contains binary string b (|a| ≤ |b| ≤ 200 000). Both strings are guaranteed to consist of characters '0' and '1' only. Output Print a single integer — the sum of Hamming distances between a and all contiguous substrings of b of length |a|. Examples Input 01 00111 Output 3 Input 0011 0110 Output 2 Note For the first sample case, there are four contiguous substrings of b of length |a|: "00", "01", "11", and "11". The distance between "01" and "00" is |0 - 0| + |1 - 0| = 1. The distance between "01" and "01" is |0 - 0| + |1 - 1| = 0. The distance between "01" and "11" is |0 - 1| + |1 - 1| = 1. Last distance counts twice, as there are two occurrences of string "11". The sum of these edit distances is 1 + 0 + 1 + 1 = 3. The second sample case is described in the statement. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
from sys import stdin input=stdin.readline ''' if i+k ''' def getcnt(a): cnt=[[0,0] for i in range(len(a)+1)] for i in range(len(a)): # if i==0: # cnt[i][a[i]]+=1 # else: cnt[i+1][0]=cnt[i][0] cnt[i+1][1]=cnt[i][1] cnt[i+1][a[i]]+=1 return cnt def f(a,b): ans=0 a=list(map(int,list(a))) b=list(map(int,list(b))) lb=len(b) la=len(a) cnt=getcnt(a) ans=0 for i in range(len(b)): lo=max(0,i-(lb-la)) hi=min(i+1,la) # print(lo,hi) # if lo==0: # lr=[0,0] # else: lr=cnt[lo] rr=cnt[hi] t=list(map(lambda x,y:x-y,rr,lr)) ans+=t[b[i]^1] return ans s=input().strip() t=input().strip() print(f(s,t))
python
code_algorithm
[ { "input": "01\n00111\n", "output": "3\n" }, { "input": "0011\n0110\n", "output": "2\n" }, { "input": "1001101001101110101101000\n01111000010011111111110010001101000100011110101111\n", "output": "321\n" }, { "input": "1\n0\n", "output": "1\n" }, { "input": "0\n1\n...
code_contests
python
0
7ccca6f982f9ed722cdccd534f0d6bb0
You are given names of two days of the week. Please, determine whether it is possible that during some non-leap year the first day of some month was equal to the first day of the week you are given, while the first day of the next month was equal to the second day of the week you are given. Both months should belong to one year. In this problem, we consider the Gregorian calendar to be used. The number of months in this calendar is equal to 12. The number of days in months during any non-leap year is: 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31. Names of the days of the week are given with lowercase English letters: "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday". Input The input consists of two lines, each of them containing the name of exactly one day of the week. It's guaranteed that each string in the input is from the set "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday". Output Print "YES" (without quotes) if such situation is possible during some non-leap year. Otherwise, print "NO" (without quotes). Examples Input monday tuesday Output NO Input sunday sunday Output YES Input saturday tuesday Output YES Note In the second sample, one can consider February 1 and March 1 of year 2015. Both these days were Sundays. In the third sample, one can consider July 1 and August 1 of year 2017. First of these two days is Saturday, while the second one is Tuesday. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
a = str(input()) b = str(input()) k = {'monday':1,'tuesday':2,'wednesday':3,'thursday':4,'friday':5,'saturday':6,'sunday':7} a=k[a]-1 b=k[b]-1 res = False res = res or ((a+2)%7+1)%7==b res = res or ((a+1)%7+1)%7==b res = res or ((a+6)%7+1)%7==b if res: print("YES") else: print("NO")
python
code_algorithm
[ { "input": "monday\ntuesday\n", "output": "NO\n" }, { "input": "saturday\ntuesday\n", "output": "YES\n" }, { "input": "sunday\nsunday\n", "output": "YES\n" }, { "input": "friday\ntuesday\n", "output": "NO\n" }, { "input": "thursday\nmonday\n", "output": "NO\n"...
code_contests
python
0.7
2150aa584d740238b4f56afb7ceb07fa
There is the faculty of Computer Science in Berland. In the social net "TheContact!" for each course of this faculty there is the special group whose name equals the year of university entrance of corresponding course of students at the university. Each of students joins the group of his course and joins all groups for which the year of student's university entrance differs by no more than x from the year of university entrance of this student, where x — some non-negative integer. A value x is not given, but it can be uniquely determined from the available data. Note that students don't join other groups. You are given the list of groups which the student Igor joined. According to this information you need to determine the year of Igor's university entrance. Input The first line contains the positive odd integer n (1 ≤ n ≤ 5) — the number of groups which Igor joined. The next line contains n distinct integers a1, a2, ..., an (2010 ≤ ai ≤ 2100) — years of student's university entrance for each group in which Igor is the member. It is guaranteed that the input data is correct and the answer always exists. Groups are given randomly. Output Print the year of Igor's university entrance. Examples Input 3 2014 2016 2015 Output 2015 Input 1 2050 Output 2050 Note In the first test the value x = 1. Igor entered the university in 2015. So he joined groups members of which are students who entered the university in 2014, 2015 and 2016. In the second test the value x = 0. Igor entered only the group which corresponds to the year of his university entrance. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
n = int(input()) a = list(map(int, input().split())) a.sort() if n % 2: print(a[n//2])
python
code_algorithm
[ { "input": "1\n2050\n", "output": "2050\n" }, { "input": "3\n2014 2016 2015\n", "output": "2015\n" }, { "input": "5\n2099 2096 2095 2097 2098\n", "output": "2097\n" }, { "input": "3\n2011 2010 2012\n", "output": "2011\n" }, { "input": "5\n2097 2099 2100 2098 2096\...
code_contests
python
0.8
1cc179af8c6980635ae9bf5db9646f55
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question? Input The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the initial prices. Output Print the only line containing the minimum number of seconds needed for prices to become equal, of «-1» if it is impossible. Examples Input 3 3 12 9 15 Output 3 Input 2 2 10 9 Output -1 Input 4 1 1 1000000000 1000000000 1000000000 Output 2999999997 Note Consider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds. There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3. In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal. In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
n,k=map(int,input().split()) l=list(map(int,input().split())) K=min(l) for i in range(n): if (l[i]-K)%k!=0: print(-1) exit() Sum=sum(l) K=K*n Sum=Sum-K print(Sum//k)
python
code_algorithm
[ { "input": "2 2\n10 9\n", "output": "-1\n" }, { "input": "3 3\n12 9 15\n", "output": "3\n" }, { "input": "4 1\n1 1000000000 1000000000 1000000000\n", "output": "2999999997\n" }, { "input": "3 3\n1 3 5\n", "output": "-1\n" }, { "input": "10 2\n2 1000000000 10000000...
code_contests
python
0.8
80b759423c59680c366433a2e628775b
Alice is a beginner composer and now she is ready to create another masterpiece. And not even the single one but two at the same time! Alice has a sheet with n notes written on it. She wants to take two such non-empty non-intersecting subsequences that both of them form a melody and sum of their lengths is maximal. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. Subsequence forms a melody when each two adjacent notes either differs by 1 or are congruent modulo 7. You should write a program which will calculate maximum sum of lengths of such two non-empty non-intersecting subsequences that both of them form a melody. Input The first line contains one integer number n (2 ≤ n ≤ 5000). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — notes written on a sheet. Output Print maximum sum of lengths of such two non-empty non-intersecting subsequences that both of them form a melody. Examples Input 4 1 2 4 5 Output 4 Input 6 62 22 60 61 48 49 Output 5 Note In the first example subsequences [1, 2] and [4, 5] give length 4 in total. In the second example subsequences [62, 48, 49] and [60, 61] give length 5 in total. If you choose subsequence [62, 61] in the first place then the second melody will have maximum length 2, that gives the result of 4, which is not maximal. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
import sys n = int(input()) + 1 a = [0] + list(map(int, input().split())) mod7 = [x % 7 for x in a] dp = [[0]*n for _ in range(n)] maxnum = [0]*(10**5+10) ans = 0 for i in range(n): maxmod = [0]*7 for j in range(n): maxnum[a[j]] = 0 for j in range(i): maxnum[a[j]] = max(maxnum[a[j]], dp[j][i]) maxmod[mod7[j]] = max(maxmod[mod7[j]], dp[j][i]) for j in range(i+1, n): dp[i][j] = max( maxnum[a[j]-1], maxnum[a[j]+1], maxmod[mod7[j]], dp[0][i] ) + 1 maxnum[a[j]] = max(maxnum[a[j]], dp[i][j]) maxmod[mod7[j]] = max(maxmod[mod7[j]], dp[i][j]) ans = max(ans, dp[i][j]) print(ans)
python
code_algorithm
[ { "input": "6\n62 22 60 61 48 49\n", "output": "5\n" }, { "input": "4\n1 2 4 5\n", "output": "4\n" }, { "input": "10\n7776 32915 1030 71664 7542 72359 65387 75222 95899 40333\n", "output": "6\n" }, { "input": "6\n7 20 21 22 23 28\n", "output": "6\n" }, { "input": ...
code_contests
python
0
f18ba2bbc2dc133c378a1022edb0fc1c
In Arcady's garden there grows a peculiar apple-tree that fruits one time per year. Its peculiarity can be explained in following way: there are n inflorescences, numbered from 1 to n. Inflorescence number 1 is situated near base of tree and any other inflorescence with number i (i > 1) is situated at the top of branch, which bottom is pi-th inflorescence and pi < i. Once tree starts fruiting, there appears exactly one apple in each inflorescence. The same moment as apples appear, they start to roll down along branches to the very base of tree. Each second all apples, except ones in first inflorescence simultaneously roll down one branch closer to tree base, e.g. apple in a-th inflorescence gets to pa-th inflorescence. Apples that end up in first inflorescence are gathered by Arcady in exactly the same moment. Second peculiarity of this tree is that once two apples are in same inflorescence they annihilate. This happens with each pair of apples, e.g. if there are 5 apples in same inflorescence in same time, only one will not be annihilated and if there are 8 apples, all apples will be annihilated. Thus, there can be no more than one apple in each inflorescence in each moment of time. Help Arcady with counting number of apples he will be able to collect from first inflorescence during one harvest. Input First line of input contains single integer number n (2 ≤ n ≤ 100 000) — number of inflorescences. Second line of input contains sequence of n - 1 integer numbers p2, p3, ..., pn (1 ≤ pi < i), where pi is number of inflorescence into which the apple from i-th inflorescence rolls down. Output Single line of output should contain one integer number: amount of apples that Arcady will be able to collect from first inflorescence during one harvest. Examples Input 3 1 1 Output 1 Input 5 1 2 2 2 Output 3 Input 18 1 1 1 4 4 3 2 2 2 10 8 9 9 9 10 10 4 Output 4 Note In first example Arcady will be able to collect only one apple, initially situated in 1st inflorescence. In next second apples from 2nd and 3rd inflorescences will roll down and annihilate, and Arcady won't be able to collect them. In the second example Arcady will be able to collect 3 apples. First one is one initially situated in first inflorescence. In a second apple from 2nd inflorescence will roll down to 1st (Arcady will collect it) and apples from 3rd, 4th, 5th inflorescences will roll down to 2nd. Two of them will annihilate and one not annihilated will roll down from 2-nd inflorescence to 1st one in the next second and Arcady will collect it. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
from collections import defaultdict,Counter,deque as dq from sys import stdin input=stdin.readline n=int(input()) g=defaultdict(list) w=list(map(int,input().strip().split())) for i in range(len(w)): g[w[i]-1].append(i+1) g[i+1].append(w[i]-1) # print(g) q=dq([0]) d=[-1]*(n) d[0]=1 cnt=defaultdict(int) cnt[1]+=1 while q: t=q.popleft() for i in g[t]: if d[i]==-1: d[i]=d[t]+1 cnt[d[i]]+=1 q.append(i) ans=0 for i in cnt: if cnt[i]%2!=0: ans+=1 print(ans)
python
code_algorithm
[ { "input": "18\n1 1 1 4 4 3 2 2 2 10 8 9 9 9 10 10 4\n", "output": "4\n" }, { "input": "3\n1 1\n", "output": "1\n" }, { "input": "5\n1 2 2 2\n", "output": "3\n" }, { "input": "3\n1 2\n", "output": "3\n" }, { "input": "20\n1 2 2 4 3 5 5 6 6 9 11 9 9 12 13 10 15 13 ...
code_contests
python
0.1
4c80cfadc39cfe987ac73cab3bdf8822
Two players play a game. Initially there are n integers a_1, a_2, …, a_n written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. n - 1 turns are made. The first player makes the first move, then players alternate turns. The first player wants to minimize the last number that would be left on the board, while the second player wants to maximize it. You want to know what number will be left on the board after n - 1 turns if both players make optimal moves. Input The first line contains one integer n (1 ≤ n ≤ 1000) — the number of numbers on the board. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^6). Output Print one number that will be left on the board. Examples Input 3 2 1 3 Output 2 Input 3 2 2 2 Output 2 Note In the first sample, the first player erases 3 and the second erases 1. 2 is left on the board. In the second sample, 2 is left on the board regardless of the actions of the players. Write Python code to solve the problem. Present the code in the code block: ```python Your code ``` Write Python code to solve the problem. Present the code in the code block: ```python Your code ```
x = int(input()) l = [int(n) for n in input().split()] l.sort() i = 0 while len(l) > 1: if i % 2 == 0: l = l[0:len(l) - 1] else: l = l[1:len(l)] i = i + 1 print(l[0])
python
code_algorithm
[ { "input": "3\n2 2 2\n", "output": "2\n" }, { "input": "3\n2 1 3\n", "output": "2\n" }, { "input": "10\n38 82 23 37 96 4 81 60 67 86\n", "output": "60\n" }, { "input": "9\n44 53 51 80 5 27 74 79 94\n", "output": "53\n" }, { "input": "3\n9 92 12\n", "output": "...
code_contests
python
0.8
c4d124f595a44772df2544f04300dda0