message
stringlengths
2
45.8k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
254
108k
cluster
float64
3
3
__index_level_0__
int64
508
217k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently an official statement of the world Olympic Committee said that the Olympic Winter Games 2030 will be held in Tomsk. The city officials decided to prepare for the Olympics thoroughly and to build all the necessary Olympic facilities as early as possible. First, a biathlon track will be built. To construct a biathlon track a plot of land was allocated, which is a rectangle divided into n × m identical squares. Each of the squares has two coordinates: the number of the row (from 1 to n), where it is located, the number of the column (from 1 to m), where it is located. Also each of the squares is characterized by its height. During the sports the biathletes will have to move from one square to another. If a biathlete moves from a higher square to a lower one, he makes a descent. If a biathlete moves from a lower square to a higher one, he makes an ascent. If a biathlete moves between two squares with the same height, then he moves on flat ground. The biathlon track should be a border of some rectangular area of the allocated land on which biathletes will move in the clockwise direction. It is known that on one move on flat ground an average biathlete spends tp seconds, an ascent takes tu seconds, a descent takes td seconds. The Tomsk Administration wants to choose the route so that the average biathlete passes it in as close to t seconds as possible. In other words, the difference between time ts of passing the selected track and t should be minimum. For a better understanding you can look at the first sample of the input data. In this sample n = 6, m = 7, and the administration wants the track covering time to be as close to t = 48 seconds as possible, also, tp = 3, tu = 6 and td = 2. If we consider the rectangle shown on the image by arrows, the average biathlete can move along the boundary in a clockwise direction in exactly 48 seconds. The upper left corner of this track is located in the square with the row number 4, column number 3 and the lower right corner is at square with row number 6, column number 7. <image> Among other things the administration wants all sides of the rectangle which boundaries will be the biathlon track to consist of no less than three squares and to be completely contained within the selected land. You are given the description of the given plot of land and all necessary time values. You are to write the program to find the most suitable rectangle for a biathlon track. If there are several such rectangles, you are allowed to print any of them. Input The first line of the input contains three integers n, m and t (3 ≤ n, m ≤ 300, 1 ≤ t ≤ 109) — the sizes of the land plot and the desired distance covering time. The second line also contains three integers tp, tu and td (1 ≤ tp, tu, td ≤ 100) — the time the average biathlete needs to cover a flat piece of the track, an ascent and a descent respectively. Then n lines follow, each line contains m integers that set the heights of each square of the given plot of land. Each of the height values is a positive integer, not exceeding 106. Output In a single line of the output print four positive integers — the number of the row and the number of the column of the upper left corner and the number of the row and the number of the column of the lower right corner of the rectangle that is chosen for the track. Examples Input 6 7 48 3 6 2 5 4 8 3 3 7 9 4 1 6 8 7 1 1 1 6 4 6 4 8 6 7 2 6 1 6 9 4 1 9 8 6 3 9 2 4 5 6 8 4 3 7 Output 4 3 6 7 Submitted Solution: ``` n,m,t = map(int, input().split()) p,u,d = map(int, input().split()) h = [None] * n for i in range(n): h[i] = [int(i) for i in input().split()] row = [None] * n col = [None] * m for i in range(n): row[i] = [None] * m for j in range(m): row[i][j] = [None] * m row[i][j][j] = 0 for k in range(j-1, -1, -1): if h[i][k+1] > h[i][k]: row[i][j][k] = row[i][j][k+1] + d elif h[i][k+1] == h[i][k]: row[i][j][k] = row[i][j][k+1] + p else: row[i][j][k] = row[i][j][k+1] + u for k in range(j+1,m): if h[i][k-1] > h[i][k]: row[i][j][k] = row[i][j][k-1] + d elif h[i][k-1] == h[i][k]: row[i][j][k] = row[i][j][k-1] + p else: row[i][j][k] = row[i][j][k-1] + u for i in range(m): col[i] = [0] * (n * n) for j in range(n): col[i][j] = [None] * n col[i][j][j] = 0 for k in range(j-1,-1,-1): if h[k+1][i] > h[k][i]: col[i][j][k] = col[i][j][k+1]+d elif h[k+1][i] == h[k][i]: col[i][j][k] = col[i][j][k+1]+p else: col[i][j][k] = col[i][j][k+1]+u for k in range(j+1,n): if h[k-1][i] > h[k][i]: col[i][j][k] = col[i][j][k-1]+d elif h[k-1][i] == h[k][i]: col[i][j][k] = col[i][j][k-1]+p else: col[i][j][k] = col[i][j][k-1]+u r = [0,0,0,0] tt = 9000001 for i in range(n): for j in range(i+1,n): for k in range(m): for l in range(k+1,m): ct = row[i][k][l] + row[j][l][k] + col[k][j][i] + col[l][i][j] if abs(ct-t) < tt: r[0] = i r[2] = j r[1] = k r[3] = l tt = abs(ct-t) print(r[0]+1,r[1]+1,r[2]+1,r[3]+1) ```
instruction
0
42,444
3
84,888
No
output
1
42,444
3
84,889
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently an official statement of the world Olympic Committee said that the Olympic Winter Games 2030 will be held in Tomsk. The city officials decided to prepare for the Olympics thoroughly and to build all the necessary Olympic facilities as early as possible. First, a biathlon track will be built. To construct a biathlon track a plot of land was allocated, which is a rectangle divided into n × m identical squares. Each of the squares has two coordinates: the number of the row (from 1 to n), where it is located, the number of the column (from 1 to m), where it is located. Also each of the squares is characterized by its height. During the sports the biathletes will have to move from one square to another. If a biathlete moves from a higher square to a lower one, he makes a descent. If a biathlete moves from a lower square to a higher one, he makes an ascent. If a biathlete moves between two squares with the same height, then he moves on flat ground. The biathlon track should be a border of some rectangular area of the allocated land on which biathletes will move in the clockwise direction. It is known that on one move on flat ground an average biathlete spends tp seconds, an ascent takes tu seconds, a descent takes td seconds. The Tomsk Administration wants to choose the route so that the average biathlete passes it in as close to t seconds as possible. In other words, the difference between time ts of passing the selected track and t should be minimum. For a better understanding you can look at the first sample of the input data. In this sample n = 6, m = 7, and the administration wants the track covering time to be as close to t = 48 seconds as possible, also, tp = 3, tu = 6 and td = 2. If we consider the rectangle shown on the image by arrows, the average biathlete can move along the boundary in a clockwise direction in exactly 48 seconds. The upper left corner of this track is located in the square with the row number 4, column number 3 and the lower right corner is at square with row number 6, column number 7. <image> Among other things the administration wants all sides of the rectangle which boundaries will be the biathlon track to consist of no less than three squares and to be completely contained within the selected land. You are given the description of the given plot of land and all necessary time values. You are to write the program to find the most suitable rectangle for a biathlon track. If there are several such rectangles, you are allowed to print any of them. Input The first line of the input contains three integers n, m and t (3 ≤ n, m ≤ 300, 1 ≤ t ≤ 109) — the sizes of the land plot and the desired distance covering time. The second line also contains three integers tp, tu and td (1 ≤ tp, tu, td ≤ 100) — the time the average biathlete needs to cover a flat piece of the track, an ascent and a descent respectively. Then n lines follow, each line contains m integers that set the heights of each square of the given plot of land. Each of the height values is a positive integer, not exceeding 106. Output In a single line of the output print four positive integers — the number of the row and the number of the column of the upper left corner and the number of the row and the number of the column of the lower right corner of the rectangle that is chosen for the track. Examples Input 6 7 48 3 6 2 5 4 8 3 3 7 9 4 1 6 8 7 1 1 1 6 4 6 4 8 6 7 2 6 1 6 9 4 1 9 8 6 3 9 2 4 5 6 8 4 3 7 Output 4 3 6 7 Submitted Solution: ``` n,m,t = map(int, input().split()) p,u,d = map(int, input().split()) h = [None] * n for i in range(n): h[i] = [int(i) for i in input().split()] row = [None] * n col = [None] * m for i in range(n): row[i] = [None] * m for j in range(m): row[i][j] = [None] * m row[i][j][j] = 0 for k in range(j-1, -1, -1): if h[i][k+1] > h[i][k]: row[i][j][k] = row[i][j][k+1] + d elif h[i][k+1] == h[i][k]: row[i][j][k] = row[i][j][k+1] + p else: row[i][j][k] = row[i][j][k+1] + u for k in range(j+1,m): if h[i][k-1] > h[i][k]: row[i][j][k] = row[i][j][k-1] + d elif h[i][k-1] == h[i][k]: row[i][j][k] = row[i][j][k-1] + p else: row[i][j][k] = row[i][j][k-1] + u for i in range(m): col[i] = [0] * (n * n) for j in range(n): col[i][j] = [None] * n col[i][j][j] = 0 for k in range(j-1,-1,-1): if h[k+1][i] > h[k][i]: col[i][j][k] = col[i][j][k+1]+d elif h[k+1][i] == h[k][i]: col[i][j][k] = col[i][j][k+1]+p else: col[i][j][k] = col[i][j][k+1]+u for k in range(j+1,n): if h[k-1][i] > h[k][i]: col[i][j][k] = col[i][j][k-1]+d elif h[k-1][i] == h[k][i]: col[i][j][k] = col[i][j][k-1]+p else: col[i][j][k] = col[i][j][k-1]+u r = [0,0,0,0] tt = 9000001 for i in range(n): for j in range(i+1,n): for k in range(m): for l in range(k+1,m): if (j-i+1) * (l-k+1) < 15: continue ct = row[i][k][l] + row[j][l][k] + col[k][j][i] + col[l][i][j] if abs(ct-t) < tt: r[0] = i r[2] = j r[1] = k r[3] = l tt = abs(ct-t) print(r[0]+1,r[1]+1,r[2]+1,r[3]+1) ```
instruction
0
42,445
3
84,890
No
output
1
42,445
3
84,891
Provide tags and a correct Python 3 solution for this coding contest problem. Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of L meters today. <image> Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner. While watching previous races the organizers have noticed that Willman can perform only steps of length equal to w meters, and Bolt can perform only steps of length equal to b meters. Organizers decided to slightly change the rules of the race. Now, at the end of the racetrack there will be an abyss, and the winner will be declared the athlete, who manages to run farther from the starting point of the the racetrack (which is not the subject to change by any of the athletes). Note that none of the athletes can run infinitely far, as they both will at some moment of time face the point, such that only one step further will cause them to fall in the abyss. In other words, the athlete will not fall into the abyss if the total length of all his steps will be less or equal to the chosen distance L. Since the organizers are very fair, the are going to set the length of the racetrack as an integer chosen randomly and uniformly in range from 1 to t (both are included). What is the probability that Willman and Bolt tie again today? Input The first line of the input contains three integers t, w and b (1 ≤ t, w, b ≤ 5·1018) — the maximum possible length of the racetrack, the length of Willman's steps and the length of Bolt's steps respectively. Output Print the answer to the problem as an irreducible fraction <image>. Follow the format of the samples output. The fraction <image> (p and q are integers, and both p ≥ 0 and q > 0 holds) is called irreducible, if there is no such integer d > 1, that both p and q are divisible by d. Examples Input 10 3 2 Output 3/10 Input 7 1 2 Output 3/7 Note In the first sample Willman and Bolt will tie in case 1, 6 or 7 are chosen as the length of the racetrack.
instruction
0
42,503
3
85,006
Tags: math Correct Solution: ``` n, w, b = map(int, input().split()) from math import gcd L = w*b//gcd(w, b) m = min(b, w) ans = (n-m+1) // L + 1 ans *= m if n // L == (n-m+1) // L: pass else: cn = n // L * L ans += n - cn + 1 ans -= 1 g = gcd(ans, n) print(ans//g,'/',n//g,sep='') ```
output
1
42,503
3
85,007
Provide tags and a correct Python 3 solution for this coding contest problem. Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of L meters today. <image> Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner. While watching previous races the organizers have noticed that Willman can perform only steps of length equal to w meters, and Bolt can perform only steps of length equal to b meters. Organizers decided to slightly change the rules of the race. Now, at the end of the racetrack there will be an abyss, and the winner will be declared the athlete, who manages to run farther from the starting point of the the racetrack (which is not the subject to change by any of the athletes). Note that none of the athletes can run infinitely far, as they both will at some moment of time face the point, such that only one step further will cause them to fall in the abyss. In other words, the athlete will not fall into the abyss if the total length of all his steps will be less or equal to the chosen distance L. Since the organizers are very fair, the are going to set the length of the racetrack as an integer chosen randomly and uniformly in range from 1 to t (both are included). What is the probability that Willman and Bolt tie again today? Input The first line of the input contains three integers t, w and b (1 ≤ t, w, b ≤ 5·1018) — the maximum possible length of the racetrack, the length of Willman's steps and the length of Bolt's steps respectively. Output Print the answer to the problem as an irreducible fraction <image>. Follow the format of the samples output. The fraction <image> (p and q are integers, and both p ≥ 0 and q > 0 holds) is called irreducible, if there is no such integer d > 1, that both p and q are divisible by d. Examples Input 10 3 2 Output 3/10 Input 7 1 2 Output 3/7 Note In the first sample Willman and Bolt will tie in case 1, 6 or 7 are chosen as the length of the racetrack.
instruction
0
42,504
3
85,008
Tags: math Correct Solution: ``` import sys def gcd(a, b): if b == 0: return a return gcd(b, a % b) a, b, c = tuple(map(int, input().split())) if b == c or a < min(b, c): print("1/1") sys.exit(0) ans = min(b, c) - 1 x = b * c // gcd(b, c) ans += ((a // x) * (min(b, c))) y = max((a // x) * x + min(b, c) - 1 - a, 0) ans -= y; y = gcd(ans, a) ans //= y a //= y print(str(ans) + "/" + str(a)) ```
output
1
42,504
3
85,009
Provide tags and a correct Python 3 solution for this coding contest problem. Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of L meters today. <image> Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner. While watching previous races the organizers have noticed that Willman can perform only steps of length equal to w meters, and Bolt can perform only steps of length equal to b meters. Organizers decided to slightly change the rules of the race. Now, at the end of the racetrack there will be an abyss, and the winner will be declared the athlete, who manages to run farther from the starting point of the the racetrack (which is not the subject to change by any of the athletes). Note that none of the athletes can run infinitely far, as they both will at some moment of time face the point, such that only one step further will cause them to fall in the abyss. In other words, the athlete will not fall into the abyss if the total length of all his steps will be less or equal to the chosen distance L. Since the organizers are very fair, the are going to set the length of the racetrack as an integer chosen randomly and uniformly in range from 1 to t (both are included). What is the probability that Willman and Bolt tie again today? Input The first line of the input contains three integers t, w and b (1 ≤ t, w, b ≤ 5·1018) — the maximum possible length of the racetrack, the length of Willman's steps and the length of Bolt's steps respectively. Output Print the answer to the problem as an irreducible fraction <image>. Follow the format of the samples output. The fraction <image> (p and q are integers, and both p ≥ 0 and q > 0 holds) is called irreducible, if there is no such integer d > 1, that both p and q are divisible by d. Examples Input 10 3 2 Output 3/10 Input 7 1 2 Output 3/7 Note In the first sample Willman and Bolt will tie in case 1, 6 or 7 are chosen as the length of the racetrack.
instruction
0
42,505
3
85,010
Tags: math Correct Solution: ``` import fractions def lcm(a, b): return ((a * b) // fractions.gcd(a, b)); def solve(): t, w, b = map(int, input().split()) if w > b: tt = w w = b b = tt l = lcm(w, b) ans = w - 1 c = t // l ans += w * (c - 1) last = l * c ans += min(w, t - last + 1) g = fractions.gcd(ans, t) ans = ans // g t = t // g print(int(ans), '/', int(t), sep='') solve() ```
output
1
42,505
3
85,011
Provide tags and a correct Python 3 solution for this coding contest problem. Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of L meters today. <image> Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner. While watching previous races the organizers have noticed that Willman can perform only steps of length equal to w meters, and Bolt can perform only steps of length equal to b meters. Organizers decided to slightly change the rules of the race. Now, at the end of the racetrack there will be an abyss, and the winner will be declared the athlete, who manages to run farther from the starting point of the the racetrack (which is not the subject to change by any of the athletes). Note that none of the athletes can run infinitely far, as they both will at some moment of time face the point, such that only one step further will cause them to fall in the abyss. In other words, the athlete will not fall into the abyss if the total length of all his steps will be less or equal to the chosen distance L. Since the organizers are very fair, the are going to set the length of the racetrack as an integer chosen randomly and uniformly in range from 1 to t (both are included). What is the probability that Willman and Bolt tie again today? Input The first line of the input contains three integers t, w and b (1 ≤ t, w, b ≤ 5·1018) — the maximum possible length of the racetrack, the length of Willman's steps and the length of Bolt's steps respectively. Output Print the answer to the problem as an irreducible fraction <image>. Follow the format of the samples output. The fraction <image> (p and q are integers, and both p ≥ 0 and q > 0 holds) is called irreducible, if there is no such integer d > 1, that both p and q are divisible by d. Examples Input 10 3 2 Output 3/10 Input 7 1 2 Output 3/7 Note In the first sample Willman and Bolt will tie in case 1, 6 or 7 are chosen as the length of the racetrack.
instruction
0
42,506
3
85,012
Tags: math Correct Solution: ``` import fractions [t, w, b] = [int(x) for x in input().split()] if w > b: w, b = b, w gcd = fractions.gcd(w, b) m = w * b // gcd l, k = t // m, t % m ans = l * w - 1 + min(k + 1, w) gcd = fractions.gcd(ans, t) print("%d/%d" % (ans // gcd, t // gcd)) ```
output
1
42,506
3
85,013
Provide tags and a correct Python 3 solution for this coding contest problem. Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of L meters today. <image> Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner. While watching previous races the organizers have noticed that Willman can perform only steps of length equal to w meters, and Bolt can perform only steps of length equal to b meters. Organizers decided to slightly change the rules of the race. Now, at the end of the racetrack there will be an abyss, and the winner will be declared the athlete, who manages to run farther from the starting point of the the racetrack (which is not the subject to change by any of the athletes). Note that none of the athletes can run infinitely far, as they both will at some moment of time face the point, such that only one step further will cause them to fall in the abyss. In other words, the athlete will not fall into the abyss if the total length of all his steps will be less or equal to the chosen distance L. Since the organizers are very fair, the are going to set the length of the racetrack as an integer chosen randomly and uniformly in range from 1 to t (both are included). What is the probability that Willman and Bolt tie again today? Input The first line of the input contains three integers t, w and b (1 ≤ t, w, b ≤ 5·1018) — the maximum possible length of the racetrack, the length of Willman's steps and the length of Bolt's steps respectively. Output Print the answer to the problem as an irreducible fraction <image>. Follow the format of the samples output. The fraction <image> (p and q are integers, and both p ≥ 0 and q > 0 holds) is called irreducible, if there is no such integer d > 1, that both p and q are divisible by d. Examples Input 10 3 2 Output 3/10 Input 7 1 2 Output 3/7 Note In the first sample Willman and Bolt will tie in case 1, 6 or 7 are chosen as the length of the racetrack.
instruction
0
42,507
3
85,014
Tags: math Correct Solution: ``` import sys from math import gcd,sqrt,ceil,log2 from collections import defaultdict,Counter,deque from bisect import bisect_left,bisect_right import math sys.setrecursionlimit(2*10**5+10) import heapq from itertools import permutations # input=sys.stdin.readline # def print(x): # sys.stdout.write(str(x)+"\n") # sys.stdin = open('input.txt', 'r') # sys.stdout = open('output.txt', 'w') import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 aa='abcdefghijklmnopqrstuvwxyz' 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") # import sys # import io, os # input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def get_sum(bit,i): s = 0 i+=1 while i>0: s+=bit[i] i-=i&(-i) return s def update(bit,n,i,v): i+=1 while i<=n: bit[i]+=v i+=i&(-i) def modInverse(b,m): g = math.gcd(b, m) if (g != 1): return -1 else: return pow(b, m - 2, m) def primeFactors(n): sa = [] # sa.add(n) while n % 2 == 0: sa.append(2) n = n // 2 for i in range(3,int(math.sqrt(n))+1,2): while n % i== 0: sa.append(i) n = n // i # sa.add(n) if n > 2: sa.append(n) return sa def seive(n): pri = [True]*(n+1) p = 2 while p*p<=n: if pri[p] == True: for i in range(p*p,n+1,p): pri[i] = False p+=1 return pri def check_prim(n): if n<0: return False for i in range(2,int(sqrt(n))+1): if n%i == 0: return False return True def getZarr(string, z): n = len(string) # [L,R] make a window which matches # with prefix of s l, r, k = 0, 0, 0 for i in range(1, n): # if i>R nothing matches so we will calculate. # Z[i] using naive way. if i > r: l, r = i, i # R-L = 0 in starting, so it will start # checking from 0'th index. For example, # for "ababab" and i = 1, the value of R # remains 0 and Z[i] becomes 0. For string # "aaaaaa" and i = 1, Z[i] and R become 5 while r < n and string[r - l] == string[r]: r += 1 z[i] = r - l r -= 1 else: # k = i-L so k corresponds to number which # matches in [L,R] interval. k = i - l # if Z[k] is less than remaining interval # then Z[i] will be equal to Z[k]. # For example, str = "ababab", i = 3, R = 5 # and L = 2 if z[k] < r - i + 1: z[i] = z[k] # For example str = "aaaaaa" and i = 2, # R is 5, L is 0 else: # else start from R and check manually l = i while r < n and string[r - l] == string[r]: r += 1 z[i] = r - l r -= 1 def search(text, pattern): # Create concatenated string "P$T" concat = pattern + "$" + text l = len(concat) z = [0] * l getZarr(concat, z) ha = [] for i in range(l): if z[i] == len(pattern): ha.append(i - len(pattern) - 1) return ha # n,k = map(int,input().split()) # l = list(map(int,input().split())) # # n = int(input()) # l = list(map(int,input().split())) # # hash = defaultdict(list) # la = [] # # for i in range(n): # la.append([l[i],i+1]) # # la.sort(key = lambda x: (x[0],-x[1])) # ans = [] # r = n # flag = 0 # lo = [] # ha = [i for i in range(n,0,-1)] # yo = [] # for a,b in la: # # if a == 1: # ans.append([r,b]) # # hash[(1,1)].append([b,r]) # lo.append((r,b)) # ha.pop(0) # yo.append([r,b]) # r-=1 # # elif a == 2: # # print(yo,lo) # # print(hash[1,1]) # if lo == []: # flag = 1 # break # c,d = lo.pop(0) # yo.pop(0) # if b>=d: # flag = 1 # break # ans.append([c,b]) # yo.append([c,b]) # # # # elif a == 3: # # if yo == []: # flag = 1 # break # c,d = yo.pop(0) # if b>=d: # flag = 1 # break # if ha == []: # flag = 1 # break # # ka = ha.pop(0) # # ans.append([ka,b]) # ans.append([ka,d]) # yo.append([ka,b]) # # if flag: # print(-1) # else: # print(len(ans)) # for a,b in ans: # print(a,b) def mergeIntervals(arr): # Sorting based on the increasing order # of the start intervals arr.sort(key = lambda x: x[0]) # array to hold the merged intervals m = [] s = -10000 max = -100000 for i in range(len(arr)): a = arr[i] if a[0] > max: if i != 0: m.append([s,max]) max = a[1] s = a[0] else: if a[1] >= max: max = a[1] #'max' value gives the last point of # that particular interval # 's' gives the starting point of that interval # 'm' array contains the list of all merged intervals if max != -100000 and [s, max] not in m: m.append([s, max]) return m class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) def ncr(n, r, p): num = den = 1 for i in range(r): num = (num * (n - i)) % p den = (den * (i + 1)) % p return (num * pow(den, p - 2, p)) % p def sol(n): seti = set() for i in range(1,int(sqrt(n))+1): if n%i == 0: seti.add(n//i) seti.add(i) return seti def lcm(a,b): return (a*b)//gcd(a,b) # # n,p = map(int,input().split()) # # s = input() # # if n <=2: # if n == 1: # pass # if n == 2: # pass # i = n-1 # idx = -1 # while i>=0: # z = ord(s[i])-96 # k = chr(z+1+96) # flag = 1 # if i-1>=0: # if s[i-1]!=k: # flag+=1 # else: # flag+=1 # if i-2>=0: # if s[i-2]!=k: # flag+=1 # else: # flag+=1 # if flag == 2: # idx = i # s[i] = k # break # if idx == -1: # print('NO') # exit() # for i in range(idx+1,n): # if # def moore_voting(l): count1 = 0 count2 = 0 first = 10**18 second = 10**18 n = len(l) for i in range(n): if l[i] == first: count1+=1 elif l[i] == second: count2+=1 elif count1 == 0: count1+=1 first = l[i] elif count2 == 0: count2+=1 second = l[i] else: count1-=1 count2-=1 for i in range(n): if l[i] == first: count1+=1 elif l[i] == second: count2+=1 if count1>n//3: return first if count2>n//3: return second return -1 def find_parent(u,parent): if u!=parent[u]: parent[u] = find_parent(parent[u],parent) return parent[u] def dis_union(n,e): par = [i for i in range(n+1)] rank = [1]*(n+1) for a,b in e: z1,z2 = find_parent(a,par),find_parent(b,par) if rank[z1]>rank[z2]: z1,z2 = z2,z1 if z1!=z2: par[z1] = z2 rank[z2]+=rank[z1] else: return a,b def dijkstra(n,tot,hash): hea = [[0,n]] dis = [10**18]*(tot+1) dis[n] = 0 boo = defaultdict(bool) check = defaultdict(int) while hea: a,b = heapq.heappop(hea) if boo[b]: continue boo[b] = True for i,w in hash[b]: if b == 1: c = 0 if (1,i,w) in nodes: c = nodes[(1,i,w)] del nodes[(1,i,w)] if dis[b]+w<dis[i]: dis[i] = dis[b]+w check[i] = c elif dis[b]+w == dis[i] and c == 0: dis[i] = dis[b]+w check[i] = c else: if dis[b]+w<=dis[i]: dis[i] = dis[b]+w check[i] = check[b] heapq.heappush(hea,[dis[i],i]) return check def power(x,y,p): res = 1 x = x%p if x == 0: return 0 while y>0: if (y&1) == 1: res*=x x = x*x y = y>>1 return res import sys from math import ceil,log2 INT_MAX = sys.maxsize def minVal(x, y) : return x if (x < y) else y def getMid(s, e) : return s + (e - s) // 2 def RMQUtil( st, ss, se, qs, qe, index) : if (qs <= ss and qe >= se) : return st[index] if (se < qs or ss > qe) : return INT_MAX mid = getMid(ss, se) return minVal(RMQUtil(st, ss, mid, qs, qe, 2 * index + 1), RMQUtil(st, mid + 1, se, qs, qe, 2 * index + 2)) def RMQ( st, n, qs, qe) : if (qs < 0 or qe > n - 1 or qs > qe) : print("Invalid Input") return -1 return RMQUtil(st, 0, n - 1, qs, qe, 0) def constructSTUtil(arr, ss, se, st, si) : if (ss == se) : st[si] = arr[ss] return arr[ss] mid = getMid(ss, se) st[si] = minVal(constructSTUtil(arr, ss, mid, st, si * 2 + 1), constructSTUtil(arr, mid + 1, se, st, si * 2 + 2)) return st[si] def constructST( arr, n) : x = (int)(ceil(log2(n))) max_size = 2 * (int)(2**x) - 1 st = [0] * (max_size) constructSTUtil(arr, 0, n - 1, st, 0) return st # t = int(input()) # for _ in range(t): # # n = int(input()) # l = list(map(int,input().split())) # # x,y = 0,10 # st = constructST(l, n) # # pre = [0] # suf = [0] # for i in range(n): # pre.append(max(pre[-1],l[i])) # for i in range(n-1,-1,-1): # suf.append(max(suf[-1],l[i])) # # # i = 1 # # print(pre,suf) # flag = 0 # x,y,z = -1,-1,-1 # # suf.reverse() # print(suf) # while i<len(pre): # # z = pre[i] # j = bisect_left(suf,z) # if suf[j] == z: # while i<n and l[i]<=z: # i+=1 # if pre[i]>z: # break # while j<n and l[n-j]<=z: # j+=1 # if suf[j]>z: # break # # j-=1 # print(i,n-j) # # break/ # if RMQ(st,n,i,j) == z: # c = i+j-i+1 # x,y,z = i,j-i+1,n-c # break # else: # i+=1 # # else: # i+=1 # # # # if x!=-1: # print('Yes') # print(x,y,z) # else: # print('No') # t = int(input()) # # for _ in range(t): # # def debug(n): # ans = [] # for i in range(1,n+1): # for j in range(i+1,n+1): # if (i*(j+1))%(j-i) == 0 : # ans.append([i,j]) # return ans # # # n = int(input()) # print(debug(n)) # import sys # input = sys.stdin.readline # import bisect # # t=int(input()) # for tests in range(t): # n=int(input()) # A=list(map(int,input().split())) # # LEN = len(A) # Sparse_table = [A] # # for i in range(LEN.bit_length()-1): # j = 1<<i # B = [] # for k in range(len(Sparse_table[-1])-j): # B.append(min(Sparse_table[-1][k], Sparse_table[-1][k+j])) # Sparse_table.append(B) # # def query(l,r): # [l,r)におけるminを求める. # i=(r-l).bit_length()-1 # 何番目のSparse_tableを見るか. # # return min(Sparse_table[i][l],Sparse_table[i][r-(1<<i)]) # (1<<i)個あれば[l, r)が埋まるので, それを使ってminを求める. # # LMAX=[A[0]] # for i in range(1,n): # LMAX.append(max(LMAX[-1],A[i])) # # RMAX=A[-1] # # for i in range(n-1,-1,-1): # RMAX=max(RMAX,A[i]) # # x=bisect.bisect(LMAX,RMAX) # #print(RMAX,x) # print(RMAX,x,i) # if x==0: # continue # # v=min(x,i-1) # if v<=0: # continue # # if LMAX[v-1]==query(v,i)==RMAX: # print("YES") # print(v,i-v,n-i) # break # # v-=1 # if v<=0: # continue # if LMAX[v-1]==query(v,i)==RMAX: # print("YES") # print(v,i-v,n-i) # break # else: # print("NO") # # # # # # # # # # t = int(input()) # # for _ in range(t): # # x = int(input()) # mini = 10**18 # n = ceil((-1 + sqrt(1+8*x))/2) # for i in range(-100,1): # z = x+-1*i # z1 = (abs(i)*(abs(i)+1))//2 # z+=z1 # # print(z) # n = ceil((-1 + sqrt(1+8*z))/2) # # y = (n*(n+1))//2 # # print(n,y,z,i) # mini = min(n+y-z,mini) # print(n+y-z,i) # # # print(mini) # # # # # # n = int(input()) # ans = [1]*(n) # l = [] # for i in range(n): # # la = list(map(float,input().split())) # l.append(la) # # k = 2**n - 1 # # yo = # # print(bin(k)[2:]) # # for i in range(3,k+1): # z = '0'*(n - len(bin(i)[2:])) + bin(i)[2:] # ha = [] # for j in range(n): # if z[j] == '1': # ha.append(j) # # for x in ha: # for y in ha: # if x!=y: # ans[x]*=l[x][y] # # # print(*ans) t,w,b = map(int,input().split()) if w == b: print('1/1') exit() w,b = min(w,b),max(w,b) den = t z = lcm(w,b) k = t//z num = k + k*(w-1) # print(z,k) if k*z + w>t: num+=t-k*z else: num+=w-1 # print(num,den) g = gcd(num,den) a = str(num//g) + "/" + str(den//g) print(a) ```
output
1
42,507
3
85,015
Provide tags and a correct Python 3 solution for this coding contest problem. Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of L meters today. <image> Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner. While watching previous races the organizers have noticed that Willman can perform only steps of length equal to w meters, and Bolt can perform only steps of length equal to b meters. Organizers decided to slightly change the rules of the race. Now, at the end of the racetrack there will be an abyss, and the winner will be declared the athlete, who manages to run farther from the starting point of the the racetrack (which is not the subject to change by any of the athletes). Note that none of the athletes can run infinitely far, as they both will at some moment of time face the point, such that only one step further will cause them to fall in the abyss. In other words, the athlete will not fall into the abyss if the total length of all his steps will be less or equal to the chosen distance L. Since the organizers are very fair, the are going to set the length of the racetrack as an integer chosen randomly and uniformly in range from 1 to t (both are included). What is the probability that Willman and Bolt tie again today? Input The first line of the input contains three integers t, w and b (1 ≤ t, w, b ≤ 5·1018) — the maximum possible length of the racetrack, the length of Willman's steps and the length of Bolt's steps respectively. Output Print the answer to the problem as an irreducible fraction <image>. Follow the format of the samples output. The fraction <image> (p and q are integers, and both p ≥ 0 and q > 0 holds) is called irreducible, if there is no such integer d > 1, that both p and q are divisible by d. Examples Input 10 3 2 Output 3/10 Input 7 1 2 Output 3/7 Note In the first sample Willman and Bolt will tie in case 1, 6 or 7 are chosen as the length of the racetrack.
instruction
0
42,508
3
85,016
Tags: math Correct Solution: ``` def gcd(x, y): return gcd(y % x, x) if x else y t, w, b = (int(x) for x in input().split()) lcm = w * b // gcd(w, b) tmp = t // lcm ans = tmp * min(w, b) ans -= max(0, tmp * lcm + min(w - 1, b - 1) - t) ans += min(w - 1, b - 1) g = gcd(ans, t) if g: ans //= g t //= g print("%d/%d" % (ans, t)) ```
output
1
42,508
3
85,017
Provide tags and a correct Python 3 solution for this coding contest problem. Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of L meters today. <image> Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner. While watching previous races the organizers have noticed that Willman can perform only steps of length equal to w meters, and Bolt can perform only steps of length equal to b meters. Organizers decided to slightly change the rules of the race. Now, at the end of the racetrack there will be an abyss, and the winner will be declared the athlete, who manages to run farther from the starting point of the the racetrack (which is not the subject to change by any of the athletes). Note that none of the athletes can run infinitely far, as they both will at some moment of time face the point, such that only one step further will cause them to fall in the abyss. In other words, the athlete will not fall into the abyss if the total length of all his steps will be less or equal to the chosen distance L. Since the organizers are very fair, the are going to set the length of the racetrack as an integer chosen randomly and uniformly in range from 1 to t (both are included). What is the probability that Willman and Bolt tie again today? Input The first line of the input contains three integers t, w and b (1 ≤ t, w, b ≤ 5·1018) — the maximum possible length of the racetrack, the length of Willman's steps and the length of Bolt's steps respectively. Output Print the answer to the problem as an irreducible fraction <image>. Follow the format of the samples output. The fraction <image> (p and q are integers, and both p ≥ 0 and q > 0 holds) is called irreducible, if there is no such integer d > 1, that both p and q are divisible by d. Examples Input 10 3 2 Output 3/10 Input 7 1 2 Output 3/7 Note In the first sample Willman and Bolt will tie in case 1, 6 or 7 are chosen as the length of the racetrack.
instruction
0
42,509
3
85,018
Tags: math Correct Solution: ``` def gcd(a,b): if b==0: return a; else: return gcd(b,a%b); t,w,b=map(int,input().split(" ")); GCD=w*b//gcd(w,b); MIN=min(w,b); ans=MIN-1+(int(t//GCD)-1)*MIN+min(MIN,t-int(t//GCD)*GCD+1) son=int(ans//gcd(ans,t)) mom=int(int(t)//int(gcd(ans,t))) # print(ans,gcd(ans,t),t,t/gcd(ans,t)) print("%d/%d" %(son,mom)) ```
output
1
42,509
3
85,019
Provide tags and a correct Python 3 solution for this coding contest problem. Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of L meters today. <image> Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner. While watching previous races the organizers have noticed that Willman can perform only steps of length equal to w meters, and Bolt can perform only steps of length equal to b meters. Organizers decided to slightly change the rules of the race. Now, at the end of the racetrack there will be an abyss, and the winner will be declared the athlete, who manages to run farther from the starting point of the the racetrack (which is not the subject to change by any of the athletes). Note that none of the athletes can run infinitely far, as they both will at some moment of time face the point, such that only one step further will cause them to fall in the abyss. In other words, the athlete will not fall into the abyss if the total length of all his steps will be less or equal to the chosen distance L. Since the organizers are very fair, the are going to set the length of the racetrack as an integer chosen randomly and uniformly in range from 1 to t (both are included). What is the probability that Willman and Bolt tie again today? Input The first line of the input contains three integers t, w and b (1 ≤ t, w, b ≤ 5·1018) — the maximum possible length of the racetrack, the length of Willman's steps and the length of Bolt's steps respectively. Output Print the answer to the problem as an irreducible fraction <image>. Follow the format of the samples output. The fraction <image> (p and q are integers, and both p ≥ 0 and q > 0 holds) is called irreducible, if there is no such integer d > 1, that both p and q are divisible by d. Examples Input 10 3 2 Output 3/10 Input 7 1 2 Output 3/7 Note In the first sample Willman and Bolt will tie in case 1, 6 or 7 are chosen as the length of the racetrack.
instruction
0
42,510
3
85,020
Tags: math Correct Solution: ``` from sys import stdin import math # stdin = open('in.txt') # t, w, b = map(int, stdin.readline().split()) t, w, b = map(int, input().split()) d = math.gcd(w, b) l = (w*b)//d add = min(w, b) ans = add*(t//l) m = t%l ans += min(add, m+1) ans -= 1 d = math.gcd(ans, t) ans //= d t //= d print(ans, '/', t, sep='') ```
output
1
42,510
3
85,021
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of L meters today. <image> Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner. While watching previous races the organizers have noticed that Willman can perform only steps of length equal to w meters, and Bolt can perform only steps of length equal to b meters. Organizers decided to slightly change the rules of the race. Now, at the end of the racetrack there will be an abyss, and the winner will be declared the athlete, who manages to run farther from the starting point of the the racetrack (which is not the subject to change by any of the athletes). Note that none of the athletes can run infinitely far, as they both will at some moment of time face the point, such that only one step further will cause them to fall in the abyss. In other words, the athlete will not fall into the abyss if the total length of all his steps will be less or equal to the chosen distance L. Since the organizers are very fair, the are going to set the length of the racetrack as an integer chosen randomly and uniformly in range from 1 to t (both are included). What is the probability that Willman and Bolt tie again today? Input The first line of the input contains three integers t, w and b (1 ≤ t, w, b ≤ 5·1018) — the maximum possible length of the racetrack, the length of Willman's steps and the length of Bolt's steps respectively. Output Print the answer to the problem as an irreducible fraction <image>. Follow the format of the samples output. The fraction <image> (p and q are integers, and both p ≥ 0 and q > 0 holds) is called irreducible, if there is no such integer d > 1, that both p and q are divisible by d. Examples Input 10 3 2 Output 3/10 Input 7 1 2 Output 3/7 Note In the first sample Willman and Bolt will tie in case 1, 6 or 7 are chosen as the length of the racetrack. Submitted Solution: ``` def gcd(a,b): if(b==0): return a else: return gcd(b,a%b) t, x, y = input().split() t = int(t) x = int(x) y = int(y) z = gcd(x,y) lcm = x*(y//z) if(x<y): cnt = x-1 else: cnt = y-1 z = cnt+1 cnt = cnt + (t//lcm - 1)*z if(t%lcm < z): cnt = cnt + t%lcm+1 else: cnt = cnt + z z = gcd(cnt,t) # print(t,cnt,z) cnt = cnt // z t = t//z s = str(cnt)+'/'+str(t) print(s) ```
instruction
0
42,511
3
85,022
Yes
output
1
42,511
3
85,023
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of L meters today. <image> Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner. While watching previous races the organizers have noticed that Willman can perform only steps of length equal to w meters, and Bolt can perform only steps of length equal to b meters. Organizers decided to slightly change the rules of the race. Now, at the end of the racetrack there will be an abyss, and the winner will be declared the athlete, who manages to run farther from the starting point of the the racetrack (which is not the subject to change by any of the athletes). Note that none of the athletes can run infinitely far, as they both will at some moment of time face the point, such that only one step further will cause them to fall in the abyss. In other words, the athlete will not fall into the abyss if the total length of all his steps will be less or equal to the chosen distance L. Since the organizers are very fair, the are going to set the length of the racetrack as an integer chosen randomly and uniformly in range from 1 to t (both are included). What is the probability that Willman and Bolt tie again today? Input The first line of the input contains three integers t, w and b (1 ≤ t, w, b ≤ 5·1018) — the maximum possible length of the racetrack, the length of Willman's steps and the length of Bolt's steps respectively. Output Print the answer to the problem as an irreducible fraction <image>. Follow the format of the samples output. The fraction <image> (p and q are integers, and both p ≥ 0 and q > 0 holds) is called irreducible, if there is no such integer d > 1, that both p and q are divisible by d. Examples Input 10 3 2 Output 3/10 Input 7 1 2 Output 3/7 Note In the first sample Willman and Bolt will tie in case 1, 6 or 7 are chosen as the length of the racetrack. Submitted Solution: ``` def gcd(a, b): while a > 0: b %= a (a, b) = (b, a) return b # (t, a , b) = map(int, input().split()) n = a * b // gcd(a, b) m = min(a, b) ans = 0 if (m > 1): ans += m - 1 ans += t // n * m if (t % n + 1 < m): ans += (t % n) + 1 - m else: ans = t // n print(ans // gcd(ans, t), '/', t // gcd(ans, t), sep = '') ```
instruction
0
42,512
3
85,024
Yes
output
1
42,512
3
85,025
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of L meters today. <image> Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner. While watching previous races the organizers have noticed that Willman can perform only steps of length equal to w meters, and Bolt can perform only steps of length equal to b meters. Organizers decided to slightly change the rules of the race. Now, at the end of the racetrack there will be an abyss, and the winner will be declared the athlete, who manages to run farther from the starting point of the the racetrack (which is not the subject to change by any of the athletes). Note that none of the athletes can run infinitely far, as they both will at some moment of time face the point, such that only one step further will cause them to fall in the abyss. In other words, the athlete will not fall into the abyss if the total length of all his steps will be less or equal to the chosen distance L. Since the organizers are very fair, the are going to set the length of the racetrack as an integer chosen randomly and uniformly in range from 1 to t (both are included). What is the probability that Willman and Bolt tie again today? Input The first line of the input contains three integers t, w and b (1 ≤ t, w, b ≤ 5·1018) — the maximum possible length of the racetrack, the length of Willman's steps and the length of Bolt's steps respectively. Output Print the answer to the problem as an irreducible fraction <image>. Follow the format of the samples output. The fraction <image> (p and q are integers, and both p ≥ 0 and q > 0 holds) is called irreducible, if there is no such integer d > 1, that both p and q are divisible by d. Examples Input 10 3 2 Output 3/10 Input 7 1 2 Output 3/7 Note In the first sample Willman and Bolt will tie in case 1, 6 or 7 are chosen as the length of the racetrack. Submitted Solution: ``` import sys, math def gcd(a, b): if b==0: return a return gcd(b, a%b) b, w, t = [int(x) for x in input().split()] g = gcd(t, w) s = min(t, w)-1 nok = t*w//g; delta = min(t, w) s += ((b // nok)-1)*delta s += min(b-((b // nok)*nok)+1, delta) #print(s, b) ans1 = s ans2 = b ans1 //= gcd(s, b) ans2 //= gcd(s, b) print(ans1, '/', ans2, sep = '') ```
instruction
0
42,513
3
85,026
Yes
output
1
42,513
3
85,027
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of L meters today. <image> Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner. While watching previous races the organizers have noticed that Willman can perform only steps of length equal to w meters, and Bolt can perform only steps of length equal to b meters. Organizers decided to slightly change the rules of the race. Now, at the end of the racetrack there will be an abyss, and the winner will be declared the athlete, who manages to run farther from the starting point of the the racetrack (which is not the subject to change by any of the athletes). Note that none of the athletes can run infinitely far, as they both will at some moment of time face the point, such that only one step further will cause them to fall in the abyss. In other words, the athlete will not fall into the abyss if the total length of all his steps will be less or equal to the chosen distance L. Since the organizers are very fair, the are going to set the length of the racetrack as an integer chosen randomly and uniformly in range from 1 to t (both are included). What is the probability that Willman and Bolt tie again today? Input The first line of the input contains three integers t, w and b (1 ≤ t, w, b ≤ 5·1018) — the maximum possible length of the racetrack, the length of Willman's steps and the length of Bolt's steps respectively. Output Print the answer to the problem as an irreducible fraction <image>. Follow the format of the samples output. The fraction <image> (p and q are integers, and both p ≥ 0 and q > 0 holds) is called irreducible, if there is no such integer d > 1, that both p and q are divisible by d. Examples Input 10 3 2 Output 3/10 Input 7 1 2 Output 3/7 Note In the first sample Willman and Bolt will tie in case 1, 6 or 7 are chosen as the length of the racetrack. Submitted Solution: ``` import math def lcm(a, b): return (a*b)//(math.gcd(a,b)) t, a, b = [int(x) for x in input().split()] mcm = lcm(a, b) mn = min(a,b)-1 cycles = t//mcm ans = ((cycles*mn)) + min(mn, t%mcm) + cycles g = math.gcd(ans, t) print(ans//g, "/", t//g, sep="") ```
instruction
0
42,514
3
85,028
Yes
output
1
42,514
3
85,029
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of L meters today. <image> Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner. While watching previous races the organizers have noticed that Willman can perform only steps of length equal to w meters, and Bolt can perform only steps of length equal to b meters. Organizers decided to slightly change the rules of the race. Now, at the end of the racetrack there will be an abyss, and the winner will be declared the athlete, who manages to run farther from the starting point of the the racetrack (which is not the subject to change by any of the athletes). Note that none of the athletes can run infinitely far, as they both will at some moment of time face the point, such that only one step further will cause them to fall in the abyss. In other words, the athlete will not fall into the abyss if the total length of all his steps will be less or equal to the chosen distance L. Since the organizers are very fair, the are going to set the length of the racetrack as an integer chosen randomly and uniformly in range from 1 to t (both are included). What is the probability that Willman and Bolt tie again today? Input The first line of the input contains three integers t, w and b (1 ≤ t, w, b ≤ 5·1018) — the maximum possible length of the racetrack, the length of Willman's steps and the length of Bolt's steps respectively. Output Print the answer to the problem as an irreducible fraction <image>. Follow the format of the samples output. The fraction <image> (p and q are integers, and both p ≥ 0 and q > 0 holds) is called irreducible, if there is no such integer d > 1, that both p and q are divisible by d. Examples Input 10 3 2 Output 3/10 Input 7 1 2 Output 3/7 Note In the first sample Willman and Bolt will tie in case 1, 6 or 7 are chosen as the length of the racetrack. Submitted Solution: ``` from fractions import * from math import * t, w, b = map(int, input().split()) d = w*b//gcd(w, b) e = min(w, b) f = (t-e+1)//d g = max(e, min(0, t-f*d-e)) n = Fraction(f*e-1+g, t) print(f"{n.numerator}/{n.denominator}") ''' 10 3 2 7 1 2 ''' ```
instruction
0
42,515
3
85,030
No
output
1
42,515
3
85,031
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of L meters today. <image> Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner. While watching previous races the organizers have noticed that Willman can perform only steps of length equal to w meters, and Bolt can perform only steps of length equal to b meters. Organizers decided to slightly change the rules of the race. Now, at the end of the racetrack there will be an abyss, and the winner will be declared the athlete, who manages to run farther from the starting point of the the racetrack (which is not the subject to change by any of the athletes). Note that none of the athletes can run infinitely far, as they both will at some moment of time face the point, such that only one step further will cause them to fall in the abyss. In other words, the athlete will not fall into the abyss if the total length of all his steps will be less or equal to the chosen distance L. Since the organizers are very fair, the are going to set the length of the racetrack as an integer chosen randomly and uniformly in range from 1 to t (both are included). What is the probability that Willman and Bolt tie again today? Input The first line of the input contains three integers t, w and b (1 ≤ t, w, b ≤ 5·1018) — the maximum possible length of the racetrack, the length of Willman's steps and the length of Bolt's steps respectively. Output Print the answer to the problem as an irreducible fraction <image>. Follow the format of the samples output. The fraction <image> (p and q are integers, and both p ≥ 0 and q > 0 holds) is called irreducible, if there is no such integer d > 1, that both p and q are divisible by d. Examples Input 10 3 2 Output 3/10 Input 7 1 2 Output 3/7 Note In the first sample Willman and Bolt will tie in case 1, 6 or 7 are chosen as the length of the racetrack. Submitted Solution: ``` string = input() t = int(string.split(' ')[0]) a = int(string.split(' ')[1]) b = int(string.split(' ')[2]) if a > b: temp = a a = b b = temp def gcd(x, y): if x: return gcd(y % x, x) return y g = int(gcd(a, b)) nok = int(a * b / g) if t < nok: ans = int(min(a - 1, t)) gg = int(gcd(ans, t)) ans = int(ans // gg) t = int(t // gg) print(str(ans) + '/' + str(t)) else: ans = int(min(a - 1, t)) ans += int(max(int(t // nok), 1) - 1) * a if t % nok >= a: ans += a else: ans += (t % nok) + 1 ans = int(ans) gg = int(gcd(ans, t)) ans = int(ans // gg) t = int(t // gg) print(str(ans) + '/' + str(t)) ```
instruction
0
42,516
3
85,032
No
output
1
42,516
3
85,033
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of L meters today. <image> Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner. While watching previous races the organizers have noticed that Willman can perform only steps of length equal to w meters, and Bolt can perform only steps of length equal to b meters. Organizers decided to slightly change the rules of the race. Now, at the end of the racetrack there will be an abyss, and the winner will be declared the athlete, who manages to run farther from the starting point of the the racetrack (which is not the subject to change by any of the athletes). Note that none of the athletes can run infinitely far, as they both will at some moment of time face the point, such that only one step further will cause them to fall in the abyss. In other words, the athlete will not fall into the abyss if the total length of all his steps will be less or equal to the chosen distance L. Since the organizers are very fair, the are going to set the length of the racetrack as an integer chosen randomly and uniformly in range from 1 to t (both are included). What is the probability that Willman and Bolt tie again today? Input The first line of the input contains three integers t, w and b (1 ≤ t, w, b ≤ 5·1018) — the maximum possible length of the racetrack, the length of Willman's steps and the length of Bolt's steps respectively. Output Print the answer to the problem as an irreducible fraction <image>. Follow the format of the samples output. The fraction <image> (p and q are integers, and both p ≥ 0 and q > 0 holds) is called irreducible, if there is no such integer d > 1, that both p and q are divisible by d. Examples Input 10 3 2 Output 3/10 Input 7 1 2 Output 3/7 Note In the first sample Willman and Bolt will tie in case 1, 6 or 7 are chosen as the length of the racetrack. Submitted Solution: ``` from fractions import Fraction t,w,b = map(int,input().split()) r=min(t,min(b-1,w-1)) count=-1; x,y=w,b while(y): tmp=x%y x=y y=tmp gcd=x lcm=(w*b)//x for i in range(0,r+1): count+=(1+(t-i)//lcm) if(count==t): print("1/1") else: print(Fraction(count/t).limit_denominator()) ```
instruction
0
42,517
3
85,034
No
output
1
42,517
3
85,035
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of L meters today. <image> Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner. While watching previous races the organizers have noticed that Willman can perform only steps of length equal to w meters, and Bolt can perform only steps of length equal to b meters. Organizers decided to slightly change the rules of the race. Now, at the end of the racetrack there will be an abyss, and the winner will be declared the athlete, who manages to run farther from the starting point of the the racetrack (which is not the subject to change by any of the athletes). Note that none of the athletes can run infinitely far, as they both will at some moment of time face the point, such that only one step further will cause them to fall in the abyss. In other words, the athlete will not fall into the abyss if the total length of all his steps will be less or equal to the chosen distance L. Since the organizers are very fair, the are going to set the length of the racetrack as an integer chosen randomly and uniformly in range from 1 to t (both are included). What is the probability that Willman and Bolt tie again today? Input The first line of the input contains three integers t, w and b (1 ≤ t, w, b ≤ 5·1018) — the maximum possible length of the racetrack, the length of Willman's steps and the length of Bolt's steps respectively. Output Print the answer to the problem as an irreducible fraction <image>. Follow the format of the samples output. The fraction <image> (p and q are integers, and both p ≥ 0 and q > 0 holds) is called irreducible, if there is no such integer d > 1, that both p and q are divisible by d. Examples Input 10 3 2 Output 3/10 Input 7 1 2 Output 3/7 Note In the first sample Willman and Bolt will tie in case 1, 6 or 7 are chosen as the length of the racetrack. Submitted Solution: ``` string = input() t = int(string.split(' ')[0]) a = int(string.split(' ')[1]) b = int(string.split(' ')[2]) if a > b: temp = a a = b b = temp def gcd(x, y): if x: return gcd(y % x, x) return y g = gcd(a, b) nok = int(a * b / g) if t < nok: ans = min(a - 1, t) gg = gcd(ans, t) ans = int(ans / gg) t = int(t / gg) print(str(ans) + '/' + str(t)) else: ans = min(a - 1, t) ans += int(max(int(t / nok), 1) - 1) * a if t % nok >= a: ans += a else: ans += (t % nok) + 1 ans = int(ans) gg = gcd(ans, t) ans = int(ans / gg) t = int(t // gg) print(str(ans) + '/' + str(t)) ```
instruction
0
42,518
3
85,036
No
output
1
42,518
3
85,037
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fox Ciel saw a large field while she was on a bus. The field was a n × m rectangle divided into 1 × 1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure: * Assume that the rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right, and a cell in row i and column j is represented as (i, j). * First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1, 1) → ... → (1, m) → (2, 1) → ... → (2, m) → ... → (n, 1) → ... → (n, m). Waste cells will be ignored. * Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on. The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell. <image> Now she is wondering how to determine the crop plants in some certain cells. Input In the first line there are four positive integers n, m, k, t (1 ≤ n ≤ 4·104, 1 ≤ m ≤ 4·104, 1 ≤ k ≤ 103, 1 ≤ t ≤ 103), each of which represents the height of the field, the width of the field, the number of waste cells and the number of queries that ask the kind of crop plants in a certain cell. Following each k lines contains two integers a, b (1 ≤ a ≤ n, 1 ≤ b ≤ m), which denotes a cell (a, b) is waste. It is guaranteed that the same cell will not appear twice in this section. Following each t lines contains two integers i, j (1 ≤ i ≤ n, 1 ≤ j ≤ m), which is a query that asks you the kind of crop plants of a cell (i, j). Output For each query, if the cell is waste, print Waste. Otherwise, print the name of crop plants in the cell: either Carrots or Kiwis or Grapes. Examples Input 4 5 5 6 4 3 1 3 3 3 2 5 3 2 1 3 1 4 2 3 2 4 1 1 1 1 Output Waste Grapes Carrots Kiwis Carrots Carrots Note The sample corresponds to the figure in the statement. Submitted Solution: ``` n, m, k, t = map(int, input().split()) waste = [] for _ in range(k): i, j = map(int, input().split()) waste += [(i-1)*m + (j-1)] waste.sort() put = ["Carrots", "Kiwis", "Grapes"] for _ in range(t): i, j = map(int, input().split()) numc = (i-1)*m + (j-1) c = 0 for x in waste: #print(x, numc) if x > numc: break c += 1 if numc in waste: print("Waste") else: print(put[(numc - c) % 3]) ```
instruction
0
42,564
3
85,128
Yes
output
1
42,564
3
85,129
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fox Ciel saw a large field while she was on a bus. The field was a n × m rectangle divided into 1 × 1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure: * Assume that the rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right, and a cell in row i and column j is represented as (i, j). * First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1, 1) → ... → (1, m) → (2, 1) → ... → (2, m) → ... → (n, 1) → ... → (n, m). Waste cells will be ignored. * Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on. The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell. <image> Now she is wondering how to determine the crop plants in some certain cells. Input In the first line there are four positive integers n, m, k, t (1 ≤ n ≤ 4·104, 1 ≤ m ≤ 4·104, 1 ≤ k ≤ 103, 1 ≤ t ≤ 103), each of which represents the height of the field, the width of the field, the number of waste cells and the number of queries that ask the kind of crop plants in a certain cell. Following each k lines contains two integers a, b (1 ≤ a ≤ n, 1 ≤ b ≤ m), which denotes a cell (a, b) is waste. It is guaranteed that the same cell will not appear twice in this section. Following each t lines contains two integers i, j (1 ≤ i ≤ n, 1 ≤ j ≤ m), which is a query that asks you the kind of crop plants of a cell (i, j). Output For each query, if the cell is waste, print Waste. Otherwise, print the name of crop plants in the cell: either Carrots or Kiwis or Grapes. Examples Input 4 5 5 6 4 3 1 3 3 3 2 5 3 2 1 3 1 4 2 3 2 4 1 1 1 1 Output Waste Grapes Carrots Kiwis Carrots Carrots Note The sample corresponds to the figure in the statement. Submitted Solution: ``` n, m, k, t = map(int, input().split()) a = [] for i in range(k): b, c = map(int, input().split()) a.append([b,c]) a.sort() for i in range(t): d, e = map(int, input().split()) if [d, e] in a: print('Waste') else: g = (d-1)*m + (e-1) h = 0 for i in range(k): if(d > a[i][0]): h += 1 elif(d == a[i][0] and e > a[i][1]): h += 1 v = (g-h)%3 if(v == 0): print('Carrots') elif(v == 1): print('Kiwis') else: print('Grapes') ```
instruction
0
42,565
3
85,130
Yes
output
1
42,565
3
85,131
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fox Ciel saw a large field while she was on a bus. The field was a n × m rectangle divided into 1 × 1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure: * Assume that the rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right, and a cell in row i and column j is represented as (i, j). * First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1, 1) → ... → (1, m) → (2, 1) → ... → (2, m) → ... → (n, 1) → ... → (n, m). Waste cells will be ignored. * Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on. The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell. <image> Now she is wondering how to determine the crop plants in some certain cells. Input In the first line there are four positive integers n, m, k, t (1 ≤ n ≤ 4·104, 1 ≤ m ≤ 4·104, 1 ≤ k ≤ 103, 1 ≤ t ≤ 103), each of which represents the height of the field, the width of the field, the number of waste cells and the number of queries that ask the kind of crop plants in a certain cell. Following each k lines contains two integers a, b (1 ≤ a ≤ n, 1 ≤ b ≤ m), which denotes a cell (a, b) is waste. It is guaranteed that the same cell will not appear twice in this section. Following each t lines contains two integers i, j (1 ≤ i ≤ n, 1 ≤ j ≤ m), which is a query that asks you the kind of crop plants of a cell (i, j). Output For each query, if the cell is waste, print Waste. Otherwise, print the name of crop plants in the cell: either Carrots or Kiwis or Grapes. Examples Input 4 5 5 6 4 3 1 3 3 3 2 5 3 2 1 3 1 4 2 3 2 4 1 1 1 1 Output Waste Grapes Carrots Kiwis Carrots Carrots Note The sample corresponds to the figure in the statement. Submitted Solution: ``` n,m,k,t = map(int,input().split()) p=[] fruit=["Carrots","Kiwis","Grapes"] for i in range(k): a,b = map(int,input().split()) p.append([a,b]) p.sort() #print(p) for q in range(t): a,b=map(int,input().split()) if([a,b] in p): print("Waste") else: I = (a-1)*m+b-1 i = 0 while(i<k): if(p[i][0]==a): if(p[i][1] > b): break elif(p[i][0]>a): break i += 1 #print((I-i)%3) print(fruit[(I-i)%3]) ```
instruction
0
42,566
3
85,132
Yes
output
1
42,566
3
85,133
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fox Ciel saw a large field while she was on a bus. The field was a n × m rectangle divided into 1 × 1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure: * Assume that the rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right, and a cell in row i and column j is represented as (i, j). * First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1, 1) → ... → (1, m) → (2, 1) → ... → (2, m) → ... → (n, 1) → ... → (n, m). Waste cells will be ignored. * Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on. The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell. <image> Now she is wondering how to determine the crop plants in some certain cells. Input In the first line there are four positive integers n, m, k, t (1 ≤ n ≤ 4·104, 1 ≤ m ≤ 4·104, 1 ≤ k ≤ 103, 1 ≤ t ≤ 103), each of which represents the height of the field, the width of the field, the number of waste cells and the number of queries that ask the kind of crop plants in a certain cell. Following each k lines contains two integers a, b (1 ≤ a ≤ n, 1 ≤ b ≤ m), which denotes a cell (a, b) is waste. It is guaranteed that the same cell will not appear twice in this section. Following each t lines contains two integers i, j (1 ≤ i ≤ n, 1 ≤ j ≤ m), which is a query that asks you the kind of crop plants of a cell (i, j). Output For each query, if the cell is waste, print Waste. Otherwise, print the name of crop plants in the cell: either Carrots or Kiwis or Grapes. Examples Input 4 5 5 6 4 3 1 3 3 3 2 5 3 2 1 3 1 4 2 3 2 4 1 1 1 1 Output Waste Grapes Carrots Kiwis Carrots Carrots Note The sample corresponds to the figure in the statement. Submitted Solution: ``` n, m, k, t = [int(i) for i in input().split()] waste = [] for j in range(k): a = [int(z) for z in input().split()] waste.append(a) waste.sort() # print(waste) for y in range(t): b = [int(y) for y in input().split()] if True: count = 0 f = 0 for q in range(k): if waste[q][0] < b[0]: count += 1 continue elif waste[q][0] == b[0]: if waste[q][1] == b[1]: print("Waste") f = 1 break # count += 1 elif waste[q][1] > b[1]: break else: count += 1 else: break if f == 1: continue expected = (b[0] - 1) * (m) + (b[1]) # print(expected , count) reality = expected - count # print(reality) rem = reality % 3 if (rem == 2): print("Kiwis") elif (rem == 1): print("Carrots") else: print("Grapes") ```
instruction
0
42,567
3
85,134
Yes
output
1
42,567
3
85,135
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fox Ciel saw a large field while she was on a bus. The field was a n × m rectangle divided into 1 × 1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure: * Assume that the rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right, and a cell in row i and column j is represented as (i, j). * First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1, 1) → ... → (1, m) → (2, 1) → ... → (2, m) → ... → (n, 1) → ... → (n, m). Waste cells will be ignored. * Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on. The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell. <image> Now she is wondering how to determine the crop plants in some certain cells. Input In the first line there are four positive integers n, m, k, t (1 ≤ n ≤ 4·104, 1 ≤ m ≤ 4·104, 1 ≤ k ≤ 103, 1 ≤ t ≤ 103), each of which represents the height of the field, the width of the field, the number of waste cells and the number of queries that ask the kind of crop plants in a certain cell. Following each k lines contains two integers a, b (1 ≤ a ≤ n, 1 ≤ b ≤ m), which denotes a cell (a, b) is waste. It is guaranteed that the same cell will not appear twice in this section. Following each t lines contains two integers i, j (1 ≤ i ≤ n, 1 ≤ j ≤ m), which is a query that asks you the kind of crop plants of a cell (i, j). Output For each query, if the cell is waste, print Waste. Otherwise, print the name of crop plants in the cell: either Carrots or Kiwis or Grapes. Examples Input 4 5 5 6 4 3 1 3 3 3 2 5 3 2 1 3 1 4 2 3 2 4 1 1 1 1 Output Waste Grapes Carrots Kiwis Carrots Carrots Note The sample corresponds to the figure in the statement. Submitted Solution: ``` food = ['Carrots','Kiwis','Grapes'] n,m,k,t = [int(x) for x in input().split(' ')] wasts = [] for _k in range(k): _x,_y = [int(x)-1 for x in input().split(' ')] wasts.append((_x,_y)) queries = [] squeries = [] for _t in range(t): query = [int(x)-1 for x in input().split(' ')] queries.append(str(query[0])+','+str(query[1])) squeries.append((query[0],query[1])) squeries = sorted(squeries,key=lambda query: str(query[0])+','+str(query[1])) nbrAnswed = 0 current = '' p = 0 finish = False for i in range(n): if finish: break for j in range(m): if finish: break if (i,j) not in wasts: current = food[p] p = (p + 1)%3 else: current = 'Waste' while (i,j) == squeries[nbrAnswed]: queries[queries.index(str(i)+','+str(j))] = current nbrAnswed += 1 if nbrAnswed >= t: finish = True break for a in queries: print(a) ```
instruction
0
42,568
3
85,136
No
output
1
42,568
3
85,137
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fox Ciel saw a large field while she was on a bus. The field was a n × m rectangle divided into 1 × 1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure: * Assume that the rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right, and a cell in row i and column j is represented as (i, j). * First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1, 1) → ... → (1, m) → (2, 1) → ... → (2, m) → ... → (n, 1) → ... → (n, m). Waste cells will be ignored. * Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on. The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell. <image> Now she is wondering how to determine the crop plants in some certain cells. Input In the first line there are four positive integers n, m, k, t (1 ≤ n ≤ 4·104, 1 ≤ m ≤ 4·104, 1 ≤ k ≤ 103, 1 ≤ t ≤ 103), each of which represents the height of the field, the width of the field, the number of waste cells and the number of queries that ask the kind of crop plants in a certain cell. Following each k lines contains two integers a, b (1 ≤ a ≤ n, 1 ≤ b ≤ m), which denotes a cell (a, b) is waste. It is guaranteed that the same cell will not appear twice in this section. Following each t lines contains two integers i, j (1 ≤ i ≤ n, 1 ≤ j ≤ m), which is a query that asks you the kind of crop plants of a cell (i, j). Output For each query, if the cell is waste, print Waste. Otherwise, print the name of crop plants in the cell: either Carrots or Kiwis or Grapes. Examples Input 4 5 5 6 4 3 1 3 3 3 2 5 3 2 1 3 1 4 2 3 2 4 1 1 1 1 Output Waste Grapes Carrots Kiwis Carrots Carrots Note The sample corresponds to the figure in the statement. Submitted Solution: ``` n, m, k, t = map(int, input().split(' ')) field = [] for i in range(n): field.append(list(0 for i in range(m))) for i in range(k): l, g = map(int, input().split(' ')) field[l-1][g-1] = -1 count = 0 for i in range(t): l, g = map(int, input().split(' ')) if field[l-1][g-1] == -1: print('Waste') continue for i in range(l): for j in range(g): if field[i][j] == 0: count += 1 if count%3 == 0: print('Grapes') count = 0 continue elif count%3 == 2: print('Kiwis') count = 0 continue else: print('Carrots') count = 0 continue ```
instruction
0
42,569
3
85,138
No
output
1
42,569
3
85,139
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fox Ciel saw a large field while she was on a bus. The field was a n × m rectangle divided into 1 × 1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure: * Assume that the rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right, and a cell in row i and column j is represented as (i, j). * First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1, 1) → ... → (1, m) → (2, 1) → ... → (2, m) → ... → (n, 1) → ... → (n, m). Waste cells will be ignored. * Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on. The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell. <image> Now she is wondering how to determine the crop plants in some certain cells. Input In the first line there are four positive integers n, m, k, t (1 ≤ n ≤ 4·104, 1 ≤ m ≤ 4·104, 1 ≤ k ≤ 103, 1 ≤ t ≤ 103), each of which represents the height of the field, the width of the field, the number of waste cells and the number of queries that ask the kind of crop plants in a certain cell. Following each k lines contains two integers a, b (1 ≤ a ≤ n, 1 ≤ b ≤ m), which denotes a cell (a, b) is waste. It is guaranteed that the same cell will not appear twice in this section. Following each t lines contains two integers i, j (1 ≤ i ≤ n, 1 ≤ j ≤ m), which is a query that asks you the kind of crop plants of a cell (i, j). Output For each query, if the cell is waste, print Waste. Otherwise, print the name of crop plants in the cell: either Carrots or Kiwis or Grapes. Examples Input 4 5 5 6 4 3 1 3 3 3 2 5 3 2 1 3 1 4 2 3 2 4 1 1 1 1 Output Waste Grapes Carrots Kiwis Carrots Carrots Note The sample corresponds to the figure in the statement. Submitted Solution: ``` n, m, k, t = list(map(int, input().split(' '))) wastes = [] for _ in range(k): wastes.append(list(map(int, input().split(' ')))) wastes = sorted(wastes) # print(wastes) def lower_bound(wastes, x, y): lo, hi = 0, len(wastes)-1 while lo<=hi: mid = (hi+lo)//2 if wastes[mid][0]==x: if wastes[mid][1]==y: print("Waste") return elif wastes[mid][1]>y: hi = mid-1 else: lo = mid + 1 elif wastes[mid][0]>x: hi = mid-1 else: lo = mid+1 return mid mapping = {0:'Carrots', 1:'Kiwis', 2:'Grapes'} for _ in range(t): x, y = list(map(int, input().split(' '))) # find index of the lower bound from the waste num_wastes = lower_bound(wastes, x, y) # print(x,y, num_wastes) if num_wastes is None: continue # total elements upto x, y - waste elements % 3 is the answer print(mapping[((x-1)*m+y- num_wastes-1)%3]) ```
instruction
0
42,570
3
85,140
No
output
1
42,570
3
85,141
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fox Ciel saw a large field while she was on a bus. The field was a n × m rectangle divided into 1 × 1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure: * Assume that the rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right, and a cell in row i and column j is represented as (i, j). * First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1, 1) → ... → (1, m) → (2, 1) → ... → (2, m) → ... → (n, 1) → ... → (n, m). Waste cells will be ignored. * Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on. The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell. <image> Now she is wondering how to determine the crop plants in some certain cells. Input In the first line there are four positive integers n, m, k, t (1 ≤ n ≤ 4·104, 1 ≤ m ≤ 4·104, 1 ≤ k ≤ 103, 1 ≤ t ≤ 103), each of which represents the height of the field, the width of the field, the number of waste cells and the number of queries that ask the kind of crop plants in a certain cell. Following each k lines contains two integers a, b (1 ≤ a ≤ n, 1 ≤ b ≤ m), which denotes a cell (a, b) is waste. It is guaranteed that the same cell will not appear twice in this section. Following each t lines contains two integers i, j (1 ≤ i ≤ n, 1 ≤ j ≤ m), which is a query that asks you the kind of crop plants of a cell (i, j). Output For each query, if the cell is waste, print Waste. Otherwise, print the name of crop plants in the cell: either Carrots or Kiwis or Grapes. Examples Input 4 5 5 6 4 3 1 3 3 3 2 5 3 2 1 3 1 4 2 3 2 4 1 1 1 1 Output Waste Grapes Carrots Kiwis Carrots Carrots Note The sample corresponds to the figure in the statement. Submitted Solution: ``` n,m,k,t = map(int, input().split()) arr= [0] for i in range(n*m): arr.append(1) for i in range(k): a,b = map(int,input().split()) arr[((a-1)*m)+b]=0 pre = 3 for index, i in enumerate(arr): if i == 1: if pre == 3: val = 1 elif pre == 1: val = 2 elif pre == 2: val = 3 pre = val arr[index] = val for i in range(t): i,j = map(int, input().split()) ind = ((i-1)*m)+j val= arr[ind] if val ==0: print("Waste") elif val == 1: print("Carrot") elif val == 2: print("Kiwis") elif val == 3: print("Grapes") ```
instruction
0
42,571
3
85,142
No
output
1
42,571
3
85,143
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The weather is fine today and hence it's high time to climb the nearby pine and enjoy the landscape. The pine's trunk includes several branches, located one above another and numbered from 2 to y. Some of them (more precise, from 2 to p) are occupied by tiny vile grasshoppers which you're at war with. These grasshoppers are known for their awesome jumping skills: the grasshopper at branch x can jump to branches <image>. Keeping this in mind, you wisely decided to choose such a branch that none of the grasshoppers could interrupt you. At the same time you wanna settle as high as possible since the view from up there is simply breathtaking. In other words, your goal is to find the highest branch that cannot be reached by any of the grasshoppers or report that it's impossible. Input The only line contains two integers p and y (2 ≤ p ≤ y ≤ 109). Output Output the number of the highest suitable branch. If there are none, print -1 instead. Examples Input 3 6 Output 5 Input 3 4 Output -1 Note In the first sample case grasshopper from branch 2 reaches branches 2, 4 and 6 while branch 3 is initially settled by another grasshopper. Therefore the answer is 5. It immediately follows that there are no valid branches in second sample case. Submitted Solution: ``` """Problem B - Vile Grasshoppers. http://codeforces.com/contest/937/problem/B The weather is fine today and hence it's high time to climb the nearby pine and enjoy the landscape. The pine's trunk includes several branches, located one above another and numbered from 2 to y. Some of them (more precise, from 2 to p) are occupied by tiny vile grasshoppers which you're at war with. These grasshoppers are known for their awesome jumping skills: the grasshopper at branch x can jump to branches . Keeping this in mind, you wisely decided to choose such a branch that none of the grasshoppers could interrupt you. At the same time you wanna settle as high as possible since the view from up there is simply breathtaking. In other words, your goal is to find the highest branch that cannot be reached by any of the grasshoppers or report that it's impossible. Input: The only line contains two integers p and y (2 ≤ p ≤ y ≤ 109). Output: Output the number of the highest suitable branch. If there are none, print -1 instead. """ import logging fmt = '%(levelname)s - %(name)s (line:%(lineno)s) - %(message)s' formatter = logging.Formatter(fmt) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) ch.setFormatter(formatter) logger = logging.getLogger('vile_grasshoppers') logger.setLevel(logging.DEBUG) logger.addHandler(ch) def is_prime(p): # Only for p > 3 if p % 2 == 0: return False for a in [2, 3]: if pow(a, p - 1, p) != 1: return False for i in range(3, int(p ** 0.5 + 1), 1): if p % i == 0: return False return True def solve(p, y): for i in reversed(range(p + 1, y + 1)): # Check first if its prime if is_prime(i): return i for j in range(2, p + 1): if i % j == 0: break else: return i return -1 # def solve(p, y): # nop = set() # for x in range(2, p + 1): # nop.add(x) # for j in range(1, y // x + 1): # if j * x > y: # break # nop.add(j * x) # for x in reversed(range(2, y + 1)): # if x not in nop: # return x # return -1 def main(): # Some common input types below, use as needed. p, y = map(int, input().strip().split()) result = solve(p, y) print(result) if __name__ == '__main__': main() ```
instruction
0
42,623
3
85,246
Yes
output
1
42,623
3
85,247
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The weather is fine today and hence it's high time to climb the nearby pine and enjoy the landscape. The pine's trunk includes several branches, located one above another and numbered from 2 to y. Some of them (more precise, from 2 to p) are occupied by tiny vile grasshoppers which you're at war with. These grasshoppers are known for their awesome jumping skills: the grasshopper at branch x can jump to branches <image>. Keeping this in mind, you wisely decided to choose such a branch that none of the grasshoppers could interrupt you. At the same time you wanna settle as high as possible since the view from up there is simply breathtaking. In other words, your goal is to find the highest branch that cannot be reached by any of the grasshoppers or report that it's impossible. Input The only line contains two integers p and y (2 ≤ p ≤ y ≤ 109). Output Output the number of the highest suitable branch. If there are none, print -1 instead. Examples Input 3 6 Output 5 Input 3 4 Output -1 Note In the first sample case grasshopper from branch 2 reaches branches 2, 4 and 6 while branch 3 is initially settled by another grasshopper. Therefore the answer is 5. It immediately follows that there are no valid branches in second sample case. Submitted Solution: ``` p,y = map(int,input().split()) for x in range(y,p,-1): if all(x%i for i in range(2,min(p,int(x**.5))+1)): print(x) exit() print(-1) ```
instruction
0
42,624
3
85,248
Yes
output
1
42,624
3
85,249
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The weather is fine today and hence it's high time to climb the nearby pine and enjoy the landscape. The pine's trunk includes several branches, located one above another and numbered from 2 to y. Some of them (more precise, from 2 to p) are occupied by tiny vile grasshoppers which you're at war with. These grasshoppers are known for their awesome jumping skills: the grasshopper at branch x can jump to branches <image>. Keeping this in mind, you wisely decided to choose such a branch that none of the grasshoppers could interrupt you. At the same time you wanna settle as high as possible since the view from up there is simply breathtaking. In other words, your goal is to find the highest branch that cannot be reached by any of the grasshoppers or report that it's impossible. Input The only line contains two integers p and y (2 ≤ p ≤ y ≤ 109). Output Output the number of the highest suitable branch. If there are none, print -1 instead. Examples Input 3 6 Output 5 Input 3 4 Output -1 Note In the first sample case grasshopper from branch 2 reaches branches 2, 4 and 6 while branch 3 is initially settled by another grasshopper. Therefore the answer is 5. It immediately follows that there are no valid branches in second sample case. Submitted Solution: ``` import math p, y = [int(c) for c in input().split(" ")] def p1(p, y): primelist = [2] for i in range(3, p + 1, 2): tempstatus = True for pp in primelist: if i % pp == 0: tempstatus = False break if tempstatus: primelist.append(i) ans = -1 for i in range(y, p, -1): tempstatus = True for pp in primelist: if i % pp == 0: tempstatus = False break if tempstatus: ans = i break #print(primelist[:100]) return ans def p2(p, y): primelist = [2] for i in range(3, min(int(math.sqrt(y)), p) + 1, 2): tempstatus = True for pp in primelist: if i % pp == 0: tempstatus = False break if tempstatus: primelist.append(i) ans = -1 for i in range(y, p, -1): tempstatus = True for pp in primelist: if i % pp == 0: tempstatus = False break if tempstatus: ans = i break # print(primelist[:100]) return ans print(p2(p, y)) ```
instruction
0
42,625
3
85,250
Yes
output
1
42,625
3
85,251
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The weather is fine today and hence it's high time to climb the nearby pine and enjoy the landscape. The pine's trunk includes several branches, located one above another and numbered from 2 to y. Some of them (more precise, from 2 to p) are occupied by tiny vile grasshoppers which you're at war with. These grasshoppers are known for their awesome jumping skills: the grasshopper at branch x can jump to branches <image>. Keeping this in mind, you wisely decided to choose such a branch that none of the grasshoppers could interrupt you. At the same time you wanna settle as high as possible since the view from up there is simply breathtaking. In other words, your goal is to find the highest branch that cannot be reached by any of the grasshoppers or report that it's impossible. Input The only line contains two integers p and y (2 ≤ p ≤ y ≤ 109). Output Output the number of the highest suitable branch. If there are none, print -1 instead. Examples Input 3 6 Output 5 Input 3 4 Output -1 Note In the first sample case grasshopper from branch 2 reaches branches 2, 4 and 6 while branch 3 is initially settled by another grasshopper. Therefore the answer is 5. It immediately follows that there are no valid branches in second sample case. Submitted Solution: ``` def SieveOfEratosthenes(n): # Create a boolean array "prime[0..n]" and initialize # all entries it as true. A value in prime[i] will # finally be false if i is Not a prime, else true. prime = [True for i in range(n + 1)] p = 2 while (p * p <= n): # If prime[p] is not changed, then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * 2, n + 1, p): prime[i] = False p += 1 ls=[] # Print all prime numbers for p in range(2, n): if prime[p]: ls.append(p) return ls ls=SieveOfEratosthenes(100000) p,y=[int(i) for i in input().split(" ")] while (y!=p): flag=0 for i in ls: if i>p: break if not y%i: flag=1 break if not flag: print(y) exit(0) y-=1 print(-1) ```
instruction
0
42,626
3
85,252
Yes
output
1
42,626
3
85,253
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The weather is fine today and hence it's high time to climb the nearby pine and enjoy the landscape. The pine's trunk includes several branches, located one above another and numbered from 2 to y. Some of them (more precise, from 2 to p) are occupied by tiny vile grasshoppers which you're at war with. These grasshoppers are known for their awesome jumping skills: the grasshopper at branch x can jump to branches <image>. Keeping this in mind, you wisely decided to choose such a branch that none of the grasshoppers could interrupt you. At the same time you wanna settle as high as possible since the view from up there is simply breathtaking. In other words, your goal is to find the highest branch that cannot be reached by any of the grasshoppers or report that it's impossible. Input The only line contains two integers p and y (2 ≤ p ≤ y ≤ 109). Output Output the number of the highest suitable branch. If there are none, print -1 instead. Examples Input 3 6 Output 5 Input 3 4 Output -1 Note In the first sample case grasshopper from branch 2 reaches branches 2, 4 and 6 while branch 3 is initially settled by another grasshopper. Therefore the answer is 5. It immediately follows that there are no valid branches in second sample case. Submitted Solution: ``` from math import sqrt p, y = [int(x) for x in input().split()] def isprime(n): if n == 2: return False for x in range(2, min(int(sqrt(n)) + 1, p)): if n % x == 0: return False return True for i in range(y, p,-1): if isprime(i): print(i) exit() print(-1) ```
instruction
0
42,627
3
85,254
No
output
1
42,627
3
85,255
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The weather is fine today and hence it's high time to climb the nearby pine and enjoy the landscape. The pine's trunk includes several branches, located one above another and numbered from 2 to y. Some of them (more precise, from 2 to p) are occupied by tiny vile grasshoppers which you're at war with. These grasshoppers are known for their awesome jumping skills: the grasshopper at branch x can jump to branches <image>. Keeping this in mind, you wisely decided to choose such a branch that none of the grasshoppers could interrupt you. At the same time you wanna settle as high as possible since the view from up there is simply breathtaking. In other words, your goal is to find the highest branch that cannot be reached by any of the grasshoppers or report that it's impossible. Input The only line contains two integers p and y (2 ≤ p ≤ y ≤ 109). Output Output the number of the highest suitable branch. If there are none, print -1 instead. Examples Input 3 6 Output 5 Input 3 4 Output -1 Note In the first sample case grasshopper from branch 2 reaches branches 2, 4 and 6 while branch 3 is initially settled by another grasshopper. Therefore the answer is 5. It immediately follows that there are no valid branches in second sample case. Submitted Solution: ``` # -*- coding: utf-8 -*- """ Created on Wed Mar 7 09:39:50 2018 @author: wangjun """ import math def Grasshopper(ng,nb): if nb%2 ==0 : nb=nb-1 nng = math.floor( nb ** 0.5 ) if nng >ng : nng=ng if nng < 3: nng=3 for branch in range(nb,ng,-2): flag =True for hopper in range(3,nng+1,2): if branch % hopper == 0: flag = False break if flag==True : return branch return -1 def hello(): """Print "Hello World" and return None""" ar = list(map(int, input().strip().split(' '))) result=Grasshopper(ar[0],ar[1]) print(result) # main program starts here hello() ```
instruction
0
42,628
3
85,256
No
output
1
42,628
3
85,257
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The weather is fine today and hence it's high time to climb the nearby pine and enjoy the landscape. The pine's trunk includes several branches, located one above another and numbered from 2 to y. Some of them (more precise, from 2 to p) are occupied by tiny vile grasshoppers which you're at war with. These grasshoppers are known for their awesome jumping skills: the grasshopper at branch x can jump to branches <image>. Keeping this in mind, you wisely decided to choose such a branch that none of the grasshoppers could interrupt you. At the same time you wanna settle as high as possible since the view from up there is simply breathtaking. In other words, your goal is to find the highest branch that cannot be reached by any of the grasshoppers or report that it's impossible. Input The only line contains two integers p and y (2 ≤ p ≤ y ≤ 109). Output Output the number of the highest suitable branch. If there are none, print -1 instead. Examples Input 3 6 Output 5 Input 3 4 Output -1 Note In the first sample case grasshopper from branch 2 reaches branches 2, 4 and 6 while branch 3 is initially settled by another grasshopper. Therefore the answer is 5. It immediately follows that there are no valid branches in second sample case. Submitted Solution: ``` from math import * def all_primes(start, end): return list( sorted( set(range(start,end+1)).difference(set((p * f) for p in range(2, int(floor(end ** 0.5)) + 2) for f in range(2, (end//p) + 1))) ) ) [p, y] = [int(x) for x in input().split(' ')] # i = list(reversed(range(2,y+1))) if (p == 2): if (y % 2 ==0): print(y - 1) else: print(y) else: primes = all_primes(3, p) if (y %2 ==0): y = y - 1 while(1): var = False for pr in primes: if (y % pr == 0): var = True break if (var == True): y = y - 2 if (y <= p): print(-1) break else: print(y) break ```
instruction
0
42,629
3
85,258
No
output
1
42,629
3
85,259
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A system of n vessels with water is given. Several pairs of vessels are connected by tubes with transfusion mechanisms. One may transfer an integer amount of liters of water between two vessels connected by such tube (tube works in both directions). There might be multiple tubes between two vessels. Total number of tubes equals e. Volume of each vessel equals v liters. Of course, the amount of the water in any vessel cannot exceed v liters in the process of transfusions. Given the initial amounts ai of water in the vessels and the desired amounts bi find a sequence of transfusions that deals with the task. Total number of transfusions must not exceed 2·n2. Input First line of the input contains integers n, v, e (1 ≤ n ≤ 300, 1 ≤ v ≤ 109, 0 ≤ e ≤ 50000). Next two lines contain n integers each: initial ai and the desired amounts bi of water in corresponding vessels (0 ≤ ai, bi ≤ v). Next e lines describe one tube each in the format x y (1 ≤ x, y ≤ n, x ≠ y) for a tube between vessels number x and y. There might be multiple tubes between two vessels. You may assume that vessels are numbered from 1 to n in some way. Output Print "NO" (without quotes), if such sequence of transfusions does not exist. Otherwise print any suitable sequence in the following format. On the first line print the total number of transfusions k (k should not exceed 2·n2). In the following k lines print transfusions in the format x y d (transfusion of d liters from the vessel number x to the vessel number y, x and y must be distinct). For all transfusions d must be a non-negative integer. Examples Input 2 10 1 1 9 5 5 1 2 Output 1 2 1 4 Input 2 10 0 5 2 4 2 Output NO Input 2 10 0 4 2 4 2 Output 0 Submitted Solution: ``` n, v, e = (int(i) for i in input().split()) a = [0] * (n + 15) b = [0] * (n + 15) E = [[] for i in range(n)] f = [int(i) for i in range(n)] vis = [0] * (n + 15) res = [] re = 0 def fd(x): if f[x] == x: return x else: f[x] = fd(f[x]) return f[x] def dfs2(u, f, ty): global re if re <= a[u] and re > 0: if ty == 0: res.append([f,u, re]) a[u] -= re a[f] += re re = 0 else: re -= a[u] for v in E[u]: if v == f or vis[v]: continue dfs2(v, u, ty) if re == 0:break if f != -1: if ty == 0: res.append([u, f, a[u]]) else: res.append([f,u, a[u]]) a[f] += a[u] a[u] = 0 def solve(c): if a[c] == b[c]: return global re if a[c] < b[c]: re = b[c] dfs2(c, -1, 0) else: for i in range(n): a[i], b[i] = v - a[i], v - b[i] re = b[c] dfs2(c, -1, 1) for i in range(n): a[i], b[i] = v - a[i], v - b[i] def dfs(u, f): for v in E[u]: if v == f: continue dfs(v, u) solve(u) vis[u] = 1 a = list(map(int, input().split())) b = list(map(int, input().split())) for i in range(e): x, y = map(lambda x: int(x) - 1, input().split()) if fd(x) != fd(y): E[x].append(y) E[y].append(x) f[fd(x)] = fd(y) for i in range(n): if fd(i) != i: continue sa = sum(a[j] for j in range(n) if (fd(j) == i)) sb = sum(b[j] for j in range(n) if (fd(j) == i)) if sa != sb: print("NO") exit() dfs(i, -1) print(len(res)) for c in res: print(c[0] + 1, c[1] + 1, c[2]) ''' #A m, n = map(int, input().split()) if m % 2 == 1: if n <= (m + 1) // 2: print(2 * n - 1) else: print(2 * n - (m + 1)) else: if n <= m // 2: print(2 * n - 1) else: print(2 * n - m) #B s = input() l = s.split('heavy') res = 0 for i in range(1, len(l)): res += i * l[i].count('metal') print(res) #C s = input().split() x, y, m = (int(i) for i in s) res = 0 if x >= m or y >= m: print(0) elif x <= 0 and y <= 0: print(-1) else: if x < 0: q = abs(x // y) res += q x += y * q elif y < 0: q = abs(y // x) res += q y += x * q while x < m and y < m: res += 1 if x < y: x += y else: y += x print(res) ''' ```
instruction
0
43,303
3
86,606
No
output
1
43,303
3
86,607
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A system of n vessels with water is given. Several pairs of vessels are connected by tubes with transfusion mechanisms. One may transfer an integer amount of liters of water between two vessels connected by such tube (tube works in both directions). There might be multiple tubes between two vessels. Total number of tubes equals e. Volume of each vessel equals v liters. Of course, the amount of the water in any vessel cannot exceed v liters in the process of transfusions. Given the initial amounts ai of water in the vessels and the desired amounts bi find a sequence of transfusions that deals with the task. Total number of transfusions must not exceed 2·n2. Input First line of the input contains integers n, v, e (1 ≤ n ≤ 300, 1 ≤ v ≤ 109, 0 ≤ e ≤ 50000). Next two lines contain n integers each: initial ai and the desired amounts bi of water in corresponding vessels (0 ≤ ai, bi ≤ v). Next e lines describe one tube each in the format x y (1 ≤ x, y ≤ n, x ≠ y) for a tube between vessels number x and y. There might be multiple tubes between two vessels. You may assume that vessels are numbered from 1 to n in some way. Output Print "NO" (without quotes), if such sequence of transfusions does not exist. Otherwise print any suitable sequence in the following format. On the first line print the total number of transfusions k (k should not exceed 2·n2). In the following k lines print transfusions in the format x y d (transfusion of d liters from the vessel number x to the vessel number y, x and y must be distinct). For all transfusions d must be a non-negative integer. Examples Input 2 10 1 1 9 5 5 1 2 Output 1 2 1 4 Input 2 10 0 5 2 4 2 Output NO Input 2 10 0 4 2 4 2 Output 0 Submitted Solution: ``` n, v, e = (int(i) for i in input().split()) a = [0] * (n + 15) b = [0] * (n + 15) E = [[] for i in range(n)] f = [int(i) for i in range(n)] vis = [0] * (n + 15) res = [] re = 0 def fd(x): if f[x] == x: return x else: f[x] = fd(f[x]) return f[x] def dfs2(u, f, ty): global re if re <= a[u] and re > 0: if ty == 0: res.append([u, f, re]) else: res.append([f, u, re]) a[u] -= re a[f] += re re = 0 else: re -= a[u] for v in E[u]: if v == f or vis[v]: continue dfs2(v, u, ty) if re == 0:break if f != -1: if ty == 0: res.append([u, f, a[u]]) else: res.append([f,u, a[u]]) a[f] += a[u] a[u] = 0 def solve(c): if a[c] == b[c]: return global re if a[c] < b[c]: re = b[c] dfs2(c, -1, 0) else: for i in range(n): a[i], b[i] = v - a[i], v - b[i] re = b[c] dfs2(c, -1, 1) for i in range(n): a[i], b[i] = v - a[i], v - b[i] def dfs(u, f): for v in E[u]: if v == f: continue dfs(v, u) solve(u) vis[u] = 1 a = list(map(int, input().split())) b = list(map(int, input().split())) for i in range(e): x, y = map(lambda x: int(x) - 1, input().split()) if fd(x) != fd(y): E[x].append(y) E[y].append(x) f[fd(x)] = fd(y) for i in range(n): if fd(i) != i: continue sa = sum(a[j] for j in range(n) if (fd(j) == i)) sb = sum(b[j] for j in range(n) if (fd(j) == i)) if sa != sb: print("NO") exit() dfs(i, -1) print(len(res)) for c in res: print(c[0] + 1, c[1] + 1, c[2]) ''' 2 10 1 1 9 5 5 1 2 #A m, n = map(int, input().split()) if m % 2 == 1: if n <= (m + 1) // 2: print(2 * n - 1) else: print(2 * n - (m + 1)) else: if n <= m // 2: print(2 * n - 1) else: print(2 * n - m) #B s = input() l = s.split('heavy') res = 0 for i in range(1, len(l)): res += i * l[i].count('metal') print(res) #C s = input().split() x, y, m = (int(i) for i in s) res = 0 if x >= m or y >= m: print(0) elif x <= 0 and y <= 0: print(-1) else: if x < 0: q = abs(x // y) res += q x += y * q elif y < 0: q = abs(y // x) res += q y += x * q while x < m and y < m: res += 1 if x < y: x += y else: y += x print(res) ''' ```
instruction
0
43,304
3
86,608
No
output
1
43,304
3
86,609
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A system of n vessels with water is given. Several pairs of vessels are connected by tubes with transfusion mechanisms. One may transfer an integer amount of liters of water between two vessels connected by such tube (tube works in both directions). There might be multiple tubes between two vessels. Total number of tubes equals e. Volume of each vessel equals v liters. Of course, the amount of the water in any vessel cannot exceed v liters in the process of transfusions. Given the initial amounts ai of water in the vessels and the desired amounts bi find a sequence of transfusions that deals with the task. Total number of transfusions must not exceed 2·n2. Input First line of the input contains integers n, v, e (1 ≤ n ≤ 300, 1 ≤ v ≤ 109, 0 ≤ e ≤ 50000). Next two lines contain n integers each: initial ai and the desired amounts bi of water in corresponding vessels (0 ≤ ai, bi ≤ v). Next e lines describe one tube each in the format x y (1 ≤ x, y ≤ n, x ≠ y) for a tube between vessels number x and y. There might be multiple tubes between two vessels. You may assume that vessels are numbered from 1 to n in some way. Output Print "NO" (without quotes), if such sequence of transfusions does not exist. Otherwise print any suitable sequence in the following format. On the first line print the total number of transfusions k (k should not exceed 2·n2). In the following k lines print transfusions in the format x y d (transfusion of d liters from the vessel number x to the vessel number y, x and y must be distinct). For all transfusions d must be a non-negative integer. Examples Input 2 10 1 1 9 5 5 1 2 Output 1 2 1 4 Input 2 10 0 5 2 4 2 Output NO Input 2 10 0 4 2 4 2 Output 0 Submitted Solution: ``` read = lambda: map(int, input().split()) n, v, e = read() adj = [[]] * (n + 1) As = [0] + list(read()) Bs = [0] + list(read()) ans = [] for _ in range(e): a, b = map(int, input().split()) adj[a].append(b) adj[b].append(a) def flow(a, b, d): As[a] -= d As[b] += d ans.append((a, b, d)); def augment(path, e, d): if e: dd = min(d, As[path[e - 1]], v - As[path[e]]) flow(path[e - 1], path[e], dd) augment(path, e - 1, d) if d > dd: flow(path[e - 1], path[e], d - dd); def adjust(s): pre = [0] * (n + 1) pre[s] = -1 stk = [s] e = 0 while len(stk): p = stk[-1] del stk[-1] if As[p] < Bs[p]: e = p break for to in adj[p]: if not pre[to]: pre[to] = p stk.append(to) if not e: raise Exception path = [] while e > 0: path.insert(0, e) e = pre[e] augment(path, len(path) - 1, min(Bs[path[-1]] - As[path[-1]], As[s] - Bs[s])) try: while True: check = False for i in range(1, n + 1): if As[i] > Bs[i]: adjust(i) check = True if not check: break for i in range(1, n + 1): if As[i] != Bs[i]: raise Exception print(len(ans)) for tp in ans: print(*tp) except Exception: print("NO") ```
instruction
0
43,305
3
86,610
No
output
1
43,305
3
86,611
Provide tags and a correct Python 3 solution for this coding contest problem. During the loading of the game "Dungeons and Candies" you are required to get descriptions of k levels from the server. Each description is a map of an n × m checkered rectangular field. Some cells of the field contain candies (each cell has at most one candy). An empty cell is denoted as "." on the map, but if a cell has a candy, it is denoted as a letter of the English alphabet. A level may contain identical candies, in this case the letters in the corresponding cells of the map will be the same. <image> When you transmit information via a network, you want to minimize traffic — the total size of the transferred data. The levels can be transmitted in any order. There are two ways to transmit the current level A: 1. You can transmit the whole level A. Then you need to transmit n·m bytes via the network. 2. You can transmit the difference between level A and some previously transmitted level B (if it exists); this operation requires to transmit dA, B·w bytes, where dA, B is the number of cells of the field that are different for A and B, and w is a constant. Note, that you should compare only the corresponding cells of levels A and B to calculate dA, B. You cannot transform the maps of levels, i.e. rotate or shift them relatively to each other. Your task is to find a way to transfer all the k levels and minimize the traffic. Input The first line contains four integers n, m, k, w (1 ≤ n, m ≤ 10; 1 ≤ k, w ≤ 1000). Then follows the description of k levels. Each level is described by n lines, each line contains m characters. Each character is either a letter of the English alphabet or a dot ("."). Please note that the case of the letters matters. Output In the first line print the required minimum number of transferred bytes. Then print k pairs of integers x1, y1, x2, y2, ..., xk, yk, describing the way to transfer levels. Pair xi, yi means that level xi needs to be transferred by way yi. If yi equals 0, that means that the level must be transferred using the first way, otherwise yi must be equal to the number of a previously transferred level. It means that you will transfer the difference between levels yi and xi to transfer level xi. Print the pairs in the order of transferring levels. The levels are numbered 1 through k in the order they follow in the input. If there are multiple optimal solutions, you can print any of them. Examples Input 2 3 3 2 A.A ... A.a ..C X.Y ... Output 14 1 0 2 1 3 1 Input 1 1 4 1 A . B . Output 3 1 0 2 0 4 2 3 0 Input 1 3 5 2 ABA BBB BBA BAB ABB Output 11 1 0 3 1 2 3 4 2 5 1
instruction
0
43,338
3
86,676
Tags: dsu, graphs, greedy, trees Correct Solution: ``` def put(): return map(int, input().split()) def diff(x,y): ans = 0 for i in range(n*m): if s[x][i]!= s[y][i]: ans+=1 return ans def find(i): if i==p[i]: return i p[i] = find(p[i]) return p[i] def union(i,j): if rank[i]>rank[j]: i,j = j,i elif rank[i]==rank[j]: rank[j]+=1 p[i]= j def dfs(i,p): if i!=0: print(i,p) for j in tree[i]: if j!=p: dfs(j,i) n,m,k,w = put() s = ['']*k for i in range(k): for j in range(n): s[i]+=input() edge = [] k+=1 rank = [0]*(k) p = list(range(k)) cost = 0 tree = [[] for i in range(k)] for i in range(k): for j in range(i+1,k): if i==0: z=n*m else: z = diff(i-1,j-1)*w edge.append((z,i,j)) edge.sort() for z,i,j in edge: u = find(i) v = find(j) if u!=v: union(u,v) cost+= z tree[i].append(j) tree[j].append(i) print(cost) dfs(0,-1) ```
output
1
43,338
3
86,677
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. During the loading of the game "Dungeons and Candies" you are required to get descriptions of k levels from the server. Each description is a map of an n × m checkered rectangular field. Some cells of the field contain candies (each cell has at most one candy). An empty cell is denoted as "." on the map, but if a cell has a candy, it is denoted as a letter of the English alphabet. A level may contain identical candies, in this case the letters in the corresponding cells of the map will be the same. <image> When you transmit information via a network, you want to minimize traffic — the total size of the transferred data. The levels can be transmitted in any order. There are two ways to transmit the current level A: 1. You can transmit the whole level A. Then you need to transmit n·m bytes via the network. 2. You can transmit the difference between level A and some previously transmitted level B (if it exists); this operation requires to transmit dA, B·w bytes, where dA, B is the number of cells of the field that are different for A and B, and w is a constant. Note, that you should compare only the corresponding cells of levels A and B to calculate dA, B. You cannot transform the maps of levels, i.e. rotate or shift them relatively to each other. Your task is to find a way to transfer all the k levels and minimize the traffic. Input The first line contains four integers n, m, k, w (1 ≤ n, m ≤ 10; 1 ≤ k, w ≤ 1000). Then follows the description of k levels. Each level is described by n lines, each line contains m characters. Each character is either a letter of the English alphabet or a dot ("."). Please note that the case of the letters matters. Output In the first line print the required minimum number of transferred bytes. Then print k pairs of integers x1, y1, x2, y2, ..., xk, yk, describing the way to transfer levels. Pair xi, yi means that level xi needs to be transferred by way yi. If yi equals 0, that means that the level must be transferred using the first way, otherwise yi must be equal to the number of a previously transferred level. It means that you will transfer the difference between levels yi and xi to transfer level xi. Print the pairs in the order of transferring levels. The levels are numbered 1 through k in the order they follow in the input. If there are multiple optimal solutions, you can print any of them. Examples Input 2 3 3 2 A.A ... A.a ..C X.Y ... Output 14 1 0 2 1 3 1 Input 1 1 4 1 A . B . Output 3 1 0 2 0 4 2 3 0 Input 1 3 5 2 ABA BBB BBA BAB ABB Output 11 1 0 3 1 2 3 4 2 5 1 Submitted Solution: ``` class Graph: def __init__(self,vertices): self.V = vertices self.graph = [] def addEdge(self,u,v,w): self.graph.append([u,v,w]) def find(self, parent, i): if parent[i] == i: return i return self.find(parent, parent[i]) def union(self, parent, rank, x, y): xroot = self.find(parent, x) yroot = self.find(parent, y) if rank[xroot] < rank[yroot]: parent[xroot] = yroot elif rank[xroot] > rank[yroot]: parent[yroot] = xroot else: parent[yroot] = xroot rank[xroot] += 1 def KruskalMST(self): ans = 0 result = [] i,e = [0,0] self.graph = sorted(self.graph,key = lambda item: item[2]) parent = [] rank = [] for q in range(self.V): parent.append(q) rank.append(0) while e < self.V -1 : u,v,w = self.graph[i] i = i + 1 x = self.find(parent, u) y = self.find(parent ,v) if x != y: ans+=w e = e + 1 result.append([u,v,w]) self.union(parent, rank, x, y) print(ans) visited = [False]*(k+1) ans_tree = [[False]*(k+1) for _ in range(k+1)] for u,v,w in result: ans_tree[u][v] = True for i in range(1,k+1): ans_tree[i][0] = ans_tree[0][i] for i in range(1,k+1): for j in range(k+1): if(ans_tree[i][j]==True and visited[i]==False): print(i,j) visited[i] = True ```
instruction
0
43,339
3
86,678
No
output
1
43,339
3
86,679
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. During the loading of the game "Dungeons and Candies" you are required to get descriptions of k levels from the server. Each description is a map of an n × m checkered rectangular field. Some cells of the field contain candies (each cell has at most one candy). An empty cell is denoted as "." on the map, but if a cell has a candy, it is denoted as a letter of the English alphabet. A level may contain identical candies, in this case the letters in the corresponding cells of the map will be the same. <image> When you transmit information via a network, you want to minimize traffic — the total size of the transferred data. The levels can be transmitted in any order. There are two ways to transmit the current level A: 1. You can transmit the whole level A. Then you need to transmit n·m bytes via the network. 2. You can transmit the difference between level A and some previously transmitted level B (if it exists); this operation requires to transmit dA, B·w bytes, where dA, B is the number of cells of the field that are different for A and B, and w is a constant. Note, that you should compare only the corresponding cells of levels A and B to calculate dA, B. You cannot transform the maps of levels, i.e. rotate or shift them relatively to each other. Your task is to find a way to transfer all the k levels and minimize the traffic. Input The first line contains four integers n, m, k, w (1 ≤ n, m ≤ 10; 1 ≤ k, w ≤ 1000). Then follows the description of k levels. Each level is described by n lines, each line contains m characters. Each character is either a letter of the English alphabet or a dot ("."). Please note that the case of the letters matters. Output In the first line print the required minimum number of transferred bytes. Then print k pairs of integers x1, y1, x2, y2, ..., xk, yk, describing the way to transfer levels. Pair xi, yi means that level xi needs to be transferred by way yi. If yi equals 0, that means that the level must be transferred using the first way, otherwise yi must be equal to the number of a previously transferred level. It means that you will transfer the difference between levels yi and xi to transfer level xi. Print the pairs in the order of transferring levels. The levels are numbered 1 through k in the order they follow in the input. If there are multiple optimal solutions, you can print any of them. Examples Input 2 3 3 2 A.A ... A.a ..C X.Y ... Output 14 1 0 2 1 3 1 Input 1 1 4 1 A . B . Output 3 1 0 2 0 4 2 3 0 Input 1 3 5 2 ABA BBB BBA BAB ABB Output 11 1 0 3 1 2 3 4 2 5 1 Submitted Solution: ``` class Graph: def __init__(self,vertices): self.V = vertices self.graph = [] def addEdge(self,u,v,w): self.graph.append([u,v,w]) def find(self, parent, i): if parent[i] == i: return i return self.find(parent, parent[i]) def union(self, parent, rank, x, y): xroot = self.find(parent, x) yroot = self.find(parent, y) if rank[xroot] < rank[yroot]: parent[xroot] = yroot elif rank[xroot] > rank[yroot]: parent[yroot] = xroot else: parent[yroot] = xroot rank[xroot] += 1 def KruskalMST(self): ans = 0 result = [] i,e = [0,0] self.graph = sorted(self.graph,key = lambda item: item[2]) parent = [] rank = [] for q in range(self.V): parent.append(q) rank.append(0) while e < self.V -1 : u,v,w = self.graph[i] i = i + 1 x = self.find(parent, u) y = self.find(parent ,v) if x != y: ans+=w e = e + 1 result.append([u,v,w]) self.union(parent, rank, x, y) #print(ans,result) for p in range(len(result)-1,-1,-1): u = result[p][0] v = result[p][1] if(u==0): print(v,u) else: print(u,v) #MAIN PROGRAM n,m,k,w = [int(x) for x in input().split()] arr = [] g = Graph(k+1) for i in range(1,k+1): temp = [] for j in range(n): temp.append(input()) for p in range(len(arr)): diff = 0 for r in range(n): for q in range(m): if(arr[p][r][q]!=temp[r][q]): diff+=1 g.addEdge(i,p+1,diff*w) arr.append(temp) for i in range(1,k+1): g.addEdge(0,i,n*m) g.KruskalMST() ```
instruction
0
43,340
3
86,680
No
output
1
43,340
3
86,681
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. During the loading of the game "Dungeons and Candies" you are required to get descriptions of k levels from the server. Each description is a map of an n × m checkered rectangular field. Some cells of the field contain candies (each cell has at most one candy). An empty cell is denoted as "." on the map, but if a cell has a candy, it is denoted as a letter of the English alphabet. A level may contain identical candies, in this case the letters in the corresponding cells of the map will be the same. <image> When you transmit information via a network, you want to minimize traffic — the total size of the transferred data. The levels can be transmitted in any order. There are two ways to transmit the current level A: 1. You can transmit the whole level A. Then you need to transmit n·m bytes via the network. 2. You can transmit the difference between level A and some previously transmitted level B (if it exists); this operation requires to transmit dA, B·w bytes, where dA, B is the number of cells of the field that are different for A and B, and w is a constant. Note, that you should compare only the corresponding cells of levels A and B to calculate dA, B. You cannot transform the maps of levels, i.e. rotate or shift them relatively to each other. Your task is to find a way to transfer all the k levels and minimize the traffic. Input The first line contains four integers n, m, k, w (1 ≤ n, m ≤ 10; 1 ≤ k, w ≤ 1000). Then follows the description of k levels. Each level is described by n lines, each line contains m characters. Each character is either a letter of the English alphabet or a dot ("."). Please note that the case of the letters matters. Output In the first line print the required minimum number of transferred bytes. Then print k pairs of integers x1, y1, x2, y2, ..., xk, yk, describing the way to transfer levels. Pair xi, yi means that level xi needs to be transferred by way yi. If yi equals 0, that means that the level must be transferred using the first way, otherwise yi must be equal to the number of a previously transferred level. It means that you will transfer the difference between levels yi and xi to transfer level xi. Print the pairs in the order of transferring levels. The levels are numbered 1 through k in the order they follow in the input. If there are multiple optimal solutions, you can print any of them. Examples Input 2 3 3 2 A.A ... A.a ..C X.Y ... Output 14 1 0 2 1 3 1 Input 1 1 4 1 A . B . Output 3 1 0 2 0 4 2 3 0 Input 1 3 5 2 ABA BBB BBA BAB ABB Output 11 1 0 3 1 2 3 4 2 5 1 Submitted Solution: ``` class Graph: def __init__(self,vertices): self.V = vertices self.graph = [] def addEdge(self,u,v,w): self.graph.append([u,v,w]) def find(self, parent, i): if parent[i] == i: return i return self.find(parent, parent[i]) def union(self, parent, rank, x, y): xroot = self.find(parent, x) yroot = self.find(parent, y) if rank[xroot] < rank[yroot]: parent[xroot] = yroot elif rank[xroot] > rank[yroot]: parent[yroot] = xroot else: parent[yroot] = xroot rank[xroot] += 1 def KruskalMST(self): ans = 0 result = [] i,e = [0,0] self.graph = sorted(self.graph,key = lambda item: item[2]) parent = [] rank = [] for q in range(self.V): parent.append(q) rank.append(0) while e < self.V -1 : u,v,w = self.graph[i] i = i + 1 x = self.find(parent, u) y = self.find(parent ,v) if x != y: ans+=w e = e + 1 result.append([u,v,w]) self.union(parent, rank, x, y) #print(ans,result) for u,v,w in result: if(u==0): print(v,u) else: print(u,v) #MAIN PROGRAM n,m,k,w = [int(x) for x in input().split()] arr = [] g = Graph(k+1) for i in range(1,k+1): temp = [] for j in range(n): temp.append(input()) for p in range(len(arr)): diff = 0 for r in range(n): for q in range(m): if(arr[p][r][q]!=temp[r][q]): diff+=1 g.addEdge(i,p+1,diff*w) arr.append(temp) for i in range(1,k+1): g.addEdge(0,i,n*m) g.KruskalMST() ```
instruction
0
43,341
3
86,682
No
output
1
43,341
3
86,683
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. During the loading of the game "Dungeons and Candies" you are required to get descriptions of k levels from the server. Each description is a map of an n × m checkered rectangular field. Some cells of the field contain candies (each cell has at most one candy). An empty cell is denoted as "." on the map, but if a cell has a candy, it is denoted as a letter of the English alphabet. A level may contain identical candies, in this case the letters in the corresponding cells of the map will be the same. <image> When you transmit information via a network, you want to minimize traffic — the total size of the transferred data. The levels can be transmitted in any order. There are two ways to transmit the current level A: 1. You can transmit the whole level A. Then you need to transmit n·m bytes via the network. 2. You can transmit the difference between level A and some previously transmitted level B (if it exists); this operation requires to transmit dA, B·w bytes, where dA, B is the number of cells of the field that are different for A and B, and w is a constant. Note, that you should compare only the corresponding cells of levels A and B to calculate dA, B. You cannot transform the maps of levels, i.e. rotate or shift them relatively to each other. Your task is to find a way to transfer all the k levels and minimize the traffic. Input The first line contains four integers n, m, k, w (1 ≤ n, m ≤ 10; 1 ≤ k, w ≤ 1000). Then follows the description of k levels. Each level is described by n lines, each line contains m characters. Each character is either a letter of the English alphabet or a dot ("."). Please note that the case of the letters matters. Output In the first line print the required minimum number of transferred bytes. Then print k pairs of integers x1, y1, x2, y2, ..., xk, yk, describing the way to transfer levels. Pair xi, yi means that level xi needs to be transferred by way yi. If yi equals 0, that means that the level must be transferred using the first way, otherwise yi must be equal to the number of a previously transferred level. It means that you will transfer the difference between levels yi and xi to transfer level xi. Print the pairs in the order of transferring levels. The levels are numbered 1 through k in the order they follow in the input. If there are multiple optimal solutions, you can print any of them. Examples Input 2 3 3 2 A.A ... A.a ..C X.Y ... Output 14 1 0 2 1 3 1 Input 1 1 4 1 A . B . Output 3 1 0 2 0 4 2 3 0 Input 1 3 5 2 ABA BBB BBA BAB ABB Output 11 1 0 3 1 2 3 4 2 5 1 Submitted Solution: ``` import heapq import math import sys def find_parent(a): if parents[a] != a: parents[a] = find_parent(parents[a]) return parents[a] def make_union(a, b): pa = find_parent(a) pb = find_parent(b) if pa == pb: return False ra = ranks[pa] rb = ranks[pb] if ra <= rb: parents[pa] = pb if ra == rb: ranks[pb] += 1 else: parents[pb] = pa return True N, M, K, W = map(int, sys.stdin.readline().split()) parents = [j for j in range(K+1)] ranks = [1 for j in range(K+1)] def difference(A, B): s = 0 for i in range(len(A)): for j in range(len(A[i])): s += A[i][j] != B[i][j] return s*W levels = [[['-' for j in range(M)] for j in range(N)]] for lvl in range(K): levl = [sys.stdin.readline().strip() for j in range(N)] levels.append(levl) edges = [] for j in range(1,K+1): for i in range(j+1, K+1): edges.append( (difference(levels[j], levels[i]), j, i) ) for j in range(1,K+1): edges.append((N*M, 0, j)) edges.sort() ww = 0 res = [] for w, start, stop in edges: if make_union(start, stop): ww += w res.append([stop, start]) print(ww) res.sort() for u,j in res: print(u, j) ```
instruction
0
43,342
3
86,684
No
output
1
43,342
3
86,685
Provide tags and a correct Python 3 solution for this coding contest problem. When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging — but why not make a similar programming contest problem while we're at it? You're given a sequence of n data points a1, ..., an. There aren't any big jumps between consecutive data points — for each 1 ≤ i < n, it's guaranteed that |ai + 1 - ai| ≤ 1. A range [l, r] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let M be the maximum and m the minimum value of ai for l ≤ i ≤ r; the range [l, r] is almost constant if M - m ≤ 1. Find the length of the longest almost constant range. Input The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of data points. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000). Output Print a single number — the maximum length of an almost constant range of the given sequence. Examples Input 5 1 2 3 3 2 Output 4 Input 11 5 4 5 5 6 7 8 8 8 7 6 Output 5 Note In the first sample, the longest almost constant range is [2, 5]; its length (the number of data points in it) is 4. In the second sample, there are three almost constant ranges of length 4: [1, 4], [6, 9] and [7, 10]; the only almost constant range of the maximum length 5 is [6, 10].
instruction
0
43,412
3
86,824
Tags: dp, implementation, two pointers Correct Solution: ``` n=int(input()) l=list(map(int,input().split())) a=l[0] b=l[0] k=1 ma=1 for i in range(1,n) : if abs(l[i]-a)<=1 and abs(l[i]-b)<=1 : k=k+1 if l[i]!=a : b=l[i] else : ma=max(k,ma) k=1 for j in range(i-1,-1,-1) : if abs(l[i]-l[j])>1 : break else : k=k+1 b=l[i] a=l[j+1] ma=max(ma,k) print(ma) ```
output
1
43,412
3
86,825
Provide tags and a correct Python 3 solution for this coding contest problem. When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging — but why not make a similar programming contest problem while we're at it? You're given a sequence of n data points a1, ..., an. There aren't any big jumps between consecutive data points — for each 1 ≤ i < n, it's guaranteed that |ai + 1 - ai| ≤ 1. A range [l, r] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let M be the maximum and m the minimum value of ai for l ≤ i ≤ r; the range [l, r] is almost constant if M - m ≤ 1. Find the length of the longest almost constant range. Input The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of data points. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000). Output Print a single number — the maximum length of an almost constant range of the given sequence. Examples Input 5 1 2 3 3 2 Output 4 Input 11 5 4 5 5 6 7 8 8 8 7 6 Output 5 Note In the first sample, the longest almost constant range is [2, 5]; its length (the number of data points in it) is 4. In the second sample, there are three almost constant ranges of length 4: [1, 4], [6, 9] and [7, 10]; the only almost constant range of the maximum length 5 is [6, 10].
instruction
0
43,413
3
86,826
Tags: dp, implementation, two pointers Correct Solution: ``` n = int(input()) a = list(map(int, input().split())) idx = dict() length, l, idx[a[0]] = 1, 0, 0 for i in range(1, n): l = max(l, idx.get(a[i] + 2, -1) + 1, idx.get(a[i] - 2, -1) + 1) length = max(length, i - l + 1) idx[a[i]] = i print(length) ```
output
1
43,413
3
86,827
Provide tags and a correct Python 3 solution for this coding contest problem. When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging — but why not make a similar programming contest problem while we're at it? You're given a sequence of n data points a1, ..., an. There aren't any big jumps between consecutive data points — for each 1 ≤ i < n, it's guaranteed that |ai + 1 - ai| ≤ 1. A range [l, r] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let M be the maximum and m the minimum value of ai for l ≤ i ≤ r; the range [l, r] is almost constant if M - m ≤ 1. Find the length of the longest almost constant range. Input The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of data points. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000). Output Print a single number — the maximum length of an almost constant range of the given sequence. Examples Input 5 1 2 3 3 2 Output 4 Input 11 5 4 5 5 6 7 8 8 8 7 6 Output 5 Note In the first sample, the longest almost constant range is [2, 5]; its length (the number of data points in it) is 4. In the second sample, there are three almost constant ranges of length 4: [1, 4], [6, 9] and [7, 10]; the only almost constant range of the maximum length 5 is [6, 10].
instruction
0
43,414
3
86,828
Tags: dp, implementation, two pointers Correct Solution: ``` import sys import string import math from collections import defaultdict from functools import lru_cache from collections import Counter def mi(s): return map(int, s.strip().split()) def lmi(s): return list(mi(s)) def tmi(s): return tuple(mi(s)) def mf(f, s): return map(f, s) def lmf(f, s): return list(mf(f, s)) def js(lst): return " ".join(str(d) for d in lst) def line(): return sys.stdin.readline().strip() def linesp(): return line().split() def iline(): return int(line()) def mat(n): matr = [] for _ in range(n): matr.append(linesp()) return matr def mati(n): mat = [] for _ in range(n): mat.append(lmi(line())) return mat def dist(x, y): return ((x[0] - y[0])**2 + (x[1] - y[1])**2)**0.5 def main(arr): m_g = {} m_l = {} m_g[0] = 1 m_l[0] = 1 longest = 1 for i in range(1, len(arr)): if arr[i - 1] == arr[i]: m_g[i] = m_g[i - 1] + 1 m_l[i] = m_l[i - 1] + 1 elif arr[i - 1] > arr[i]: m_g[i] = m_l[i - 1] + 1 m_l[i] = 1 elif arr[i - 1] < arr[i]: m_l[i] = m_g[i - 1] + 1 m_g[i] = 1 longest = max([longest, m_l[i], m_g[i]]) print(longest) if __name__ == "__main__": line() arr = lmi(line()) main(arr) ```
output
1
43,414
3
86,829
Provide tags and a correct Python 3 solution for this coding contest problem. When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging — but why not make a similar programming contest problem while we're at it? You're given a sequence of n data points a1, ..., an. There aren't any big jumps between consecutive data points — for each 1 ≤ i < n, it's guaranteed that |ai + 1 - ai| ≤ 1. A range [l, r] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let M be the maximum and m the minimum value of ai for l ≤ i ≤ r; the range [l, r] is almost constant if M - m ≤ 1. Find the length of the longest almost constant range. Input The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of data points. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000). Output Print a single number — the maximum length of an almost constant range of the given sequence. Examples Input 5 1 2 3 3 2 Output 4 Input 11 5 4 5 5 6 7 8 8 8 7 6 Output 5 Note In the first sample, the longest almost constant range is [2, 5]; its length (the number of data points in it) is 4. In the second sample, there are three almost constant ranges of length 4: [1, 4], [6, 9] and [7, 10]; the only almost constant range of the maximum length 5 is [6, 10].
instruction
0
43,415
3
86,830
Tags: dp, implementation, two pointers Correct Solution: ``` class Node: def __init__(self, data = None, pos = None): self.data = data self.pos = pos n = int(input()) a = list(map(int, input().split())) Max = [Node(0, 0) for i in range(10**5 + 1)] frontMax, frontMin, rearMax, rearMin = 1, 1, 0, 0 Min = [Node(0, 0) for i in range(10**5 + 1)] l = 0 res = 0 for r in range(n): while frontMax <= rearMax and Max[rearMax].data <= a[r]: rearMax -= 1 while frontMin <= rearMin and Min[rearMin].data >= a[r]: rearMin -= 1 rearMax += 1 Max[rearMax] = Node(a[r], r) rearMin += 1 Min[rearMin] = Node(a[r], r) while l <= r and Max[frontMax].data - Min[frontMin].data > 1: l += 1 if Max[frontMax].pos < l: frontMax += 1 if Min[frontMin].pos < l: frontMin += 1 res = max(res, r - l + 1) print(res) ```
output
1
43,415
3
86,831
Provide tags and a correct Python 3 solution for this coding contest problem. When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging — but why not make a similar programming contest problem while we're at it? You're given a sequence of n data points a1, ..., an. There aren't any big jumps between consecutive data points — for each 1 ≤ i < n, it's guaranteed that |ai + 1 - ai| ≤ 1. A range [l, r] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let M be the maximum and m the minimum value of ai for l ≤ i ≤ r; the range [l, r] is almost constant if M - m ≤ 1. Find the length of the longest almost constant range. Input The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of data points. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000). Output Print a single number — the maximum length of an almost constant range of the given sequence. Examples Input 5 1 2 3 3 2 Output 4 Input 11 5 4 5 5 6 7 8 8 8 7 6 Output 5 Note In the first sample, the longest almost constant range is [2, 5]; its length (the number of data points in it) is 4. In the second sample, there are three almost constant ranges of length 4: [1, 4], [6, 9] and [7, 10]; the only almost constant range of the maximum length 5 is [6, 10].
instruction
0
43,416
3
86,832
Tags: dp, implementation, two pointers Correct Solution: ``` n = int(input()) a = list(map(int, input().split())) fre = [0] * (10 ** 5 + 5) diff = 0 j = 0 longest_range = 0 for i in range(n): if fre[a[i]] == 0: diff += 1 fre[a[i]] += 1 while j < n and diff > 2: if fre[a[j]] == 1: diff -= 1 fre[a[j]] -= 1 j += 1 longest_range = max(longest_range, i - j + 1) print(longest_range) ```
output
1
43,416
3
86,833
Provide tags and a correct Python 3 solution for this coding contest problem. When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging — but why not make a similar programming contest problem while we're at it? You're given a sequence of n data points a1, ..., an. There aren't any big jumps between consecutive data points — for each 1 ≤ i < n, it's guaranteed that |ai + 1 - ai| ≤ 1. A range [l, r] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let M be the maximum and m the minimum value of ai for l ≤ i ≤ r; the range [l, r] is almost constant if M - m ≤ 1. Find the length of the longest almost constant range. Input The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of data points. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000). Output Print a single number — the maximum length of an almost constant range of the given sequence. Examples Input 5 1 2 3 3 2 Output 4 Input 11 5 4 5 5 6 7 8 8 8 7 6 Output 5 Note In the first sample, the longest almost constant range is [2, 5]; its length (the number of data points in it) is 4. In the second sample, there are three almost constant ranges of length 4: [1, 4], [6, 9] and [7, 10]; the only almost constant range of the maximum length 5 is [6, 10].
instruction
0
43,417
3
86,834
Tags: dp, implementation, two pointers Correct Solution: ``` # map(int, input().split(" ")) n = int(input()) dp = [[1,1,1] for i in range(n)] l = list(map(int, input().split(" "))) for i in range(1,n): if l[i] == l[i-1]: dp[i][0]+=dp[i-1][0] dp[i][1]+=dp[i-1][1] dp[i][2]+=dp[i-1][2] if l[i] == l[i-1]-1: dp[i][2] += max(dp[i-1][1], dp[i-1][0]) if l[i] == l[i-1]+1: dp[i][0] += max(dp[i-1][1], dp[i-1][2]) ans = 0 for i in dp: ans = max(ans, max(i)) # print(dp) print(ans) ```
output
1
43,417
3
86,835
Provide tags and a correct Python 3 solution for this coding contest problem. When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging — but why not make a similar programming contest problem while we're at it? You're given a sequence of n data points a1, ..., an. There aren't any big jumps between consecutive data points — for each 1 ≤ i < n, it's guaranteed that |ai + 1 - ai| ≤ 1. A range [l, r] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let M be the maximum and m the minimum value of ai for l ≤ i ≤ r; the range [l, r] is almost constant if M - m ≤ 1. Find the length of the longest almost constant range. Input The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of data points. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000). Output Print a single number — the maximum length of an almost constant range of the given sequence. Examples Input 5 1 2 3 3 2 Output 4 Input 11 5 4 5 5 6 7 8 8 8 7 6 Output 5 Note In the first sample, the longest almost constant range is [2, 5]; its length (the number of data points in it) is 4. In the second sample, there are three almost constant ranges of length 4: [1, 4], [6, 9] and [7, 10]; the only almost constant range of the maximum length 5 is [6, 10].
instruction
0
43,418
3
86,836
Tags: dp, implementation, two pointers Correct Solution: ``` n = int(input()) a = list(map(int, input().split())) j = left = delta = ans = 0 for i in range(1, n): xy = a[i]-a[i-1] if xy: if delta == xy: left = j j, delta = i, xy ans = max(ans, i-left+1) print(ans) ```
output
1
43,418
3
86,837
Provide tags and a correct Python 3 solution for this coding contest problem. When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging — but why not make a similar programming contest problem while we're at it? You're given a sequence of n data points a1, ..., an. There aren't any big jumps between consecutive data points — for each 1 ≤ i < n, it's guaranteed that |ai + 1 - ai| ≤ 1. A range [l, r] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let M be the maximum and m the minimum value of ai for l ≤ i ≤ r; the range [l, r] is almost constant if M - m ≤ 1. Find the length of the longest almost constant range. Input The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of data points. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000). Output Print a single number — the maximum length of an almost constant range of the given sequence. Examples Input 5 1 2 3 3 2 Output 4 Input 11 5 4 5 5 6 7 8 8 8 7 6 Output 5 Note In the first sample, the longest almost constant range is [2, 5]; its length (the number of data points in it) is 4. In the second sample, there are three almost constant ranges of length 4: [1, 4], [6, 9] and [7, 10]; the only almost constant range of the maximum length 5 is [6, 10].
instruction
0
43,419
3
86,838
Tags: dp, implementation, two pointers Correct Solution: ``` if __name__ == "__main__": n = int( input() ) a = [ int(x) for x in input().split() ] maxLen = 2 left = 0 right = 1 sumA = a[0] + a[1] m = min( a[0] , a[1] ) M = max( a[0] , a[1] ) curLen = 2 for i in range( 2 , n ): if a[i] > M: while M * (right-left+1) != sumA: sumA -= a[left] left += 1 m = M M = a[i] elif a[i] < m: while m * (right-left+1) != sumA: sumA -= a[left] left += 1 M = m m = a[i] right += 1 sumA += a[i] curLen = right-left+1 maxLen = max( maxLen , curLen ) print( maxLen ) ```
output
1
43,419
3
86,839
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging — but why not make a similar programming contest problem while we're at it? You're given a sequence of n data points a1, ..., an. There aren't any big jumps between consecutive data points — for each 1 ≤ i < n, it's guaranteed that |ai + 1 - ai| ≤ 1. A range [l, r] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let M be the maximum and m the minimum value of ai for l ≤ i ≤ r; the range [l, r] is almost constant if M - m ≤ 1. Find the length of the longest almost constant range. Input The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of data points. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000). Output Print a single number — the maximum length of an almost constant range of the given sequence. Examples Input 5 1 2 3 3 2 Output 4 Input 11 5 4 5 5 6 7 8 8 8 7 6 Output 5 Note In the first sample, the longest almost constant range is [2, 5]; its length (the number of data points in it) is 4. In the second sample, there are three almost constant ranges of length 4: [1, 4], [6, 9] and [7, 10]; the only almost constant range of the maximum length 5 is [6, 10]. Submitted Solution: ``` class CodeforcesTask602BSolution: def __init__(self): self.result = '' self.n = 0 self.sequence = [] def read_input(self): self.n = int(input()) self.sequence = [int(x) for x in input().split(" ")] def process_task(self): devel = [x % 3 for x in self.sequence] maxlen = 0 for level in range(3): clen = 0 for x in range(self.n): if devel[x] == level: maxlen = max(maxlen, clen) clen = 0 else: clen += 1 maxlen = max(maxlen, clen) self.result = str(maxlen) def get_result(self): return self.result if __name__ == "__main__": Solution = CodeforcesTask602BSolution() Solution.read_input() Solution.process_task() print(Solution.get_result()) ```
instruction
0
43,420
3
86,840
Yes
output
1
43,420
3
86,841