message
stringlengths
2
65.1k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
0
108k
cluster
float64
14
14
__index_level_0__
int64
0
217k
Provide tags and a correct Python 3 solution for this coding contest problem. Mr. Chanek is currently participating in a science fair that is popular in town. He finds an exciting puzzle in the fair and wants to solve it. There are N atoms numbered from 1 to N. These atoms are especially quirky. Initially, each atom is in normal state. Each atom can be in an excited. Exciting atom i requires D_i energy. When atom i is excited, it will give A_i energy. You can excite any number of atoms (including zero). These atoms also form a peculiar one-way bond. For each i, (1 ≀ i < N), if atom i is excited, atom E_i will also be excited at no cost. Initially, E_i = i+1. Note that atom N cannot form a bond to any atom. Mr. Chanek must change exactly K bonds. Exactly K times, Mr. Chanek chooses an atom i, (1 ≀ i < N) and changes E_i to a different value other than i and the current E_i. Note that an atom's bond can remain unchanged or changed more than once. Help Mr. Chanek determine the maximum energy that he can achieve! note: You must first change exactly K bonds before you can start exciting atoms. Input The first line contains two integers N K (4 ≀ N ≀ 10^5, 0 ≀ K < N), the number of atoms, and the number of bonds that must be changed. The second line contains N integers A_i (1 ≀ A_i ≀ 10^6), which denotes the energy given by atom i when on excited state. The third line contains N integers D_i (1 ≀ D_i ≀ 10^6), which denotes the energy needed to excite atom i. Output A line with an integer that denotes the maximum number of energy that Mr. Chanek can get. Example Input 6 1 5 6 7 8 10 2 3 5 6 7 1 10 Output 35 Note An optimal solution to change E_5 to 1 and then excite atom 5 with energy 1. It will cause atoms 1, 2, 3, 4, 5 be excited. The total energy gained by Mr. Chanek is (5 + 6 + 7 + 8 + 10) - 1 = 35. Another possible way is to change E_3 to 1 and then exciting atom 3 (which will excite atom 1, 2, 3) and exciting atom 4 (which will excite atom 4, 5, 6). The total energy gained by Mr. Chanek is (5 + 6 + 7 + 8 + 10 + 2) - (6 + 7) = 25 which is not optimal.
instruction
0
70,917
14
141,834
Tags: greedy, implementation Correct Solution: ``` n, k = map(int, input().split()) a = list(map(int, input().split())) d = list(map(int, input().split())) if k == 0: best = 0 curr = sum(a) for i in range(n): best = max(best, curr - d[i]) curr -= a[i] print(best) elif k == 1: best = sum(a[:-1]) - min(d[:-1]) other = sum(a) other -= sorted(d)[0] other -= sorted(d)[1] curr = sum(a) for i in range(n): if i: best = max(best, curr - d[i]) curr -= a[i] o2 = sum(a) - min(a[1:]) - d[0] print(max((best,other,0, o2))) else: print(max((sum(a) - min(d[:-1]),0,a[-1] - d[-1]))) ```
output
1
70,917
14
141,835
Provide tags and a correct Python 3 solution for this coding contest problem. Mr. Chanek is currently participating in a science fair that is popular in town. He finds an exciting puzzle in the fair and wants to solve it. There are N atoms numbered from 1 to N. These atoms are especially quirky. Initially, each atom is in normal state. Each atom can be in an excited. Exciting atom i requires D_i energy. When atom i is excited, it will give A_i energy. You can excite any number of atoms (including zero). These atoms also form a peculiar one-way bond. For each i, (1 ≀ i < N), if atom i is excited, atom E_i will also be excited at no cost. Initially, E_i = i+1. Note that atom N cannot form a bond to any atom. Mr. Chanek must change exactly K bonds. Exactly K times, Mr. Chanek chooses an atom i, (1 ≀ i < N) and changes E_i to a different value other than i and the current E_i. Note that an atom's bond can remain unchanged or changed more than once. Help Mr. Chanek determine the maximum energy that he can achieve! note: You must first change exactly K bonds before you can start exciting atoms. Input The first line contains two integers N K (4 ≀ N ≀ 10^5, 0 ≀ K < N), the number of atoms, and the number of bonds that must be changed. The second line contains N integers A_i (1 ≀ A_i ≀ 10^6), which denotes the energy given by atom i when on excited state. The third line contains N integers D_i (1 ≀ D_i ≀ 10^6), which denotes the energy needed to excite atom i. Output A line with an integer that denotes the maximum number of energy that Mr. Chanek can get. Example Input 6 1 5 6 7 8 10 2 3 5 6 7 1 10 Output 35 Note An optimal solution to change E_5 to 1 and then excite atom 5 with energy 1. It will cause atoms 1, 2, 3, 4, 5 be excited. The total energy gained by Mr. Chanek is (5 + 6 + 7 + 8 + 10) - 1 = 35. Another possible way is to change E_3 to 1 and then exciting atom 3 (which will excite atom 1, 2, 3) and exciting atom 4 (which will excite atom 4, 5, 6). The total energy gained by Mr. Chanek is (5 + 6 + 7 + 8 + 10 + 2) - (6 + 7) = 25 which is not optimal.
instruction
0
70,918
14
141,836
Tags: greedy, implementation Correct Solution: ``` import sys n, k = list(map(int, input().split(' '))) activate = list(map(int, input().split(' '))) deactivate = list(map(int, input().split(' '))) presum = [0 for _ in range(n + 2)] for i in range(1, n + 1): presum[i] = presum[i - 1] + activate[i - 1] ret = 0 if k == 0: for i in range(1, n + 1): # 情冡0οΌŒδΈιœ€θ¦θ€ƒθ™‘θΏžεΈ¦ ret = max(ret, presum[n] - presum[i - 1] - deactivate[i - 1]) elif k == 1: for i in range(1, n): # 情冡3 n-1连1 ret = max(ret, presum[n - 1] - deactivate[i - 1]) # 情冡3ε†εŠ δΈŠη¬¬NδΈͺ离子 if deactivate[n - 1] < activate[n - 1]: ret += (activate[n - 1] - deactivate[n - 1]) deac = sorted(deactivate[1:n - 1]) ac = sorted(activate[1:n - 1]) # 情冡5οΌŒζΏ€ζ΄»1οΌŒθ·³θΏ‡1δΈͺθŠ‚η‚Ή ret = max(ret, presum[n] - deactivate[0] - ac[0]) # 情冡6 ζΏ€ζ΄»1οΌŒθ·³θΏ‡1δΈͺθŠ‚η‚ΉεŽοΌŒε†ζΏ€ζ΄» ret = max(ret, presum[n] - deactivate[0] - deac[0]) # 情冡4 ret = max(ret, presum[n] - deac[0] - deac[1]) # 情冡7 1连nοΌŒζΏ€ζ΄»i for i in range(2, n + 1): ret = max(ret, presum[n] - presum[i - 1] - deactivate[i - 1]) else: # 情冡1 for i in range(1, n): ret = max(ret, presum[n] - deactivate[i - 1]) # 情冡2 ret = max(ret, activate[n - 1] - deactivate[n - 1]) print(ret) ```
output
1
70,918
14
141,837
Provide tags and a correct Python 3 solution for this coding contest problem. Mr. Chanek is currently participating in a science fair that is popular in town. He finds an exciting puzzle in the fair and wants to solve it. There are N atoms numbered from 1 to N. These atoms are especially quirky. Initially, each atom is in normal state. Each atom can be in an excited. Exciting atom i requires D_i energy. When atom i is excited, it will give A_i energy. You can excite any number of atoms (including zero). These atoms also form a peculiar one-way bond. For each i, (1 ≀ i < N), if atom i is excited, atom E_i will also be excited at no cost. Initially, E_i = i+1. Note that atom N cannot form a bond to any atom. Mr. Chanek must change exactly K bonds. Exactly K times, Mr. Chanek chooses an atom i, (1 ≀ i < N) and changes E_i to a different value other than i and the current E_i. Note that an atom's bond can remain unchanged or changed more than once. Help Mr. Chanek determine the maximum energy that he can achieve! note: You must first change exactly K bonds before you can start exciting atoms. Input The first line contains two integers N K (4 ≀ N ≀ 10^5, 0 ≀ K < N), the number of atoms, and the number of bonds that must be changed. The second line contains N integers A_i (1 ≀ A_i ≀ 10^6), which denotes the energy given by atom i when on excited state. The third line contains N integers D_i (1 ≀ D_i ≀ 10^6), which denotes the energy needed to excite atom i. Output A line with an integer that denotes the maximum number of energy that Mr. Chanek can get. Example Input 6 1 5 6 7 8 10 2 3 5 6 7 1 10 Output 35 Note An optimal solution to change E_5 to 1 and then excite atom 5 with energy 1. It will cause atoms 1, 2, 3, 4, 5 be excited. The total energy gained by Mr. Chanek is (5 + 6 + 7 + 8 + 10) - 1 = 35. Another possible way is to change E_3 to 1 and then exciting atom 3 (which will excite atom 1, 2, 3) and exciting atom 4 (which will excite atom 4, 5, 6). The total energy gained by Mr. Chanek is (5 + 6 + 7 + 8 + 10 + 2) - (6 + 7) = 25 which is not optimal.
instruction
0
70,919
14
141,838
Tags: greedy, implementation Correct Solution: ``` n, k = map(int, input().split()) a = list(map(int, input().split())) d = list(map(int, input().split())) pref=[0] for i in range(n): pref.append(pref[-1]+a[i]) if k==0: ans=0 for i in range(1,n+1): ans=max(ans,pref[-1]-pref[i-1]-d[i-1]) print(ans) elif k == 1: best = sum(a[:n-1]) - min(d[:n-1]) other = sum(a) other -= sorted(d)[0] other -= sorted(d)[1] curr = sum(a) for i in range(n): if i: best = max(best, curr - d[i]) curr -= a[i] o2 = sum(a) - min(a[1:]) - d[0] print(max((best,other,0, o2))) else: print(max((sum(a) - min(d[:-1]),0,a[-1] - d[-1]))) ```
output
1
70,919
14
141,839
Provide tags and a correct Python 3 solution for this coding contest problem. Mr. Chanek is currently participating in a science fair that is popular in town. He finds an exciting puzzle in the fair and wants to solve it. There are N atoms numbered from 1 to N. These atoms are especially quirky. Initially, each atom is in normal state. Each atom can be in an excited. Exciting atom i requires D_i energy. When atom i is excited, it will give A_i energy. You can excite any number of atoms (including zero). These atoms also form a peculiar one-way bond. For each i, (1 ≀ i < N), if atom i is excited, atom E_i will also be excited at no cost. Initially, E_i = i+1. Note that atom N cannot form a bond to any atom. Mr. Chanek must change exactly K bonds. Exactly K times, Mr. Chanek chooses an atom i, (1 ≀ i < N) and changes E_i to a different value other than i and the current E_i. Note that an atom's bond can remain unchanged or changed more than once. Help Mr. Chanek determine the maximum energy that he can achieve! note: You must first change exactly K bonds before you can start exciting atoms. Input The first line contains two integers N K (4 ≀ N ≀ 10^5, 0 ≀ K < N), the number of atoms, and the number of bonds that must be changed. The second line contains N integers A_i (1 ≀ A_i ≀ 10^6), which denotes the energy given by atom i when on excited state. The third line contains N integers D_i (1 ≀ D_i ≀ 10^6), which denotes the energy needed to excite atom i. Output A line with an integer that denotes the maximum number of energy that Mr. Chanek can get. Example Input 6 1 5 6 7 8 10 2 3 5 6 7 1 10 Output 35 Note An optimal solution to change E_5 to 1 and then excite atom 5 with energy 1. It will cause atoms 1, 2, 3, 4, 5 be excited. The total energy gained by Mr. Chanek is (5 + 6 + 7 + 8 + 10) - 1 = 35. Another possible way is to change E_3 to 1 and then exciting atom 3 (which will excite atom 1, 2, 3) and exciting atom 4 (which will excite atom 4, 5, 6). The total energy gained by Mr. Chanek is (5 + 6 + 7 + 8 + 10 + 2) - (6 + 7) = 25 which is not optimal.
instruction
0
70,920
14
141,840
Tags: greedy, implementation Correct Solution: ``` n, k = map(int, input().split()) r = list(map(int, input().split())) c = list(map(int, input().split())) z = max(r[-1]-c[-1], 0) if k == 0: best = z acc = 0 for i in range(n-1, -1, -1): acc += r[i] best = max(best, acc-c[i]) print(best) elif k > 1: print(max(sum(r)-min(c[:-1]), z)) else: best = max(z, sum(r) - sum(sorted(c)[:2]), sum(r[:-1]) - min(c[:-1]), sum(r) - min(r[1:]) - c[0]) acc = 0 for i in range(n-1, 0, -1): acc += r[i] best = max(best, acc-c[i]) print(best) ```
output
1
70,920
14
141,841
Provide tags and a correct Python 3 solution for this coding contest problem. Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory. Though Ryouko is forgetful, she is also born with superb analyzing abilities. However, analyzing depends greatly on gathered information, in other words, memory. So she has to shuffle through her notebook whenever she needs to analyze, which is tough work. Ryouko's notebook consists of n pages, numbered from 1 to n. To make life (and this problem) easier, we consider that to turn from page x to page y, |x - y| pages should be turned. During analyzing, Ryouko needs m pieces of information, the i-th piece of information is on page ai. Information must be read from the notebook in order, so the total number of pages that Ryouko needs to turn is <image>. Ryouko wants to decrease the number of pages that need to be turned. In order to achieve this, she can merge two pages of her notebook. If Ryouko merges page x to page y, she would copy all the information on page x to y (1 ≀ x, y ≀ n), and consequently, all elements in sequence a that was x would become y. Note that x can be equal to y, in which case no changes take place. Please tell Ryouko the minimum number of pages that she needs to turn. Note she can apply the described operation at most once before the reading. Note that the answer can exceed 32-bit integers. Input The first line of input contains two integers n and m (1 ≀ n, m ≀ 105). The next line contains m integers separated by spaces: a1, a2, ..., am (1 ≀ ai ≀ n). Output Print a single integer β€” the minimum number of pages Ryouko needs to turn. Examples Input 4 6 1 2 3 4 3 2 Output 3 Input 10 5 9 4 3 8 8 Output 6 Note In the first sample, the optimal solution is to merge page 4 to 3, after merging sequence a becomes {1, 2, 3, 3, 3, 2}, so the number of pages Ryouko needs to turn is |1 - 2| + |2 - 3| + |3 - 3| + |3 - 3| + |3 - 2| = 3. In the second sample, optimal solution is achieved by merging page 9 to 4.
instruction
0
71,103
14
142,206
Tags: implementation, math, sortings Correct Solution: ``` # Made By Mostafa_Khaled bot = True n, m = map(int, input().split()) s, p = 0, [[] for i in range(n + 1)] t = list(map(int, input().split())) for i in range(m - 1): if t[i] != t[i + 1]: p[t[i + 1]].append(t[i]) p[t[i]].append(t[i + 1]) for i, q in enumerate(p): if q: q.sort() k = q[len(q) // 2] d = sum(abs(i - j) - abs(k - j) for j in q) if d > s: s = d print(sum(abs(t[i + 1] - t[i]) for i in range(m - 1)) - s) # Made By Mostafa_Khaled ```
output
1
71,103
14
142,207
Provide tags and a correct Python 3 solution for this coding contest problem. Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory. Though Ryouko is forgetful, she is also born with superb analyzing abilities. However, analyzing depends greatly on gathered information, in other words, memory. So she has to shuffle through her notebook whenever she needs to analyze, which is tough work. Ryouko's notebook consists of n pages, numbered from 1 to n. To make life (and this problem) easier, we consider that to turn from page x to page y, |x - y| pages should be turned. During analyzing, Ryouko needs m pieces of information, the i-th piece of information is on page ai. Information must be read from the notebook in order, so the total number of pages that Ryouko needs to turn is <image>. Ryouko wants to decrease the number of pages that need to be turned. In order to achieve this, she can merge two pages of her notebook. If Ryouko merges page x to page y, she would copy all the information on page x to y (1 ≀ x, y ≀ n), and consequently, all elements in sequence a that was x would become y. Note that x can be equal to y, in which case no changes take place. Please tell Ryouko the minimum number of pages that she needs to turn. Note she can apply the described operation at most once before the reading. Note that the answer can exceed 32-bit integers. Input The first line of input contains two integers n and m (1 ≀ n, m ≀ 105). The next line contains m integers separated by spaces: a1, a2, ..., am (1 ≀ ai ≀ n). Output Print a single integer β€” the minimum number of pages Ryouko needs to turn. Examples Input 4 6 1 2 3 4 3 2 Output 3 Input 10 5 9 4 3 8 8 Output 6 Note In the first sample, the optimal solution is to merge page 4 to 3, after merging sequence a becomes {1, 2, 3, 3, 3, 2}, so the number of pages Ryouko needs to turn is |1 - 2| + |2 - 3| + |3 - 3| + |3 - 3| + |3 - 2| = 3. In the second sample, optimal solution is achieved by merging page 9 to 4.
instruction
0
71,104
14
142,208
Tags: implementation, math, sortings Correct Solution: ``` input() a = input().split() a = [int(x) for x in a] neighbours = dict() for x in a: neighbours[x] = [] cost = 0 for i in range(len(a) - 1): if a[i] != a[i+1]: neighbours[a[i]].append(a[i+1]) neighbours[a[i+1]].append(a[i]) cost += abs(a[i] - a[i+1]) def cost_by(ar, v): return sum([abs(v - x) for x in ar] + [0]) def max_save(ar, v): if len(ar) == 0: return 0 default = cost_by(ar, v) ar = sorted(ar) best_v = ar[int(len(ar)/2)] return default - cost_by(ar, best_v) max_save = max([max_save(neighbours[x], x) for x in neighbours.keys()] + [0]) print(cost - max_save) ```
output
1
71,104
14
142,209
Provide tags and a correct Python 3 solution for this coding contest problem. Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory. Though Ryouko is forgetful, she is also born with superb analyzing abilities. However, analyzing depends greatly on gathered information, in other words, memory. So she has to shuffle through her notebook whenever she needs to analyze, which is tough work. Ryouko's notebook consists of n pages, numbered from 1 to n. To make life (and this problem) easier, we consider that to turn from page x to page y, |x - y| pages should be turned. During analyzing, Ryouko needs m pieces of information, the i-th piece of information is on page ai. Information must be read from the notebook in order, so the total number of pages that Ryouko needs to turn is <image>. Ryouko wants to decrease the number of pages that need to be turned. In order to achieve this, she can merge two pages of her notebook. If Ryouko merges page x to page y, she would copy all the information on page x to y (1 ≀ x, y ≀ n), and consequently, all elements in sequence a that was x would become y. Note that x can be equal to y, in which case no changes take place. Please tell Ryouko the minimum number of pages that she needs to turn. Note she can apply the described operation at most once before the reading. Note that the answer can exceed 32-bit integers. Input The first line of input contains two integers n and m (1 ≀ n, m ≀ 105). The next line contains m integers separated by spaces: a1, a2, ..., am (1 ≀ ai ≀ n). Output Print a single integer β€” the minimum number of pages Ryouko needs to turn. Examples Input 4 6 1 2 3 4 3 2 Output 3 Input 10 5 9 4 3 8 8 Output 6 Note In the first sample, the optimal solution is to merge page 4 to 3, after merging sequence a becomes {1, 2, 3, 3, 3, 2}, so the number of pages Ryouko needs to turn is |1 - 2| + |2 - 3| + |3 - 3| + |3 - 3| + |3 - 2| = 3. In the second sample, optimal solution is achieved by merging page 9 to 4.
instruction
0
71,105
14
142,210
Tags: implementation, math, sortings Correct Solution: ``` import sys from collections import defaultdict read = lambda t=int: list(map(t,sys.stdin.readline().split())) n, m = read() ar = read() price = sum(abs(a-b) for a,b in zip(ar,ar[1:])) xss = defaultdict(list) for a,b in zip(ar,ar[1:]): if a != b: xss[a].append(b) xss[b].append(a) median = lambda xs: sorted(xs)[len(xs)//2] best = 0 for i,xs in xss.items(): m = median(xs) safe = sum(abs(i-x) for x in xs) - sum(abs(m-x) for x in xs) best = max(best, safe) # print(i, m, xs, safe) print(price-best) ```
output
1
71,105
14
142,211
Provide tags and a correct Python 3 solution for this coding contest problem. Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory. Though Ryouko is forgetful, she is also born with superb analyzing abilities. However, analyzing depends greatly on gathered information, in other words, memory. So she has to shuffle through her notebook whenever she needs to analyze, which is tough work. Ryouko's notebook consists of n pages, numbered from 1 to n. To make life (and this problem) easier, we consider that to turn from page x to page y, |x - y| pages should be turned. During analyzing, Ryouko needs m pieces of information, the i-th piece of information is on page ai. Information must be read from the notebook in order, so the total number of pages that Ryouko needs to turn is <image>. Ryouko wants to decrease the number of pages that need to be turned. In order to achieve this, she can merge two pages of her notebook. If Ryouko merges page x to page y, she would copy all the information on page x to y (1 ≀ x, y ≀ n), and consequently, all elements in sequence a that was x would become y. Note that x can be equal to y, in which case no changes take place. Please tell Ryouko the minimum number of pages that she needs to turn. Note she can apply the described operation at most once before the reading. Note that the answer can exceed 32-bit integers. Input The first line of input contains two integers n and m (1 ≀ n, m ≀ 105). The next line contains m integers separated by spaces: a1, a2, ..., am (1 ≀ ai ≀ n). Output Print a single integer β€” the minimum number of pages Ryouko needs to turn. Examples Input 4 6 1 2 3 4 3 2 Output 3 Input 10 5 9 4 3 8 8 Output 6 Note In the first sample, the optimal solution is to merge page 4 to 3, after merging sequence a becomes {1, 2, 3, 3, 3, 2}, so the number of pages Ryouko needs to turn is |1 - 2| + |2 - 3| + |3 - 3| + |3 - 3| + |3 - 2| = 3. In the second sample, optimal solution is achieved by merging page 9 to 4.
instruction
0
71,106
14
142,212
Tags: implementation, math, sortings Correct Solution: ``` n, m = map(int, input().split()) arr = list(map(int, input().split())) price = sum(abs(a - b) for a, b in zip(arr, arr[1:])) from collections import defaultdict adj = defaultdict(list) for a,b in zip(arr, arr[1:]): if a != b: adj[a].append(b) adj[b].append(a) def median(xs): return sorted(xs)[len(xs)//2] res = 0 for i, xs in adj.items(): m = median(xs) a = sum(abs(i - x) for x in xs) b = sum(abs(m - x) for x in xs) res = max(res, a - b) print(price - res) ```
output
1
71,106
14
142,213
Provide tags and a correct Python 3 solution for this coding contest problem. Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory. Though Ryouko is forgetful, she is also born with superb analyzing abilities. However, analyzing depends greatly on gathered information, in other words, memory. So she has to shuffle through her notebook whenever she needs to analyze, which is tough work. Ryouko's notebook consists of n pages, numbered from 1 to n. To make life (and this problem) easier, we consider that to turn from page x to page y, |x - y| pages should be turned. During analyzing, Ryouko needs m pieces of information, the i-th piece of information is on page ai. Information must be read from the notebook in order, so the total number of pages that Ryouko needs to turn is <image>. Ryouko wants to decrease the number of pages that need to be turned. In order to achieve this, she can merge two pages of her notebook. If Ryouko merges page x to page y, she would copy all the information on page x to y (1 ≀ x, y ≀ n), and consequently, all elements in sequence a that was x would become y. Note that x can be equal to y, in which case no changes take place. Please tell Ryouko the minimum number of pages that she needs to turn. Note she can apply the described operation at most once before the reading. Note that the answer can exceed 32-bit integers. Input The first line of input contains two integers n and m (1 ≀ n, m ≀ 105). The next line contains m integers separated by spaces: a1, a2, ..., am (1 ≀ ai ≀ n). Output Print a single integer β€” the minimum number of pages Ryouko needs to turn. Examples Input 4 6 1 2 3 4 3 2 Output 3 Input 10 5 9 4 3 8 8 Output 6 Note In the first sample, the optimal solution is to merge page 4 to 3, after merging sequence a becomes {1, 2, 3, 3, 3, 2}, so the number of pages Ryouko needs to turn is |1 - 2| + |2 - 3| + |3 - 3| + |3 - 3| + |3 - 2| = 3. In the second sample, optimal solution is achieved by merging page 9 to 4.
instruction
0
71,107
14
142,214
Tags: implementation, math, sortings Correct Solution: ``` from collections import defaultdict LIM = 10 ** 5 + 123 n, m = map(int, input().split()) occ = [[] for i in range(LIM)] add = [0 for i in range(LIM)] a = list(map(int, input().split())) base_ans = 0 for i in range(1, m): if a[i] != a[i - 1]: occ[a[i]].append(a[i - 1]) occ[a[i - 1]].append(a[i]) t = abs(a[i] - a[i - 1]) base_ans += t add[a[i]] += t add[a[i - 1]] += t ans = base_ans for i in range(LIM): if len(occ[i]) == 0: continue occ[i].sort() k = len(occ[i]) sum_before = 0 sum_after = sum(occ[i]) for idx, c in enumerate(occ[i], 1): sum_before += c sum_after -= c cur = idx * c - sum_before cur += sum_after - (k - idx) * c ans = min(ans, base_ans - add[i] + cur) print(ans) ```
output
1
71,107
14
142,215
Provide tags and a correct Python 3 solution for this coding contest problem. Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory. Though Ryouko is forgetful, she is also born with superb analyzing abilities. However, analyzing depends greatly on gathered information, in other words, memory. So she has to shuffle through her notebook whenever she needs to analyze, which is tough work. Ryouko's notebook consists of n pages, numbered from 1 to n. To make life (and this problem) easier, we consider that to turn from page x to page y, |x - y| pages should be turned. During analyzing, Ryouko needs m pieces of information, the i-th piece of information is on page ai. Information must be read from the notebook in order, so the total number of pages that Ryouko needs to turn is <image>. Ryouko wants to decrease the number of pages that need to be turned. In order to achieve this, she can merge two pages of her notebook. If Ryouko merges page x to page y, she would copy all the information on page x to y (1 ≀ x, y ≀ n), and consequently, all elements in sequence a that was x would become y. Note that x can be equal to y, in which case no changes take place. Please tell Ryouko the minimum number of pages that she needs to turn. Note she can apply the described operation at most once before the reading. Note that the answer can exceed 32-bit integers. Input The first line of input contains two integers n and m (1 ≀ n, m ≀ 105). The next line contains m integers separated by spaces: a1, a2, ..., am (1 ≀ ai ≀ n). Output Print a single integer β€” the minimum number of pages Ryouko needs to turn. Examples Input 4 6 1 2 3 4 3 2 Output 3 Input 10 5 9 4 3 8 8 Output 6 Note In the first sample, the optimal solution is to merge page 4 to 3, after merging sequence a becomes {1, 2, 3, 3, 3, 2}, so the number of pages Ryouko needs to turn is |1 - 2| + |2 - 3| + |3 - 3| + |3 - 3| + |3 - 2| = 3. In the second sample, optimal solution is achieved by merging page 9 to 4.
instruction
0
71,108
14
142,216
Tags: implementation, math, sortings Correct Solution: ``` n, m = map(int, input().split()) s, p = 0, [[] for i in range(n + 1)] t = list(map(int, input().split())) for i in range(m - 1): if t[i] != t[i + 1]: p[t[i + 1]].append(t[i]) p[t[i]].append(t[i + 1]) for i, q in enumerate(p): if q: q.sort() k = q[len(q) // 2] d = sum(abs(i - j) - abs(k - j) for j in q) if d > s: s = d print(sum(abs(t[i + 1] - t[i]) for i in range(m - 1)) - s) ```
output
1
71,108
14
142,217
Provide tags and a correct Python 3 solution for this coding contest problem. Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory. Though Ryouko is forgetful, she is also born with superb analyzing abilities. However, analyzing depends greatly on gathered information, in other words, memory. So she has to shuffle through her notebook whenever she needs to analyze, which is tough work. Ryouko's notebook consists of n pages, numbered from 1 to n. To make life (and this problem) easier, we consider that to turn from page x to page y, |x - y| pages should be turned. During analyzing, Ryouko needs m pieces of information, the i-th piece of information is on page ai. Information must be read from the notebook in order, so the total number of pages that Ryouko needs to turn is <image>. Ryouko wants to decrease the number of pages that need to be turned. In order to achieve this, she can merge two pages of her notebook. If Ryouko merges page x to page y, she would copy all the information on page x to y (1 ≀ x, y ≀ n), and consequently, all elements in sequence a that was x would become y. Note that x can be equal to y, in which case no changes take place. Please tell Ryouko the minimum number of pages that she needs to turn. Note she can apply the described operation at most once before the reading. Note that the answer can exceed 32-bit integers. Input The first line of input contains two integers n and m (1 ≀ n, m ≀ 105). The next line contains m integers separated by spaces: a1, a2, ..., am (1 ≀ ai ≀ n). Output Print a single integer β€” the minimum number of pages Ryouko needs to turn. Examples Input 4 6 1 2 3 4 3 2 Output 3 Input 10 5 9 4 3 8 8 Output 6 Note In the first sample, the optimal solution is to merge page 4 to 3, after merging sequence a becomes {1, 2, 3, 3, 3, 2}, so the number of pages Ryouko needs to turn is |1 - 2| + |2 - 3| + |3 - 3| + |3 - 3| + |3 - 2| = 3. In the second sample, optimal solution is achieved by merging page 9 to 4.
instruction
0
71,109
14
142,218
Tags: implementation, math, sortings Correct Solution: ``` def median(a): if len(a) == 0: return 0 if len(a) % 2 == 1: return a[len(a) // 2] else: return (a[len(a) // 2] + a[(len(a) // 2) - 1]) // 2 def profit(a, old_val): a.sort() med = median(a) sum_old = 0 sum_new = 0 for i in a: sum_old += abs(i - old_val) sum_new += abs(i - med) return sum_old - sum_new n, m = [int(c) for c in input().split()] pages = [int(c) for c in input().split()] count = {pages[0]: []} current_page_switches = 0 for i in range(1, len(pages)): cur_i = pages[i] prev_i = pages[i - 1] if not(cur_i in count): count[cur_i] = [] if cur_i != prev_i: count[cur_i].append(prev_i) count[prev_i].append(cur_i) current_page_switches += abs(cur_i - prev_i) max_profit = 0 for i in count: if len(count[i]) > 0: tmp = profit(count[i], i) if tmp > max_profit: max_profit = tmp print(current_page_switches - max_profit) ```
output
1
71,109
14
142,219
Provide tags and a correct Python 3 solution for this coding contest problem. Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory. Though Ryouko is forgetful, she is also born with superb analyzing abilities. However, analyzing depends greatly on gathered information, in other words, memory. So she has to shuffle through her notebook whenever she needs to analyze, which is tough work. Ryouko's notebook consists of n pages, numbered from 1 to n. To make life (and this problem) easier, we consider that to turn from page x to page y, |x - y| pages should be turned. During analyzing, Ryouko needs m pieces of information, the i-th piece of information is on page ai. Information must be read from the notebook in order, so the total number of pages that Ryouko needs to turn is <image>. Ryouko wants to decrease the number of pages that need to be turned. In order to achieve this, she can merge two pages of her notebook. If Ryouko merges page x to page y, she would copy all the information on page x to y (1 ≀ x, y ≀ n), and consequently, all elements in sequence a that was x would become y. Note that x can be equal to y, in which case no changes take place. Please tell Ryouko the minimum number of pages that she needs to turn. Note she can apply the described operation at most once before the reading. Note that the answer can exceed 32-bit integers. Input The first line of input contains two integers n and m (1 ≀ n, m ≀ 105). The next line contains m integers separated by spaces: a1, a2, ..., am (1 ≀ ai ≀ n). Output Print a single integer β€” the minimum number of pages Ryouko needs to turn. Examples Input 4 6 1 2 3 4 3 2 Output 3 Input 10 5 9 4 3 8 8 Output 6 Note In the first sample, the optimal solution is to merge page 4 to 3, after merging sequence a becomes {1, 2, 3, 3, 3, 2}, so the number of pages Ryouko needs to turn is |1 - 2| + |2 - 3| + |3 - 3| + |3 - 3| + |3 - 2| = 3. In the second sample, optimal solution is achieved by merging page 9 to 4.
instruction
0
71,110
14
142,220
Tags: implementation, math, sortings Correct Solution: ``` n, m = map(int, input().split()) a = list(map(int, input().split())) b = {} for ai in a: b[ai] = [] amt = 0 for i in range(1, len(a)): amt += abs(a[i]-a[i-1]) if a[i]-a[i-1]: b[a[i]] += [a[i-1]] b[a[i-1]] += [a[i]] diff = 0 for bi in b: if b[bi]: center = sorted(b[bi])[len(b[bi])//2] sum = 0 for page in b[bi]: sum += abs(page-center)-abs(page-bi) diff = min(diff, sum) print(amt+diff) ```
output
1
71,110
14
142,221
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory. Though Ryouko is forgetful, she is also born with superb analyzing abilities. However, analyzing depends greatly on gathered information, in other words, memory. So she has to shuffle through her notebook whenever she needs to analyze, which is tough work. Ryouko's notebook consists of n pages, numbered from 1 to n. To make life (and this problem) easier, we consider that to turn from page x to page y, |x - y| pages should be turned. During analyzing, Ryouko needs m pieces of information, the i-th piece of information is on page ai. Information must be read from the notebook in order, so the total number of pages that Ryouko needs to turn is <image>. Ryouko wants to decrease the number of pages that need to be turned. In order to achieve this, she can merge two pages of her notebook. If Ryouko merges page x to page y, she would copy all the information on page x to y (1 ≀ x, y ≀ n), and consequently, all elements in sequence a that was x would become y. Note that x can be equal to y, in which case no changes take place. Please tell Ryouko the minimum number of pages that she needs to turn. Note she can apply the described operation at most once before the reading. Note that the answer can exceed 32-bit integers. Input The first line of input contains two integers n and m (1 ≀ n, m ≀ 105). The next line contains m integers separated by spaces: a1, a2, ..., am (1 ≀ ai ≀ n). Output Print a single integer β€” the minimum number of pages Ryouko needs to turn. Examples Input 4 6 1 2 3 4 3 2 Output 3 Input 10 5 9 4 3 8 8 Output 6 Note In the first sample, the optimal solution is to merge page 4 to 3, after merging sequence a becomes {1, 2, 3, 3, 3, 2}, so the number of pages Ryouko needs to turn is |1 - 2| + |2 - 3| + |3 - 3| + |3 - 3| + |3 - 2| = 3. In the second sample, optimal solution is achieved by merging page 9 to 4. Submitted Solution: ``` n, m = map(int, input().split(' ')) A = list(map(int, input().split(' '))) M = [[] for i in range(n+1)] ans = 0 for i in range(1, m) : if i > 0 and A[i] != A[i-1]: M[A[i]].append(A[i-1]) M[A[i-1]].append(A[i]) index = -1 maxi = -1 c = -1 for i in range(1, n+1) : if not M[i] : continue M[i].sort() old = i new = M[i][len(M[i])//2] old_val = 0 new_val = 0 for j in M[i] : old_val += abs(old-j) new_val += abs(new-j) d = old_val - new_val if d > maxi : maxi = d index = i c = new ans = 0 for i in range(1, m) : a = A[i-1] b = A[i] if a == index : a = c if b == index : b = c ans += abs(a-b) print(ans) ```
instruction
0
71,111
14
142,222
Yes
output
1
71,111
14
142,223
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory. Though Ryouko is forgetful, she is also born with superb analyzing abilities. However, analyzing depends greatly on gathered information, in other words, memory. So she has to shuffle through her notebook whenever she needs to analyze, which is tough work. Ryouko's notebook consists of n pages, numbered from 1 to n. To make life (and this problem) easier, we consider that to turn from page x to page y, |x - y| pages should be turned. During analyzing, Ryouko needs m pieces of information, the i-th piece of information is on page ai. Information must be read from the notebook in order, so the total number of pages that Ryouko needs to turn is <image>. Ryouko wants to decrease the number of pages that need to be turned. In order to achieve this, she can merge two pages of her notebook. If Ryouko merges page x to page y, she would copy all the information on page x to y (1 ≀ x, y ≀ n), and consequently, all elements in sequence a that was x would become y. Note that x can be equal to y, in which case no changes take place. Please tell Ryouko the minimum number of pages that she needs to turn. Note she can apply the described operation at most once before the reading. Note that the answer can exceed 32-bit integers. Input The first line of input contains two integers n and m (1 ≀ n, m ≀ 105). The next line contains m integers separated by spaces: a1, a2, ..., am (1 ≀ ai ≀ n). Output Print a single integer β€” the minimum number of pages Ryouko needs to turn. Examples Input 4 6 1 2 3 4 3 2 Output 3 Input 10 5 9 4 3 8 8 Output 6 Note In the first sample, the optimal solution is to merge page 4 to 3, after merging sequence a becomes {1, 2, 3, 3, 3, 2}, so the number of pages Ryouko needs to turn is |1 - 2| + |2 - 3| + |3 - 3| + |3 - 3| + |3 - 2| = 3. In the second sample, optimal solution is achieved by merging page 9 to 4. Submitted Solution: ``` n, m = map(int, input().split()) s, p = 0, [[] for i in range(n + 1)] t = list(map(int, input().split())) for i in range(m - 1): if t[i] != t[i + 1]: p[t[i + 1]].append(t[i]) p[t[i]].append(t[i + 1]) for i, q in enumerate(p): if q: q.sort() k = q[len(q) // 2] d = sum(abs(i - j) - abs(k - j) for j in q) if d > s: s = d print(sum(abs(t[i + 1] - t[i]) for i in range(m - 1)) - s) # Made By Mostafa_Khaled ```
instruction
0
71,112
14
142,224
Yes
output
1
71,112
14
142,225
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory. Though Ryouko is forgetful, she is also born with superb analyzing abilities. However, analyzing depends greatly on gathered information, in other words, memory. So she has to shuffle through her notebook whenever she needs to analyze, which is tough work. Ryouko's notebook consists of n pages, numbered from 1 to n. To make life (and this problem) easier, we consider that to turn from page x to page y, |x - y| pages should be turned. During analyzing, Ryouko needs m pieces of information, the i-th piece of information is on page ai. Information must be read from the notebook in order, so the total number of pages that Ryouko needs to turn is <image>. Ryouko wants to decrease the number of pages that need to be turned. In order to achieve this, she can merge two pages of her notebook. If Ryouko merges page x to page y, she would copy all the information on page x to y (1 ≀ x, y ≀ n), and consequently, all elements in sequence a that was x would become y. Note that x can be equal to y, in which case no changes take place. Please tell Ryouko the minimum number of pages that she needs to turn. Note she can apply the described operation at most once before the reading. Note that the answer can exceed 32-bit integers. Input The first line of input contains two integers n and m (1 ≀ n, m ≀ 105). The next line contains m integers separated by spaces: a1, a2, ..., am (1 ≀ ai ≀ n). Output Print a single integer β€” the minimum number of pages Ryouko needs to turn. Examples Input 4 6 1 2 3 4 3 2 Output 3 Input 10 5 9 4 3 8 8 Output 6 Note In the first sample, the optimal solution is to merge page 4 to 3, after merging sequence a becomes {1, 2, 3, 3, 3, 2}, so the number of pages Ryouko needs to turn is |1 - 2| + |2 - 3| + |3 - 3| + |3 - 3| + |3 - 2| = 3. In the second sample, optimal solution is achieved by merging page 9 to 4. Submitted Solution: ``` import base64,zlib exec(zlib.decompress(base64.b85decode(b'c${@mOKt-p4Bc~z*PT)6B<(U%dJ)8eYDh&g5Poz2noK66M5-4c+wWsLDg+!6Y$6|<f{$r#B!`+N&%YE^Au(XDptZs2THqOkV&ku)h<AKSBN`(nUmN|aBgG3f;Df0L0S<pc)863i*#E9+mPU`H*P0n@N-mDn!SWgK)V!hZjtaS(x;O_{Y;%-0)4aLlp<W9Q`Y2p@rK~3xDNF2j_%e^y$gMgDvOkqPuW^?A^yIQ6-S^y0^Crh`Bfe1&sLUQkDtsndRo0oAf7|W#&dag7O_hH&R&{3'))) ```
instruction
0
71,113
14
142,226
Yes
output
1
71,113
14
142,227
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory. Though Ryouko is forgetful, she is also born with superb analyzing abilities. However, analyzing depends greatly on gathered information, in other words, memory. So she has to shuffle through her notebook whenever she needs to analyze, which is tough work. Ryouko's notebook consists of n pages, numbered from 1 to n. To make life (and this problem) easier, we consider that to turn from page x to page y, |x - y| pages should be turned. During analyzing, Ryouko needs m pieces of information, the i-th piece of information is on page ai. Information must be read from the notebook in order, so the total number of pages that Ryouko needs to turn is <image>. Ryouko wants to decrease the number of pages that need to be turned. In order to achieve this, she can merge two pages of her notebook. If Ryouko merges page x to page y, she would copy all the information on page x to y (1 ≀ x, y ≀ n), and consequently, all elements in sequence a that was x would become y. Note that x can be equal to y, in which case no changes take place. Please tell Ryouko the minimum number of pages that she needs to turn. Note she can apply the described operation at most once before the reading. Note that the answer can exceed 32-bit integers. Input The first line of input contains two integers n and m (1 ≀ n, m ≀ 105). The next line contains m integers separated by spaces: a1, a2, ..., am (1 ≀ ai ≀ n). Output Print a single integer β€” the minimum number of pages Ryouko needs to turn. Examples Input 4 6 1 2 3 4 3 2 Output 3 Input 10 5 9 4 3 8 8 Output 6 Note In the first sample, the optimal solution is to merge page 4 to 3, after merging sequence a becomes {1, 2, 3, 3, 3, 2}, so the number of pages Ryouko needs to turn is |1 - 2| + |2 - 3| + |3 - 3| + |3 - 3| + |3 - 2| = 3. In the second sample, optimal solution is achieved by merging page 9 to 4. Submitted Solution: ``` n,m = [int(x) for x in input().split()] a = [int(x)-1 for x in input().split()] assert len(a) == m tot = 0 for i in range(m-1): tot += abs(a[i+1]-a[i]) arr = [[] for i in range(n)] for i in range(m-1): if a[i] == a[i+1]: continue arr[a[i]].append(a[i+1]) arr[a[i+1]].append(a[i]) cursum = [] for i in range(n): cur = 0 for e in arr[i]: cur += abs(e-i) cursum.append(cur) assert sum(cursum) == 2*tot minsum = [0 for i in range(n)] for i in range(n): if len(arr[i]) == 0: continue arr[i].sort() med = arr[i][len(arr[i])//2] cur = 0 for e in arr[i]: cur += abs(e-med) minsum[i] = cur for i in range(n): assert minsum[i] <= cursum[i] dif = [cursum[i]-minsum[i] for i in range(n)] maxdif = max(dif) out = tot - maxdif print(out) ```
instruction
0
71,114
14
142,228
Yes
output
1
71,114
14
142,229
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory. Though Ryouko is forgetful, she is also born with superb analyzing abilities. However, analyzing depends greatly on gathered information, in other words, memory. So she has to shuffle through her notebook whenever she needs to analyze, which is tough work. Ryouko's notebook consists of n pages, numbered from 1 to n. To make life (and this problem) easier, we consider that to turn from page x to page y, |x - y| pages should be turned. During analyzing, Ryouko needs m pieces of information, the i-th piece of information is on page ai. Information must be read from the notebook in order, so the total number of pages that Ryouko needs to turn is <image>. Ryouko wants to decrease the number of pages that need to be turned. In order to achieve this, she can merge two pages of her notebook. If Ryouko merges page x to page y, she would copy all the information on page x to y (1 ≀ x, y ≀ n), and consequently, all elements in sequence a that was x would become y. Note that x can be equal to y, in which case no changes take place. Please tell Ryouko the minimum number of pages that she needs to turn. Note she can apply the described operation at most once before the reading. Note that the answer can exceed 32-bit integers. Input The first line of input contains two integers n and m (1 ≀ n, m ≀ 105). The next line contains m integers separated by spaces: a1, a2, ..., am (1 ≀ ai ≀ n). Output Print a single integer β€” the minimum number of pages Ryouko needs to turn. Examples Input 4 6 1 2 3 4 3 2 Output 3 Input 10 5 9 4 3 8 8 Output 6 Note In the first sample, the optimal solution is to merge page 4 to 3, after merging sequence a becomes {1, 2, 3, 3, 3, 2}, so the number of pages Ryouko needs to turn is |1 - 2| + |2 - 3| + |3 - 3| + |3 - 3| + |3 - 2| = 3. In the second sample, optimal solution is achieved by merging page 9 to 4. Submitted Solution: ``` n, m = map(int, input().split()) s, p = 0, [[] for i in range(n + 1)] t = list(map(int, input().split())) for i in range(m - 1): p[t[i + 1]].append(t[i]) p[t[i]].append(t[i + 1]) for i, q in enumerate(p): if q: q.sort() k = q[len(q) // 2] d = sum(abs(i - j) - abs(k - j) for j in q) if d > s: s = d print(sum(abs(t[i + 1] - t[i]) for i in range(m - 1)) - d) ```
instruction
0
71,115
14
142,230
No
output
1
71,115
14
142,231
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory. Though Ryouko is forgetful, she is also born with superb analyzing abilities. However, analyzing depends greatly on gathered information, in other words, memory. So she has to shuffle through her notebook whenever she needs to analyze, which is tough work. Ryouko's notebook consists of n pages, numbered from 1 to n. To make life (and this problem) easier, we consider that to turn from page x to page y, |x - y| pages should be turned. During analyzing, Ryouko needs m pieces of information, the i-th piece of information is on page ai. Information must be read from the notebook in order, so the total number of pages that Ryouko needs to turn is <image>. Ryouko wants to decrease the number of pages that need to be turned. In order to achieve this, she can merge two pages of her notebook. If Ryouko merges page x to page y, she would copy all the information on page x to y (1 ≀ x, y ≀ n), and consequently, all elements in sequence a that was x would become y. Note that x can be equal to y, in which case no changes take place. Please tell Ryouko the minimum number of pages that she needs to turn. Note she can apply the described operation at most once before the reading. Note that the answer can exceed 32-bit integers. Input The first line of input contains two integers n and m (1 ≀ n, m ≀ 105). The next line contains m integers separated by spaces: a1, a2, ..., am (1 ≀ ai ≀ n). Output Print a single integer β€” the minimum number of pages Ryouko needs to turn. Examples Input 4 6 1 2 3 4 3 2 Output 3 Input 10 5 9 4 3 8 8 Output 6 Note In the first sample, the optimal solution is to merge page 4 to 3, after merging sequence a becomes {1, 2, 3, 3, 3, 2}, so the number of pages Ryouko needs to turn is |1 - 2| + |2 - 3| + |3 - 3| + |3 - 3| + |3 - 2| = 3. In the second sample, optimal solution is achieved by merging page 9 to 4. Submitted Solution: ``` def median(a): if len(a) == 0: return 0 if len(a) % 2 == 1: return a[len(a) // 2] else: return (a[len(a) // 2] + a[(len(a) // 2) - 1]) // 2 def profit(a, old_val): a.sort() med = median(a) sum_old = 0 sum_new = 0 for i in a: sum_old += abs(i - old_val) sum_new += abs(i - med) return sum_old - sum_new n, m = [int(c) for c in input().split()] pages = [int(c) for c in input().split()] count = {pages[0]: []} current_page_switches = 0 for i in range(1, len(pages)): cur_i = pages[i] prev_i = pages[i - 1] if not(cur_i in count): count[cur_i] = [] count[cur_i].append(prev_i) count[prev_i].append(cur_i) current_page_switches += abs(cur_i - prev_i) max_profit = 0 for i in count: if len(count[i]) > 0: tmp = profit(count[i], i) if tmp > max_profit: max_profit = tmp print(current_page_switches - max_profit) ```
instruction
0
71,116
14
142,232
No
output
1
71,116
14
142,233
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory. Though Ryouko is forgetful, she is also born with superb analyzing abilities. However, analyzing depends greatly on gathered information, in other words, memory. So she has to shuffle through her notebook whenever she needs to analyze, which is tough work. Ryouko's notebook consists of n pages, numbered from 1 to n. To make life (and this problem) easier, we consider that to turn from page x to page y, |x - y| pages should be turned. During analyzing, Ryouko needs m pieces of information, the i-th piece of information is on page ai. Information must be read from the notebook in order, so the total number of pages that Ryouko needs to turn is <image>. Ryouko wants to decrease the number of pages that need to be turned. In order to achieve this, she can merge two pages of her notebook. If Ryouko merges page x to page y, she would copy all the information on page x to y (1 ≀ x, y ≀ n), and consequently, all elements in sequence a that was x would become y. Note that x can be equal to y, in which case no changes take place. Please tell Ryouko the minimum number of pages that she needs to turn. Note she can apply the described operation at most once before the reading. Note that the answer can exceed 32-bit integers. Input The first line of input contains two integers n and m (1 ≀ n, m ≀ 105). The next line contains m integers separated by spaces: a1, a2, ..., am (1 ≀ ai ≀ n). Output Print a single integer β€” the minimum number of pages Ryouko needs to turn. Examples Input 4 6 1 2 3 4 3 2 Output 3 Input 10 5 9 4 3 8 8 Output 6 Note In the first sample, the optimal solution is to merge page 4 to 3, after merging sequence a becomes {1, 2, 3, 3, 3, 2}, so the number of pages Ryouko needs to turn is |1 - 2| + |2 - 3| + |3 - 3| + |3 - 3| + |3 - 2| = 3. In the second sample, optimal solution is achieved by merging page 9 to 4. Submitted Solution: ``` n, m = map(int, input().split()) s, p = 0, [[] for i in range(n + 1)] t = list(map(int, input().split())) for i in range(m - 1): if t[i] != t[i + 1]: p[t[i + 1]].append(t[i]) p[t[i]].append(t[i + 1]) for i, q in enumerate(p): if q: q.sort() k = q[len(q) // 2] d = sum(abs(i - j) - abs(k - j) for j in q) if d > s: s = d print(sum(abs(t[i + 1] - t[i]) for i in range(m - 1)) - d) ```
instruction
0
71,117
14
142,234
No
output
1
71,117
14
142,235
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory. Though Ryouko is forgetful, she is also born with superb analyzing abilities. However, analyzing depends greatly on gathered information, in other words, memory. So she has to shuffle through her notebook whenever she needs to analyze, which is tough work. Ryouko's notebook consists of n pages, numbered from 1 to n. To make life (and this problem) easier, we consider that to turn from page x to page y, |x - y| pages should be turned. During analyzing, Ryouko needs m pieces of information, the i-th piece of information is on page ai. Information must be read from the notebook in order, so the total number of pages that Ryouko needs to turn is <image>. Ryouko wants to decrease the number of pages that need to be turned. In order to achieve this, she can merge two pages of her notebook. If Ryouko merges page x to page y, she would copy all the information on page x to y (1 ≀ x, y ≀ n), and consequently, all elements in sequence a that was x would become y. Note that x can be equal to y, in which case no changes take place. Please tell Ryouko the minimum number of pages that she needs to turn. Note she can apply the described operation at most once before the reading. Note that the answer can exceed 32-bit integers. Input The first line of input contains two integers n and m (1 ≀ n, m ≀ 105). The next line contains m integers separated by spaces: a1, a2, ..., am (1 ≀ ai ≀ n). Output Print a single integer β€” the minimum number of pages Ryouko needs to turn. Examples Input 4 6 1 2 3 4 3 2 Output 3 Input 10 5 9 4 3 8 8 Output 6 Note In the first sample, the optimal solution is to merge page 4 to 3, after merging sequence a becomes {1, 2, 3, 3, 3, 2}, so the number of pages Ryouko needs to turn is |1 - 2| + |2 - 3| + |3 - 3| + |3 - 3| + |3 - 2| = 3. In the second sample, optimal solution is achieved by merging page 9 to 4. Submitted Solution: ``` n, m = map(int, input().split()) arr = list(map(int, input().split())) arr = [arr[0]] + arr + [arr[-1]] turns = {i: [0, 0, 0, 0] for i in set(arr)} total = 0 for i in range(1, m+1): total += abs(arr[i]-arr[i-1]) if arr[i] != arr[i-1]: turns[arr[i]][0] += arr[i]-arr[i-1] turns[arr[i]][1] += 1 if arr[i] != arr[i+1]: turns[arr[i]][2] += arr[i+1]-arr[i] turns[arr[i]][3] += 1 min_val = total for i in range(1, m+1): left = 0 right = 0 lo = -arr[i] + 1 hi = n-arr[i] mn = abs(turns[arr[i]][0]) + abs(turns[arr[i]][2]) diff = 0 while lo < hi: mid = lo + (hi - lo) // 2 left = turns[arr[i]][0] + turns[arr[i]][1] * mid right = turns[arr[i]][2] - turns[arr[i]][3] * mid if abs(left)+abs(right) < mn: hi = mid diff = abs(turns[arr[i]][0]) + abs(turns[arr[i]][2]) - (abs(left)+abs(right)) mn = abs(left)+abs(right) else: lo = mid + 1 if total - diff < min_val: min_val = total - diff print(min_val) ```
instruction
0
71,118
14
142,236
No
output
1
71,118
14
142,237
Provide tags and a correct Python 3 solution for this coding contest problem. Girl Lena likes it when everything is in order, and looks for order everywhere. Once she was getting ready for the University and noticed that the room was in a mess β€” all the objects from her handbag were thrown about the room. Of course, she wanted to put them back into her handbag. The problem is that the girl cannot carry more than two objects at a time, and cannot move the handbag. Also, if he has taken an object, she cannot put it anywhere except her handbag β€” her inherent sense of order does not let her do so. You are given the coordinates of the handbag and the coordinates of the objects in some Π‘artesian coordinate system. It is known that the girl covers the distance between any two objects in the time equal to the squared length of the segment between the points of the objects. It is also known that initially the coordinates of the girl and the handbag are the same. You are asked to find such an order of actions, that the girl can put all the objects back into her handbag in a minimum time period. Input The first line of the input file contains the handbag's coordinates xs, ys. The second line contains number n (1 ≀ n ≀ 24) β€” the amount of objects the girl has. The following n lines contain the objects' coordinates. All the coordinates do not exceed 100 in absolute value. All the given positions are different. All the numbers are integer. Output In the first line output the only number β€” the minimum time the girl needs to put the objects into her handbag. In the second line output the possible optimum way for Lena. Each object in the input is described by its index number (from 1 to n), the handbag's point is described by number 0. The path should start and end in the handbag's point. If there are several optimal paths, print any of them. Examples Input 0 0 2 1 1 -1 1 Output 8 0 1 2 0 Input 1 1 3 4 3 3 4 0 0 Output 32 0 1 2 0 3 0
instruction
0
71,330
14
142,660
Tags: bitmasks, dp Correct Solution: ``` import sys def main(): BITS = [1 << sh for sh in range(24)] B2N = {v: u for u, v in enumerate(BITS)} def getPt(): return tuple(map(int, input().split())) def dist(ptA, ptB): return sum(((u - v) ** 2 for u, v in zip(ptA, ptB))) def getBits(val): return tuple(filter(lambda x: x & val, BITS)) def chooseTwo(pool): n = len(pool) for i in range(n): for j in range(i + 1, n): yield (pool[i], pool[j]) ori = getPt() pts = [] N = int(input()) for _ in range(N): pts.append(getPt()) vis = set([0]) mint = [0] + [1e8] * (1 << N) # minimal time for dp pres = [None] * (1 << N) # previous step for reconstruct path allb = (1 << N) - 1 # all objects contained state B2P = {BITS[u]: v for u, v in enumerate(pts)} B2P[0] = ori alld = {u: {v: dist(B2P[u], B2P[v]) for v in B2P} for u in B2P} getDP = lambda x: mint[x] newDist = lambda stt, p: mint[stt] + alld[p[0]][p[1]] \ + alld[p[0]][0] \ + alld[p[1]][0] for stt in range(1 << N): if stt not in vis: continue bits = getBits(~stt & allb) sb = bits[0] if bits else None for bit in bits: newstt = stt | sb | bit nd = newDist(stt, (sb, bit)) if getDP(newstt) > nd: mint[newstt] = nd pres[newstt] = sb | bit vis.add(newstt) print(mint[allb]) path = ['0'] stt = allb while stt: bits = getBits(pres[stt]) for bit in bits: path.append(str(B2N[bit] + 1)) path.append('0') stt ^= pres[stt] print(' '.join(path)) main() ```
output
1
71,330
14
142,661
Provide tags and a correct Python 3 solution for this coding contest problem. Girl Lena likes it when everything is in order, and looks for order everywhere. Once she was getting ready for the University and noticed that the room was in a mess β€” all the objects from her handbag were thrown about the room. Of course, she wanted to put them back into her handbag. The problem is that the girl cannot carry more than two objects at a time, and cannot move the handbag. Also, if he has taken an object, she cannot put it anywhere except her handbag β€” her inherent sense of order does not let her do so. You are given the coordinates of the handbag and the coordinates of the objects in some Π‘artesian coordinate system. It is known that the girl covers the distance between any two objects in the time equal to the squared length of the segment between the points of the objects. It is also known that initially the coordinates of the girl and the handbag are the same. You are asked to find such an order of actions, that the girl can put all the objects back into her handbag in a minimum time period. Input The first line of the input file contains the handbag's coordinates xs, ys. The second line contains number n (1 ≀ n ≀ 24) β€” the amount of objects the girl has. The following n lines contain the objects' coordinates. All the coordinates do not exceed 100 in absolute value. All the given positions are different. All the numbers are integer. Output In the first line output the only number β€” the minimum time the girl needs to put the objects into her handbag. In the second line output the possible optimum way for Lena. Each object in the input is described by its index number (from 1 to n), the handbag's point is described by number 0. The path should start and end in the handbag's point. If there are several optimal paths, print any of them. Examples Input 0 0 2 1 1 -1 1 Output 8 0 1 2 0 Input 1 1 3 4 3 3 4 0 0 Output 32 0 1 2 0 3 0
instruction
0
71,335
14
142,670
Tags: bitmasks, dp Correct Solution: ``` from itertools import chain from time import time def main(): BITS = [1 << sh for sh in range(24)] B2N = {v: u for u, v in enumerate(BITS)} def getPt(): return tuple(map(int, input().split())) def dist(ptA, ptB): return sum(((u-v)**2 for u, v in zip(ptA, ptB))) def getBits(val): return tuple(filter(lambda x: x&val, BITS)) def chooseTwo(pool): n = len(pool) for i in range(n): for j in range(i+1, n): yield (pool[i], pool[j]) ori = getPt() pts = [] N = int(input()) for _ in range(N): pts.append(getPt()) vis = set([0]) mint = [0]+[1e8]*(1<<N) pres = [None]*(1<<N) allb = (1 << N)-1 B2P = {BITS[u]: v for u, v in enumerate(pts)} B2P[0] = ori alld = {u: {v: dist(B2P[u], B2P[v]) for v in B2P} for u in B2P} getDP = lambda x: mint[x] newDist = lambda stt, p: mint[stt] + alld[p[0]][p[1]] \ + alld[p[0]][0] \ + alld[p[1]][0] for stt in range(1<<N): if stt not in vis: continue bits = getBits(~stt&allb) sb = bits[0] if bits else None for bit in bits: newstt = stt | sb | bit nd = newDist(stt, (sb, bit)) if getDP(newstt) > nd: mint[newstt] = nd pres[newstt] = sb | bit vis.add(newstt) print(mint[allb]) path = ['0'] stt = allb while stt: bits = getBits(pres[stt]) for bit in bits: path.append(str(B2N[bit]+1)) path.append('0') stt ^= pres[stt] print(' '.join(path)) import sys st = time() main() print('Run {:.6f} seconds.'.format(time()-st), file=sys.stderr) ```
output
1
71,335
14
142,671
Provide tags and a correct Python 3 solution for this coding contest problem. Throughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well. This time Igor K. got disappointed in one of his hobbies: editing and voicing videos. Moreover, he got disappointed in it so much, that he decided to destroy his secret archive for good. Igor K. use Pindows XR operation system which represents files and folders by small icons. At that, m icons can fit in a horizontal row in any window. Igor K.'s computer contains n folders in the D: disk's root catalog. The folders are numbered from 1 to n in the order from the left to the right and from top to bottom (see the images). At that the folders with secret videos have numbers from a to b inclusive. Igor K. wants to delete them forever, at that making as few frame selections as possible, and then pressing Shift+Delete exactly once. What is the minimum number of times Igor K. will have to select the folder in order to select folders from a to b and only them? Let us note that if some selected folder is selected repeatedly, then it is deselected. Each selection possesses the shape of some rectangle with sides parallel to the screen's borders. Input The only line contains four integers n, m, a, b (1 ≀ n, m ≀ 109, 1 ≀ a ≀ b ≀ n). They are the number of folders in Igor K.'s computer, the width of a window and the numbers of the first and the last folders that need to be deleted. Output Print a single number: the least possible number of times Igor K. will have to select the folders using frames to select only the folders with numbers from a to b. Examples Input 11 4 3 9 Output 3 Input 20 5 2 20 Output 2 Note The images below illustrate statement tests. The first test: <image> In this test we can select folders 3 and 4 with out first selection, folders 5, 6, 7, 8 with our second selection and folder 9 with our third, last selection. The second test: <image> In this test we can first select all folders in the first row (2, 3, 4, 5), then β€” all other ones.
instruction
0
71,356
14
142,712
Tags: implementation Correct Solution: ``` #!/usr/bin/python3 n, m, a, b = map(int, input().split()) a -= 1 b -= 1 if a // m == b // m: print(1) elif a % m == 0 and (b + 1) % m == 0: print(1) elif a % m == 0 and b + 1 == n: print(1) elif b + 1 == n: print(2) elif a % m == 0 or (b + 1) % m == 0: print(2) elif a % m == (b + 1) % m: print(2) elif b // m - a // m == 1: print(2) elif m == 2: print(2) else: print(3) ```
output
1
71,356
14
142,713
Provide tags and a correct Python 3 solution for this coding contest problem. Throughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well. This time Igor K. got disappointed in one of his hobbies: editing and voicing videos. Moreover, he got disappointed in it so much, that he decided to destroy his secret archive for good. Igor K. use Pindows XR operation system which represents files and folders by small icons. At that, m icons can fit in a horizontal row in any window. Igor K.'s computer contains n folders in the D: disk's root catalog. The folders are numbered from 1 to n in the order from the left to the right and from top to bottom (see the images). At that the folders with secret videos have numbers from a to b inclusive. Igor K. wants to delete them forever, at that making as few frame selections as possible, and then pressing Shift+Delete exactly once. What is the minimum number of times Igor K. will have to select the folder in order to select folders from a to b and only them? Let us note that if some selected folder is selected repeatedly, then it is deselected. Each selection possesses the shape of some rectangle with sides parallel to the screen's borders. Input The only line contains four integers n, m, a, b (1 ≀ n, m ≀ 109, 1 ≀ a ≀ b ≀ n). They are the number of folders in Igor K.'s computer, the width of a window and the numbers of the first and the last folders that need to be deleted. Output Print a single number: the least possible number of times Igor K. will have to select the folders using frames to select only the folders with numbers from a to b. Examples Input 11 4 3 9 Output 3 Input 20 5 2 20 Output 2 Note The images below illustrate statement tests. The first test: <image> In this test we can select folders 3 and 4 with out first selection, folders 5, 6, 7, 8 with our second selection and folder 9 with our third, last selection. The second test: <image> In this test we can first select all folders in the first row (2, 3, 4, 5), then β€” all other ones.
instruction
0
71,357
14
142,714
Tags: implementation Correct Solution: ``` n, m, a, b = map(int, input().split()) if m == 1: print("1") elif (a - 1) // m == (b - 1) // m: print("1") elif abs((a - 1) // m - (b - 1) // m) == 1 and a % m != 1: print("2") elif b == n or b % m == 0: if a % m == 1: print("1") else: print("2") elif a % m == 1 or ((b + (m - a % m + 1)) % m) == 0: print("2") else: print("3") ```
output
1
71,357
14
142,715
Provide tags and a correct Python 3 solution for this coding contest problem. Throughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well. This time Igor K. got disappointed in one of his hobbies: editing and voicing videos. Moreover, he got disappointed in it so much, that he decided to destroy his secret archive for good. Igor K. use Pindows XR operation system which represents files and folders by small icons. At that, m icons can fit in a horizontal row in any window. Igor K.'s computer contains n folders in the D: disk's root catalog. The folders are numbered from 1 to n in the order from the left to the right and from top to bottom (see the images). At that the folders with secret videos have numbers from a to b inclusive. Igor K. wants to delete them forever, at that making as few frame selections as possible, and then pressing Shift+Delete exactly once. What is the minimum number of times Igor K. will have to select the folder in order to select folders from a to b and only them? Let us note that if some selected folder is selected repeatedly, then it is deselected. Each selection possesses the shape of some rectangle with sides parallel to the screen's borders. Input The only line contains four integers n, m, a, b (1 ≀ n, m ≀ 109, 1 ≀ a ≀ b ≀ n). They are the number of folders in Igor K.'s computer, the width of a window and the numbers of the first and the last folders that need to be deleted. Output Print a single number: the least possible number of times Igor K. will have to select the folders using frames to select only the folders with numbers from a to b. Examples Input 11 4 3 9 Output 3 Input 20 5 2 20 Output 2 Note The images below illustrate statement tests. The first test: <image> In this test we can select folders 3 and 4 with out first selection, folders 5, 6, 7, 8 with our second selection and folder 9 with our third, last selection. The second test: <image> In this test we can first select all folders in the first row (2, 3, 4, 5), then β€” all other ones.
instruction
0
71,358
14
142,716
Tags: implementation Correct Solution: ``` import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n, m, a, b = map(int, input().split()) a, b = a - 1, b - 1 if b + 1 == n: b = (b // m + 1) * m - 1 if a // m == b // m: print(1) elif a % m == 0 and b % m == m - 1: print(1) elif b % m + 1 == a % m: print(2) elif a // m + 1 == b // m: print(2) else: ans = 1 + (a % m != 0) + (b % m != m - 1) print(ans) ```
output
1
71,358
14
142,717
Provide tags and a correct Python 3 solution for this coding contest problem. Throughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well. This time Igor K. got disappointed in one of his hobbies: editing and voicing videos. Moreover, he got disappointed in it so much, that he decided to destroy his secret archive for good. Igor K. use Pindows XR operation system which represents files and folders by small icons. At that, m icons can fit in a horizontal row in any window. Igor K.'s computer contains n folders in the D: disk's root catalog. The folders are numbered from 1 to n in the order from the left to the right and from top to bottom (see the images). At that the folders with secret videos have numbers from a to b inclusive. Igor K. wants to delete them forever, at that making as few frame selections as possible, and then pressing Shift+Delete exactly once. What is the minimum number of times Igor K. will have to select the folder in order to select folders from a to b and only them? Let us note that if some selected folder is selected repeatedly, then it is deselected. Each selection possesses the shape of some rectangle with sides parallel to the screen's borders. Input The only line contains four integers n, m, a, b (1 ≀ n, m ≀ 109, 1 ≀ a ≀ b ≀ n). They are the number of folders in Igor K.'s computer, the width of a window and the numbers of the first and the last folders that need to be deleted. Output Print a single number: the least possible number of times Igor K. will have to select the folders using frames to select only the folders with numbers from a to b. Examples Input 11 4 3 9 Output 3 Input 20 5 2 20 Output 2 Note The images below illustrate statement tests. The first test: <image> In this test we can select folders 3 and 4 with out first selection, folders 5, 6, 7, 8 with our second selection and folder 9 with our third, last selection. The second test: <image> In this test we can first select all folders in the first row (2, 3, 4, 5), then β€” all other ones.
instruction
0
71,359
14
142,718
Tags: implementation Correct Solution: ``` #------------------------------warmup---------------------------- # ******************************* # * AUTHOR: RAJDEEP GHOSH * # * NICK : Rajdeep2k * # * INSTITUTION: IIEST, SHIBPUR * # ******************************* import os import sys from io import BytesIO, IOBase import math BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #-------------------game starts now--------------------------------------------------- # t=(int)(input()) import math for _ in range(1): # n=(int)(input()) # l=list(map(int,input().split())) n,m,a,b=map(int,input().split()) r1=(a-1)//m r2=(b-1)//m c1=(a-1)%m +1 c2=(b-1)%m +1 if r1==r2: print('1') elif c1==1 and (c2==m or b==n): print('1') elif c1==1 or (c2==m or b==n): print('2') elif r2-r1==1: print('2') elif c1==c2+1: print('2') else: print('3') ```
output
1
71,359
14
142,719
Provide tags and a correct Python 3 solution for this coding contest problem. Throughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well. This time Igor K. got disappointed in one of his hobbies: editing and voicing videos. Moreover, he got disappointed in it so much, that he decided to destroy his secret archive for good. Igor K. use Pindows XR operation system which represents files and folders by small icons. At that, m icons can fit in a horizontal row in any window. Igor K.'s computer contains n folders in the D: disk's root catalog. The folders are numbered from 1 to n in the order from the left to the right and from top to bottom (see the images). At that the folders with secret videos have numbers from a to b inclusive. Igor K. wants to delete them forever, at that making as few frame selections as possible, and then pressing Shift+Delete exactly once. What is the minimum number of times Igor K. will have to select the folder in order to select folders from a to b and only them? Let us note that if some selected folder is selected repeatedly, then it is deselected. Each selection possesses the shape of some rectangle with sides parallel to the screen's borders. Input The only line contains four integers n, m, a, b (1 ≀ n, m ≀ 109, 1 ≀ a ≀ b ≀ n). They are the number of folders in Igor K.'s computer, the width of a window and the numbers of the first and the last folders that need to be deleted. Output Print a single number: the least possible number of times Igor K. will have to select the folders using frames to select only the folders with numbers from a to b. Examples Input 11 4 3 9 Output 3 Input 20 5 2 20 Output 2 Note The images below illustrate statement tests. The first test: <image> In this test we can select folders 3 and 4 with out first selection, folders 5, 6, 7, 8 with our second selection and folder 9 with our third, last selection. The second test: <image> In this test we can first select all folders in the first row (2, 3, 4, 5), then β€” all other ones.
instruction
0
71,360
14
142,720
Tags: implementation Correct Solution: ``` readints=lambda:map(int, input().strip('\n').split()) n,m,a,b=readints() a-=1 b-=1 # 0-index ra=a//m rb=b//m ia=a%m ib=b%m if (ra==rb) or (ia==0 and b==n-1) or (ia==0 and ib==m-1): print(1) elif (ia==0 and ib<m-1 and b!=n-1) or (ia>0 and (ib==m-1 or b==n-1)) or (ra+1==rb) or (ib+1==ia): print(2) else: print(3) ```
output
1
71,360
14
142,721
Provide tags and a correct Python 3 solution for this coding contest problem. Throughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well. This time Igor K. got disappointed in one of his hobbies: editing and voicing videos. Moreover, he got disappointed in it so much, that he decided to destroy his secret archive for good. Igor K. use Pindows XR operation system which represents files and folders by small icons. At that, m icons can fit in a horizontal row in any window. Igor K.'s computer contains n folders in the D: disk's root catalog. The folders are numbered from 1 to n in the order from the left to the right and from top to bottom (see the images). At that the folders with secret videos have numbers from a to b inclusive. Igor K. wants to delete them forever, at that making as few frame selections as possible, and then pressing Shift+Delete exactly once. What is the minimum number of times Igor K. will have to select the folder in order to select folders from a to b and only them? Let us note that if some selected folder is selected repeatedly, then it is deselected. Each selection possesses the shape of some rectangle with sides parallel to the screen's borders. Input The only line contains four integers n, m, a, b (1 ≀ n, m ≀ 109, 1 ≀ a ≀ b ≀ n). They are the number of folders in Igor K.'s computer, the width of a window and the numbers of the first and the last folders that need to be deleted. Output Print a single number: the least possible number of times Igor K. will have to select the folders using frames to select only the folders with numbers from a to b. Examples Input 11 4 3 9 Output 3 Input 20 5 2 20 Output 2 Note The images below illustrate statement tests. The first test: <image> In this test we can select folders 3 and 4 with out first selection, folders 5, 6, 7, 8 with our second selection and folder 9 with our third, last selection. The second test: <image> In this test we can first select all folders in the first row (2, 3, 4, 5), then β€” all other ones.
instruction
0
71,361
14
142,722
Tags: implementation Correct Solution: ``` import math n,m,a,b=map(int,input().split()) if (a-1)//m==(b-1)//m: print(1) elif (a-1)%m==0 and b%m==0: print(1) elif (a-1)%m==0 and b==n or m==1: print(1) elif (a-1)%m==0 or b%m==0 or b==n: print(2) elif abs((a-1)//m - (b-1)//m)==1 or m==2: print(2) elif (a-1)%m==b%m: print(2) else: print(3) ```
output
1
71,361
14
142,723
Provide tags and a correct Python 3 solution for this coding contest problem. Throughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well. This time Igor K. got disappointed in one of his hobbies: editing and voicing videos. Moreover, he got disappointed in it so much, that he decided to destroy his secret archive for good. Igor K. use Pindows XR operation system which represents files and folders by small icons. At that, m icons can fit in a horizontal row in any window. Igor K.'s computer contains n folders in the D: disk's root catalog. The folders are numbered from 1 to n in the order from the left to the right and from top to bottom (see the images). At that the folders with secret videos have numbers from a to b inclusive. Igor K. wants to delete them forever, at that making as few frame selections as possible, and then pressing Shift+Delete exactly once. What is the minimum number of times Igor K. will have to select the folder in order to select folders from a to b and only them? Let us note that if some selected folder is selected repeatedly, then it is deselected. Each selection possesses the shape of some rectangle with sides parallel to the screen's borders. Input The only line contains four integers n, m, a, b (1 ≀ n, m ≀ 109, 1 ≀ a ≀ b ≀ n). They are the number of folders in Igor K.'s computer, the width of a window and the numbers of the first and the last folders that need to be deleted. Output Print a single number: the least possible number of times Igor K. will have to select the folders using frames to select only the folders with numbers from a to b. Examples Input 11 4 3 9 Output 3 Input 20 5 2 20 Output 2 Note The images below illustrate statement tests. The first test: <image> In this test we can select folders 3 and 4 with out first selection, folders 5, 6, 7, 8 with our second selection and folder 9 with our third, last selection. The second test: <image> In this test we can first select all folders in the first row (2, 3, 4, 5), then β€” all other ones.
instruction
0
71,362
14
142,724
Tags: implementation Correct Solution: ``` n, m, a, b = map(int, input().split()) r1, r2, c1, c2 = (a - 1) // m, (b - 1) // m, (a - 1) % m, m - 1 if b == n else (b - 1) % m if r1 == r2 or c1 == 0 and c2 == m - 1: print(1) elif r2 == r1 + 1 or c1 == 0 or c2 == m - 1 or c1 == c2 + 1: print(2) else: print(3) # Made By Mostafa_Khaled ```
output
1
71,362
14
142,725
Provide tags and a correct Python 3 solution for this coding contest problem. A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees. He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one. It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum. Input The first line of input contains the number of students n (2 ≀ n ≀ 1000). The second line gives (n - 1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks. Output Output consists of n integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one. Examples Input 5 LRLR Output 2 1 2 1 2 Input 5 =RRR Output 1 1 2 3 4
instruction
0
72,121
14
144,242
Tags: dp, graphs, greedy, implementation Correct Solution: ``` import sys from math import log2,floor,ceil,sqrt,gcd import bisect # from collections import deque sys.setrecursionlimit(10**5) Ri = lambda : [int(x) for x in sys.stdin.readline().split()] ri = lambda : sys.stdin.readline().strip() def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def INT(): return int(input()) def MAP(): return map(int, input().split()) def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)] def Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') INF = 10 ** 18 MOD = 1000000007 # for _ in range(int(ri())): n = int(ri()) st = ri() arr = [0]*(n) ind = [] cnt = 1 arr[0] = 1 cnt=0 for i in range(len(st)): if st[i] == 'L': if arr[i] == 1: arr[i]+=1 arr[i+1] = 1 elif st[i] == 'R': arr[i+1] = arr[i]+1 else: arr[i+1] = arr[i] # minn = min(arr) # if minn <= 0: # arr = [ arr[i]+abs(minn)+1 for i in range(len(arr))] # for i in ind: for i in range(n-2,-1,-1): if st[i] == '=': if arr[i] != arr[i+1]: arr[i] = arr[i+1] elif st[i] == 'L': if not arr[i] > arr[i+1]: arr[i] = arr[i+1]+1 else: if not arr[i] < arr[i+1]: arr[i+1] = arr[i]+1 print(*arr) ```
output
1
72,121
14
144,243
Provide tags and a correct Python 3 solution for this coding contest problem. A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees. He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one. It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum. Input The first line of input contains the number of students n (2 ≀ n ≀ 1000). The second line gives (n - 1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks. Output Output consists of n integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one. Examples Input 5 LRLR Output 2 1 2 1 2 Input 5 =RRR Output 1 1 2 3 4
instruction
0
72,122
14
144,244
Tags: dp, graphs, greedy, implementation Correct Solution: ``` n=int(input()) r=[1]*n s=input() y=1 while y: y=0 for i in range(n-1): if s[i]=='=' and r[i]!=r[i+1]:r[i]=r[i+1]=max(r[i:i+2]);y=1 if s[i]=='L' and r[i]<=r[i+1]:r[i]=r[i+1]+1;y=1 if s[i]=='R' and r[i]>=r[i+1]:r[i+1]=r[i]+1;y=1 print(*r) ```
output
1
72,122
14
144,245
Provide tags and a correct Python 3 solution for this coding contest problem. A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees. He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one. It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum. Input The first line of input contains the number of students n (2 ≀ n ≀ 1000). The second line gives (n - 1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks. Output Output consists of n integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one. Examples Input 5 LRLR Output 2 1 2 1 2 Input 5 =RRR Output 1 1 2 3 4
instruction
0
72,123
14
144,246
Tags: dp, graphs, greedy, implementation Correct Solution: ``` n=int(input()) s=input() w=[1]*n for i in range(n-1): if s[i]=='=': w[i+1]=w[i] elif s[i]=='R': if w[i+1]<=w[i]: w[i+1]=w[i]+1 else: if w[i]<=w[i+1]: w[i]=w[i+1]+1 for i in range(n-2,-1,-1): if s[i]=='=': w[i]=w[i+1] elif s[i]=='R': if w[i+1]==w[i]: w[i+1]=w[i]+1 else: if w[i]<=w[i+1]: w[i]=w[i+1]+1 for i in range(n): print(w[i],end=' ') ```
output
1
72,123
14
144,247
Provide tags and a correct Python 3 solution for this coding contest problem. A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees. He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one. It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum. Input The first line of input contains the number of students n (2 ≀ n ≀ 1000). The second line gives (n - 1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks. Output Output consists of n integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one. Examples Input 5 LRLR Output 2 1 2 1 2 Input 5 =RRR Output 1 1 2 3 4
instruction
0
72,124
14
144,248
Tags: dp, graphs, greedy, implementation Correct Solution: ``` n=int(input()) r=[1]*n s=input() y=1 while y: y=0 for i in range(n-1): if s[i]=='=' and r[i]!=r[i+1]:r[i]=r[i+1]=max(r[i:i+2]);y=1 if s[i]=='L' and r[i]<=r[i+1]:r[i]=r[i+1]+1;y=1 if s[i]=='R' and r[i]>=r[i+1]:r[i+1]=r[i]+1;y=1 print(' '.join(map(str, r))) ```
output
1
72,124
14
144,249
Provide tags and a correct Python 3 solution for this coding contest problem. A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees. He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one. It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum. Input The first line of input contains the number of students n (2 ≀ n ≀ 1000). The second line gives (n - 1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks. Output Output consists of n integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one. Examples Input 5 LRLR Output 2 1 2 1 2 Input 5 =RRR Output 1 1 2 3 4
instruction
0
72,125
14
144,250
Tags: dp, graphs, greedy, implementation Correct Solution: ``` n = int(input()) p = 'R' + input() + 'R' t = [0] * n i = t[0] = l = r = 1 L = R = 0 while i < n + 1: if p[i] == 'L': if r > 1: t[R] = r L, r = i, 1 l += 1 elif p[i] == 'R': if l > 1: if t[R] < l: t[R] = l else: t[L] = l - 1 l = 1 R = i r += 1 i += 1 for i in range(1, n): if t[i] == 0: if p[i] == 'L': t[i] = t[i - 1] - 1 elif p[i] == 'R': t[i] = t[i - 1] + 1 else: t[i] = t[i - 1] print(' '.join(map(str, t))) ```
output
1
72,125
14
144,251
Provide tags and a correct Python 3 solution for this coding contest problem. A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees. He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one. It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum. Input The first line of input contains the number of students n (2 ≀ n ≀ 1000). The second line gives (n - 1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks. Output Output consists of n integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one. Examples Input 5 LRLR Output 2 1 2 1 2 Input 5 =RRR Output 1 1 2 3 4
instruction
0
72,126
14
144,252
Tags: dp, graphs, greedy, implementation Correct Solution: ``` import math from collections import Counter, defaultdict from itertools import accumulate R = lambda: map(int, input().split()) n = int(input()) s = input() dp = [[0] * 1005 for i in range(n + 1)] for i in range(1, 1001): dp[0][i] = i dp[0][1001] = math.inf for i in range(n): dp[i][0] = math.inf for i in range(1, n): if s[i - 1] == 'L': rmin = math.inf for j in range(1000, 0, -1): dp[i][j] = rmin + j rmin = min(rmin, dp[i - 1][j]) elif s[i - 1] == 'R': rmin = math.inf for j in range(1, 1001): dp[i][j] = rmin + j rmin = min(rmin, dp[i - 1][j]) else: for j in range(1, 1001): dp[i][j] = dp[i - 1][j] + j rem = min((dp[n - 1][j], j) for j in range(1, 1001))[0] res = [-1] * n for i in range(n - 1, -1, -1): for j in range(1, 1001): if rem == dp[i][j]: res[i] = j rem -= j continue print(' '.join(map(str, res))) ```
output
1
72,126
14
144,253
Provide tags and a correct Python 3 solution for this coding contest problem. A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees. He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one. It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum. Input The first line of input contains the number of students n (2 ≀ n ≀ 1000). The second line gives (n - 1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks. Output Output consists of n integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one. Examples Input 5 LRLR Output 2 1 2 1 2 Input 5 =RRR Output 1 1 2 3 4
instruction
0
72,127
14
144,254
Tags: dp, graphs, greedy, implementation Correct Solution: ``` n=int(input()) s=input() a=[1]*n flag=True while flag: flag=False for i in range(n-1): if s[i]=='=': if a[i]!=a[i+1]: z=max(a[i],a[i+1]) a[i],a[i+1]=z,z flag=True elif s[i]=='L': if a[i]<=a[i+1]: a[i]=a[i+1]+1 flag=True else: if a[i]>=a[i+1]: a[i+1]=a[i]+1 flag=True print(*a) ```
output
1
72,127
14
144,255
Provide tags and a correct Python 3 solution for this coding contest problem. A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees. He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one. It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum. Input The first line of input contains the number of students n (2 ≀ n ≀ 1000). The second line gives (n - 1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks. Output Output consists of n integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one. Examples Input 5 LRLR Output 2 1 2 1 2 Input 5 =RRR Output 1 1 2 3 4
instruction
0
72,128
14
144,256
Tags: dp, graphs, greedy, implementation Correct Solution: ``` n = int(input()) s = input() ans = [1] * n t = True while t: t = False for i in range(n - 1): if s[i] == '=' and ans[i] != ans[i + 1]: ans[i] = ans[i + 1] = max(ans[i], ans[i + 1]) t = True elif s[i] == 'R' and ans[i] >= ans[i + 1]: ans[i + 1] += 1 t = True elif s[i] == 'L' and ans[i] <= ans[i + 1]: ans[i] += 1 t = True print(*ans) ```
output
1
72,128
14
144,257
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees. He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one. It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum. Input The first line of input contains the number of students n (2 ≀ n ≀ 1000). The second line gives (n - 1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks. Output Output consists of n integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one. Examples Input 5 LRLR Output 2 1 2 1 2 Input 5 =RRR Output 1 1 2 3 4 Submitted Solution: ``` from collections import defaultdict class PartialTeacher(): def __init__(self, n, prefs): self.prefs = prefs def create_graph(self): num_nodes = len(list(filter(lambda x: x != '=',list(self.prefs))))+1 node_cntr = 0 node_cnts = defaultdict(lambda: 1) edge_map = defaultdict(list) rev_map = defaultdict(list) outgoing_edges = defaultdict(int) for ch in self.prefs: if ch == 'R': edge_map[node_cntr].append(node_cntr+1) rev_map[node_cntr+1].append(node_cntr) outgoing_edges[node_cntr] += 1 node_cntr += 1 elif ch == 'L': edge_map[node_cntr+1].append(node_cntr) rev_map[node_cntr].append(node_cntr+1) outgoing_edges[node_cntr+1] += 1 node_cntr += 1 else: node_cnts[node_cntr] += 1 s = set() for i in range(node_cntr+1): if outgoing_edges[i] == 0: s.add(i) order = [] while len(s) > 0: v = s.pop() order.append(v) for u in rev_map[v]: outgoing_edges[u] -= 1 if outgoing_edges[u] == 0: s.add(u) order.reverse() values = [-1]*len(order) for v in order: val_list = list(map(lambda x: values[x], rev_map[v])) val = 1 if len(val_list) == 0 else max(val_list)+1 values[v] = val complete_values = [] for i in range(len(values)): complete_values += [values[i]]*node_cnts[i] print(*complete_values) n = int(input()) prefs = input().strip(' ') pt = PartialTeacher(n, prefs) pt.create_graph() ```
instruction
0
72,131
14
144,262
Yes
output
1
72,131
14
144,263
Provide tags and a correct Python 3 solution for this coding contest problem. Three friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox. In one minute each friend independently from other friends can change the position x by 1 to the left or by 1 to the right (i.e. set x := x - 1 or x := x + 1) or even don't change it. Let's introduce the total pairwise distance β€” the sum of distances between each pair of friends. Let a', b' and c' be the final positions of the first, the second and the third friend, correspondingly. Then the total pairwise distance is |a' - b'| + |a' - c'| + |b' - c'|, where |x| is the absolute value of x. Friends are interested in the minimum total pairwise distance they can reach if they will move optimally. Each friend will move no more than once. So, more formally, they want to know the minimum total pairwise distance they can reach after one minute. You have to answer q independent test cases. Input The first line of the input contains one integer q (1 ≀ q ≀ 1000) β€” the number of test cases. The next q lines describe test cases. The i-th test case is given as three integers a, b and c (1 ≀ a, b, c ≀ 10^9) β€” initial positions of the first, second and third friend correspondingly. The positions of friends can be equal. Output For each test case print the answer on it β€” the minimum total pairwise distance (the minimum sum of distances between each pair of friends) if friends change their positions optimally. Each friend will move no more than once. So, more formally, you have to find the minimum total pairwise distance they can reach after one minute. Example Input 8 3 3 4 10 20 30 5 5 5 2 4 3 1 1000000000 1000000000 1 1000000000 999999999 3 2 5 3 2 6 Output 0 36 0 0 1999999994 1999999994 2 4
instruction
0
73,426
14
146,852
Tags: brute force, greedy, math, sortings Correct Solution: ``` t = int(input()) for _ in range(t): a, b, c = map(int, input().split()) ans = abs(a - b) + abs(a - c) + abs(b - c) ans = max(0, ans - 4) print(ans) ```
output
1
73,426
14
146,853
Provide tags and a correct Python 3 solution for this coding contest problem. Three friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox. In one minute each friend independently from other friends can change the position x by 1 to the left or by 1 to the right (i.e. set x := x - 1 or x := x + 1) or even don't change it. Let's introduce the total pairwise distance β€” the sum of distances between each pair of friends. Let a', b' and c' be the final positions of the first, the second and the third friend, correspondingly. Then the total pairwise distance is |a' - b'| + |a' - c'| + |b' - c'|, where |x| is the absolute value of x. Friends are interested in the minimum total pairwise distance they can reach if they will move optimally. Each friend will move no more than once. So, more formally, they want to know the minimum total pairwise distance they can reach after one minute. You have to answer q independent test cases. Input The first line of the input contains one integer q (1 ≀ q ≀ 1000) β€” the number of test cases. The next q lines describe test cases. The i-th test case is given as three integers a, b and c (1 ≀ a, b, c ≀ 10^9) β€” initial positions of the first, second and third friend correspondingly. The positions of friends can be equal. Output For each test case print the answer on it β€” the minimum total pairwise distance (the minimum sum of distances between each pair of friends) if friends change their positions optimally. Each friend will move no more than once. So, more formally, you have to find the minimum total pairwise distance they can reach after one minute. Example Input 8 3 3 4 10 20 30 5 5 5 2 4 3 1 1000000000 1000000000 1 1000000000 999999999 3 2 5 3 2 6 Output 0 36 0 0 1999999994 1999999994 2 4
instruction
0
73,427
14
146,854
Tags: brute force, greedy, math, sortings Correct Solution: ``` import math q = int(input()) def len_equal(array): if len(set(array)) == 1: return True return False def calc(array): return math.fabs(array[0] - array[1]) + math.fabs(array[1] - array[2]) + math.fabs(array[0] - array[2]) for x in range(q): array = list(map(int, input().split())) array.sort() if len_equal(array) == True: print(0) continue output = [calc(array)] if array[0] == array[1]: array[0] += 1 array[1] += 1 output.append(calc(array)) if array[2] == array[1]: array[1] -= 1 array[2] -= 1 output.append(calc(array)) if array[0] != array[1]: array[0] += 1 output.append(calc(array)) if array[2] != array[1]: array[2] -= 1 output.append(calc(array)) print(int(min(output))) ```
output
1
73,427
14
146,855
Provide tags and a correct Python 3 solution for this coding contest problem. Three friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox. In one minute each friend independently from other friends can change the position x by 1 to the left or by 1 to the right (i.e. set x := x - 1 or x := x + 1) or even don't change it. Let's introduce the total pairwise distance β€” the sum of distances between each pair of friends. Let a', b' and c' be the final positions of the first, the second and the third friend, correspondingly. Then the total pairwise distance is |a' - b'| + |a' - c'| + |b' - c'|, where |x| is the absolute value of x. Friends are interested in the minimum total pairwise distance they can reach if they will move optimally. Each friend will move no more than once. So, more formally, they want to know the minimum total pairwise distance they can reach after one minute. You have to answer q independent test cases. Input The first line of the input contains one integer q (1 ≀ q ≀ 1000) β€” the number of test cases. The next q lines describe test cases. The i-th test case is given as three integers a, b and c (1 ≀ a, b, c ≀ 10^9) β€” initial positions of the first, second and third friend correspondingly. The positions of friends can be equal. Output For each test case print the answer on it β€” the minimum total pairwise distance (the minimum sum of distances between each pair of friends) if friends change their positions optimally. Each friend will move no more than once. So, more formally, you have to find the minimum total pairwise distance they can reach after one minute. Example Input 8 3 3 4 10 20 30 5 5 5 2 4 3 1 1000000000 1000000000 1 1000000000 999999999 3 2 5 3 2 6 Output 0 36 0 0 1999999994 1999999994 2 4
instruction
0
73,428
14
146,856
Tags: brute force, greedy, math, sortings Correct Solution: ``` t=int(input()) for i in range(t): d=[int(x) for x in input().split()] d.sort() a,b,c=d[0],d[1],d[2] if a==b==c: print(0) elif a==b or b==c: res=abs(a-b)+abs(b-c)+abs(a-c)-4 print(max(0,res)) elif abs(a-b)>=abs(a-c) and abs(a-b)>=abs(b-c): a+=1 b-=1 res=abs(a-b)+abs(b-c)+abs(a-c) c-=1 res1=abs(a-b)+abs(b-c)+abs(a-c) print(min(res,res1)) elif abs(a-c)>=abs(a-b) and abs(a-c)>=abs(b-c): a+=1 c-=1 res=abs(a-b)+abs(b-c)+abs(a-c) b+=1 res1=abs(a-b)+abs(b-c)+abs(a-c) b-=2 res2=abs(a-b)+abs(b-c)+abs(a-c) print(min(res,res1,res2)) elif abs(b-c)>=abs(a-b) and abs(a-c)<=abs(b-c): b+=1 c-=1 res=abs(a-b)+abs(b-c)+abs(a-c) a+=1 res1=abs(a-b)+abs(b-c)+abs(a-c) print(min(res,res1)) ```
output
1
73,428
14
146,857
Provide tags and a correct Python 3 solution for this coding contest problem. Three friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox. In one minute each friend independently from other friends can change the position x by 1 to the left or by 1 to the right (i.e. set x := x - 1 or x := x + 1) or even don't change it. Let's introduce the total pairwise distance β€” the sum of distances between each pair of friends. Let a', b' and c' be the final positions of the first, the second and the third friend, correspondingly. Then the total pairwise distance is |a' - b'| + |a' - c'| + |b' - c'|, where |x| is the absolute value of x. Friends are interested in the minimum total pairwise distance they can reach if they will move optimally. Each friend will move no more than once. So, more formally, they want to know the minimum total pairwise distance they can reach after one minute. You have to answer q independent test cases. Input The first line of the input contains one integer q (1 ≀ q ≀ 1000) β€” the number of test cases. The next q lines describe test cases. The i-th test case is given as three integers a, b and c (1 ≀ a, b, c ≀ 10^9) β€” initial positions of the first, second and third friend correspondingly. The positions of friends can be equal. Output For each test case print the answer on it β€” the minimum total pairwise distance (the minimum sum of distances between each pair of friends) if friends change their positions optimally. Each friend will move no more than once. So, more formally, you have to find the minimum total pairwise distance they can reach after one minute. Example Input 8 3 3 4 10 20 30 5 5 5 2 4 3 1 1000000000 1000000000 1 1000000000 999999999 3 2 5 3 2 6 Output 0 36 0 0 1999999994 1999999994 2 4
instruction
0
73,429
14
146,858
Tags: brute force, greedy, math, sortings Correct Solution: ``` Q=int(input()) for q in range(0,Q): a,b,c=map(int, input().split()) if a==b and b==c: print(0) else: A=[] if a>b: A.append(a-b) else: A.append(b-a) if b>c: A.append(b-c) else: A.append(c-b) if c>a: A.append(c-a) else: A.append(a-c) s=sum(A) if s<=4: print(0) else: print(s-4) ```
output
1
73,429
14
146,859
Provide tags and a correct Python 3 solution for this coding contest problem. Three friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox. In one minute each friend independently from other friends can change the position x by 1 to the left or by 1 to the right (i.e. set x := x - 1 or x := x + 1) or even don't change it. Let's introduce the total pairwise distance β€” the sum of distances between each pair of friends. Let a', b' and c' be the final positions of the first, the second and the third friend, correspondingly. Then the total pairwise distance is |a' - b'| + |a' - c'| + |b' - c'|, where |x| is the absolute value of x. Friends are interested in the minimum total pairwise distance they can reach if they will move optimally. Each friend will move no more than once. So, more formally, they want to know the minimum total pairwise distance they can reach after one minute. You have to answer q independent test cases. Input The first line of the input contains one integer q (1 ≀ q ≀ 1000) β€” the number of test cases. The next q lines describe test cases. The i-th test case is given as three integers a, b and c (1 ≀ a, b, c ≀ 10^9) β€” initial positions of the first, second and third friend correspondingly. The positions of friends can be equal. Output For each test case print the answer on it β€” the minimum total pairwise distance (the minimum sum of distances between each pair of friends) if friends change their positions optimally. Each friend will move no more than once. So, more formally, you have to find the minimum total pairwise distance they can reach after one minute. Example Input 8 3 3 4 10 20 30 5 5 5 2 4 3 1 1000000000 1000000000 1 1000000000 999999999 3 2 5 3 2 6 Output 0 36 0 0 1999999994 1999999994 2 4
instruction
0
73,430
14
146,860
Tags: brute force, greedy, math, sortings Correct Solution: ``` import math for _ in range(int(input())): a , b , c = [int(x) for x in input().split()] k = (a+b+c)/3 k_c = math.ceil(k) k_f= math.floor(k) if k - k_f <.5: k = k_f else: k = k_c if a>k: a-=1 elif a<k: a+=1 if b>k: b-=1 elif b<k: b+=1 if c>k: c-=1 elif c<k: c+=1 print(abs(a-b)+abs(a-c)+abs(b-c)) ```
output
1
73,430
14
146,861
Provide tags and a correct Python 3 solution for this coding contest problem. Three friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox. In one minute each friend independently from other friends can change the position x by 1 to the left or by 1 to the right (i.e. set x := x - 1 or x := x + 1) or even don't change it. Let's introduce the total pairwise distance β€” the sum of distances between each pair of friends. Let a', b' and c' be the final positions of the first, the second and the third friend, correspondingly. Then the total pairwise distance is |a' - b'| + |a' - c'| + |b' - c'|, where |x| is the absolute value of x. Friends are interested in the minimum total pairwise distance they can reach if they will move optimally. Each friend will move no more than once. So, more formally, they want to know the minimum total pairwise distance they can reach after one minute. You have to answer q independent test cases. Input The first line of the input contains one integer q (1 ≀ q ≀ 1000) β€” the number of test cases. The next q lines describe test cases. The i-th test case is given as three integers a, b and c (1 ≀ a, b, c ≀ 10^9) β€” initial positions of the first, second and third friend correspondingly. The positions of friends can be equal. Output For each test case print the answer on it β€” the minimum total pairwise distance (the minimum sum of distances between each pair of friends) if friends change their positions optimally. Each friend will move no more than once. So, more formally, you have to find the minimum total pairwise distance they can reach after one minute. Example Input 8 3 3 4 10 20 30 5 5 5 2 4 3 1 1000000000 1000000000 1 1000000000 999999999 3 2 5 3 2 6 Output 0 36 0 0 1999999994 1999999994 2 4
instruction
0
73,431
14
146,862
Tags: brute force, greedy, math, sortings Correct Solution: ``` from math import * t=int(input()) for _ in range(t): a,b,c =map(int,input().split()) l=[a,b,c] l.sort() s=0 if l[0]==l[1] and l[1]==l[2]: pass elif l[0]!=l[1] and l[1]!=l[2]: l[0]=l[0]+1 l[2]=l[2]-1 elif l[0]==l[1] and l[1]!=l[2]: if l[2]-l[1]==1: l[2]=l[2]-1 else: l[2]=l[2]-1 l[0]=l[0]+1 l[1]=l[1]+1 elif l[1]==l[2] and l[0]!=l[1]: if l[1]-l[0]==1: l[0]=l[0]+1 else: l[0] = l[0] + 1 l[1]=l[1]-1 l[2]=l[2]-1 s = abs(l[1] - l[0]) + abs(l[2] - l[0]) + abs(l[2] - l[1]) print(s) ```
output
1
73,431
14
146,863
Provide tags and a correct Python 3 solution for this coding contest problem. Three friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox. In one minute each friend independently from other friends can change the position x by 1 to the left or by 1 to the right (i.e. set x := x - 1 or x := x + 1) or even don't change it. Let's introduce the total pairwise distance β€” the sum of distances between each pair of friends. Let a', b' and c' be the final positions of the first, the second and the third friend, correspondingly. Then the total pairwise distance is |a' - b'| + |a' - c'| + |b' - c'|, where |x| is the absolute value of x. Friends are interested in the minimum total pairwise distance they can reach if they will move optimally. Each friend will move no more than once. So, more formally, they want to know the minimum total pairwise distance they can reach after one minute. You have to answer q independent test cases. Input The first line of the input contains one integer q (1 ≀ q ≀ 1000) β€” the number of test cases. The next q lines describe test cases. The i-th test case is given as three integers a, b and c (1 ≀ a, b, c ≀ 10^9) β€” initial positions of the first, second and third friend correspondingly. The positions of friends can be equal. Output For each test case print the answer on it β€” the minimum total pairwise distance (the minimum sum of distances between each pair of friends) if friends change their positions optimally. Each friend will move no more than once. So, more formally, you have to find the minimum total pairwise distance they can reach after one minute. Example Input 8 3 3 4 10 20 30 5 5 5 2 4 3 1 1000000000 1000000000 1 1000000000 999999999 3 2 5 3 2 6 Output 0 36 0 0 1999999994 1999999994 2 4
instruction
0
73,432
14
146,864
Tags: brute force, greedy, math, sortings Correct Solution: ``` q = int(input()) for i in range(q): a, b, c = map(int, input().split()) minimum = min(a, b, c) maximum = max(a, b, c) if maximum - minimum < 2: print(0) else: print(((maximum - 1) - (minimum + 1)) * 2) ```
output
1
73,432
14
146,865
Provide tags and a correct Python 3 solution for this coding contest problem. Three friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox. In one minute each friend independently from other friends can change the position x by 1 to the left or by 1 to the right (i.e. set x := x - 1 or x := x + 1) or even don't change it. Let's introduce the total pairwise distance β€” the sum of distances between each pair of friends. Let a', b' and c' be the final positions of the first, the second and the third friend, correspondingly. Then the total pairwise distance is |a' - b'| + |a' - c'| + |b' - c'|, where |x| is the absolute value of x. Friends are interested in the minimum total pairwise distance they can reach if they will move optimally. Each friend will move no more than once. So, more formally, they want to know the minimum total pairwise distance they can reach after one minute. You have to answer q independent test cases. Input The first line of the input contains one integer q (1 ≀ q ≀ 1000) β€” the number of test cases. The next q lines describe test cases. The i-th test case is given as three integers a, b and c (1 ≀ a, b, c ≀ 10^9) β€” initial positions of the first, second and third friend correspondingly. The positions of friends can be equal. Output For each test case print the answer on it β€” the minimum total pairwise distance (the minimum sum of distances between each pair of friends) if friends change their positions optimally. Each friend will move no more than once. So, more formally, you have to find the minimum total pairwise distance they can reach after one minute. Example Input 8 3 3 4 10 20 30 5 5 5 2 4 3 1 1000000000 1000000000 1 1000000000 999999999 3 2 5 3 2 6 Output 0 36 0 0 1999999994 1999999994 2 4
instruction
0
73,433
14
146,866
Tags: brute force, greedy, math, sortings Correct Solution: ``` def main(): q = int(input()) for i in range(q): nums = list(map(int,input().split())) nums.sort() if nums[-1] == nums[1] and nums[0] != nums[1]: nums[-1] -= 1 nums[1] -= 1 if nums[0] == nums[1] and nums[1] != nums[-1]: nums[0] += 1 nums[1] += 1 if nums[0] != nums[1]: nums[0] += 1 if nums[-1] != nums[1]: nums[-1] -= 1 #print(nums) print(nums[1]-nums[0]+nums[-1]-nums[1]+nums[-1]-nums[0]) main() ```
output
1
73,433
14
146,867
Provide tags and a correct Python 3 solution for this coding contest problem. Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. <image> Recently Xenia has bought n_r red gems, n_g green gems and n_b blue gems. Each of the gems has a weight. Now, she is going to pick three gems. Xenia loves colorful things, so she will pick exactly one gem of each color. Xenia loves balance, so she will try to pick gems with little difference in weight. Specifically, supposing the weights of the picked gems are x, y and z, Xenia wants to find the minimum value of (x-y)^2+(y-z)^2+(z-x)^2. As her dear friend, can you help her? Input The first line contains a single integer t (1≀ t ≀ 100) β€” the number of test cases. Then t test cases follow. The first line of each test case contains three integers n_r,n_g,n_b (1≀ n_r,n_g,n_b≀ 10^5) β€” the number of red gems, green gems and blue gems respectively. The second line of each test case contains n_r integers r_1,r_2,…,r_{n_r} (1≀ r_i ≀ 10^9) β€” r_i is the weight of the i-th red gem. The third line of each test case contains n_g integers g_1,g_2,…,g_{n_g} (1≀ g_i ≀ 10^9) β€” g_i is the weight of the i-th green gem. The fourth line of each test case contains n_b integers b_1,b_2,…,b_{n_b} (1≀ b_i ≀ 10^9) β€” b_i is the weight of the i-th blue gem. It is guaranteed that βˆ‘ n_r ≀ 10^5, βˆ‘ n_g ≀ 10^5, βˆ‘ n_b ≀ 10^5 (the sum for all test cases). Output For each test case, print a line contains one integer β€” the minimum value which Xenia wants to find. Example Input 5 2 2 3 7 8 6 3 3 1 4 1 1 1 1 1 1000000000 2 2 2 1 2 5 4 6 7 2 2 2 1 2 3 4 6 7 3 4 1 3 2 1 7 3 3 4 6 Output 14 1999999996000000002 24 24 14 Note In the first test case, Xenia has the following gems: <image> If she picks the red gem with weight 7, the green gem with weight 6, and the blue gem with weight 4, she will achieve the most balanced selection with (x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14.
instruction
0
73,474
14
146,948
Tags: binary search, greedy, math, sortings, two pointers Correct Solution: ``` t = int(input()) def fun(x,y,z): return (x-y)**2+(y-z)**2+(z-x)**2 def partialbest(red, green, blue): ind_green_maggiore = 0 ind_blue_maggiore_l = 0 ind_blue_maggiore_r = 0 min_value = fun(red[0],green[0],blue[0]) for j in range(len(red)): k = ind_green_maggiore while k<len(green): if green[k] >= red[j]: break k = k+1 if k < len(green): l = ind_blue_maggiore_l while l < len(blue): if blue[l] >= int((green[k]+red[j])/2): break l = l + 1 if l < len(blue): min_value = min(min_value,fun(red[j],green[k],blue[l])) ind_blue_maggiore_l = l if l>=1: min_value = min(min_value,fun(red[j],green[k],blue[l-1])) ind_blue_maggiore_l = l-1 ind_green_maggiore = k if k >=1: l = ind_blue_maggiore_r while l < len(blue): if blue[l] >= int((green[k-1]+red[j])/2): break l = l + 1 if l < len(blue): min_value = min(min_value,fun(red[j],green[k-1],blue[l])) ind_blue_maggiore_r = l if l>=1: min_value = min(min_value,fun(red[j],green[k-1],blue[l-1])) ind_blue_maggiore_r = l-1 ind_green_maggiore = k-1 if green[-1] <= red[j]: if blue[-1] <= int((green[-1]+red[j])/2): min_value = min(min_value,fun(red[j],green[-1],blue[-1])) l = ind_blue_maggiore_l while l < len(blue): if blue[l] >= int((green[-1]+red[j])/2): break l = l+1 if l< len(blue): min_value = min(min_value,fun(red[j],green[-1],blue[l])) ind_blue_maggiore_l = l if l>=1: min_value = min(min_value,fun(red[j],green[-1],blue[l-1])) ind_blue_maggiore_l = l-1 return min_value for i in range(t): values = [int(j) for j in input().split()] red = [int(j) for j in input().split()] green = [int(j) for j in input().split()] blue = [int(j) for j in input().split()] red = list(set(red)) green = list(set(green)) blue = list(set(blue)) red.sort() green.sort() blue.sort() print(min(partialbest(red, green, blue), partialbest(red,blue, green))) ```
output
1
73,474
14
146,949
Provide tags and a correct Python 3 solution for this coding contest problem. Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. <image> Recently Xenia has bought n_r red gems, n_g green gems and n_b blue gems. Each of the gems has a weight. Now, she is going to pick three gems. Xenia loves colorful things, so she will pick exactly one gem of each color. Xenia loves balance, so she will try to pick gems with little difference in weight. Specifically, supposing the weights of the picked gems are x, y and z, Xenia wants to find the minimum value of (x-y)^2+(y-z)^2+(z-x)^2. As her dear friend, can you help her? Input The first line contains a single integer t (1≀ t ≀ 100) β€” the number of test cases. Then t test cases follow. The first line of each test case contains three integers n_r,n_g,n_b (1≀ n_r,n_g,n_b≀ 10^5) β€” the number of red gems, green gems and blue gems respectively. The second line of each test case contains n_r integers r_1,r_2,…,r_{n_r} (1≀ r_i ≀ 10^9) β€” r_i is the weight of the i-th red gem. The third line of each test case contains n_g integers g_1,g_2,…,g_{n_g} (1≀ g_i ≀ 10^9) β€” g_i is the weight of the i-th green gem. The fourth line of each test case contains n_b integers b_1,b_2,…,b_{n_b} (1≀ b_i ≀ 10^9) β€” b_i is the weight of the i-th blue gem. It is guaranteed that βˆ‘ n_r ≀ 10^5, βˆ‘ n_g ≀ 10^5, βˆ‘ n_b ≀ 10^5 (the sum for all test cases). Output For each test case, print a line contains one integer β€” the minimum value which Xenia wants to find. Example Input 5 2 2 3 7 8 6 3 3 1 4 1 1 1 1 1 1000000000 2 2 2 1 2 5 4 6 7 2 2 2 1 2 3 4 6 7 3 4 1 3 2 1 7 3 3 4 6 Output 14 1999999996000000002 24 24 14 Note In the first test case, Xenia has the following gems: <image> If she picks the red gem with weight 7, the green gem with weight 6, and the blue gem with weight 4, she will achieve the most balanced selection with (x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14.
instruction
0
73,475
14
146,950
Tags: binary search, greedy, math, sortings, two pointers Correct Solution: ``` import bisect ans=10000000000000000000 def tempCalc(r,b,g): return (r-b)**2 +(r-g)**2+(b-g)**2 def getLow(p, x ): l = 0 r = len(p) while r-l>1: m = (l + r) // 2 if p[m] <= x: l = m else: r = m return p[l] def getHigh(p,x): l = -1 r = len(p)-1 while r - l > 1: m = (l + r) // 2 if (p[m] < x): l = m else: r = m return p[r] def solve(a,b,c): global ans for i in a: a1=tempCalc(i,getHigh(b,i),getLow(c, i)) a2=tempCalc(i,getHigh(c,i),getLow(b, i)) ans=min(ans,a1,a2) t = int(input()) for i in range(0,t): ans=0xFFFFFFFFFFFFFFFF cnt = [int(f) for f in input().split()] r=[int(f) for f in input().split()] b=[int(f) for f in input().split()] g=[int(f) for f in input().split()] r.sort() b.sort() g.sort() solve(r,g,b) solve(r,b,g) solve(g,b,r) solve(g,r,b) solve(b,g,r) solve(b,r,g) print(ans) ```
output
1
73,475
14
146,951
Provide tags and a correct Python 3 solution for this coding contest problem. Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. <image> Recently Xenia has bought n_r red gems, n_g green gems and n_b blue gems. Each of the gems has a weight. Now, she is going to pick three gems. Xenia loves colorful things, so she will pick exactly one gem of each color. Xenia loves balance, so she will try to pick gems with little difference in weight. Specifically, supposing the weights of the picked gems are x, y and z, Xenia wants to find the minimum value of (x-y)^2+(y-z)^2+(z-x)^2. As her dear friend, can you help her? Input The first line contains a single integer t (1≀ t ≀ 100) β€” the number of test cases. Then t test cases follow. The first line of each test case contains three integers n_r,n_g,n_b (1≀ n_r,n_g,n_b≀ 10^5) β€” the number of red gems, green gems and blue gems respectively. The second line of each test case contains n_r integers r_1,r_2,…,r_{n_r} (1≀ r_i ≀ 10^9) β€” r_i is the weight of the i-th red gem. The third line of each test case contains n_g integers g_1,g_2,…,g_{n_g} (1≀ g_i ≀ 10^9) β€” g_i is the weight of the i-th green gem. The fourth line of each test case contains n_b integers b_1,b_2,…,b_{n_b} (1≀ b_i ≀ 10^9) β€” b_i is the weight of the i-th blue gem. It is guaranteed that βˆ‘ n_r ≀ 10^5, βˆ‘ n_g ≀ 10^5, βˆ‘ n_b ≀ 10^5 (the sum for all test cases). Output For each test case, print a line contains one integer β€” the minimum value which Xenia wants to find. Example Input 5 2 2 3 7 8 6 3 3 1 4 1 1 1 1 1 1000000000 2 2 2 1 2 5 4 6 7 2 2 2 1 2 3 4 6 7 3 4 1 3 2 1 7 3 3 4 6 Output 14 1999999996000000002 24 24 14 Note In the first test case, Xenia has the following gems: <image> If she picks the red gem with weight 7, the green gem with weight 6, and the blue gem with weight 4, she will achieve the most balanced selection with (x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14.
instruction
0
73,476
14
146,952
Tags: binary search, greedy, math, sortings, two pointers Correct Solution: ``` from bisect import bisect_left from itertools import permutations import sys input = sys.stdin.readline def calc(aa, bb, cc): i = j = 0 ans = float('inf') while j < len(bb): while i+1 < len(aa) and aa[i+1] <= bb[j]: i += 1 x, y = aa[i], bb[j] k = bisect_left(cc, y) if k < len(cc) and y <= cc[k]: z = cc[k] ans = min(ans, (x-y)**2 + (y-z)**2 + (z-x)**2) j += 1 return ans t = int(input()) for _ in range(t): nr, ng, nb = map(int, input().split()) r = list(map(int, input().split())) g = list(map(int, input().split())) b = list(map(int, input().split())) r.sort() g.sort() b.sort() ans = float('inf') for perm in permutations([r, g, b]): ans = min(ans, calc(*perm)) print(ans) ```
output
1
73,476
14
146,953
Provide tags and a correct Python 3 solution for this coding contest problem. Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. <image> Recently Xenia has bought n_r red gems, n_g green gems and n_b blue gems. Each of the gems has a weight. Now, she is going to pick three gems. Xenia loves colorful things, so she will pick exactly one gem of each color. Xenia loves balance, so she will try to pick gems with little difference in weight. Specifically, supposing the weights of the picked gems are x, y and z, Xenia wants to find the minimum value of (x-y)^2+(y-z)^2+(z-x)^2. As her dear friend, can you help her? Input The first line contains a single integer t (1≀ t ≀ 100) β€” the number of test cases. Then t test cases follow. The first line of each test case contains three integers n_r,n_g,n_b (1≀ n_r,n_g,n_b≀ 10^5) β€” the number of red gems, green gems and blue gems respectively. The second line of each test case contains n_r integers r_1,r_2,…,r_{n_r} (1≀ r_i ≀ 10^9) β€” r_i is the weight of the i-th red gem. The third line of each test case contains n_g integers g_1,g_2,…,g_{n_g} (1≀ g_i ≀ 10^9) β€” g_i is the weight of the i-th green gem. The fourth line of each test case contains n_b integers b_1,b_2,…,b_{n_b} (1≀ b_i ≀ 10^9) β€” b_i is the weight of the i-th blue gem. It is guaranteed that βˆ‘ n_r ≀ 10^5, βˆ‘ n_g ≀ 10^5, βˆ‘ n_b ≀ 10^5 (the sum for all test cases). Output For each test case, print a line contains one integer β€” the minimum value which Xenia wants to find. Example Input 5 2 2 3 7 8 6 3 3 1 4 1 1 1 1 1 1000000000 2 2 2 1 2 5 4 6 7 2 2 2 1 2 3 4 6 7 3 4 1 3 2 1 7 3 3 4 6 Output 14 1999999996000000002 24 24 14 Note In the first test case, Xenia has the following gems: <image> If she picks the red gem with weight 7, the green gem with weight 6, and the blue gem with weight 4, she will achieve the most balanced selection with (x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14.
instruction
0
73,477
14
146,954
Tags: binary search, greedy, math, sortings, two pointers Correct Solution: ``` # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------- fast io -------------------- from bisect import bisect_left as bis def dist(p1,p2,p3): a1=(p1-p2) a2=(p1-p3) a3=(p2-p3) return (a1*a1 +a2*a2 +a3*a3) def mindist(red,green,blue): r=len(red);g=len(green);b=len(blue) minsofar=dist(red[0],green[0],blue[0]) for s in range(r): #4 cases p1=red[s] #case 1(00) c1ind1=min(bis(green,p1),g-1);c1ind2=min(bis(blue,p1),b-1) if c1ind1>0 and green[c1ind1]>p1: c1ind1-=1 if c1ind2>0 and blue[c1ind2]>p1: c1ind2-=1 c1p2=green[c1ind1];c1p3=blue[c1ind2];d1=dist(p1,c1p2,c1p3);minsofar=min(minsofar,d1) #case 2(10) c2ind1=min(bis(green,p1),g-1);c2ind2=min(bis(blue,p1),b-1) if c2ind2>0 and blue[c2ind2]>p1: c2ind2-=1 c2p2=green[c2ind1];c2p3=blue[c2ind2];d2=dist(p1,c2p2,c2p3);minsofar=min(minsofar,d2) #case 3(01) c3ind1=min(bis(green,p1),g-1);c3ind2=min(bis(blue,p1),b-1) if c3ind1>0 and green[c3ind1]>p1: c3ind1-=1 c3p2=green[c3ind1];c3p3=blue[c3ind2];d3=dist(p1,c3p2,c3p3);minsofar=min(minsofar,d3) #case 4(11) c4ind1=min(bis(green,p1),g-1);c4ind2=min(bis(blue,p1),b-1) c4p2=green[c4ind1];c4p3=blue[c4ind2];d4=dist(p1,c4p2,c4p3);minsofar=min(minsofar,d4) return minsofar for j in range(int(input())): r,g,b=map(int,input().split()) red=list(map(int,input().split())) green=list(map(int,input().split())) blue=list(map(int,input().split())) red.sort();green.sort();blue.sort() minr=mindist(red,green,blue);ming=mindist(green,red,blue);minb=mindist(blue,red,green) print(min(minr,ming,minb)) ```
output
1
73,477
14
146,955