Dataset Preview
Viewer
The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
An error occurred while generating the dataset
Error code:   UnexpectedError

Need help to make the dataset viewer work? Open a discussion for direct support.

prob_desc_time_limit
string
prob_desc_sample_outputs
string
src_uid
string
prob_desc_notes
string
prob_desc_description
string
prob_desc_output_spec
string
prob_desc_input_spec
string
prob_desc_output_to
string
prob_desc_input_from
string
lang
string
lang_cluster
string
difficulty
int64
file_name
string
code_uid
string
prob_desc_memory_limit
string
prob_desc_sample_inputs
string
exec_outcome
string
source_code
string
prob_desc_created_at
string
tags
sequence
hidden_unit_tests
string
2 seconds
["2\n2 4\n3 3\n3 1"]
591372383cf3624f69793c41370022de
null
Numbers $$$1, 2, 3, \dots n$$$ (each integer from $$$1$$$ to $$$n$$$ once) are written on a board. In one operation you can erase any two numbers $$$a$$$ and $$$b$$$ from the board and write one integer $$$\frac{a + b}{2}$$$ rounded up instead.You should perform the given operation $$$n - 1$$$ times and make the resulting number that will be left on the board as small as possible. For example, if $$$n = 4$$$, the following course of action is optimal: choose $$$a = 4$$$ and $$$b = 2$$$, so the new number is $$$3$$$, and the whiteboard contains $$$[1, 3, 3]$$$; choose $$$a = 3$$$ and $$$b = 3$$$, so the new number is $$$3$$$, and the whiteboard contains $$$[1, 3]$$$; choose $$$a = 1$$$ and $$$b = 3$$$, so the new number is $$$2$$$, and the whiteboard contains $$$[2]$$$. It's easy to see that after $$$n - 1$$$ operations, there will be left only one number. Your goal is to minimize it.
For each test case, in the first line, print the minimum possible number left on the board after $$$n - 1$$$ operations. Each of the next $$$n - 1$$$ lines should contain two integersΒ β€” numbers $$$a$$$ and $$$b$$$ chosen and erased in each operation.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β€” the number of test cases. The only line of each test case contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$)Β β€” the number of integers written on the board initially. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.
standard output
standard input
Python 3
Python
1,000
train_000.jsonl
88084dde61bbebdebe163309a2bda179
256 megabytes
["1\n4"]
PASSED
def ii(): return int(input()) def mi(): return map(int, input().split()) if __name__ == '__main__': for _ in range(ii()): n = ii() # if n == 3: # print("2\n3 1\n2 2") # continue if n == 2: print("2\n2 1") continue l = list(range(1, n+1)) a = l.pop() answer = [] b = l.pop(-2) answer.append((a, b)) a = int((a + b) / 2) while l: b = l.pop() answer.append((a, b)) a = int((a + b) / 2) print(a) for i in answer: print(*i)
1602407100
[ "greedy", "constructive algorithms", "math", "implementation", "data structures" ]
3 seconds
["4\n10\n4\n0"]
afcd41492158e68095b01ff1e88c3dd4
NoteIn the first test case of the example, the optimal sequence of moves can be as follows: before making moves $$$a=[40, 6, 40, 3, 20, 1]$$$; choose $$$c=6$$$; now $$$a=[40, 3, 40, 3, 20, 1]$$$; choose $$$c=40$$$; now $$$a=[20, 3, 20, 3, 20, 1]$$$; choose $$$c=20$$$; now $$$a=[10, 3, 10, 3, 10, 1]$$$; choose $$$c=10$$$; now $$$a=[5, 3, 5, 3, 5, 1]$$$ β€” all numbers are odd. Thus, all numbers became odd after $$$4$$$ moves. In $$$3$$$ or fewer moves, you cannot make them all odd.
There are $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$. For the one move you can choose any even value $$$c$$$ and divide by two all elements that equal $$$c$$$.For example, if $$$a=[6,8,12,6,3,12]$$$ and you choose $$$c=6$$$, and $$$a$$$ is transformed into $$$a=[3,8,12,3,3,12]$$$ after the move.You need to find the minimal number of moves for transforming $$$a$$$ to an array of only odd integers (each element shouldn't be divisible by $$$2$$$).
For $$$t$$$ test cases print the answers in the order of test cases in the input. The answer for the test case is the minimal number of moves needed to make all numbers in the test case odd (i.e. not divisible by $$$2$$$).
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of a test case contains $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) β€” the number of integers in the sequence $$$a$$$. The second line contains positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). The sum of $$$n$$$ for all test cases in the input doesn't exceed $$$2\cdot10^5$$$.
standard output
standard input
Python 3
Python
1,200
train_000.jsonl
df0e2ae03513f2b9280e19a1df6c8d84
256 megabytes
["4\n6\n40 6 40 3 20 1\n1\n1024\n4\n2 4 8 16\n3\n3 1 7"]
PASSED
a = int(input()) for i in range(a): f = int(input()) k = list(map(int, input().split())) l = set() ch = 0 lol = 0 for i in range(len(k)): lol = k[i] while lol % 2 == 0: l.add(lol) lol /= 2 print(len(l))
1576321500
[ "number theory", "greedy" ]
2 seconds
["5", "16", "18"]
e52ec2fa5bcf5d2027d57b0694b4e15a
NoteIn 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.
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.
Print one integer β€” the minimum number of coins you have to pay to make the graph connected.
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le m \le 2 \cdot 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, \dots, a_n$$$ ($$$1 \le a_i \le 10^{12}$$$) β€” the numbers written on the vertices. Then $$$m$$$ lines follow, each containing three integers $$$x$$$, $$$y$$$ and $$$w$$$ ($$$1 \le x, y \le n$$$, $$$1 \le w \le 10^{12}$$$, $$$x \ne y$$$) denoting a special offer: you may add an edge connecting vertex $$$x$$$ and vertex $$$y$$$, and this edge will cost $$$w$$$ coins.
standard output
standard input
Python 3
Python
1,900
train_000.jsonl
d045b0ecd6aaad78a2574780f55d22a1
256 megabytes
["3 2\n1 3 3\n2 3 5\n2 1 1", "4 0\n1 3 3 7", "5 4\n1 2 3 4 5\n1 2 8\n1 3 10\n1 4 7\n1 5 15"]
PASSED
def read_nums(): return [int(x) for x in input().split()] class UnionFind: def __init__(self, size): self._parents = list(range(size)) # number of elements rooted at i self._sizes = [1 for _ in range(size)] def _root(self, a): while a != self._parents[a]: self._parents[a] = self._parents[self._parents[a]] a = self._parents[a] return a def find(self, a, b): return self._root(a) == self._root(b) def union(self, a, b): a, b = self._root(a), self._root(b) if self._sizes[a] < self._sizes[b]: self._parents[a] = b self._sizes[b] += self._sizes[a] else: self._parents[b] = a self._sizes[a] += self._sizes[b] def count_result(num_vertex, edges): uf = UnionFind(num_vertex) res = 0 for start, end, cost in edges: if uf.find(start, end): continue else: uf.union(start, end) res += cost return res def main(): n, m = read_nums() vertex_nums = read_nums() edges = [] for i in range(m): nums = read_nums() nums[0] -= 1 nums[1] -= 1 edges.append(nums) min_index = min([x for x in zip(vertex_nums, range(n))], key=lambda x: x[0])[1] for i in range(n): if i != min_index: edges.append((min_index, i, vertex_nums[min_index] + vertex_nums[i])) edges = sorted(edges, key=lambda x: x[2]) print(count_result(n, edges)) if __name__ == '__main__': main()
1545921300
[ "dsu", "greedy", "graphs" ]
1 second
["2\n5000 9\n1\n7 \n4\n800 70 6 9000 \n1\n10000 \n1\n10"]
cd2519f4a7888b2c292f05c64a9db13a
null
A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from $$$1$$$ to $$$9$$$ (inclusive) are round.For example, the following numbers are round: $$$4000$$$, $$$1$$$, $$$9$$$, $$$800$$$, $$$90$$$. The following numbers are not round: $$$110$$$, $$$707$$$, $$$222$$$, $$$1001$$$.You are given a positive integer $$$n$$$ ($$$1 \le n \le 10^4$$$). Represent the number $$$n$$$ as a sum of round numbers using the minimum number of summands (addends). In other words, you need to represent the given number $$$n$$$ as a sum of the least number of terms, each of which is a round number.
Print $$$t$$$ answers to the test cases. Each answer must begin with an integer $$$k$$$ β€” the minimum number of summands. Next, $$$k$$$ terms must follow, each of which is a round number, and their sum is $$$n$$$. The terms can be printed in any order. If there are several answers, print any of them.
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is a line containing an integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
standard output
standard input
PyPy 3
Python
800
train_000.jsonl
52a2313fac7f87cb6696ab7b8e4dc447
256 megabytes
["5\n5009\n7\n9876\n10000\n10"]
PASSED
t = int(input()) for i in range(t): canPrintLength = True summends = [] num = int(input()) if num in range(1,11): print(1) print(num) else: a = 10 g = str(num) length = len(g) while num!=0: rem = num%a if rem !=0: summends.append(rem) a*=10 num-=rem else: a*=10 pass if canPrintLength==True: print(str(len(summends))) print(*summends)
1590154500
[ "implementation", "math" ]
1 second
["9", "14"]
d7fe15a027750c004e4f50175e1e20d2
null
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands: Include a person to the chat ('Add' command). Remove a person from the chat ('Remove' command). Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command). Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.As Polycarp has no time, he is asking for your help in solving this problem.
Print a single number β€” answer to the problem.
Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following: +&lt;name&gt; for 'Add' command. -&lt;name&gt; for 'Remove' command. &lt;sender_name&gt;:&lt;message_text&gt; for 'Send' command. &lt;name&gt; and &lt;sender_name&gt; is a non-empty sequence of Latin letters and digits. &lt;message_text&gt; can contain letters, digits and spaces, but can't start or end with a space. &lt;message_text&gt; can be an empty line. It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc. All names are case-sensitive.
standard output
standard input
Python 2
Python
1,000
train_005.jsonl
68e7ea5367d538b53e8e36e804665b20
64 megabytes
["+Mike\nMike:hello\n+Kate\n+Dmitry\n-Dmitry\nKate:hi\n-Kate", "+Mike\n-Mike\n+Mike\nMike:Hi I am here\n-Mike\n+Kate\n-Kate"]
PASSED
import sys z=x=0 for s in sys.stdin: if s[0]=='+': x+=1 elif s[0]=='-': x-=1 else: z+=(len(s)-s.find(':')-2)*x print z
1269100800
[ "implementation" ]
1 second
["1", "0"]
a34f2aa89fe0e78b495b20400d73acf1
NoteThe first test case corresponds to the tree shown in the statement. As we have seen before, we can transform the tree into a star with center at vertex $$$5$$$ by applying a single operation to vertices $$$2$$$, $$$4$$$, and $$$5$$$.In the second test case, the given tree is already a star with the center at vertex $$$4$$$, so no operations have to be performed.
You are given a tree with $$$n$$$ vertices. You are allowed to modify the structure of the tree through the following multi-step operation: Choose three vertices $$$a$$$, $$$b$$$, and $$$c$$$ such that $$$b$$$ is adjacent to both $$$a$$$ and $$$c$$$. For every vertex $$$d$$$ other than $$$b$$$ that is adjacent to $$$a$$$, remove the edge connecting $$$d$$$ and $$$a$$$ and add the edge connecting $$$d$$$ and $$$c$$$. Delete the edge connecting $$$a$$$ and $$$b$$$ and add the edge connecting $$$a$$$ and $$$c$$$. As an example, consider the following tree: The following diagram illustrates the sequence of steps that happen when we apply an operation to vertices $$$2$$$, $$$4$$$, and $$$5$$$: It can be proven that after each operation, the resulting graph is still a tree.Find the minimum number of operations that must be performed to transform the tree into a star. A star is a tree with one vertex of degree $$$n - 1$$$, called its center, and $$$n - 1$$$ vertices of degree $$$1$$$.
Print a single integer Β β€” the minimum number of operations needed to transform the tree into a star. It can be proven that under the given constraints, it is always possible to transform the tree into a star using at most $$$10^{18}$$$ operations.
The first line contains an integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) Β β€” the number of vertices in the tree. The $$$i$$$-th of the following $$$n - 1$$$ lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \neq v_i$$$) denoting that there exists an edge connecting vertices $$$u_i$$$ and $$$v_i$$$. It is guaranteed that the given edges form a tree.
standard output
standard input
PyPy 3
Python
2,800
train_005.jsonl
62ef7edca328924e63757b39c5d42156
256 megabytes
["6\n4 5\n2 6\n3 2\n1 2\n2 4", "4\n2 4\n4 1\n3 4"]
PASSED
import sys from collections import defaultdict def rl(): return sys.stdin.readline().strip() def BFS(s,nbrs): level = defaultdict(int) ind = 0 level[ind] += 1 frontier = [s] visited = {s} while frontier: next = [] ind += 1 for u in frontier: for v in nbrs[u]: if v not in visited: next.append(v) visited.add(v) level[ind] += 1 frontier = next return level n = int(rl()) vert = [] nbrs = defaultdict(list) for i in range(n-1): vert.append(list(map(int,rl().split()))) j = vert[-1][0] k = vert[-1][1] nbrs[j].append(k) nbrs[k].append(j) new = 0 counter = BFS(1,nbrs) for i in range(2,n-1,2): new += counter[i] ans = min(n-2-new,new) print(ans)
1593873900
[ "graphs", "constructive algorithms", "graph matchings", "dfs and similar", "trees", "brute force" ]
2 seconds
["0.320000000000", "1.000000000000"]
5d76ec741a9d873ce9d7c3ef55eb984c
NoteConsider that [a, b] denotes an interval of integers; this interval includes the boundaries. That is, In first case there are 32 suitable pairs: (1, 7), (1, 8), (1, 9), (1, 10), (2, 7), (2, 8), (2, 9), (2, 10), (3, 7), (3, 8), (3, 9), (3, 10), (4, 7), (4, 8), (4, 9), (4, 10), (7, 1), (7, 2), (7, 3), (7, 4), (8, 1), (8, 2), (8, 3), (8, 4), (9, 1), (9, 2), (9, 3), (9, 4), (10, 1), (10, 2), (10, 3), (10, 4). Total number of possible pairs is 10Β·10 = 100, so answer is 32 / 100.In second case Petya always get number less than Vasya and the only lucky 7 is between this numbers, so there will be always 1 lucky number.
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya and his friend Vasya play an interesting game. Petya randomly chooses an integer p from the interval [pl, pr] and Vasya chooses an integer v from the interval [vl, vr] (also randomly). Both players choose their integers equiprobably. Find the probability that the interval [min(v, p), max(v, p)] contains exactly k lucky numbers.
On the single line print the result with an absolute error of no more than 10 - 9.
The single line contains five integers pl, pr, vl, vr and k (1 ≀ pl ≀ pr ≀ 109, 1 ≀ vl ≀ vr ≀ 109, 1 ≀ k ≀ 1000).
standard output
standard input
Python 2
Python
1,900
train_005.jsonl
7794c865344b2dcd8d5a6cff3c092176
256 megabytes
["1 10 1 10 2", "5 6 8 10 1"]
PASSED
pl,pr,vl,vr,k=map(int,raw_input().split()) def conv(x): t=0 while x>1: t=t*10+(7 if x&1 else 4) x>>=1 return t a=filter(lambda x: x>=min(pl,vl) and x<=max(pr,vr),[conv(x) for x in xrange(2,1<<11)]) a.sort() n,s=len(a),0 a+=[10**10] def size(a,b,c,d): return max(0,min(b,d)-max(a,c)+1) for i in xrange(n-k+1): p1=a[i-1]+1 if i>0 else 1 p2=a[i] v1,v2=a[i+k-1],a[i+k]-1 s+=size(p1,p2,pl,pr)*size(v1,v2,vl,vr) s+=size(p1,p2,vl,vr)*size(v1,v2,pl,pr) if 1==k and pl<=p2<=pr and vl<=p2<=vr:s-=1 print s/1.0/(pr-pl+1)/(vr-vl+1)
1314633600
[ "probabilities", "brute force" ]
1 second
["2 2 3", "1 2 3"]
c0abbbf1cf6c8ec11e942cdaaf01ad7c
NoteThe picture corresponds to the first example test case. When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.
For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.
The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$)Β β€” the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.
standard output
standard input
Python 3
Python
1,000
train_005.jsonl
a445d878254a8a26ec3ab50321e403b2
256 megabytes
["3\n2 3 2", "3\n1 2 3"]
PASSED
def solve(arr, n): ans = "" for i in range(1, n+1): holes = [0] * (n+1) holes[i] = 1 j = i while holes[j] < 2: j = arr[j] holes[j] += 1 ans += str(j) + " " print(ans) # Main def main(): n = int(input()) arr = list(map(int, input().split())) arr2 = [0] arr2.extend(arr) solve(arr2, n) # end main # Program Start if __name__ == "__main__": main()
1533994500
[ "dfs and similar", "brute force", "graphs" ]
2 seconds
["1\n5", "2\n4 5"]
2ac69434cc4a1c78b537d365b895a27e
NoteIn the first sample, if you shut down road 5, all cities can still reach a police station within k = 4 kilometers.In the second sample, although this is the only largest valid set of roads that can be shut down, you can print either 4 5 or 5 4 in the second line.
Inzane finally found Zane with a lot of money to spare, so they together decided to establish a country of their own.Ruling a country is not an easy job. Thieves and terrorists are always ready to ruin the country's peace. To fight back, Zane and Inzane have enacted a very effective law: from each city it must be possible to reach a police station by traveling at most d kilometers along the roads. There are n cities in the country, numbered from 1 to n, connected only by exactly n - 1 roads. All roads are 1 kilometer long. It is initially possible to travel from a city to any other city using these roads. The country also has k police stations located in some cities. In particular, the city's structure satisfies the requirement enforced by the previously mentioned law. Also note that there can be multiple police stations in one city.However, Zane feels like having as many as n - 1 roads is unnecessary. The country is having financial issues, so it wants to minimize the road maintenance cost by shutting down as many roads as possible.Help Zane find the maximum number of roads that can be shut down without breaking the law. Also, help him determine such roads.
In the first line, print one integer s that denotes the maximum number of roads that can be shut down. In the second line, print s distinct integers, the indices of such roads, in any order. If there are multiple answers, print any of them.
The first line contains three integers n, k, and d (2 ≀ n ≀ 3Β·105, 1 ≀ k ≀ 3Β·105, 0 ≀ d ≀ n - 1)Β β€” the number of cities, the number of police stations, and the distance limitation in kilometers, respectively. The second line contains k integers p1, p2, ..., pk (1 ≀ pi ≀ n)Β β€” each denoting the city each police station is located in. The i-th of the following n - 1 lines contains two integers ui and vi (1 ≀ ui, vi ≀ n, ui ≠ vi)Β β€” the cities directly connected by the road with index i. It is guaranteed that it is possible to travel from one city to any other city using only the roads. Also, it is possible from any city to reach a police station within d kilometers.
standard output
standard input
PyPy 3
Python
2,100
train_005.jsonl
3616665694df775684c1c7644e6ef776
256 megabytes
["6 2 4\n1 6\n1 2\n2 3\n3 4\n4 5\n5 6", "6 3 2\n1 5 6\n1 2\n1 3\n1 4\n1 5\n5 6"]
PASSED
import math import sys input = sys.stdin.readline inf = int(1e9) n, m, d = map(int, input().split()) l = [0] * (n - 1) r = [0] * (n - 1) g = [[] for _ in range(n)] station = [int(_) - 1 for _ in input().split()] for i in range(n - 1): l[i], r[i] = map(lambda i : int(i) - 1 , input().split()) g[l[i]].append(i) g[r[i]].append(i) queue = [] dist = [inf] * n need = [True] * (n - 1) for i in station: queue.append(i) dist[i] = 0 cur = 0 while cur < len(queue): x, cur = queue[cur], cur + 1 for edge in g[x]: y = l[edge] ^ r[edge] ^ x if dist[y] > 1 + dist[x]: dist[y] = 1 + dist[x] queue.append(y) need[edge] = False print(sum(need)) edgeList = [] for i in range(n - 1): if need[i]: edgeList.append(str(i + 1)) print(' '.join(edgeList))
1491842100
[ "dp", "graphs", "constructive algorithms", "shortest paths", "dfs and similar", "trees" ]
1 second
["5", "-1", "1"]
cd6bc23ea61c43b38c537f9e04ad11a6
NoteIn the first example it is needed to paint 5 cells β€” (2, 2), (2, 3), (3, 2), (3, 3) and (4, 2). Then there will be a square with side equal to three, and the upper left corner in (2, 2).In the second example all the cells are painted black and form a rectangle, so it's impossible to get a square.In the third example all cells are colored white, so it's sufficient to color any cell black.
Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.You are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. The square's side should have positive length.
Print the minimum number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. If it is impossible, print -1.
The first line contains two integers n and m (1 ≀ n, m ≀ 100) β€” the sizes of the sheet. The next n lines contain m letters 'B' or 'W' each β€” the description of initial cells' colors. If a letter is 'B', then the corresponding cell is painted black, otherwise it is painted white.
standard output
standard input
PyPy 2
Python
1,300
train_005.jsonl
a815decba7bf44e3450e2938e132cec0
256 megabytes
["5 4\nWWWW\nWWWB\nWWWB\nWWBB\nWWWW", "1 2\nBB", "3 3\nWWW\nWWW\nWWW"]
PASSED
from sys import stdin n, m = map(int, stdin.readline().strip().split()) u = float('inf') d = -float('inf') l = float('inf') r = -float('inf') num_blacks = 0 for i in xrange(n): row = stdin.readline().strip() for j in xrange(m): if row[j] == 'B': if i <= u: u = i if i >= d: d = i if j <= l: l = j if j >= r: r = j num_blacks += 1 if num_blacks == 0: print 1 else: s = max(d-u, r-l)+1 if s > m or s > n: print -1 else: print s*s - num_blacks
1499791500
[ "implementation" ]
1 second
["1\n2\n1 3", "0", "1\n4\n1 2 5 6"]
f78d04f699fc94103e5b08023949854d
NoteIn the first sample, the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '(((', and no more operations can be performed on it. Another valid answer is choosing indices $$$2$$$ and $$$3$$$, which results in the same final string.In the second sample, it is already impossible to perform any operations.
Now that Kuroni has reached 10 years old, he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by $$$n$$$ characters '(' or ')' is simple if its length $$$n$$$ is even and positive, its first $$$\frac{n}{2}$$$ characters are '(', and its last $$$\frac{n}{2}$$$ characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
In the first line, print an integer $$$k$$$ Β β€” the minimum number of operations you have to apply. Then, print $$$2k$$$ lines describing the operations in the following format: For each operation, print a line containing an integer $$$m$$$ Β β€” the number of characters in the subsequence you will remove. Then, print a line containing $$$m$$$ integers $$$1 \le a_1 &lt; a_2 &lt; \dots &lt; a_m$$$ Β β€” the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string. If there are multiple valid sequences of operations with the smallest $$$k$$$, you may print any of them.
The only line of input contains a string $$$s$$$ ($$$1 \le |s| \le 1000$$$) formed by characters '(' and ')', where $$$|s|$$$ is the length of $$$s$$$.
standard output
standard input
Python 3
Python
1,200
train_005.jsonl
a1c2ac3f5608d4165a7ebd50c2047367
256 megabytes
["(()((", ")(", "(()())"]
PASSED
s = input() a = [] i = 0 j = len(s) - 1 while i < j: while i < j and s[i] != '(': i += 1 while i < j and s[j] != ')': j -= 1 if i < j and s[i] == '(' and s[j] == ')': a.append(i + 1) a.append(j + 1) i += 1 j -= 1 if a: print(1) print(len(a)) print(*sorted(a)) else: print(0)
1583246100
[ "constructive algorithms", "two pointers", "greedy", "strings" ]
0.5 seconds
["50", "110", "0"]
9b1b082319d045cf0ec6d124f97a8184
NoteIn sample 1 numbers 10 and 1 are beautiful, number 5 is not not.In sample 2 number 11 is not beautiful (contains two '1's), all others are beautiful.In sample 3 number 3 is not beautiful, all others are beautiful.
It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse!There are exactly n distinct countries in the world and the i-th country added ai tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful.Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case.
Print a single number without leading zeroesΒ β€” the product of the number of tanks presented by each country.
The first line of the input contains the number of countries n (1 ≀ n ≀ 100 000). The second line contains n non-negative integers ai without leading zeroesΒ β€” the number of tanks of the i-th country. It is guaranteed that the second line contains at least n - 1 beautiful numbers and the total length of all these number's representations doesn't exceed 100 000.
standard output
standard input
PyPy 3
Python
1,400
train_005.jsonl
31da23fc0f4086926cd12c10c0062e82
256 megabytes
["3\n5 10 1", "4\n1 1 10 11", "5\n0 3 1 100 1"]
PASSED
def check(string): if len(string) == 1: return string[0] != '1' if string[0] != '1': return True if any(s != '0' for s in string[1:]): return True return False if __name__ == "__main__": n = int(input()) if n == 1: print(input()) exit(0) tanks = [str(x) for x in input().split(' ')] for x in tanks: if x == '0': print(0) exit(0) not_b = '1' for i in range(n): if check(tanks[i]): not_b = tanks[i] tanks[i] = '_' break result = [not_b] for i, x in enumerate(tanks): if x != '_': result.append('0' * (len(x) - 1)) print(''.join(result))
1452789300
[ "implementation", "math" ]
1 second
["next 0 5\n\nnext 0 1 3\n\nnext 2 3 0 1 4 5 6 7 8 9\n\nnext 9 8 7 6 5 4 3 2 1 0\n\nnext 0 1 3 5\n\nnext 1 3 5\n\ndone"]
b2ea06e06e60adf88e601f1164c360cd
NoteIn the sample input and output values are aligned only for simplicity of interpreting them chronologically. In real interaction no "extra" line breaks should appear.In the example, the friends move as follows:
This is an interactive problem.Misha likes to play cooperative games with incomplete information. Today he suggested ten his friends to play a cooperative game "Lake".Misha has already come up with a field for the upcoming game. The field for this game is a directed graph consisting of two parts. The first part is a road along the coast of the lake which is a cycle of $$$c$$$ vertices. The second part is a path from home to the lake which is a chain of $$$t$$$ vertices, and there is an edge from the last vertex of this chain to the vertex of the road along the coast which has the most beautiful view of the lake, also known as the finish vertex. Misha decided to keep the field secret, so nobody knows neither $$$t$$$ nor $$$c$$$. Note that each vertex of the field has exactly one outgoing edge and all the vertices except the home vertex and the finish vertex have exactly one ingoing edge. The home vertex has no incoming edges, the finish vertex has two incoming edges.At the beginning of the game pieces of all the ten players, indexed with consecutive integers from $$$0$$$ to $$$9$$$, are at the home vertex. After that on each turn some of the players can ask Misha to simultaneously move their pieces along the corresponding edges. Misha will not answer more than $$$q$$$ such queries. After each move Misha will tell players whose pieces are at the same vertices and whose pieces are at different vertices.The goal of the game is to move all the pieces to the finish vertex. Misha's friends have no idea how to win in such a game without knowledge of $$$c$$$, $$$t$$$ and $$$q$$$, but luckily they are your friends. Help them: coordinate their actions to win the game. Misha has drawn such a field that $$$1 \le t, c$$$, $$$(t+c) \leq 1000$$$ and $$$q = 3 \cdot (t+c)$$$.
After all friends gather at the finish vertex, print "done" and terminate your program.
There is no inputΒ β€” go to the interaction part straight away.
standard output
standard input
Python 3
Python
2,400
train_005.jsonl
558180b38fec1d385946c85d20d5831b
512 megabytes
["2 05 12346789\n\n3 246789 135 0\n\n3 246789 0 135\n\n3 246789 0 135\n\n2 135 0246789\n\n1 0123456789"]
PASSED
def move(s): print('next', s) return int(input().split()[0]) while 1: move('0 1') if move('1') == 2: break while 1: if move('0 1 2 3 4 5 6 7 8 9') == 1: break print('done')
1552035900
[ "constructive algorithms", "number theory", "interactive" ]
2 seconds
["2.000000000", "1.909090909"]
9fd09b05d0e49236dca45615e684ad85
null
It is well known that the planet suffers from the energy crisis. Little Petya doesn't like that and wants to save the world. For this purpose he needs every accumulator to contain the same amount of energy. Initially every accumulator has some amount of energy: the i-th accumulator has ai units of energy. Energy can be transferred from one accumulator to the other. Every time x units of energy are transferred (x is not necessarily an integer) k percent of it is lost. That is, if x units were transferred from one accumulator to the other, amount of energy in the first one decreased by x units and in other increased by units.Your task is to help Petya find what maximum equal amount of energy can be stored in each accumulator after the transfers.
Output maximum possible amount of energy that can remain in each of accumulators after the transfers of energy. The absolute or relative error in the answer should not exceed 10 - 6.
First line of the input contains two integers n and k (1 ≀ n ≀ 10000, 0 ≀ k ≀ 99) β€” number of accumulators and the percent of energy that is lost during transfers. Next line contains n integers a1, a2, ... , an β€” amounts of energy in the first, second, .., n-th accumulator respectively (0 ≀ ai ≀ 1000, 1 ≀ i ≀ n).
standard output
standard input
Python 3
Python
1,600
train_005.jsonl
81dae1504f89a8495a69d5025ce6df25
256 megabytes
["3 50\n4 2 1", "2 90\n1 11"]
PASSED
n, k = map(int, input().split()) A = list(map(int, input().split())) def f(x): over = 0 need = 0 for a in A: if a > x: over += (a - x) else: need += (x - a) return need <= (over * (1 - k/100)) left = 0 right = 1000 while right - left > 1e-12: m = (left + right) / 2 if f(m): left = m else: right = m print(round(right, 8))
1300464000
[ "binary search" ]
2 seconds
["YES", "NO"]
98f5b6aac08f48f95b2a8ce0738de657
NoteIn the first sample Kirito's strength initially equals 2. As the first dragon's strength is less than 2, Kirito can fight it and defeat it. After that he gets the bonus and his strength increases to 2 + 99 = 101. Now he can defeat the second dragon and move on to the next level.In the second sample Kirito's strength is too small to defeat the only dragon and win.
Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito's strength equals s.If Kirito starts duelling with the i-th (1 ≀ i ≀ n) dragon and Kirito's strength is not greater than the dragon's strength xi, then Kirito loses the duel and dies. But if Kirito's strength is greater than the dragon's strength, then he defeats the dragon and gets a bonus strength increase by yi.Kirito can fight the dragons in any order. Determine whether he can move on to the next level of the game, that is, defeat all dragons without a single loss.
On a single line print "YES" (without the quotes), if Kirito can move on to the next level and print "NO" (without the quotes), if he can't.
The first line contains two space-separated integers s and n (1 ≀ s ≀ 104, 1 ≀ n ≀ 103). Then n lines follow: the i-th line contains space-separated integers xi and yi (1 ≀ xi ≀ 104, 0 ≀ yi ≀ 104) β€” the i-th dragon's strength and the bonus for defeating it.
standard output
standard input
Python 2
Python
1,000
train_000.jsonl
90ce033e902d98d9883c4706938b4caf
256 megabytes
["2 2\n1 99\n100 0", "10 1\n100 100"]
PASSED
def test(s): lines = s.split("\n") s, n = tuple(map(int,lines[0].split())) li_x = [] li_y = [] for i in range(1,n+1): x, y =tuple(map(int,lines[i].split())) li_x.append(x) li_y.append(y) lt_both = zip(li_x, li_y) lt_both = sorted(lt_both) for x, y in lt_both: #print s, x if s <= x: print 'NO' return s += y print 'YES' s_all = '' while True: try: s_all += (raw_input()) + '\n' except: break test(s_all)
1349105400
[ "sortings", "greedy" ]
1 second
["YES", "NO", "YES"]
cf595689b5cbda4f1d629524ad275650
NoteIn the first sample, one can split words into syllables in the following way: in-telco-dech al-len-geSince the word "ch" in the third line doesn't contain vowels, we can ignore it. As the result we get 2 syllabels in first two lines and 3 syllables in the third one.
You are given a text consisting of n lines. Each line contains some space-separated words, consisting of lowercase English letters.We define a syllable as a string that contains exactly one vowel and any arbitrary number (possibly none) of consonants. In English alphabet following letters are considered to be vowels: 'a', 'e', 'i', 'o', 'u' and 'y'.Each word of the text that contains at least one vowel can be divided into syllables. Each character should be a part of exactly one syllable. For example, the word "mamma" can be divided into syllables as "ma" and "mma", "mam" and "ma", and "mamm" and "a". Words that consist of only consonants should be ignored.The verse patterns for the given text is a sequence of n integers p1, p2, ..., pn. Text matches the given verse pattern if for each i from 1 to n one can divide words of the i-th line in syllables in such a way that the total number of syllables is equal to pi.You are given the text and the verse pattern. Check, if the given text matches the given verse pattern.
If the given text matches the given verse pattern, then print "YES" (without quotes) in the only line of the output. Otherwise, print "NO" (without quotes).
The first line of the input contains a single integer n (1 ≀ n ≀ 100)Β β€” the number of lines in the text. The second line contains integers p1, ..., pn (0 ≀ pi ≀ 100)Β β€” the verse pattern. Next n lines contain the text itself. Text consists of lowercase English letters and spaces. It's guaranteed that all lines are non-empty, each line starts and ends with a letter and words are separated by exactly one space. The length of each line doesn't exceed 100 characters.
standard output
standard input
Python 3
Python
1,200
train_005.jsonl
e2cf6d7c279000f896ce0e7195209d5c
256 megabytes
["3\n2 2 3\nintel\ncode\nch allenge", "4\n1 2 3 1\na\nbcdefghi\njklmnopqrstu\nvwxyz", "4\n13 11 15 15\nto be or not to be that is the question\nwhether tis nobler in the mind to suffer\nthe slings and arrows of outrageous fortune\nor to take arms against a sea of troubles"]
PASSED
n=int(input()) patterns=list(map(int,input().split())) texts=[] for i in range(n): texts.append(input().split()) test=True for i in range(n): pattern=patterns[i] text=texts[i] voyels=0 for ch in text: voyels+=ch.count("a")+ch.count("e")+ch.count("i")+ch.count("o")+ch.count("u")+ch.count("y") if voyels!=pattern: test=False break if test: print("YES") else: print("NO")
1475330700
[ "implementation", "strings" ]
1 second
["YES\n1 2 1", "YES\n2 3 2 1 2"]
f097cc7057bb9a6b9fc1d2a11ee99835
null
Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from $$$1$$$ to $$$n$$$. Each of its vertices also has an integer $$$a_i$$$ written on it. For each vertex $$$i$$$, Evlampiy calculated $$$c_i$$$Β β€” the number of vertices $$$j$$$ in the subtree of vertex $$$i$$$, such that $$$a_j &lt; a_i$$$. Illustration for the second example, the first integer is $$$a_i$$$ and the integer in parentheses is $$$c_i$$$After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of $$$c_i$$$, but he completely forgot which integers $$$a_i$$$ were written on the vertices.Help him to restore initial integers!
If a solution exists, in the first line print "YES", and in the second line output $$$n$$$ integers $$$a_i$$$ $$$(1 \leq a_i \leq {10}^{9})$$$. If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all $$$a_i$$$ are between $$$1$$$ and $$$10^9$$$. If there are no solutions, print "NO".
The first line contains an integer $$$n$$$ $$$(1 \leq n \leq 2000)$$$ β€” the number of vertices in the tree. The next $$$n$$$ lines contain descriptions of vertices: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$0 \leq p_i \leq n$$$; $$$0 \leq c_i \leq n-1$$$), where $$$p_i$$$ is the parent of vertex $$$i$$$ or $$$0$$$ if vertex $$$i$$$ is root, and $$$c_i$$$ is the number of vertices $$$j$$$ in the subtree of vertex $$$i$$$, such that $$$a_j &lt; a_i$$$. It is guaranteed that the values of $$$p_i$$$ describe a rooted tree with $$$n$$$ vertices.
standard output
standard input
Python 3
Python
1,800
train_005.jsonl
e90e7a54127337b2cce02c51de519a8e
256 megabytes
["3\n2 0\n0 2\n2 0", "5\n0 1\n1 3\n2 1\n3 0\n2 0"]
PASSED
# https://codeforces.com/contest/1287/problem/D def push(g, u, v): if u not in g: g[u] = [] g[u].append(v) def build(): S = [root] i = 0 order = {} while i < len(S): u = S[i] if u in g: for v in g[u]: S.append(v) i+=1 for u in S[::-1]: order[u] = [] flg=False if u not in g: if cnt[u]==0: order[u].append(u) flg=True else: return False, root, order else: cur = 0 for v in g[u]: for x in order[v]: if cur==cnt[u]: flg=True order[u].append(u) cur+=1 order[u].append(x) cur+=1 if flg == False: if cnt[u] > len(order[u]): return False, root, order else: order[u].append(u) return True, root, order n = int(input()) g = {} cnt = {} for i in range(1, n+1): p, c = map(int, input().split()) cnt[i] = c if p==0: root = i else: push(g, p, i) flg, root, order = build() if flg==False: print('NO') else: ans = [-1] * n for val, u in zip(list(range(n)), order[root]): ans[u-1] = val + 1 print('YES') print(' '.join([str(x) for x in ans])) #5 #0 1 #1 3 #2 1 #3 0 #2 0 #3 #2 0 #0 2 #2 0
1578233100
[ "graphs", "constructive algorithms", "data structures", "dfs and similar", "trees" ]
2 seconds
["0\n4\n1\n5"]
80a03e6d513f4051175cd5cd1dea33b4
NoteOn the first day, Vasiliy won't be able to buy a drink in any of the shops.On the second day, Vasiliy can buy a drink in the shops 1, 2, 3 and 4.On the third day, Vasiliy can buy a drink only in the shop number 1.Finally, on the last day Vasiliy can buy a drink in any shop.
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins.Vasiliy plans to buy his favorite drink for q consecutive days. He knows, that on the i-th day he will be able to spent mi coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of "Beecola".
Print q integers. The i-th of them should be equal to the number of shops where Vasiliy will be able to buy a bottle of the drink on the i-th day.
The first line of the input contains a single integer n (1 ≀ n ≀ 100 000)Β β€” the number of shops in the city that sell Vasiliy's favourite drink. The second line contains n integers xi (1 ≀ xi ≀ 100 000)Β β€” prices of the bottles of the drink in the i-th shop. The third line contains a single integer q (1 ≀ q ≀ 100 000)Β β€” the number of days Vasiliy plans to buy the drink. Then follow q lines each containing one integer mi (1 ≀ mi ≀ 109)Β β€” the number of coins Vasiliy can spent on the i-th day.
standard output
standard input
Python 3
Python
1,100
train_005.jsonl
a8374af63120a761c5ccee08bffd70ec
256 megabytes
["5\n3 10 8 6 11\n4\n1\n10\n3\n11"]
PASSED
from bisect import bisect n = int(input()) f = list(map(int, input().split())) f.sort() q = int(input()) for j in range(q): c = int(input()) print(bisect(f, c) )
1470933300
[ "dp", "binary search", "implementation" ]
3 seconds
["2\n6 3\n0\n\n3\n4 1 7 \n2\n1 4", "6\n18 11 12 1 6 21 \n1\n1 \n1\n3 \n1\n2 \n1\n6 \n0\n\n1\n4 \n0\n\n1\n1 \n2\n1 11"]
9f8660190134606194cdd8db891a3d46
NoteIn the first example, answers are: "onetwone", "testme" β€” Polycarp likes it, there is nothing to remove, "oneoneone", "twotwo". In the second example, answers are: "onetwonetwooneooonetwooo", "two", "one", "twooooo", "ttttwo", "ttwwoo" β€” Polycarp likes it, there is nothing to remove, "ooone", "onnne" β€” Polycarp likes it, there is nothing to remove, "oneeeee", "oneeeeeeetwooooo".
You are given a non-empty string $$$s=s_1s_2\dots s_n$$$, which consists only of lowercase Latin letters. Polycarp does not like a string if it contains at least one string "one" or at least one string "two" (or both at the same time) as a substring. In other words, Polycarp does not like the string $$$s$$$ if there is an integer $$$j$$$ ($$$1 \le j \le n-2$$$), that $$$s_{j}s_{j+1}s_{j+2}=$$$"one" or $$$s_{j}s_{j+1}s_{j+2}=$$$"two".For example: Polycarp does not like strings "oneee", "ontwow", "twone" and "oneonetwo" (they all have at least one substring "one" or "two"), Polycarp likes strings "oonnee", "twwwo" and "twnoe" (they have no substrings "one" and "two"). Polycarp wants to select a certain set of indices (positions) and remove all letters on these positions. All removals are made at the same time.For example, if the string looks like $$$s=$$$"onetwone", then if Polycarp selects two indices $$$3$$$ and $$$6$$$, then "onetwone" will be selected and the result is "ontwne".What is the minimum number of indices (positions) that Polycarp needs to select to make the string liked? What should these positions be?
Print an answer for each test case in the input in order of their appearance. The first line of each answer should contain $$$r$$$ ($$$0 \le r \le |s|$$$) β€” the required minimum number of positions to be removed, where $$$|s|$$$ is the length of the given line. The second line of each answer should contain $$$r$$$ different integers β€” the indices themselves for removal in any order. Indices are numbered from left to right from $$$1$$$ to the length of the string. If $$$r=0$$$, then the second line can be skipped (or you can print empty). If there are several answers, print any of them.
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. Next, the test cases are given. Each test case consists of one non-empty string $$$s$$$. Its length does not exceed $$$1.5\cdot10^5$$$. The string $$$s$$$ consists only of lowercase Latin letters. It is guaranteed that the sum of lengths of all lines for all input data in the test does not exceed $$$1.5\cdot10^6$$$.
standard output
standard input
Python 3
Python
1,400
train_005.jsonl
08cebcfb29f7a688e412b2f8c1b69ba5
256 megabytes
["4\nonetwone\ntestme\noneoneone\ntwotwo", "10\nonetwonetwooneooonetwooo\ntwo\none\ntwooooo\nttttwo\nttwwoo\nooone\nonnne\noneeeee\noneeeeeeetwooooo"]
PASSED
from heapq import heappush,heappop,heapify from collections import deque,defaultdict,Counter import itertools from itertools import permutations,combinations import sys import bisect import string import math import time #import random def I(): return int(input()) def MI(): return map(int,input().split()) def LI(): return [int(i) for i in input().split()] def LI_(): return [int(i)-1 for i in input().split()] def StoI(): return [ord(i)-97 for i in input()] def ItoS(nn): return chr(nn+97) def GI(V,E,Directed=False,index=0): org_inp=[] g=[[] for i in range(n)] for i in range(E): inp=LI() org_inp.append(inp) if index==0: inp[0]-=1 inp[1]-=1 if len(inp)==2: a,b=inp g[a].append(b) if not Directed: g[b].append(a) elif len(inp)==3: a,b,c=inp aa=(inp[0],inp[2]) bb=(inp[1],inp[2]) g[a].append(bb) if not Directed: g[b].append(aa) return g,org_inp def show(*inp,end='\n'): if show_flg: print(*inp,end=end) YN=['Yes','No'] mo=10**9+7 inf=float('inf') l_alp=string.ascii_lowercase u_alp=string.ascii_uppercase #sys.setrecursionlimit(10**5) input=lambda: sys.stdin.readline().rstrip() show_flg=False show_flg=True t=I() for _ in range(t): s=input() n=len(s) ''' import random K=list('twone')+['two','one','twone']*3+['o']*5 n=50 s=''.join([K[random.randint(0,18)] for i in range(n)]) s+=['two','one','twone'][random.randint(0,2)] n=len(s) ''' ans=[] i=0 while i<n: if s[i]=='o': if i<n-1 and s[i+1]=='n': if i<n-2 and s[i+2]=='e': ans+=[i+1 +1] elif s[i]=='t': if i<n-1 and s[i+1]=='w': if i<n-2 and s[i+2]=='o': if i<n-3 and s[i+3]=='n': if i<n-4 and s[i+4]=='e': ans+=[i+2 +1] i=i+4 else: ans+=[i+1 +1] i=i+1 else: ans+=[i+1 +1] i=i+1 i+=1 print(len(ans)) print(*ans) ''' tmp='' for i in range(len(s)): if i+1 not in ans: tmp+=s[i] else: tmp+=' ' if 'two' in ''.join(tmp.split()) or 'one' in ''.join(tmp.split()): print('Error') show(tmp) show(s) #show(s,tmp) '''
1576321500
[ "dp", "greedy" ]
2 seconds
["2", "7"]
e82b6958c45ff4b2c269cebe043d49de
NoteIn the first test case, two good subsequences β€” $$$[a_1, a_2, a_3]$$$ and $$$[a_2, a_3]$$$.In the second test case, seven good subsequences β€” $$$[a_1, a_2, a_3, a_4], [a_1, a_2], [a_1, a_3], [a_1, a_4], [a_2, a_3], [a_2, a_4]$$$ and $$$[a_3, a_4]$$$.
The sequence of integers $$$a_1, a_2, \dots, a_k$$$ is called a good array if $$$a_1 = k - 1$$$ and $$$a_1 &gt; 0$$$. For example, the sequences $$$[3, -1, 44, 0], [1, -99]$$$ are good arrays, and the sequences $$$[3, 7, 8], [2, 5, 4, 1], [0]$$$ β€” are not.A sequence of integers is called good if it can be divided into a positive number of good arrays. Each good array should be a subsegment of sequence and each element of the sequence should belong to exactly one array. For example, the sequences $$$[2, -3, 0, 1, 4]$$$, $$$[1, 2, 3, -3, -9, 4]$$$ are good, and the sequences $$$[2, -3, 0, 1]$$$, $$$[1, 2, 3, -3 -9, 4, 1]$$$ β€” are not.For a given sequence of numbers, count the number of its subsequences that are good sequences, and print the number of such subsequences modulo 998244353.
In the single line output one integer β€” the number of subsequences of the original sequence that are good sequences, taken modulo 998244353.
The first line contains the number $$$n~(1 \le n \le 10^3)$$$ β€” the length of the initial sequence. The following line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n~(-10^9 \le a_i \le 10^9)$$$ β€” the sequence itself.
standard output
standard input
PyPy 3
Python
1,900
train_005.jsonl
55217bb2806f04beb7d63c32a37d4aa4
256 megabytes
["3\n2 1 1", "4\n1 1 1 1"]
PASSED
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") # ------------------------------ from math import factorial from collections import Counter, defaultdict from heapq import heapify, heappop, heappush 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) def ctd(chr): return ord(chr)-ord("a") mod = 998244353 INF = float('inf') # ------------------------------ def main(): n = N() arr = RLL() cb = [[0]*(n+1) for _ in range(n+1)] for i in range(n+1): for j in range(i+1): if j==0 or j==n: cb[i][j] = 1 else: cb[i][j] = (cb[i-1][j]+cb[i-1][j-1])%mod dp = [0]*(n+1) dp[-1] = 1 for i in range(n-1, -1, -1): for j in range(i+1, n+1): if j-1-i>=arr[i] and arr[i]>0: dp[i] += (cb[j-1-i][arr[i]]*dp[j])%mod res = 0 for i in dp[:-1]: res+=i%mod print(res%mod) # 0, 1, 2, 3 # 2, 2, 1 # 3, # i, j-1) j if __name__ == "__main__": main()
1530110100
[ "dp", "combinatorics" ]
2 seconds
["1 0 0 2", "0 0 0 1 0 2 4"]
905df05453a12008fc9247ff4d02e7f0
null
You are given two arrays $$$a$$$ and $$$b$$$, both of length $$$n$$$. All elements of both arrays are from $$$0$$$ to $$$n-1$$$.You can reorder elements of the array $$$b$$$ (if you want, you may leave the order of elements as it is). After that, let array $$$c$$$ be the array of length $$$n$$$, the $$$i$$$-th element of this array is $$$c_i = (a_i + b_i) \% n$$$, where $$$x \% y$$$ is $$$x$$$ modulo $$$y$$$.Your task is to reorder elements of the array $$$b$$$ to obtain the lexicographically minimum possible array $$$c$$$.Array $$$x$$$ of length $$$n$$$ is lexicographically less than array $$$y$$$ of length $$$n$$$, if there exists such $$$i$$$ ($$$1 \le i \le n$$$), that $$$x_i &lt; y_i$$$, and for any $$$j$$$ ($$$1 \le j &lt; i$$$) $$$x_j = y_j$$$.
Print the lexicographically minimum possible array $$$c$$$. Recall that your task is to reorder elements of the array $$$b$$$ and obtain the lexicographically minimum possible array $$$c$$$, where the $$$i$$$-th element of $$$c$$$ is $$$c_i = (a_i + b_i) \% n$$$.
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$, $$$b$$$ and $$$c$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i &lt; n$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$0 \le b_i &lt; n$$$), where $$$b_i$$$ is the $$$i$$$-th element of $$$b$$$.
standard output
standard input
PyPy 2
Python
1,700
train_005.jsonl
6ff3dd847bcdd38ed84193dccb09ebf3
256 megabytes
["4\n0 1 2 1\n3 2 1 1", "7\n2 5 1 5 3 4 3\n2 4 3 5 6 5 1"]
PASSED
#!/usr/bin/env python from __future__ import division, print_function import os import sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip else: _str = str str = lambda x=b"": x if type(x) is bytes else _str(x).encode() class SegmentTree: def __init__(self, data, default=0, func=lambda x, y: max(x, y)): """initialize the segment tree with data""" self._len = _len = len(data) self._size = _size = 1 << (_len - 1).bit_length() self._data = _data = [default] * (2 * _size) self._default = default self._func = func _data[_size:_size + _len] = data for i in reversed(range(_size)): _data[i] = func(_data[2 * i], _data[2 * i + 1]) def __delitem__(self, key): self[key] = self._default def __getitem__(self, key): return self._data[key + self._size] def __setitem__(self, key, value): key += self._size self._data[key] = value key >>= 1 while key: self._data[key] = self._func(self._data[2 * key], self._data[2 * key + 1]) key >>= 1 def __len__(self): return self._len def bisect_left(self, value): i = 1 while i < self._size: i = 2 * i + 1 if value > self._data[2 * i] else 2 * i return i - self._size def bisect_right(self, value): i = 1 while i < self._size: i = 2 * i + 1 if value >= self._data[2 * i] else 2 * i return i - self._size bisect = bisect_right def query(self, begin, end): begin += self._size end += self._size res = self._default while begin < end: if begin & 1: res = self._func(res, self._data[begin]) begin += 1 if end & 1: end -= 1 res = self._func(res, self._data[end]) begin >>= 1 end >>= 1 return res def main(): n = int(readline()) a = map(int, input().split()) b = SegmentTree(sorted(map(int, input().split())), -1) start = 0 for ai in a: idx = b.bisect_left(n - ai) if b[idx] < n - ai: idx = start while b[idx] == -1: idx += 1 start = idx cout << (b[idx] + ai) % n << ' ' del b[idx] cout << '\n' # region template BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._buffer = BytesIO() self._fd = file.fileno() 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): if self._buffer.tell(): return self._buffer.read() return os.read(self._fd, os.fstat(self._fd).st_size) 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 ostream: def __lshift__(self, a): if a is endl: sys.stdout.write(b"\n") sys.stdout.flush() else: sys.stdout.write(str(a)) return self def print(*args, **kwargs): sep, file = kwargs.pop("sep", b" "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", b"\n")) if kwargs.pop("flush", False): file.flush() sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) cout, endl = ostream(), object() readline = sys.stdin.readline readlist = lambda var=int: [var(n) for n in readline().split()] input = lambda: readline().rstrip(b"\r\n") # endregion if __name__ == "__main__": main()
1556289300
[ "data structures", "binary search", "greedy" ]
1 second
["0", "1", "6"]
fa7a44fd24fa0a8910cb7cc0aa4f2155
NoteIn the first sample test it is possible to change the string like the following: .In the second sample test it is possible to change the string like the following: .In the third sample test it is possible to change the string like the following: .
Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and the other contains 1, then we are allowed to remove these two digits from the string, obtaining a string of length n - 2 as a result.Now Andreid thinks about what is the minimum length of the string that can remain after applying the described operation several times (possibly, zero)? Help him to calculate this number.
Output the minimum length of the string that may remain after applying the described operations several times.
First line of the input contains a single integer n (1 ≀ n ≀ 2Β·105), the length of the string that Andreid has. The second line contains the string of length n consisting only from zeros and ones.
standard output
standard input
Python 3
Python
900
train_005.jsonl
774f2b6d100583986ba9a2e7c30aede5
256 megabytes
["4\n1100", "5\n01010", "8\n11101111"]
PASSED
# FILE: caseOfZerosAndOnes.py # CodeForces 556A def main(): length = int(input()) string = input() countZero = 0 countOne = 0 for i in range(length): if(string[i] == '0'): countZero += 1 else: countOne += 1 min = countZero if(countOne < countZero): min = countOne print(length - (2 * min)) main()
1435414200
[ "greedy" ]
2 seconds
["a\nabcdfdcba\nxyzyx\nc\nabba"]
042008e186c5a7265fbe382b0bdfc9bc
NoteIn the first test, the string $$$s = $$$"a" satisfies all conditions.In the second test, the string "abcdfdcba" satisfies all conditions, because: Its length is $$$9$$$, which does not exceed the length of the string $$$s$$$, which equals $$$11$$$. It is a palindrome. "abcdfdcba" $$$=$$$ "abcdfdc" $$$+$$$ "ba", and "abcdfdc" is a prefix of $$$s$$$ while "ba" is a suffix of $$$s$$$. It can be proven that there does not exist a longer string which satisfies the conditions.In the fourth test, the string "c" is correct, because "c" $$$=$$$ "c" $$$+$$$ "" and $$$a$$$ or $$$b$$$ can be empty. The other possible solution for this test is "s".
This is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.You are given a string $$$s$$$, consisting of lowercase English letters. Find the longest string, $$$t$$$, which satisfies the following conditions: The length of $$$t$$$ does not exceed the length of $$$s$$$. $$$t$$$ is a palindrome. There exists two strings $$$a$$$ and $$$b$$$ (possibly empty), such that $$$t = a + b$$$ ( "$$$+$$$" represents concatenation), and $$$a$$$ is prefix of $$$s$$$ while $$$b$$$ is suffix of $$$s$$$.
For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$), the number of test cases. The next $$$t$$$ lines each describe a test case. Each test case is a non-empty string $$$s$$$, consisting of lowercase English letters. It is guaranteed that the sum of lengths of strings over all test cases does not exceed $$$5000$$$.
standard output
standard input
PyPy 3
Python
1,500
train_005.jsonl
13d6438ca59a651779ff99f96e465480
256 megabytes
["5\na\nabcdfdcecba\nabbaxyzyx\ncodeforces\nacbba"]
PASSED
import sys, heapq as h input = sys.stdin.readline def getInts(): return [int(s) for s in input().split()] def getInt(): return int(input()) def getStrs(): return [s for s in input().split()] def getStr(): return input().strip() def listStr(): return list(input().strip()) import collections as col import math """ Longest matching prefix and suffix Then for each start / end point, the longest palindrome going forwards and then longest palidrome going backwards """ def longest_prefix_suffix_palindrome(S,N): i = -1 while i+1 <= N-i-2 and S[i+1] == S[N-i-2]: i += 1 return i def longest_palindromic_prefix(S): tmp = S + "?" S = S[::-1] tmp = tmp + S N = len(tmp) lps = [0] * N for i in range(1, N): #Length of longest prefix till less than i L = lps[i - 1] # Calculate length for i+1 while (L > 0 and tmp[L] != tmp[i]): L = lps[L - 1] #If character at current index and L are same then increment length by 1 if (tmp[i] == tmp[L]): L += 1 #Update the length at current index to L lps[i] = L return tmp[:lps[N - 1]] def solve(): S = getStr() N = len(S) i = longest_prefix_suffix_palindrome(S,N) #so S[:i+1] and S[N-i-1:] are palindromic if i >= N//2-1: return S #so there are least 2 elements between S[i] and S[N-i-1] new_str = S[i+1:N-i-1] longest_pref = longest_palindromic_prefix(new_str) longest_suff = longest_palindromic_prefix(new_str[::-1])[::-1] add_on = longest_pref if len(longest_pref) >= len(longest_suff) else longest_suff return S[:i+1] + add_on + S[N-i-1:] for _ in range(getInt()): print(solve()) #print(solve())
1584628500
[ "hashing", "string suffix structures", "strings" ]
1 second
["90", "-1", "33"]
4a48b828e35efa065668703edc22bf9b
NoteIn the first example you can, for example, choose displays $$$1$$$, $$$4$$$ and $$$5$$$, because $$$s_1 &lt; s_4 &lt; s_5$$$ ($$$2 &lt; 4 &lt; 10$$$), and the rent cost is $$$40 + 10 + 40 = 90$$$.In the second example you can't select a valid triple of indices, so the answer is -1.
It is the middle of 2018 and Maria Stepanovna, who lives outside Krasnokamensk (a town in Zabaikalsky region), wants to rent three displays to highlight an important problem.There are $$$n$$$ displays placed along a road, and the $$$i$$$-th of them can display a text with font size $$$s_i$$$ only. Maria Stepanovna wants to rent such three displays with indices $$$i &lt; j &lt; k$$$ that the font size increases if you move along the road in a particular direction. Namely, the condition $$$s_i &lt; s_j &lt; s_k$$$ should be held.The rent cost is for the $$$i$$$-th display is $$$c_i$$$. Please determine the smallest cost Maria Stepanovna should pay.
If there are no three displays that satisfy the criteria, print -1. Otherwise print a single integerΒ β€” the minimum total rent cost of three displays with indices $$$i &lt; j &lt; k$$$ such that $$$s_i &lt; s_j &lt; s_k$$$.
The first line contains a single integer $$$n$$$ ($$$3 \le n \le 3\,000$$$)Β β€” the number of displays. The second line contains $$$n$$$ integers $$$s_1, s_2, \ldots, s_n$$$ ($$$1 \le s_i \le 10^9$$$)Β β€” the font sizes on the displays in the order they stand along the road. The third line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \le c_i \le 10^8$$$)Β β€” the rent costs for each display.
standard output
standard input
Python 3
Python
1,400
train_005.jsonl
a94a7da1c33946723d590a818d593179
256 megabytes
["5\n2 4 5 4 10\n40 30 20 10 40", "3\n100 101 100\n2 4 5", "10\n1 2 3 4 5 6 7 8 9 10\n10 13 11 14 15 12 13 13 18 13"]
PASSED
from operator import __gt__, __lt__ def helper(op): xx = list(map(float, input().split())) le, ri, a = [], [], xx[0] for b in xx: if a > b: a = b le.append(a) for a in reversed(xx): if op(b, a): b = a ri.append(b) ri.reverse() return xx, le, ri n, res = int(input()), 9e9 ss, sLe, sRi = helper(__lt__) cc, cLe, cRi = helper(__gt__) for j in sorted(range(1, n - 1), key=cc.__getitem__): s, c = ss[j], cc[j] if cLe[j - 1] + c + cRi[j + 1] < res and sLe[j - 1] < s < sRi[j + 1]: a = b = 9e9 for i in range(j): if ss[i] < s and a > cc[i]: a = cc[i] for k in range(j + 1, n): if s < ss[k] and b > cc[k]: b = cc[k] if res > a + b + c: res = a + b + c print(int(res) if res < 9e9 else -1)
1527608100
[ "dp", "implementation", "brute force" ]
1 second
["YES", "NO"]
52f4f2a48063c9d0e412a5f78c873e6f
NoteIn the first example, you can make all elements equal to zero in $$$3$$$ operations: Decrease $$$a_1$$$ and $$$a_2$$$, Decrease $$$a_3$$$ and $$$a_4$$$, Decrease $$$a_3$$$ and $$$a_4$$$ In the second example, one can show that it is impossible to make all elements equal to zero.
You are given an array $$$a_1, a_2, \ldots, a_n$$$.In one operation you can choose two elements $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) and decrease each of them by one.You need to check whether it is possible to make all the elements equal to zero or not.
Print "YES" if it is possible to make all elements zero, otherwise print "NO".
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β€” the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)Β β€” the elements of the array.
standard output
standard input
PyPy 3
Python
1,500
train_005.jsonl
c5ab9a828ef6ba4a275b204bbec3c526
256 megabytes
["4\n1 1 2 2", "6\n1 2 3 4 5 6"]
PASSED
x=int(input()) a=list(map(int,input().split())) c=sum(a) d=max(a) if d<=c//2 and x>1 and c%2==0: print("YES") else: print("NO")
1564936500
[ "greedy", "math" ]
1 second
["72900", "317451037"]
6fcd8713af5a108d590bc99da314cded
NoteIn the first example, $$$f_{4} = 90$$$, $$$f_{5} = 72900$$$.In the second example, $$$f_{17} \approx 2.28 \times 10^{29587}$$$.
Let $$$f_{x} = c^{2x-6} \cdot f_{x-1} \cdot f_{x-2} \cdot f_{x-3}$$$ for $$$x \ge 4$$$.You have given integers $$$n$$$, $$$f_{1}$$$, $$$f_{2}$$$, $$$f_{3}$$$, and $$$c$$$. Find $$$f_{n} \bmod (10^{9}+7)$$$.
Print $$$f_{n} \bmod (10^{9} + 7)$$$.
The only line contains five integers $$$n$$$, $$$f_{1}$$$, $$$f_{2}$$$, $$$f_{3}$$$, and $$$c$$$ ($$$4 \le n \le 10^{18}$$$, $$$1 \le f_{1}$$$, $$$f_{2}$$$, $$$f_{3}$$$, $$$c \le 10^{9}$$$).
standard output
standard input
Python 3
Python
2,300
train_000.jsonl
3bf934bfa45c8ccf487e4f51f1003160
256 megabytes
["5 1 2 5 3", "17 97 41 37 11"]
PASSED
def mat_mul(a, b): n, m, p = len(a), len(b), len(b[0]) res = [[0]*p for _ in range(n)] for i in range(n): for j in range(p): for k in range(m): res[i][j] += a[i][k]*b[k][j] res[i][j] %= 1000000006 return res def mat_pow(a, n): if n == 1: return a if n%2 == 1: return mat_mul(mat_pow(a, n-1), a) t = mat_pow(a, n//2) return mat_mul(t, t) n, f1, f2, f3, c = map(int, input().split()) m1 = [[3, 1000000004, 0, 1000000005, 1], [1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0]] m2 = [[2], [0], [0], [0], [0]] t1 = pow(c, mat_mul(mat_pow(m1, n), m2)[-1][0], 1000000007) m1 = [[0, 0, 1], [1, 0, 1], [0, 1, 1]] m2 = [[1], [0], [0]] m3 = mat_mul(mat_pow(m1, n-1), m2) t2 = pow(f1, m3[0][0], 1000000007) t3 = pow(f2, m3[1][0], 1000000007) t4 = pow(f3, m3[2][0], 1000000007) print(t1*t2*t3*t4%1000000007)
1560258300
[ "dp", "number theory", "math", "matrices" ]
2 seconds
["2", "Still Rozdil"]
ce68f1171d9972a1b40b0450a05aa9cd
NoteIn the first sample there are only two cities where the Little Elephant can go. The travel time for the first town equals 7, to the second one β€” 4. The town which is closest to Rodzil (the only one) is the second one, so the answer is 2.In the second sample the closest cities are cities two and five, the travelling time to both of them equals 4, so the answer is "Still Rozdil".
The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil").However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum time to travel to. If there are multiple such cities, then the Little Elephant won't go anywhere.For each town except for Rozdil you know the time needed to travel to this town. Find the town the Little Elephant will go to or print "Still Rozdil", if he stays in Rozdil.
Print the answer on a single line β€” the number of the town the Little Elephant will go to. If there are multiple cities with minimum travel time, print "Still Rozdil" (without the quotes).
The first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of cities. The next line contains n integers, separated by single spaces: the i-th integer represents the time needed to go from town Rozdil to the i-th town. The time values are positive integers, not exceeding 109. You can consider the cities numbered from 1 to n, inclusive. Rozdil is not among the numbered cities.
standard output
standard input
PyPy 3
Python
900
train_005.jsonl
bb756e6128c4f5deb649bc1dd8b7e923
256 megabytes
["2\n7 4", "7\n7 4 47 100 4 9 12"]
PASSED
import re import sys from bisect import bisect, bisect_left, insort, insort_left from collections import Counter, defaultdict, deque from copy import deepcopy from decimal import Decimal from itertools import ( accumulate, combinations, combinations_with_replacement, groupby, permutations, product) from math import (acos, asin, atan, ceil, cos, degrees, factorial, gcd, hypot, log2, pi, radians, sin, sqrt, tan) from operator import itemgetter, mul from string import ascii_lowercase, ascii_uppercase, digits def inp(): return(int(input())) def inlist(): return(list(map(int, input().split()))) def instr(): s = input() return(list(s[:len(s)])) def invr(): return(map(int, input().split())) n = inp() a = inlist() min1 = 1000000001 min2 = min1+1 ind = 0 for i in range(n): if a[i] < min1: min1 = a[i] ind = i elif a[i] < min2 and a[i] >= min1: min2 = a[i] if min1 == min2: print("Still Rozdil") else: print(ind + 1)
1342020600
[ "implementation", "brute force" ]
1 second
["YES\n1 0\n2 3\n4 1", "NO"]
5c026adda2ae3d7b707d5054bd84db3f
NoteIn the first example area of the triangle should be equal to $$$\frac{nm}{k} = 4$$$. The triangle mentioned in the output is pictured below: In the second example there is no triangle with area $$$\frac{nm}{k} = \frac{16}{7}$$$.
Vasya has got three integers $$$n$$$, $$$m$$$ and $$$k$$$. He'd like to find three integer points $$$(x_1, y_1)$$$, $$$(x_2, y_2)$$$, $$$(x_3, y_3)$$$, such that $$$0 \le x_1, x_2, x_3 \le n$$$, $$$0 \le y_1, y_2, y_3 \le m$$$ and the area of the triangle formed by these points is equal to $$$\frac{nm}{k}$$$.Help Vasya! Find such points (if it's possible). If there are multiple solutions, print any of them.
If there are no such points, print "NO". Otherwise print "YES" in the first line. The next three lines should contain integers $$$x_i, y_i$$$ β€” coordinates of the points, one point per line. If there are multiple solutions, print any of them. You can print each letter in any case (upper or lower).
The single line contains three integers $$$n$$$, $$$m$$$, $$$k$$$ ($$$1\le n, m \le 10^9$$$, $$$2 \le k \le 10^9$$$).
standard output
standard input
PyPy 3
Python
1,800
train_005.jsonl
3ab5974739b59a2f7707451462505fae
256 megabytes
["4 3 3", "4 4 7"]
PASSED
#Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction import collections from itertools import permutations from collections import defaultdict 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") #-------------------game starts now----------------------------------------------------- n,m,k=map(int,input().split()) g=math.gcd(n*m,k) d=(n*m)//g f=k//g #print(d,f) if d%f!=0 and f!=2: print("NO") else: j=1 l=1 copy1,copy2=n,m ch=1 if k%2==0: k//=2 ch=0 while k%2==0: k//=2 if n%2==0: n//=2 else: m//=2 for i in range (3,int(math.sqrt(k))+1,2): while k%i==0: k//=i if n%i==0: n//=i else: m//=i if k>2: if n%k==0: n//=k else: m//=k if ch==1: if n*2<=copy1: n*=2 else: m*=2 print("YES") print("0 0") print(0,m) print(n,0)
1537707900
[ "number theory", "geometry" ]
1 second
["2\nabba", "0\nababab", "1\nba"]
8ad06ac90b258a8233e2a1cf51f68078
NoteIn the first example Nikolay has to perform two operations. For example, he can replace the first 'b' with 'a' and the last 'b' with 'a'. In the second example Nikolay doesn't need to do anything because each prefix of an even length of the initial string already contains an equal amount of letters 'a' and 'b'.
Nikolay got a string $$$s$$$ of even length $$$n$$$, which consists only of lowercase Latin letters 'a' and 'b'. Its positions are numbered from $$$1$$$ to $$$n$$$.He wants to modify his string so that every its prefix of even length has an equal amount of letters 'a' and 'b'. To achieve that, Nikolay can perform the following operation arbitrary number of times (possibly, zero): choose some position in his string and replace the letter on this position with the other letter (i.e. replace 'a' with 'b' or replace 'b' with 'a'). Nikolay can use no letters except 'a' and 'b'.The prefix of string $$$s$$$ of length $$$l$$$ ($$$1 \le l \le n$$$) is a string $$$s[1..l]$$$.For example, for the string $$$s=$$$"abba" there are two prefixes of the even length. The first is $$$s[1\dots2]=$$$"ab" and the second $$$s[1\dots4]=$$$"abba". Both of them have the same number of 'a' and 'b'.Your task is to calculate the minimum number of operations Nikolay has to perform with the string $$$s$$$ to modify it so that every its prefix of even length has an equal amount of letters 'a' and 'b'.
In the first line print the minimum number of operations Nikolay has to perform with the string $$$s$$$ to modify it so that every its prefix of even length has an equal amount of letters 'a' and 'b'. In the second line print the string Nikolay obtains after applying all the operations. If there are multiple answers, you can print any of them.
The first line of the input contains one even integer $$$n$$$ $$$(2 \le n \le 2\cdot10^{5})$$$ β€” the length of string $$$s$$$. The second line of the input contains the string $$$s$$$ of length $$$n$$$, which consists only of lowercase Latin letters 'a' and 'b'.
standard output
standard input
PyPy 3
Python
800
train_005.jsonl
b438a19e66ae7d78c39b64d8aa713c87
256 megabytes
["4\nbbbb", "6\nababab", "2\naa"]
PASSED
n,a,b=int(input()),0,0 s=input() tot = 0 l=list(s) for i in range(len(s)): if s[i] == 'a':a+=1 else:b+=1 # print(s[i],a,b) if i&1: tot+=1 if a>b: a-=1 b+=1 # print(l) l[i]='b' # print(l,a,b,i) elif b>a: a+=1 b-=1 l[i]='a' # print(l) else:tot-=1 print(tot) print(''.join(l))
1569049500
[ "strings" ]
2 seconds
["1", "0"]
d7e6e5042b8860bb2470d5a493b0adf6
NoteIn the first example, the initial number could be 12.In the second example the sum of the digits of n is not less than k. The initial number could be equal to n.
Some natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change.You have to find the minimum number of digits in which these two numbers can differ.
Print the minimum number of digits in which the initial number and n can differ.
The first line contains integer k (1 ≀ k ≀ 109). The second line contains integer n (1 ≀ n &lt; 10100000). There are no leading zeros in n. It's guaranteed that this situation is possible.
standard output
standard input
Python 2
Python
1,100
train_005.jsonl
6874083a225b2902c70dd8277e2c3f55
256 megabytes
["3\n11", "3\n99"]
PASSED
from math import ceil def min_digits_for_sum_increase(digit_count, delta): num_digits = 0 for digit in xrange(9): current_digits = min( ceil(delta / (9.0 - digit)), digit_count[digit] ) current_digits = int(current_digits) delta -= current_digits * (9 - digit) num_digits += current_digits if delta <= 0: break return num_digits k = int(raw_input()) digits = [0 for i in xrange(10)] sum_digits = 0 for c in raw_input(): d = ord(c) - ord('0') digits[d] += 1 sum_digits += d delta = k - sum_digits if delta <= 0: print 0 else: print min_digits_for_sum_increase(digits, delta)
1501511700
[ "greedy" ]
1 second
["Yes\nYes\nNo\nNo\nYes\nYes"]
a5e649f4d984a5c5365ca31436ad5883
NoteFor the first and second test cases, all conditions are already satisfied.For the third test case, there is only one empty cell $$$(2,2)$$$, and if it is replaced with a wall then the good person at $$$(1,2)$$$ will not be able to escape.For the fourth test case, the good person at $$$(1,1)$$$ cannot escape.For the fifth test case, Vivek can block the cells $$$(2,3)$$$ and $$$(2,2)$$$.For the last test case, Vivek can block the destination cell $$$(2, 2)$$$.
Vivek has encountered a problem. He has a maze that can be represented as an $$$n \times m$$$ grid. Each of the grid cells may represent the following: EmptyΒ β€” '.' WallΒ β€” '#' Good person Β β€” 'G' Bad personΒ β€” 'B' The only escape from the maze is at cell $$$(n, m)$$$.A person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' cannot be blocked and can be travelled through.Help him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions.It is guaranteed that the cell $$$(n,m)$$$ is empty. Vivek can also block this cell.
For each test case, print "Yes" if there exists a way to replace some empty cells with walls to satisfy the given conditions. Otherwise print "No" You may print every letter in any case (upper or lower).
The first line contains one integer $$$t$$$ $$$(1 \le t \le 100)$$$Β β€” the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$m$$$ $$$(1 \le n, m \le 50)$$$Β β€” the number of rows and columns in the maze. Each of the next $$$n$$$ lines contain $$$m$$$ characters. They describe the layout of the maze. If a character on a line equals '.', the corresponding cell is empty. If it equals '#', the cell has a wall. 'G' corresponds to a good person and 'B' corresponds to a bad person.
standard output
standard input
PyPy 3
Python
1,700
train_005.jsonl
d038faba7d151a510df0665476b9ac9b
256 megabytes
["6\n1 1\n.\n1 2\nG.\n2 2\n#B\nG.\n2 3\nG.#\nB#.\n3 3\n#B.\n#..\nGG.\n2 2\n#B\nB."]
PASSED
import sys input = sys.stdin.buffer.readline def main(): t = int(input()) for _ in range(t): n, m = map(int, input().split()) M = [list(str(input())[2:m+2]) for _ in range(n)] M = [['#']*m] + M + [['#']*m] M = [['#']+c+['#'] for c in M] #print(M) B = [] G = [] flag1 = True for i in range(1, n+1): for j in range(1, m+1): if M[i][j] == 'B': for di, dj in (-1, 0), (1, 0), (0, -1), (0, 1): ni, nj = i+di, j+dj if 1 <= ni <= n and 1 <= nj <= m: if M[ni][nj] == '.': M[ni][nj] = '#' if M[ni][nj] == 'G': flag1 = False break B.append((i, j)) if M[i][j] == 'G': G.append((i, j)) if not flag1: print('No') continue if len(G) > 0 and M[n][m] == '#': print('No') continue s = [] s.append((n, m)) visit = [[-1]*(m+2) for _ in range(n+2)] visit[n][m] = 0 while s: y, x = s.pop() for dy, dx in (-1, 0), (1, 0), (0, -1), (0, 1): ny, nx = y+dy, x+dx if visit[ny][nx] == -1 and M[ny][nx] != '#': visit[ny][nx] = visit[y][x]+1 s.append((ny, nx)) flag = True for sy, sx in G: if visit[sy][sx] == -1: flag = False break #print(visit) if flag: print('Yes') else: print('No') if __name__ == '__main__': main()
1591540500
[ "greedy", "graphs", "constructive algorithms", "shortest paths", "dsu", "implementation", "dfs and similar" ]
2 seconds
["4", "0", "-8"]
c7cca8c6524991da6ea1b423a8182d24
NoteIn the first example: d(a1, a2) = 0; d(a1, a3) = 2; d(a1, a4) = 0; d(a1, a5) = 2; d(a2, a3) = 0; d(a2, a4) = 0; d(a2, a5) = 0; d(a3, a4) =  - 2; d(a3, a5) = 0; d(a4, a5) = 2.
Let's denote a function You are given an array a consisting of n integers. You have to calculate the sum of d(ai, aj) over all pairs (i, j) such that 1 ≀ i ≀ j ≀ n.
Print one integer β€” the sum of d(ai, aj) over all pairs (i, j) such that 1 ≀ i ≀ j ≀ n.
The first line contains one integer n (1 ≀ n ≀ 200000) β€” the number of elements in a. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” elements of the array.
standard output
standard input
Python 3
Python
2,200
train_005.jsonl
c7b34015d82e882cfc2613b163a5f8b7
256 megabytes
["5\n1 2 3 1 3", "4\n6 6 5 5", "4\n6 6 4 4"]
PASSED
n = int(input()) a = list(map(int,input().split())) s = 0 mx = a[0] dic = dict() for i in range(n): dic[a[i]] = 0 for i in range(n): s = s - a[i]*(n-i-1) + a[i]*i if a[i]-1 in dic: s = s + dic[a[i]-1]*(a[i] - 1 - a[i]) if a[i]+1 in dic: s = s + dic[a[i]+1]*(a[i] + 1 - a[i]) d = dic[a[i]]+1 t = {a[i]:d} dic.update(t) print(s)
1513091100
[ "data structures", "math" ]
2 seconds
["? 1 1\n\n? 1 2\n\n? 1 3\n\n? 2 2 3\n\n! 1 3"]
28a14d68fe01c4696ab1ccb7f3932901
NoteThe tree from the first test is shown below, and the hidden nodes are $$$1$$$ and $$$3$$$.
Note that the only difference between the easy and hard version is the constraint on the number of queries. You can make hacks only if all versions of the problem are solved.This is an interactive problem.You are given a tree consisting of $$$n$$$ nodes numbered with integers from $$$1$$$ to $$$n$$$. Ayush and Ashish chose two secret distinct nodes in the tree. You need to find out both the nodes. You can make the following query: Provide a list of nodes and you will receive a node from that list whose sum of distances to both the hidden nodes is minimal (if there are multiple such nodes in the list, you will receive any one of them). You will also get the sum of distances of that node to the hidden nodes. Recall that a tree is a connected graph without cycles. The distance between two nodes is defined as the number of edges in the simple path between them.More formally, let's define two hidden nodes as $$$s$$$ and $$$f$$$. In one query you can provide the set of nodes $$$\{a_1, a_2, \ldots, a_c\}$$$ of the tree. As a result, you will get two numbers $$$a_i$$$ and $$$dist(a_i, s) + dist(a_i, f)$$$. The node $$$a_i$$$ is any node from the provided set, for which the number $$$dist(a_i, s) + dist(a_i, f)$$$ is minimal.You can ask no more than $$$14$$$ queries.
null
The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 10)$$$Β β€” the number of test cases. Please note, how the interaction process is organized. The first line of each test case consists of a single integer $$$n$$$ $$$(2 \le n \le 1000)$$$Β β€” the number of nodes in the tree. The next $$$n - 1$$$ lines consist of two integers $$$u$$$, $$$v$$$ $$$(1 \le u, v \le n, u \ne v)$$$Β β€” the edges of the tree.
standard output
standard input
Python 3
Python
2,400
train_005.jsonl
9375afcca41149cfb5fbe1002e9e7a02
256 megabytes
["1\n3\n1 2\n1 3\n\n1 1\n\n2 3\n\n3 1\n\n3 1\n\nCorrect"]
PASSED
from collections import deque def NC_Dij(lis,start): ret = [float("inf")] * len(lis) ret[start] = 0 q = deque([start]) plis = [i for i in range(len(lis))] while len(q) > 0: now = q.popleft() for nex in lis[now]: if ret[nex] > ret[now] + 1: ret[nex] = ret[now] + 1 plis[nex] = now q.append(nex) return ret,plis tt = int(input()) for loop in range(tt): n = int(input()) lis = [ [] for i in range(n)] for i in range(n-1): v,u = map(int,input().split()) v -= 1 u -= 1 lis[v].append(u) lis[u].append(v) print ("?",n,*[i+1 for i in range(n)] , flush=True) x1,d1 = map(int,input().split()) x1 -= 1 dlis,plis = NC_Dij(lis,x1) r = max(dlis)+1 l = 0 dic = {} dic[0] = x1 while r-l != 1: m = (l+r)//2 #print (l,r,m) nodes = [] for i in range(n): if dlis[i] == m: nodes.append(i+1) print ("?",len(nodes), *nodes , flush=True) nx,nd = map(int,input().split()) nx -= 1 dic[m] = nx if nd == d1: l = m else: r = m ans1 = dic[l] dlis2,plis2 = NC_Dij(lis,ans1) nodes = [] for i in range(n): if dlis2[i] == d1: nodes.append(i+1) print ("?",len(nodes), *nodes , flush=True) ans2,tmp = map(int,input().split()) print ("!",ans1+1,ans2 , flush=True) ret = input()
1592663700
[ "graphs", "shortest paths", "interactive", "binary search", "dfs and similar", "trees" ]
2 seconds
["0.857143", "1", "0"]
5a2c9caec9c20a3caed1982ee8ed8f9c
null
As a big fan of Formula One, Charlie is really happy with the fact that he has to organize ticket sells for the next Grand Prix race in his own city. Unfortunately, the finacial crisis is striking everywhere and all the banknotes left in his country are valued either 10 euros or 20 euros. The price of all tickets for the race is 10 euros, so whenever someone comes to the ticket store only with 20 euro banknote Charlie must have a 10 euro banknote to give them change. Charlie realize that with the huge deficit of banknotes this could be a problem. Charlie has some priceless information but couldn't make use of it, so he needs your help. Exactly n + m people will come to buy a ticket. n of them will have only a single 10 euro banknote, and m of them will have only a single 20 euro banknote. Currently Charlie has k 10 euro banknotes, which he can use for change if needed. All n + m people will come to the ticket store in random order, all orders are equiprobable. Return the probability that the ticket selling process will run smoothly, i.e. Charlie will have change for every person with 20 euro banknote.
Output on a single line the desired probability with at least 4 digits after the decimal point.
The input consist of a single line with three space separated integers, n, m and k (0 ≀ n, m ≀ 105, 0 ≀ k ≀ 10).
standard output
standard input
Python 3
Python
2,400
train_005.jsonl
8a6cb4297098eb864e487d96e3926ef3
256 megabytes
["5 3 1", "0 5 5", "0 1 0"]
PASSED
#!/usr/bin/python3.5 # -*- coding: utf-8 -*- import json import sys def main(): n, m, k = map(int, input().strip().split()) if n + k < m: print(0) return ans = 1.0 for i in range(k+1): ans *= (m - i) * 1.0 / (n + i + 1) print(1.0 - ans) if __name__ == '__main__': main()
1281970800
[ "combinatorics", "probabilities", "math" ]
2 seconds
["3", "0", "1"]
5358fff5b798ac5e500d0f5deef765c7
null
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into two pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?
Output the amount of ways to cut the stripe into two non-empty pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.
The first input line contains integer n (1 ≀ n ≀ 105) β€” amount of squares in the stripe. The second line contains n space-separated numbers β€” they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.
standard output
standard input
Python 3
Python
1,200
train_005.jsonl
dddb64b650dd853d4fa152d55e2e6412
64 megabytes
["9\n1 5 -6 7 9 -16 0 -2 2", "3\n1 1 1", "2\n0 0"]
PASSED
n = int(input()) stripe = list(map(int, input().split())) count = 0 left = 0 right = sum(stripe) for s in stripe[:-1]: left += s right -= s if left == right: count += 1 print(count)
1276700400
[ "data structures", "implementation" ]
2 seconds
["YES\n2 4 8 \nNO\nNO\nNO\nYES\n3 5 823"]
0f7ceecdffe11f45d0c1d618ef3c6469
null
You are given one integer number $$$n$$$. Find three distinct integers $$$a, b, c$$$ such that $$$2 \le a, b, c$$$ and $$$a \cdot b \cdot c = n$$$ or say that it is impossible to do it.If there are several answers, you can print any.You have to answer $$$t$$$ independent test cases.
For each test case, print the answer on it. Print "NO" if it is impossible to represent $$$n$$$ as $$$a \cdot b \cdot c$$$ for some distinct integers $$$a, b, c$$$ such that $$$2 \le a, b, c$$$. Otherwise, print "YES" and any possible such representation.
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. The next $$$n$$$ lines describe test cases. The $$$i$$$-th test case is given on a new line as one integer $$$n$$$ ($$$2 \le n \le 10^9$$$).
standard output
standard input
Python 3
Python
1,300
train_005.jsonl
8842322a670790c54ce36c85751dc47e
256 megabytes
["5\n64\n32\n97\n2\n12345"]
PASSED
def factors(n): factor = [] for i in range(2, int(n**0.5)+1): if n % i == 0: factor.append(i) return factor t = int(input()) for l in range(t): n = int(input()) x = 0 factor = factors(n) lenfactor = len(factor) for i in range(lenfactor): for j in range(i+1, lenfactor): k = n/(factor[i]*factor[j]) if k%1 == 0 and k != factor[i] and k != factor[j]: print('YES') print(str(factor[i]) + ' ' + str(factor[j]) + ' ' + str(int(k)) ) x = 1 break if x == 1: break if x == 0: print('NO')
1579703700
[ "number theory", "greedy", "math" ]
2 seconds
["2 3"]
8f0172f742b058f5905c0a02d79000dc
null
Alice and Bob like games. And now they are ready to start a new game. They have placed n chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob β€” from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them with equal speed). When the player consumes a chocolate bar, he immediately starts with another. It is not allowed to eat two chocolate bars at the same time, to leave the bar unfinished and to make pauses. If both players start to eat the same bar simultaneously, Bob leaves it to Alice as a true gentleman.How many bars each of the players will consume?
Print two numbers a and b, where a is the amount of bars consumed by Alice, and b is the amount of bars consumed by Bob.
The first line contains one integer n (1 ≀ n ≀ 105) β€” the amount of bars on the table. The second line contains a sequence t1, t2, ..., tn (1 ≀ ti ≀ 1000), where ti is the time (in seconds) needed to consume the i-th bar (in the order from left to right).
standard output
standard input
Python 3
Python
1,200
train_000.jsonl
07874d1fbec94eaa7f45a9f138ff445c
64 megabytes
["5\n2 9 8 2 7"]
PASSED
n=int(input()) s=list(map(int,input().split(" "))) i,j=0,n-1 a,b=0,0 while i<=j: if a<=b:a+=s[i];i+=1 else:b+=s[j];j-=1 print(i,n-i)
1269673200
[ "two pointers", "greedy" ]
1 second
["11 6 4 0", "13"]
14fd47f6f0fcbdb16dbd73dcca8a782f
NoteIn the first testcase, value of the array $$$[11, 6, 4, 0]$$$ is $$$f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9$$$.$$$[11, 4, 0, 6]$$$ is also a valid answer.
Anu has created her own function $$$f$$$: $$$f(x, y) = (x | y) - y$$$ where $$$|$$$ denotes the bitwise OR operation. For example, $$$f(11, 6) = (11|6) - 6 = 15 - 6 = 9$$$. It can be proved that for any nonnegative numbers $$$x$$$ and $$$y$$$ value of $$$f(x, y)$$$ is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array $$$[a_1, a_2, \dots, a_n]$$$ is defined as $$$f(f(\dots f(f(a_1, a_2), a_3), \dots a_{n-1}), a_n)$$$ (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Output $$$n$$$ integers, the reordering of the array with maximum value. If there are multiple answers, print any.
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). Elements of the array are not guaranteed to be different.
standard output
standard input
PyPy 2
Python
1,500
train_005.jsonl
1c00423cdb5c32287ca07ba1abb07fb6
256 megabytes
["4\n4 0 11 6", "1\n13"]
PASSED
from __future__ import division,print_function #from sortedcontainers import SortedList import sys #sys.__stdout__.flush() le=sys.__stdin__.read().split("\n") le.pop() le=le[::-1] n=int(le.pop()) l=list(map(bin,map(int,le.pop().split()))) d=max(map(len,l)) l=['0'*(d-len(k))+k[2:] for k in l] d-=2 #print(l) tab=[0]*d for k in l: for i in range(d): tab[i]+=int(k[i]) m='0'*d im=0 for k in range(n): v=l[k] te=''.join(str(i if j==1 else 0) for i,j in zip(v,tab)) if te>m: m=te im=k m=l[im] l.remove(m) l=[m]+l l=[str(sum(2**(d-1-i)*int(k[i]) for i in range(d))) for k in l] #print(l) print(" ".join(l))
1581257100
[ "greedy", "math", "brute force" ]
1 second
["2\n3\n-1"]
36099a612ec5bbec1b95f2941e759c00
NoteIn the first query you can deal the first blow (after that the number of heads changes to $$$10 - 6 + 3 = 7$$$), and then deal the second blow.In the second query you just deal the first blow three times, and Zmei is defeated. In third query you can not defeat Zmei Gorynich. Maybe it's better to convince it to stop fighting?
You are fighting with Zmei Gorynich β€” a ferocious monster from Slavic myths, a huge dragon-like reptile with multiple heads! Initially Zmei Gorynich has $$$x$$$ heads. You can deal $$$n$$$ types of blows. If you deal a blow of the $$$i$$$-th type, you decrease the number of Gorynich's heads by $$$min(d_i, curX)$$$, there $$$curX$$$ is the current number of heads. But if after this blow Zmei Gorynich has at least one head, he grows $$$h_i$$$ new heads. If $$$curX = 0$$$ then Gorynich is defeated. You can deal each blow any number of times, in any order.For example, if $$$curX = 10$$$, $$$d = 7$$$, $$$h = 10$$$ then the number of heads changes to $$$13$$$ (you cut $$$7$$$ heads off, but then Zmei grows $$$10$$$ new ones), but if $$$curX = 10$$$, $$$d = 11$$$, $$$h = 100$$$ then number of heads changes to $$$0$$$ and Zmei Gorynich is considered defeated.Calculate the minimum number of blows to defeat Zmei Gorynich!You have to answer $$$t$$$ independent queries.
For each query print the minimum number of blows you have to deal to defeat Zmei Gorynich. If Zmei Gorynuch cannot be defeated print $$$-1$$$.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) – the number of queries. The first line of each query contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 100$$$, $$$1 \le x \le 10^9$$$) β€” the number of possible types of blows and the number of heads Zmei initially has, respectively. The following $$$n$$$ lines of each query contain the descriptions of types of blows you can deal. The $$$i$$$-th line contains two integers $$$d_i$$$ and $$$h_i$$$ ($$$1 \le d_i, h_i \le 10^9$$$) β€” the description of the $$$i$$$-th blow.
standard output
standard input
PyPy 3
Python
1,600
train_005.jsonl
51a68eedaaf699575a5c415c0a395a8f
256 megabytes
["3\n3 10\n6 3\n8 2\n1 4\n4 10\n4 1\n3 2\n2 6\n1 100\n2 15\n10 11\n14 100"]
PASSED
for i in range(int(input())): n,x = map(int,input().split()) mx = 0 mind = 1000000000000000000 d1 = 0 for i in range(n): d,h = map(int,input().split()) if d - h > mx: mx = d-h d1 = max(d1,d) import math d = d1 if x <= d1: print(1) continue if mx <= 0: print(-1) continue k = math.ceil((x-d)/mx) + 1 print(k)
1567694100
[ "greedy", "math" ]
2 seconds
["1\n3 1", "3\n2 5\n2 6\n3 7"]
c8f63597670a7b751822f8cef01b8ba3
null
To learn as soon as possible the latest news about their favourite fundamentally new operating system, BolgenOS community from Nizhni Tagil decided to develop a scheme. According to this scheme a community member, who is the first to learn the news, calls some other member, the latter, in his turn, calls some third member, and so on; i.e. a person with index i got a person with index fi, to whom he has to call, if he learns the news. With time BolgenOS community members understood that their scheme doesn't work sometimes β€” there were cases when some members didn't learn the news at all. Now they want to supplement the scheme: they add into the scheme some instructions of type (xi, yi), which mean that person xi has to call person yi as well. What is the minimum amount of instructions that they need to add so, that at the end everyone learns the news, no matter who is the first to learn it?
In the first line output one number β€” the minimum amount of instructions to add. Then output one of the possible variants to add these instructions into the scheme, one instruction in each line. If the solution is not unique, output any.
The first input line contains number n (2 ≀ n ≀ 105) β€” amount of BolgenOS community members. The second line contains n space-separated integer numbers fi (1 ≀ fi ≀ n, i ≠ fi) β€” index of a person, to whom calls a person with index i.
standard output
standard input
Python 3
Python
2,300
train_005.jsonl
53881e819c8eff72cb225b42a8cae123
256 megabytes
["3\n3 3 2", "7\n2 3 1 3 4 4 1"]
PASSED
#!/usr/bin/env python3 # Read data n = int(input()) f = map(int, input().split()) f = [d-1 for d in f] # Make indices 0-based # Determine in-degree of all the nodes indegree = [0 for i in range(n)] for i in range(n): indegree[f[i]] += 1 # Nodes with indegree = 0 will need to be an end-point of a new edge endpoints = [i for i in range(n) if (indegree[i] == 0)] nr_indegree_zero = len(endpoints) # Determine which (hereto unvisited) nodes will be reached by these endpoints unvisited = set(range(n)) reach = [None for i in range(n)] def determine_reach(v): path = [v] while (v in unvisited): unvisited.remove(v) v = f[v] path.append(v) for i in path: reach[i] = v for v in endpoints: determine_reach(v) # The reached nodes form good start-points for the new edges startpoints = [reach[v] for v in endpoints] # Check for isolated cycles that are not connected to the rest of the graph nr_cycles = 0 while len(unvisited) > 0: # Select a node from the unvisited set (without removing it) v = unvisited.pop() unvisited.add(v) nr_cycles += 1 determine_reach(v) endpoints.append(v) startpoints.append(reach[v]) # Special case: no indegree 0 nodes and only 1 cycle if (nr_indegree_zero == 0) and (nr_cycles == 1): # No edges need to be added print(0) exit() # Rotate the lists to each start point connects to the end-point of the next item endpoints = endpoints[1:] + endpoints[:1] print(len(startpoints)) print("\n".join(["%d %s" % (start+1,end+1) for (start,end) in zip(startpoints,endpoints)]))
1277823600
[ "dfs and similar", "trees", "graphs" ]
3 seconds
["3\n3 2 0 7 10 14", "0\n0 1 2 3"]
4a7c2e32e29734476fa40bced7ddc4e8
null
You are given an array consisting of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$, and a positive integer $$$m$$$. It is guaranteed that $$$m$$$ is a divisor of $$$n$$$.In a single move, you can choose any position $$$i$$$ between $$$1$$$ and $$$n$$$ and increase $$$a_i$$$ by $$$1$$$.Let's calculate $$$c_r$$$ ($$$0 \le r \le m-1)$$$ β€” the number of elements having remainder $$$r$$$ when divided by $$$m$$$. In other words, for each remainder, let's find the number of corresponding elements in $$$a$$$ with that remainder.Your task is to change the array in such a way that $$$c_0 = c_1 = \dots = c_{m-1} = \frac{n}{m}$$$.Find the minimum number of moves to satisfy the above requirement.
In the first line, print a single integer β€” the minimum number of moves required to satisfy the following condition: for each remainder from $$$0$$$ to $$$m - 1$$$, the number of elements of the array having this remainder equals $$$\frac{n}{m}$$$. In the second line, print any array satisfying the condition and can be obtained from the given array with the minimum number of moves. The values of the elements of the resulting array must not exceed $$$10^{18}$$$.
The first line of input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5, 1 \le m \le n$$$). It is guaranteed that $$$m$$$ is a divisor of $$$n$$$. The second line of input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$), the elements of the array.
standard output
standard input
PyPy 3
Python
1,900
train_005.jsonl
2421a5afe63ddac132f6c4fe62d1ef82
256 megabytes
["6 3\n3 2 0 6 10 12", "4 2\n0 1 2 3"]
PASSED
n,m=map(int,input().split()) d=n//m a=list(map(int,input().split())) b=[0]*m for i in range(n):b[a[i]%m]+=1 x=[[]for _ in range(m)] xx=[] ans=0 for i in range(2*m-1,-1,-1): if b[i%m]<=d: xx+=[i%m]*(d-b[i%m]) b[i%m]=d else: y=b[i%m]-d for _ in range(min(y,len(xx))): b[i%m]-=1 v=xx.pop() x[i%m].append((v-i)%m) ans+=(v-i)%m for i in range(n): if x[a[i]%m]: a[i]+=x[a[i]%m].pop() print(ans) print(*a)
1529591700
[ "data structures", "implementation", "greedy" ]
1 second
["3", "4", "0"]
e0b5169945909cd2809482b7fd7178c2
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
The first line contains two space-separated integers n, m (1 ≀ n, m ≀ 105). The second line will contain n space-separated integers representing content of the array a (1 ≀ ai ≀ 109). The third line will contain m space-separated integers representing content of the array b (1 ≀ bi ≀ 109).
standard output
standard input
Python 3
Python
1,700
train_005.jsonl
b06c371ac656735234fa51a978dc251f
256 megabytes
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
PASSED
R = lambda: map(int, input().split()) n, m = R() a = sorted(R()) b = sorted(R()) b.reverse() ans = 0 for i in range(min(n, m)): if b[i] > a[i]: ans += b[i] - a[i] print(ans)
1401895800
[ "two pointers", "binary search", "sortings", "ternary search" ]
2 seconds
["OBEY\nREBEL\nOBEY\nOBEY"]
be141f316d6e5d9d8f09192913f4be47
null
You are a rebel leader and you are planning to start a revolution in your country. But the evil Government found out about your plans and set your punishment in the form of correctional labor.You must paint a fence which consists of $$$10^{100}$$$ planks in two colors in the following way (suppose planks are numbered from left to right from $$$0$$$): if the index of the plank is divisible by $$$r$$$ (such planks have indices $$$0$$$, $$$r$$$, $$$2r$$$ and so on) then you must paint it red; if the index of the plank is divisible by $$$b$$$ (such planks have indices $$$0$$$, $$$b$$$, $$$2b$$$ and so on) then you must paint it blue; if the index is divisible both by $$$r$$$ and $$$b$$$ you can choose the color to paint the plank; otherwise, you don't need to paint the plank at all (and it is forbidden to spent paint on it). Furthermore, the Government added one additional restriction to make your punishment worse. Let's list all painted planks of the fence in ascending order: if there are $$$k$$$ consecutive planks with the same color in this list, then the Government will state that you failed the labor and execute you immediately. If you don't paint the fence according to the four aforementioned conditions, you will also be executed.The question is: will you be able to accomplish the labor (the time is not important) or the execution is unavoidable and you need to escape at all costs.
Print $$$T$$$ words β€” one per line. For each test case print REBEL (case insensitive) if the execution is unavoidable or OBEY (case insensitive) otherwise.
The first line contains single integer $$$T$$$ ($$$1 \le T \le 1000$$$) β€” the number of test cases. The next $$$T$$$ lines contain descriptions of test cases β€” one per line. Each test case contains three integers $$$r$$$, $$$b$$$, $$$k$$$ ($$$1 \le r, b \le 10^9$$$, $$$2 \le k \le 10^9$$$) β€” the corresponding coefficients.
standard output
standard input
Python 3
Python
1,700
train_005.jsonl
cd70bd3a92f2e76fa8d0da131516e9e9
256 megabytes
["4\n1 1 2\n2 10 4\n5 2 3\n3 2 2"]
PASSED
def gcd(a,b): if(b==0): return a return gcd(b,a%b) t=int(input()) for _ in range(t): r,b,k=map(int,input().split()) mini=min(r,b) maxi=max(r,b) gg=gcd(mini,maxi) mini=mini//gg maxi=maxi//gg if((k-1)*mini+1<maxi): print("REBEL") else: print("OBEY")
1574862600
[ "number theory", "greedy", "math" ]
1 second
["303", "25", "60"]
39dbd405be19c5a56c2b97b28e0edf06
NoteNote to the first sample test. 3 + 5 * (7 + 8) * 4 = 303.Note to the second sample test. (2 + 3) * 5 = 25.Note to the third sample test. (3 * 4) * 5 = 60 (also many other variants are valid, for instance, (3) * 4 * 5 = 60).
Vanya is doing his maths homework. He has an expression of form , where x1, x2, ..., xn are digits from 1 to 9, and sign represents either a plus '+' or the multiplication sign '*'. Vanya needs to add one pair of brackets in this expression so that to maximize the value of the resulting expression.
In the first line print the maximum possible value of an expression.
The first line contains expression s (1 ≀ |s| ≀ 5001, |s| is odd), its odd positions only contain digits from 1 to 9, and even positions only contain signs  +  and  * . The number of signs  *  doesn't exceed 15.
standard output
standard input
Python 2
Python
2,100
train_005.jsonl
4a4c14e78ddbf5f4e4ad1ee279e57229
256 megabytes
["3+5*7+8*4", "2+3*5", "3*4*5"]
PASSED
n = raw_input() ans = 0 a = [-1] for i in xrange(len(n)): if n[i]=='*':a.append(i) a.append(len(n)) for i in a: for j in a: if j>i: ans = max(ans,eval(n[:i+1]+'('+n[i+1:j]+')'+n[j:])) ans = max(ans,eval(n)) print ans
1434645000
[ "dp", "greedy", "implementation", "expression parsing", "brute force", "strings" ]
1 second
["YES\n1 3 1 2 1", "NO", "YES\n1 1 1"]
fa531c38833907d619f1102505ddbb6a
NoteIn the first example, if the teacher distributed $$$1$$$, $$$3$$$, $$$1$$$, $$$2$$$, $$$1$$$ candies to $$$1$$$-st, $$$2$$$-nd, $$$3$$$-rd, $$$4$$$-th, $$$5$$$-th child, respectively, then all the values calculated by the children are correct. For example, the $$$5$$$-th child was given $$$1$$$ candy, to the left of him $$$2$$$ children were given $$$1$$$ candy, $$$1$$$ child was given $$$2$$$ candies and $$$1$$$ childΒ β€” $$$3$$$ candies, so there are $$$2$$$ children to the left of him that were given more candies than him.In the second example it is impossible to distribute the candies, because the $$$4$$$-th child made a mistake in calculating the value of $$$r_4$$$, because there are no children to the right of him, so $$$r_4$$$ should be equal to $$$0$$$.In the last example all children may have got the same number of candies, that's why all the numbers are $$$0$$$. Note that each child should receive at least one candy.
There are $$$n$$$ children numbered from $$$1$$$ to $$$n$$$ in a kindergarten. Kindergarten teacher gave $$$a_i$$$ ($$$1 \leq a_i \leq n$$$) candies to the $$$i$$$-th child. Children were seated in a row in order from $$$1$$$ to $$$n$$$ from left to right and started eating candies. While the $$$i$$$-th child was eating candies, he calculated two numbers $$$l_i$$$ and $$$r_i$$$Β β€” the number of children seating to the left of him that got more candies than he and the number of children seating to the right of him that got more candies than he, respectively.Formally, $$$l_i$$$ is the number of indices $$$j$$$ ($$$1 \leq j &lt; i$$$), such that $$$a_i &lt; a_j$$$ and $$$r_i$$$ is the number of indices $$$j$$$ ($$$i &lt; j \leq n$$$), such that $$$a_i &lt; a_j$$$.Each child told to the kindergarten teacher the numbers $$$l_i$$$ and $$$r_i$$$ that he calculated. Unfortunately, she forgot how many candies she has given to each child. So, she asks you for help: given the arrays $$$l$$$ and $$$r$$$ determine whether she could have given the candies to the children such that all children correctly calculated their values $$$l_i$$$ and $$$r_i$$$, or some of them have definitely made a mistake. If it was possible, find any way how she could have done it.
If there is no way to distribute the candies to the children so that all of them calculated their numbers correctly, print Β«NOΒ» (without quotes). Otherwise, print Β«YESΒ» (without quotes) on the first line. On the next line, print $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$, separated by spacesΒ β€” the numbers of candies the children $$$1, 2, \ldots, n$$$ received, respectively. Note that some of these numbers can be equal, but all numbers should satisfy the condition $$$1 \leq a_i \leq n$$$. The number of children seating to the left of the $$$i$$$-th child that got more candies than he should be equal to $$$l_i$$$ and the number of children seating to the right of the $$$i$$$-th child that got more candies than he should be equal to $$$r_i$$$. If there is more than one solution, find any of them.
On the first line there is a single integer $$$n$$$ ($$$1 \leq n \leq 1000$$$)Β β€” the number of children in the kindergarten. On the next line there are $$$n$$$ integers $$$l_1, l_2, \ldots, l_n$$$ ($$$0 \leq l_i \leq n$$$), separated by spaces. On the next line, there are $$$n$$$ integer numbers $$$r_1, r_2, \ldots, r_n$$$ ($$$0 \leq r_i \leq n$$$), separated by spaces.
standard output
standard input
Python 3
Python
1,500
train_005.jsonl
b6a8383dbe813e7260ec384df6eb8822
256 megabytes
["5\n0 0 1 1 2\n2 0 1 0 0", "4\n0 0 2 0\n1 1 1 1", "3\n0 0 0\n0 0 0"]
PASSED
import math as ma import sys from sys import exit from decimal import Decimal as dec from itertools import permutations def li(): return list(map(int , input().split())) def num(): return map(int , input().split()) def nu(): return int(input()) def find_gcd(x , y): while (y): x , y = y , x % y return x n=nu() a=li() b=li() z=[] for i in range(n): z.append((a[i]+b[i],i)) z.sort() fl=True x=[] cc=0 xp=0 mp={} np=[] for i in range(n): if(a[i]>i): fl=False if(b[i]>(n-i-1)): fl=False if((n-a[i]-b[i])<=0): fl=False if(fl==False): print("NO") else: zz=[0]*n for i in range(n): zz[i]=(n-a[i]-b[i]) for i in range(n): xl = 0 xr = 0 for j in range(i + 1 , n): if (zz[j] > zz[i]): xr += 1 for j in range(i - 1 , -1 , -1): if (zz[j] > zz[i]): xl += 1 if (xl != a[i] or xr != b[i]): fl = False break if (fl == True): print("YES") print(*zz) else: print("NO")
1539880500
[ "constructive algorithms", "implementation" ]
2 seconds
["ross rachel\njoey rachel\njoey phoebe\njoey monica\njoey chandler", "icm codeforces\nicm technex"]
3c06e3cb2d8468e738b736a9bf88b4ca
NoteIn first example, the killer starts with ross and rachel. After day 1, ross is killed and joey appears. After day 2, rachel is killed and phoebe appears. After day 3, phoebe is killed and monica appears. After day 4, monica is killed and chandler appears.
Our beloved detective, Sherlock is currently trying to catch a serial killer who kills a person each day. Using his powers of deduction, he came to know that the killer has a strategy for selecting his next victim.The killer starts with two potential victims on his first day, selects one of these two, kills selected victim and replaces him with a new person. He repeats this procedure each day. This way, each day he has two potential victims to choose from. Sherlock knows the initial two potential victims. Also, he knows the murder that happened on a particular day and the new person who replaced this victim.You need to help him get all the pairs of potential victims at each day so that Sherlock can observe some pattern.
Output n + 1 lines, the i-th line should contain the two persons from which the killer selects for the i-th murder. The (n + 1)-th line should contain the two persons from which the next victim is selected. In each line, the two names can be printed in any order.
First line of input contains two names (length of each of them doesn't exceed 10), the two initials potential victims. Next line contains integer n (1 ≀ n ≀ 1000), the number of days. Next n lines contains two names (length of each of them doesn't exceed 10), first being the person murdered on this day and the second being the one who replaced that person. The input format is consistent, that is, a person murdered is guaranteed to be from the two potential victims at that time. Also, all the names are guaranteed to be distinct and consists of lowercase English letters.
standard output
standard input
PyPy 2
Python
900
train_005.jsonl
09bab30e474f73e8ae26b4980bbdfffd
256 megabytes
["ross rachel\n4\nross joey\nrachel phoebe\nphoebe monica\nmonica chandler", "icm codeforces\n1\ncodeforces technex"]
PASSED
now_list = raw_input().split(' ') n = int(raw_input()) print ' '.join(now_list) for i in xrange(n): x, y = raw_input().split(' ') now_list.remove(x) now_list.append(y) print ' '.join(now_list)
1487861100
[ "implementation", "brute force", "strings" ]
3 seconds
["YES\n3 1\nYES\n2 1\n1 5\n5 4\n2 5\n3 5\nYES\n1 2\n3 4\n3 1\n3 2\n2 4\nNO"]
4bee64265ade3c09002446264dcd26a6
NoteExplanation of the second test case of the example:Explanation of the third test case of the example:
You are given a graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges.You have to direct undirected edges in such a way that the resulting graph is directed and acyclic (i.e. the graph with all edges directed and having no directed cycles). Note that you have to direct all undirected edges.You have to answer $$$t$$$ independent test cases.
For each test case print the answer β€” "NO" if it is impossible to direct undirected edges in such a way that the resulting graph is directed and acyclic, otherwise print "YES" on the first line and $$$m$$$ lines describing edges of the resulted directed acyclic graph (in any order). Note that you cannot change the direction of the already directed edges. If there are several answers, you can print any.
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) β€” the number of vertices and the number of edges in the graph, respectively. The next $$$m$$$ lines describe edges of the graph. The $$$i$$$-th edge is described with three integers $$$t_i$$$, $$$x_i$$$ and $$$y_i$$$ ($$$t_i \in [0; 1]$$$, $$$1 \le x_i, y_i \le n$$$) β€” the type of the edge ($$$t_i = 0$$$ if the edge is undirected and $$$t_i = 1$$$ if the edge is directed) and vertices this edge connects (the undirected edge connects vertices $$$x_i$$$ and $$$y_i$$$ and directed edge is going from the vertex $$$x_i$$$ to the vertex $$$y_i$$$). It is guaranteed that the graph do not contain self-loops (i.e. edges from the vertex to itself) and multiple edges (i.e. for each pair ($$$x_i, y_i$$$) there are no other pairs ($$$x_i, y_i$$$) or ($$$y_i, x_i$$$)). It is guaranteed that both sum $$$n$$$ and sum $$$m$$$ do not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$; $$$\sum m \le 2 \cdot 10^5$$$).
standard output
standard input
Python 3
Python
2,000
train_005.jsonl
4cd09add421217117ebede65467bfa1e
256 megabytes
["4\n3 1\n0 1 3\n5 5\n0 2 1\n1 1 5\n1 5 4\n0 5 2\n1 3 5\n4 5\n1 1 2\n0 4 3\n1 3 1\n0 2 3\n1 2 4\n4 5\n1 4 1\n1 1 3\n0 1 2\n1 2 4\n1 3 2"]
PASSED
from collections import defaultdict, deque for _ in range(int(input())): n,m = map(int,input().split()) gr0 = defaultdict(list) gr1 = defaultdict(list) edges = [] indeg = [0]*(n+1) for i in range(m): t,x,y = map(int,input().split()) if t==0: edges.append([x,y]) else: gr0[x].append(y) indeg[y]+=1 q = deque() # vis = {} for i in range(1,n+1): if indeg[i]==0: q.append(i) # vis[i] = 1 cnt = 0 top = [] while q: s = q.popleft() top.append(s) for i in gr0[s]: indeg[i]-=1 if indeg[i]==0: q.append(i) cnt+=1 if cnt!=n: print("NO") continue mp = {} for i in range(n): mp[top[i]] = i for x,y in edges: if mp[x]<mp[y]: gr0[x].append(y) else: gr0[y].append(x) print("YES") for i in gr0.keys(): for j in gr0[i]: print(i,j)
1594996500
[ "constructive algorithms", "dfs and similar", "graphs" ]
1 second
["1 5", "1 5"]
77919677f562a6fd1af64bc8cbc79de5
NoteIn the first text sample all 5 participants earn 2 points each in any case. Depending on the jury's decision, Vasya can get the first (the best) as well as the last (the worst) fifth place.In the second test sample in the best case scenario Vasya wins again: he can win 12 points and become the absolute winner if the total results' table looks like that β€” {4:8, 6:4, 3:6, 4:4, 4:3, 5:0}.In this table all participants are sorted by decreasing points and we can see how much a participant earned in the first and in the second tour.In the worst case scenario Vasya can get the fifth place if the table looks like that β€” {4:8, 4:6, 6:4, 5:4, 4:3, 3:0}, and he earned 4 and 3 points in the first and second tours, correspondingly.
A boy named Vasya has taken part in an Olympiad. His teacher knows that in total Vasya got at least x points for both tours of the Olympiad. The teacher has the results of the first and the second tour of the Olympiad but the problem is, the results have only points, no names. The teacher has to know Vasya's chances.Help Vasya's teacher, find two numbers β€” the best and the worst place Vasya could have won. Note that the total results' table sorts the participants by the sum of points for both tours (the first place has the participant who has got the most points). If two or more participants have got the same number of points, it's up to the jury to assign places to them according to their choice. It is guaranteed that each participant of the Olympiad participated in both tours of the Olympiad.
Print two space-separated integers β€” the best and the worst place Vasya could have got on the Olympiad.
The first line contains two space-separated integers n, x (1 ≀ n ≀ 105;Β 0 ≀ x ≀ 2Β·105) β€” the number of Olympiad participants and the minimum number of points Vasya earned. The second line contains n space-separated integers: a1, a2, ..., an (0 ≀ ai ≀ 105) β€” the participants' points in the first tour. The third line contains n space-separated integers: b1, b2, ..., bn (0 ≀ bi ≀ 105) β€” the participants' points in the second tour. The participants' points are given in the arbitrary order. It is guaranteed that Vasya was present in the Olympiad β€” there are two integers i, j (1 ≀ i, j ≀ n) such, that ai + bj β‰₯ x.
standard output
standard input
Python 3
Python
1,900
train_000.jsonl
6f8e8ba5f7a06b176d5ae3d848febe27
256 megabytes
["5 2\n1 1 1 1 1\n1 1 1 1 1", "6 7\n4 3 5 6 4 4\n8 6 0 4 3 4"]
PASSED
n, s = map(int, input().split()) a = sorted(map(int, input().split()), reverse = True) b = sorted(map(int, input().split())) i = j = 0 while i < n and j < n: if a[i] + b[j] < s: j += 1 else: i += 1 j += 1 print(1, i)
1347291900
[ "two pointers", "binary search", "sortings", "greedy" ]
2 seconds
["5 3 1 2 4", "7 3 2 1 4 5 6", "7 4 2 3 6 5 1", "2 1 4 5 3"]
bef323e7c8651cc78c49db38e49ba53d
null
There are $$$n$$$ friends who want to give gifts for the New Year to each other. Each friend should give exactly one gift and receive exactly one gift. The friend cannot give the gift to himself.For each friend the value $$$f_i$$$ is known: it is either $$$f_i = 0$$$ if the $$$i$$$-th friend doesn't know whom he wants to give the gift to or $$$1 \le f_i \le n$$$ if the $$$i$$$-th friend wants to give the gift to the friend $$$f_i$$$.You want to fill in the unknown values ($$$f_i = 0$$$) in such a way that each friend gives exactly one gift and receives exactly one gift and there is no friend who gives the gift to himself. It is guaranteed that the initial information isn't contradictory.If there are several answers, you can print any.
Print $$$n$$$ integers $$$nf_1, nf_2, \dots, nf_n$$$, where $$$nf_i$$$ should be equal to $$$f_i$$$ if $$$f_i \ne 0$$$ or the number of friend whom the $$$i$$$-th friend wants to give the gift to. All values $$$nf_i$$$ should be distinct, $$$nf_i$$$ cannot be equal to $$$i$$$. Each friend gives exactly one gift and receives exactly one gift and there is no friend who gives the gift to himself. If there are several answers, you can print any.
The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) β€” the number of friends. The second line of the input contains $$$n$$$ integers $$$f_1, f_2, \dots, f_n$$$ ($$$0 \le f_i \le n$$$, $$$f_i \ne i$$$, all $$$f_i \ne 0$$$ are distinct), where $$$f_i$$$ is the either $$$f_i = 0$$$ if the $$$i$$$-th friend doesn't know whom he wants to give the gift to or $$$1 \le f_i \le n$$$ if the $$$i$$$-th friend wants to give the gift to the friend $$$f_i$$$. It is also guaranteed that there is at least two values $$$f_i = 0$$$.
standard output
standard input
Python 2
Python
1,500
train_005.jsonl
db0bff0f1fc2d9a07f73a948b77a9625
256 megabytes
["5\n5 0 0 2 4", "7\n7 0 0 1 4 0 6", "7\n7 4 0 3 0 5 1", "5\n2 1 0 0 0"]
PASSED
# -*- coding: utf-8 -*- import sys def read_int_list(): return map(int, sys.stdin.readline().strip().split()) def read_int(): return int(sys.stdin.readline().strip()) def solve(): _ = read_int() friends = read_int_list() with_present = set() unknown = set() for idx, f in enumerate(friends, 1): if f > 0: with_present.add(f) else: unknown.add(idx) without_present = set(xrange(1, len(friends) + 1)) - with_present # print('with present', with_present) # print('without present', without_present) # print('unknown', unknown) hm = {} common = unknown.intersection(without_present) for u in common: removed = False if u in without_present: without_present.remove(u) removed = True el = without_present.pop() hm[u] = el if removed: without_present.add(u) unknown = unknown - common for u in unknown: el = without_present.pop() hm[u] = el # print('u', u, 'without present', without_present, 'hm', hm) # print('hm', hm) for i in xrange(len(friends)): idx = i + 1 v = friends[i] if v == 0: friends[i] = hm[idx] sys.stdout.write(' '.join(map(str, friends)) + '\n') solve()
1577552700
[ "data structures", "constructive algorithms", "math" ]
2 seconds
["8\n998"]
80c75a4c163c6b63a614075e094ad489
NoteIn the second test case (with $$$n = 3$$$), if uncle Bogdan had $$$x = 998$$$ then $$$k = 100110011000$$$. Denis (by wiping last $$$n = 3$$$ digits) will obtain $$$r = 100110011$$$.It can be proved that the $$$100110011$$$ is the maximum possible $$$r$$$ Denis can obtain and $$$998$$$ is the minimum $$$x$$$ to obtain it.
Captain Flint and his crew keep heading to a savage shore of Byteland for several months already, drinking rum and telling stories. In such moments uncle Bogdan often remembers his nephew Denis. Today, he has told a story about how Denis helped him to come up with an interesting problem and asked the crew to solve it.In the beginning, uncle Bogdan wrote on a board a positive integer $$$x$$$ consisting of $$$n$$$ digits. After that, he wiped out $$$x$$$ and wrote integer $$$k$$$ instead, which was the concatenation of binary representations of digits $$$x$$$ consists of (without leading zeroes). For example, let $$$x = 729$$$, then $$$k = 111101001$$$ (since $$$7 = 111$$$, $$$2 = 10$$$, $$$9 = 1001$$$).After some time, uncle Bogdan understood that he doesn't know what to do with $$$k$$$ and asked Denis to help. Denis decided to wipe last $$$n$$$ digits of $$$k$$$ and named the new number as $$$r$$$.As a result, Denis proposed to find such integer $$$x$$$ of length $$$n$$$ that $$$r$$$ (as number) is maximum possible. If there are multiple valid $$$x$$$ then Denis is interested in the minimum one.All crew members, including captain Flint himself, easily solved the task. All, except cabin boy Kostya, who was too drunk to think straight. But what about you?Note: in this task, we compare integers ($$$x$$$ or $$$k$$$) as numbers (despite what representations they are written in), so $$$729 &lt; 1999$$$ or $$$111 &lt; 1000$$$.
For each test case, print the minimum integer $$$x$$$ of length $$$n$$$ such that obtained by Denis number $$$r$$$ is maximum possible.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β€” the number of test cases. Next $$$t$$$ lines contain test casesΒ β€” one per test case. The one and only line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β€” the length of the integer $$$x$$$ you need to find. It's guaranteed that the sum of $$$n$$$ from all test cases doesn't exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3
Python
1,000
train_005.jsonl
55e84ca9d1187dd71ba802557aacadf0
256 megabytes
["2\n1\n3"]
PASSED
t=int(input()) for i in range(t): x=int(input()) ans=8 u=0 an="" n=0 if x<=4: for i in range(u+1,x): ans+=(9)*(10**i) print(ans) else: a="" q=(x-1)//4 a+='9'*(x-q-1) a+='8'*(q+1) print(int(a))
1596119700
[ "greedy", "math" ]
2 seconds
["500000004", "0", "230769233"]
08b0292d639afd9b52c93a4978f9b2f7
NoteIn the first sample, the first word can be converted into (1) or (2). The second option is the only one that will make it lexicographically larger than the second word. So, the answer to the problem will be , that is 500000004, because .In the second example, there is no replacement for the zero in the second word that will make the first one lexicographically larger. So, the answer to the problem is , that is 0.
Ancient Egyptians are known to have used a large set of symbols to write on the walls of the temples. Fafa and Fifa went to one of the temples and found two non-empty words S1 and S2 of equal lengths on the wall of temple written one below the other. Since this temple is very ancient, some symbols from the words were erased. The symbols in the set have equal probability for being in the position of any erased symbol.Fifa challenged Fafa to calculate the probability that S1 is lexicographically greater than S2. Can you help Fafa with this task?You know that , i.Β e. there were m distinct characters in Egyptians' alphabet, in this problem these characters are denoted by integers from 1 to m in alphabet order. A word x is lexicographically greater than a word y of the same length, if the words are same up to some position, and then the word x has a larger character, than the word y.We can prove that the probability equals to some fraction , where P and Q are coprime integers, and . Print as the answer the value , i.Β e. such a non-negative integer less than 109 + 7, such that , where means that a and b give the same remainders when divided by m.
Print the value , where P and Q are coprime and is the answer to the problem.
The first line contains two integers n and m (1 ≀ n,  m ≀ 105) β€” the length of each of the two words and the size of the alphabet , respectively. The second line contains n integers a1, a2, ..., an (0 ≀ ai ≀ m) β€” the symbols of S1. If ai = 0, then the symbol at position i was erased. The third line contains n integers representing S2 with the same format as S1.
standard output
standard input
Python 3
Python
1,900
train_006.jsonl
caac0bc3dd3c5a1d7b68f7951094e47b
256 megabytes
["1 2\n0\n1", "1 2\n1\n0", "7 26\n0 15 12 9 13 0 14\n11 1 0 13 15 12 0"]
PASSED
def main(): n, m = map(int,input().split()) S1 = list(map(int,input().split())) S2 = list(map(int,input().split())) p = 0; q = 1; mod = 1000000007 prbq = 1; for i in range (0,n): if(S1[i]==S2[i]): if(S1[i]==0): p = (p*prbq*2*m+q*(m-1))%mod q = q*prbq*2*m%mod prbq = prbq*m%mod continue elif(S1[i]>S2[i]): if(S2[i]!=0): p = (p*prbq+q)%mod q = (q*prbq)%mod break p = (p*m*prbq+q*(S1[i]-1))%mod q = (q*prbq*m)%mod prbq = prbq*m%mod else: if(S1[i]!=0): break p = (p*m*prbq+q*(m-S2[i]))%mod q = (q*prbq*m)%mod prbq = prbq*m%mod print(p*pow(q,mod-2,mod)%mod) main()
1519058100
[ "probabilities", "math" ]
1 second
["Matching\n2\nIndSet\n1\nIndSet\n2 4\nMatching\n1 15"]
0cca30daffe672caa6a6fdbb6a935f43
NoteThe first two graphs are same, and there are both a matching of size 1 and an independent set of size 1. Any of these matchings and independent sets is a correct answer.The third graph does not have a matching of size 2, however, there is an independent set of size 2. Moreover, there is an independent set of size 5: 2 3 4 5 6. However such answer is not correct, because you are asked to find an independent set (or matching) of size exactly $$$n$$$.The fourth graph does not have an independent set of size 2, but there is a matching of size 2.
You are given a graph with $$$3 \cdot n$$$ vertices and $$$m$$$ edges. You are to find a matching of $$$n$$$ edges, or an independent set of $$$n$$$ vertices.A set of edges is called a matching if no two edges share an endpoint.A set of vertices is called an independent set if no two vertices are connected with an edge.
Print your answer for each of the $$$T$$$ graphs. Output your answer for a single graph in the following format. If you found a matching of size $$$n$$$, on the first line print "Matching" (without quotes), and on the second line print $$$n$$$ integersΒ β€” the indices of the edges in the matching. The edges are numbered from $$$1$$$ to $$$m$$$ in the input order. If you found an independent set of size $$$n$$$, on the first line print "IndSet" (without quotes), and on the second line print $$$n$$$ integersΒ β€” the indices of the vertices in the independent set. If there is no matching and no independent set of the specified size, print "Impossible" (without quotes). You can print edges and vertices in any order. If there are several solutions, print any. In particular, if there are both a matching of size $$$n$$$, and an independent set of size $$$n$$$, then you should print exactly one of such matchings or exactly one of such independent sets.
The first line contains a single integer $$$T \ge 1$$$Β β€” the number of graphs you need to process. The description of $$$T$$$ graphs follows. The first line of description of a single graph contains two integers $$$n$$$ and $$$m$$$, where $$$3 \cdot n$$$ is the number of vertices, and $$$m$$$ is the number of edges in the graph ($$$1 \leq n \leq 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$). Each of the next $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ ($$$1 \leq v_i, u_i \leq 3 \cdot n$$$), meaning that there is an edge between vertices $$$v_i$$$ and $$$u_i$$$. It is guaranteed that there are no self-loops and no multiple edges in the graph. It is guaranteed that the sum of all $$$n$$$ over all graphs in a single test does not exceed $$$10^{5}$$$, and the sum of all $$$m$$$ over all graphs in a single test does not exceed $$$5 \cdot 10^{5}$$$.
standard output
standard input
PyPy 3
Python
2,000
train_006.jsonl
8980f99302324d7e031f5fd5b9e94516
256 megabytes
["4\n1 2\n1 3\n1 2\n1 2\n1 3\n1 2\n2 5\n1 2\n3 1\n1 4\n5 1\n1 6\n2 15\n1 2\n1 3\n1 4\n1 5\n1 6\n2 3\n2 4\n2 5\n2 6\n3 4\n3 5\n3 6\n4 5\n4 6\n5 6"]
PASSED
import sys input = sys.stdin.readline def main(): tes = int(input()) for testcase in [0]*tes: n,m = map(int,input().split()) new = [True]*(3*n) res = [] for i in range(1,m+1): u,v = map(int,input().split()) if new[u-1] and new[v-1]: if len(res) < n: res.append(i) new[u-1] = new[v-1] = False if len(res) >= n: print("Matching") print(*res) else: vs = [] for i in range(3*n): if new[i]: vs.append(i+1) if len(vs) >= n: break print("IndSet") print(*vs) if __name__ == '__main__': main()
1564497300
[ "constructive algorithms", "greedy", "graphs" ]
2 seconds
["2", "4"]
75d500bad37fbd2c5456a942bde09cd3
NoteIn the first sample, friends 3 and 4 can come on any day in range [117, 128].In the second sample, friends with indices 3, 4, 5 and 6 can come on day 140.
Famil Door wants to celebrate his birthday with his friends from Far Far Away. He has n friends and each of them can come to the party in a specific range of days of the year from ai to bi. Of course, Famil Door wants to have as many friends celebrating together with him as possible.Far cars are as weird as Far Far Away citizens, so they can only carry two people of opposite gender, that is exactly one male and one female. However, Far is so far from here that no other transportation may be used to get to the party.Famil Door should select some day of the year and invite some of his friends, such that they all are available at this moment and the number of male friends invited is equal to the number of female friends invited. Find the maximum number of friends that may present at the party.
Print the maximum number of people that may come to Famil Door's party.
The first line of the input contains a single integer n (1 ≀ n ≀ 5000)Β β€” then number of Famil Door's friends. Then follow n lines, that describe the friends. Each line starts with a capital letter 'F' for female friends and with a capital letter 'M' for male friends. Then follow two integers ai and bi (1 ≀ ai ≀ bi ≀ 366), providing that the i-th friend can come to the party from day ai to day bi inclusive.
standard output
standard input
Python 3
Python
1,100
train_006.jsonl
44d8c304791e218d734c270396caaf3d
256 megabytes
["4\nM 151 307\nF 343 352\nF 117 145\nM 24 128", "6\nM 128 130\nF 128 131\nF 131 140\nF 131 141\nM 131 200\nM 140 200"]
PASSED
n = int(input()) m = [0 for _ in range(366 + 1)] f = [0 for _ in range(366 + 1)] for i in range(n): g, a, b = input().split() a, b = int(a), int(b) if g == 'M': for j in range(a, b + 1): m[j] += 1 else: for j in range(a, b + 1): f[j] += 1 answ = 0 for i in range(1, 366 + 1): answ = max(answ, min(m[i], f[i]) * 2) print(answ)
1455986100
[ "brute force" ]
2 seconds
["6.4641016", "1.0000000", "3.2429391"]
e27cff5d681217460d5238bf7ef6a876
null
NN is an experienced internet user and that means he spends a lot of time on the social media. Once he found the following image on the Net, which asked him to compare the sizes of inner circles: It turned out that the circles are equal. NN was very surprised by this fact, so he decided to create a similar picture himself.He managed to calculate the number of outer circles $$$n$$$ and the radius of the inner circle $$$r$$$. NN thinks that, using this information, you can exactly determine the radius of the outer circles $$$R$$$ so that the inner circle touches all of the outer ones externally and each pair of neighboring outer circles also touches each other. While NN tried very hard to guess the required radius, he didn't manage to do that. Help NN find the required radius for building the required picture.
Output a single number $$$R$$$Β β€” the radius of the outer circle required for building the required picture. Your answer will be accepted if its relative or absolute error does not exceed $$$10^{-6}$$$. Formally, if your answer is $$$a$$$ and the jury's answer is $$$b$$$. Your answer is accepted if and only when $$$\frac{|a-b|}{max(1, |b|)} \le 10^{-6}$$$.
The first and the only line of the input file contains two numbers $$$n$$$ and $$$r$$$ ($$$3 \leq n \leq 100$$$, $$$1 \leq r \leq 100$$$)Β β€” the number of the outer circles and the radius of the inner circle respectively.
standard output
standard input
Python 3
Python
1,200
train_006.jsonl
3cab2a35d6eaf514095fb2166c897ab7
256 megabytes
["3 1", "6 1", "100 100"]
PASSED
import math def quadratic(a, b, c): return (-1 * b + math.sqrt(b * b - 4 * a * c))/(2 * a) PI = 3.14159265 x = input().split() n = int(x[0]) r = int(x[1]) k = 360.0/n; R = quadratic((2/(1-math.cos(k * PI/180)))-1, - 2 * r, - r * r); print(R)
1547390100
[ "binary search", "geometry", "math" ]
1 second
["YES"]
d8a5578de51d6585d434516da6222204
NoteOn the picture below, the two polygons are well-connected, as the edges of the vertical polygon cross the area of the horizontal one exactly once in one direction (for example, from above to below), and zero times in the other (in this case, from below to above). Note that the polygons do not have to be parallel to any of the xy-,xz-,yz- planes in general.
Cowboy Beblop is a funny little boy who likes sitting at his computer. He somehow obtained two elastic hoops in the shape of 2D polygons, which are not necessarily convex. Since there's no gravity on his spaceship, the hoops are standing still in the air. Since the hoops are very elastic, Cowboy Beblop can stretch, rotate, translate or shorten their edges as much as he wants.For both hoops, you are given the number of their vertices, as well as the position of each vertex, defined by the X , Y and Z coordinates. The vertices are given in the order they're connected: the 1stβ€―vertex is connected to the 2nd, which is connected to the 3rd, etc., and the last vertex is connected to the first one. Two hoops are connected if it's impossible to pull them to infinity in different directions by manipulating their edges, without having their edges or vertices intersect at any point – just like when two links of a chain are connected. The polygons' edges do not intersect or overlap. To make things easier, we say that two polygons are well-connected, if the edges of one polygon cross the area of the other polygon in two different directions (from the upper and lower sides of the plane defined by that polygon) a different number of times.Cowboy Beblop is fascinated with the hoops he has obtained and he would like to know whether they are well-connected or not. Since he’s busy playing with his dog, Zwei, he’d like you to figure it out for him. He promised you some sweets if you help him!
Your output should contain only one line, with the words "YES" or "NO", depending on whether the two given polygons are well-connected.
The first line of input contains an integer n (3 ≀ n ≀ 100 000), which denotes the number of edges of the first polygon. The next N lines each contain the integers x, y and z ( - 1 000 000 ≀ x, y, z ≀ 1 000 000)Β β€” coordinates of the vertices, in the manner mentioned above. The next line contains an integer m (3 ≀ m ≀ 100 000) , denoting the number of edges of the second polygon, followed by m lines containing the coordinates of the second polygon’s vertices. It is guaranteed that both polygons are simple (no self-intersections), and in general that the obtained polygonal lines do not intersect each other. Also, you can assume that no 3 consecutive points of a polygon lie on the same line.
standard output
standard input
PyPy 3
Python
2,800
train_006.jsonl
f53ddde251732f334ce1b246b608a19b
256 megabytes
["4\n0 0 0\n2 0 0\n2 2 0\n0 2 0\n4\n1 1 -1\n1 1 1\n1 3 1\n1 3 -1"]
PASSED
from math import gcd, sqrt from functools import reduce import sys input = sys.stdin.readline EPS = 0.000000001 def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def GCD(args): return reduce(gcd, args) def plane_value(plane, point): A, B, C, D = plane x, y, z = point return A*x + B*y + C*z + D def plane(p1, p2, p3): x1, y1, z1 = p1 x2, y2, z2 = p2 x3, y3, z3 = p3 a1, b1, c1 = x2 - x1, y2 - y1, z2 - z1 a2, b2, c2 = x3 - x1, y3 - y1, z3 - z1 a, b, c = b1 * c2 - b2 * c1, a2 * c1 - a1 * c2, a1 * b2 - b1 * a2 d = (- a * x1 - b * y1 - c * z1) g = GCD([a,b,c,d]) return a//g, b//g, c//g, d//g def cross(a, b): return (a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]) def intersection_of_two_planes(p1, p2): A1, B1, C1, D1 = p1 A2, B2, C2, D2 = p2 crossprod = cross([A1,B1,C1],[A2,B2,C2]) if (A1*B2-A2*B1) != 0: x = ((B1*D2-B2*D1)/(A1*B2-A2*B1), crossprod[0]) y = ((A2*D1-A1*D2)/(A1*B2-A2*B1), crossprod[1]) z = (0,crossprod[2]) elif (B1*C2-B2*C1) != 0: x = (0,crossprod[0]) y = ((C1*D2-C2*D1)/(B1*C2-B2*C1), crossprod[1]) z = ((B2*D1-B1*D2)/(B1*C2-B2*C1), crossprod[2]) elif (A1*C2-A2*C1) != 0: x = ((C1*D2-C2*D1)/(A1*C2-A2*C1), crossprod[0]) y = (0,crossprod[1]) z = ((A2*D1-A1*D2)/(A1*C2-A2*C1), crossprod[2]) else: return None return x, y, z def line_parametric(p1, p2): x1, y1, z1 = p1 x2, y2, z2 = p2 return (x2,x1-x2), (y2,y1-y2), (z2,z1-z2) def solve_2_by_2(row1, row2): a1, b1, c1 = row1 a2, b2, c2 = row2 if a1*b2-b1*a2: return (c1*b2-b1*c2)/(a1*b2-b1*a2), (a1*c2-c1*a2)/(a1*b2-b1*a2) else: return None def sgn(x): return 1 if x>0 else 0 if x==0 else -1 def lines_intersection_point(i1, i2): x1, y1, z1 = i1 x2, y2, z2 = i2 try: t1, t2 = solve_2_by_2([x1[1], -x2[1], x2[0]-x1[0]], [y1[1], -y2[1], y2[0]-y1[0]]) if abs(t1*z1[1] - t2*z2[1] - z2[0] + z1[0]) < EPS: return (x1[0]+t1*x1[1], y1[0]+t1*y1[1], z1[0]+t1*z1[1]), t2 else: return None except: try: t1, t2 = solve_2_by_2([x1[1], -x2[1], x2[0]-x1[0]], [z1[1], -z2[1], z2[0]-z1[0]]) if abs(t1*y1[1] - t2*y2[1] - y2[0] + y1[0]) < EPS: return (x1[0]+t1*x1[1], y1[0]+t1*y1[1], z1[0]+t1*z1[1]), t2 else: return None except: try: t1, t2 = solve_2_by_2([y1[1], -y2[1], y2[0]-y1[0]], [z1[1], -z2[1], z2[0]-z1[0]]) if abs(t1*x1[1] - t2*x2[1] - x2[0] + x1[0]) < EPS: return (x1[0]+t1*x1[1], y1[0]+t1*y1[1], z1[0]+t1*z1[1]), t2 else: return None except: return None def foo(points): down_cnt, up_cnt = 0, 0 first = points[0] other = 1-first down = True intrusion = True for p in points[1:]: if p==first: intrusion = not intrusion else: if intrusion: if down: down_cnt+=1 else: up_cnt+=1 down = not down return down_cnt==up_cnt def populate(plane, poly, tag): res = [] prev = plane_value(plane,poly[-1]) prev_serious = plane_value(plane,poly[-2]) if not prev else prev p_prev = poly[-1] for i in range(len(poly)+1): p = poly[i%len(poly)] curr = plane_value(plane,p) if sgn(curr) == -sgn(prev_serious): intersector = line_parametric(p_prev,p) point, t = lines_intersection_point(intersector,intersectee) res.append((t,tag)) prev_serious = curr if sgn(curr): prev_serious = curr prev, p_prev = curr, p return res x_poly, y_poly = [], [] for _ in range(inp()): x_poly.append(inlt()) for _ in range(inp()): y_poly.append(inlt()) x_plane = plane(*x_poly[:3]) y_plane = plane(*y_poly[:3]) intersectee = intersection_of_two_planes(x_plane,y_plane) if intersectee: points = sorted(set(populate(y_plane,x_poly,0) + populate(x_plane,y_poly,1))) points = [i[1] for i in points] print('NO' if foo(points) else 'YES') else: print('NO')
1473584400
[ "geometry" ]
2 seconds
["3", "6"]
2ff325f206b0188713639a6cf83c2845
null
The Little Elephant has array a, consisting of n positive integers, indexed from 1 to n. Let's denote the number with index i as ai.The Little Elephant wants to count, how many pairs of integers l and r are there, such that 1 ≀ l &lt; r ≀ n and sequence b = a1a2... alarar + 1... an has no more than k inversions. An inversion in sequence b is a pair of elements of the sequence b, that change their relative order after a stable sorting of the sequence. In other words, an inversion is a pair of integers i and j, such that 1 ≀ i &lt; j ≀ |b| and bi &gt; bj, where |b| is the length of sequence b, and bj is its j-th element.Help the Little Elephant and count the number of the described pairs.
In a single line print a single number β€” the answer to the problem.
The first line contains two integers n and k (2 ≀ n ≀ 105, 0 ≀ k ≀ 1018) β€” the size of array a and the maximum allowed number of inversions respectively. The next line contains n positive integers, separated by single spaces, a1, a2, ..., an (1 ≀ ai ≀ 109) β€” elements of array a. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier.
standard output
standard input
PyPy 3
Python
2,400
train_006.jsonl
e2aba508aea2282d0d0298c91afe1eef
256 megabytes
["3 1\n1 3 2", "5 2\n1 3 2 1 7"]
PASSED
# 220E import sys from collections import defaultdict class BIT(): def __init__(self, n): self.n = n self.tree = [0] * n def _F(self, i): return i & (i + 1) def _get_sum(self, r): ''' sum on interval [0, r) ''' result = 0 while r > 0: result += self.tree[r-1] r = self._F(r-1) return result def get_sum(self, l, r): ''' sum on interval [l, r) ''' return self._get_sum(r) - self._get_sum(l) def _H(self, i): return i | (i + 1) def add(self, i, value=1): while i < self.n: self.tree[i] += value i = self._H(i) reader = (line.rstrip() for line in sys.stdin) input = reader.__next__ n, k = map(int, input().split()) a = list(map(int, input().split())) pos = defaultdict(list) for i, val in enumerate(a): pos[val].append(i) i = 0 prev = -1 for val in sorted(a): if prev == val: continue for j in pos[val]: a[j] = i i += 1 prev = val left = BIT(n) right = BIT(n) total_inv = 0 left.add(a[0]) for t in range(1, n): i = a[t] total_inv += right.get_sum(i+1, n) right.add(i) if i < a[0]: total_inv += 1 if total_inv <= k: print((n*(n-1))>>1) sys.exit() l = 0 r = 1 while r < n and total_inv > k: total_inv -= left.get_sum(a[r]+1, n) + right.get_sum(0, a[r]) right.add(a[r], -1) r += 1 pairs = 0 while r < n: while True: add = left.get_sum(a[l+1]+1, n) + right.get_sum(0, a[l+1]) if total_inv + add > k: pairs += l + 1 break else: l += 1 total_inv += add left.add(a[l]) total_inv -= left.get_sum(a[r]+1, n) + right.get_sum(0, a[r]) right.add(a[r], -1) r += 1 print(pairs)
1346427000
[ "data structures", "two pointers" ]
1.5 seconds
["5", "60"]
d38c18b0b6716cccbe11eab7b4df8c3a
null
Leha is planning his journey from Moscow to Saratov. He hates trains, so he has decided to get from one city to another by car.The path from Moscow to Saratov can be represented as a straight line (well, it's not that straight in reality, but in this problem we will consider it to be straight), and the distance between Moscow and Saratov is $$$n$$$ km. Let's say that Moscow is situated at the point with coordinate $$$0$$$ km, and Saratov β€” at coordinate $$$n$$$ km.Driving for a long time may be really difficult. Formally, if Leha has already covered $$$i$$$ kilometers since he stopped to have a rest, he considers the difficulty of covering $$$(i + 1)$$$-th kilometer as $$$a_{i + 1}$$$. It is guaranteed that for every $$$i \in [1, n - 1]$$$ $$$a_i \le a_{i + 1}$$$. The difficulty of the journey is denoted as the sum of difficulties of each kilometer in the journey.Fortunately, there may be some rest sites between Moscow and Saratov. Every integer point from $$$1$$$ to $$$n - 1$$$ may contain a rest site. When Leha enters a rest site, he may have a rest, and the next kilometer will have difficulty $$$a_1$$$, the kilometer after it β€” difficulty $$$a_2$$$, and so on.For example, if $$$n = 5$$$ and there is a rest site in coordinate $$$2$$$, the difficulty of journey will be $$$2a_1 + 2a_2 + a_3$$$: the first kilometer will have difficulty $$$a_1$$$, the second one β€” $$$a_2$$$, then Leha will have a rest, and the third kilometer will have difficulty $$$a_1$$$, the fourth β€” $$$a_2$$$, and the last one β€” $$$a_3$$$. Another example: if $$$n = 7$$$ and there are rest sites in coordinates $$$1$$$ and $$$5$$$, the difficulty of Leha's journey is $$$3a_1 + 2a_2 + a_3 + a_4$$$.Leha doesn't know which integer points contain rest sites. So he has to consider every possible situation. Obviously, there are $$$2^{n - 1}$$$ different distributions of rest sites (two distributions are different if there exists some point $$$x$$$ such that it contains a rest site in exactly one of these distributions). Leha considers all these distributions to be equiprobable. He wants to calculate $$$p$$$ β€” the expected value of difficulty of his journey.Obviously, $$$p \cdot 2^{n - 1}$$$ is an integer number. You have to calculate it modulo $$$998244353$$$.
Print one number β€” $$$p \cdot 2^{n - 1}$$$, taken modulo $$$998244353$$$.
The first line contains one number $$$n$$$ ($$$1 \le n \le 10^6$$$) β€” the distance from Moscow to Saratov. The second line contains $$$n$$$ integer numbers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_1 \le a_2 \le \dots \le a_n \le 10^6$$$), where $$$a_i$$$ is the difficulty of $$$i$$$-th kilometer after Leha has rested.
standard output
standard input
Python 3
Python
2,000
train_006.jsonl
ad03c90f3bc92096a151071fb4a1de1d
256 megabytes
["2\n1 2", "4\n1 3 3 7"]
PASSED
a = int(input()) b = list(map(int,input().split())) c = b[0]%998244353 d = b[0]%998244353 for i in range(1,a): c = (2*c + d + b[i])%998244353 d = (2*d + b[i])%998244353 print(c)
1531578900
[ "combinatorics", "probabilities", "math" ]
End of preview.

No dataset card yet

New: Create and edit this dataset card directly on the website!

Contribute a Dataset Card
Downloads last month
0
Add dataset card