text
stringlengths
198
433k
conversation_id
int64
0
109k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya likes everything infinite. Now he is studying the properties of a sequence s, such that its first element is equal to a (s1 = a), and the difference between any two neighbouring elements is equal to c (si - si - 1 = c). In particular, Vasya wonders if his favourite integer b appears in this sequence, that is, there exists a positive integer i, such that si = b. Of course, you are the person he asks for a help. Input The first line of the input contain three integers a, b and c ( - 109 ≀ a, b, c ≀ 109) β€” the first element of the sequence, Vasya's favorite number and the difference between any two neighbouring elements of the sequence, respectively. Output If b appears in the sequence s print "YES" (without quotes), otherwise print "NO" (without quotes). Examples Input 1 7 3 Output YES Input 10 10 0 Output YES Input 1 -4 5 Output NO Input 0 60 50 Output NO Note In the first sample, the sequence starts from integers 1, 4, 7, so 7 is its element. In the second sample, the favorite integer of Vasya is equal to the first element of the sequence. In the third sample all elements of the sequence are greater than Vasya's favorite integer. In the fourth sample, the sequence starts from 0, 50, 100, and all the following elements are greater than Vasya's favorite integer. Submitted Solution: ``` a,b,c=map(int,input().split()) if c==0 and a==b:exit(print("YES")) elif c==0 and a!=b:exit(print("NO")) l,r=0,10**9 while l<=r: mid=(l+r)//2 s=a+mid*c if s==b:exit(print("YES")) elif s>b:r=mid-1 else:l=mid+1 print("NO") ``` No
99,100
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya likes everything infinite. Now he is studying the properties of a sequence s, such that its first element is equal to a (s1 = a), and the difference between any two neighbouring elements is equal to c (si - si - 1 = c). In particular, Vasya wonders if his favourite integer b appears in this sequence, that is, there exists a positive integer i, such that si = b. Of course, you are the person he asks for a help. Input The first line of the input contain three integers a, b and c ( - 109 ≀ a, b, c ≀ 109) β€” the first element of the sequence, Vasya's favorite number and the difference between any two neighbouring elements of the sequence, respectively. Output If b appears in the sequence s print "YES" (without quotes), otherwise print "NO" (without quotes). Examples Input 1 7 3 Output YES Input 10 10 0 Output YES Input 1 -4 5 Output NO Input 0 60 50 Output NO Note In the first sample, the sequence starts from integers 1, 4, 7, so 7 is its element. In the second sample, the favorite integer of Vasya is equal to the first element of the sequence. In the third sample all elements of the sequence are greater than Vasya's favorite integer. In the fourth sample, the sequence starts from 0, 50, 100, and all the following elements are greater than Vasya's favorite integer. Submitted Solution: ``` a, b, c = (int(s) for s in input().strip().split()) if a==b: print('YES') elif c==0: print('NO') if a > b: c = -c a, b = b, a if c > 0 and (b-a)%c == 0: print('YES') else: print('NO') ``` No
99,101
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya likes everything infinite. Now he is studying the properties of a sequence s, such that its first element is equal to a (s1 = a), and the difference between any two neighbouring elements is equal to c (si - si - 1 = c). In particular, Vasya wonders if his favourite integer b appears in this sequence, that is, there exists a positive integer i, such that si = b. Of course, you are the person he asks for a help. Input The first line of the input contain three integers a, b and c ( - 109 ≀ a, b, c ≀ 109) β€” the first element of the sequence, Vasya's favorite number and the difference between any two neighbouring elements of the sequence, respectively. Output If b appears in the sequence s print "YES" (without quotes), otherwise print "NO" (without quotes). Examples Input 1 7 3 Output YES Input 10 10 0 Output YES Input 1 -4 5 Output NO Input 0 60 50 Output NO Note In the first sample, the sequence starts from integers 1, 4, 7, so 7 is its element. In the second sample, the favorite integer of Vasya is equal to the first element of the sequence. In the third sample all elements of the sequence are greater than Vasya's favorite integer. In the fourth sample, the sequence starts from 0, 50, 100, and all the following elements are greater than Vasya's favorite integer. Submitted Solution: ``` a,b,c = list(map(int,input().rstrip().split())) if c==0: if a==b: print("YES") else: print("NO") else: if (b-a)%c==0 and b-a>0: print("YES") else: print("NO") ``` No
99,102
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a description of a depot. It is a rectangular checkered field of n Γ— m size. Each cell in a field can be empty (".") or it can be occupied by a wall ("*"). You have one bomb. If you lay the bomb at the cell (x, y), then after triggering it will wipe out all walls in the row x and all walls in the column y. You are to determine if it is possible to wipe out all walls in the depot by placing and triggering exactly one bomb. The bomb can be laid both in an empty cell or in a cell occupied by a wall. Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 1000) β€” the number of rows and columns in the depot field. The next n lines contain m symbols "." and "*" each β€” the description of the field. j-th symbol in i-th of them stands for cell (i, j). If the symbol is equal to ".", then the corresponding cell is empty, otherwise it equals "*" and the corresponding cell is occupied by a wall. Output If it is impossible to wipe out all walls by placing and triggering exactly one bomb, then print "NO" in the first line (without quotes). Otherwise print "YES" (without quotes) in the first line and two integers in the second line β€” the coordinates of the cell at which the bomb should be laid. If there are multiple answers, print any of them. Examples Input 3 4 .*.. .... .*.. Output YES 1 2 Input 3 3 ..* .*. *.. Output NO Input 6 5 ..*.. ..*.. ***** ..*.. ..*.. ..*.. Output YES 3 3 Tags: implementation Correct Solution: ``` n, m = tuple(map(int, input().split())) rows = {} cols = {} walls = 0 for i in range(n): line = input() for j in range(m): if line[j] == '*': walls += 1 if i in rows: rows[i].append(j) else: rows[i] = [j] if j in cols: cols[j].append(i) else: cols[j] = [i] def get_def(d): ans = -1 for c in d: if len(d[c]) > 1: if ans != -1: return -10 #BAD ans = c return ans dr = get_def(rows) dc = get_def(cols) if dr == -10 or dc == -10: #Definitively impossible print("NO") elif dr != -1 and dc != -1: ok = True for r in rows: if r == dr: continue for c in rows[r]: if c != dc: ok = False for c in cols: if c == dc: continue for r in cols[c]: if r != dr: ok = False if not ok: print("NO") else: print("YES") print(str(dr + 1) + " " + str(dc + 1)) elif dr == -1 and dc == -1: if len(rows) > 2 or len(cols) > 2: print("NO") else: print("YES") rs = list(rows.keys()) cs = list(cols.keys()) if len(rows) == 0 and len(cols) == 0: print("1 1") elif len(rows) == 1: print(str(cols[cs[0]][0] + 1) + ' 1') else: r = min(cols[cs[0]][0], cols[cs[1]][0]) if r == rs[0]: c = rows[rs[1]][0] else: c = rows[rs[0]][0] print(str(r + 1) + ' ' + str(c + 1)) else: if dr == -1: g = dc src = cols else: g = dr src = rows ok = True v = -1 for a in src: if a == g: continue if v == -1: v = src[a][0] elif src[a][0] != v: ok = False break if not ok: print("NO") else: print("YES") if v == -1: v = 0 if dr == -1: print(str(v + 1) + ' ' + str(dc + 1)) else: print(str(dr + 1) + ' ' + str(v + 1)) ```
99,103
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a description of a depot. It is a rectangular checkered field of n Γ— m size. Each cell in a field can be empty (".") or it can be occupied by a wall ("*"). You have one bomb. If you lay the bomb at the cell (x, y), then after triggering it will wipe out all walls in the row x and all walls in the column y. You are to determine if it is possible to wipe out all walls in the depot by placing and triggering exactly one bomb. The bomb can be laid both in an empty cell or in a cell occupied by a wall. Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 1000) β€” the number of rows and columns in the depot field. The next n lines contain m symbols "." and "*" each β€” the description of the field. j-th symbol in i-th of them stands for cell (i, j). If the symbol is equal to ".", then the corresponding cell is empty, otherwise it equals "*" and the corresponding cell is occupied by a wall. Output If it is impossible to wipe out all walls by placing and triggering exactly one bomb, then print "NO" in the first line (without quotes). Otherwise print "YES" (without quotes) in the first line and two integers in the second line β€” the coordinates of the cell at which the bomb should be laid. If there are multiple answers, print any of them. Examples Input 3 4 .*.. .... .*.. Output YES 1 2 Input 3 3 ..* .*. *.. Output NO Input 6 5 ..*.. ..*.. ***** ..*.. ..*.. ..*.. Output YES 3 3 Tags: implementation Correct Solution: ``` """ Code of Ayush Tiwari Codechef: ayush572000 Codeforces: servermonk """ # import sys # input = sys.stdin.buffer.readline def solution(): n,m=map(int,input().split()) l=[] r=[0]*1001 c=[0]*1001 cnt=0 for i in range(n): x=list(input()) # print(x) for j in range(m): if x[j]=='*': cnt+=1 r[i]+=1 c[j]+=1 l.append(x) # print(cnt) for i in range(n): for j in range(m): x=r[i]+c[j] if l[i][j]=='*': x-=1 if x==cnt: print('YES') print(i+1,j+1) exit(0) print('NO') solution() ```
99,104
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a description of a depot. It is a rectangular checkered field of n Γ— m size. Each cell in a field can be empty (".") or it can be occupied by a wall ("*"). You have one bomb. If you lay the bomb at the cell (x, y), then after triggering it will wipe out all walls in the row x and all walls in the column y. You are to determine if it is possible to wipe out all walls in the depot by placing and triggering exactly one bomb. The bomb can be laid both in an empty cell or in a cell occupied by a wall. Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 1000) β€” the number of rows and columns in the depot field. The next n lines contain m symbols "." and "*" each β€” the description of the field. j-th symbol in i-th of them stands for cell (i, j). If the symbol is equal to ".", then the corresponding cell is empty, otherwise it equals "*" and the corresponding cell is occupied by a wall. Output If it is impossible to wipe out all walls by placing and triggering exactly one bomb, then print "NO" in the first line (without quotes). Otherwise print "YES" (without quotes) in the first line and two integers in the second line β€” the coordinates of the cell at which the bomb should be laid. If there are multiple answers, print any of them. Examples Input 3 4 .*.. .... .*.. Output YES 1 2 Input 3 3 ..* .*. *.. Output NO Input 6 5 ..*.. ..*.. ***** ..*.. ..*.. ..*.. Output YES 3 3 Tags: implementation Correct Solution: ``` import sys;input = sys.stdin.readline;print = sys.stdout.write def main(): n, m = map(int, input().split()) arr, have, dpx, dpy, cnt = [0]*n, set(), [0]*n, [0]*m, 0 for i in range(n): arr[i] = input().rstrip() for j in range(m): if arr[i][j] == "*": dpx[i], dpy[j], cnt = dpx[i] + 1, dpy[j] + 1, cnt + 1 for i in range(n): for j in range(m): if dpx[i] + dpy[j] - (arr[i][j] == "*") == cnt: print("YES\n{0} {1}".format(i + 1, j + 1)), exit(0) print("NO") main() ```
99,105
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a description of a depot. It is a rectangular checkered field of n Γ— m size. Each cell in a field can be empty (".") or it can be occupied by a wall ("*"). You have one bomb. If you lay the bomb at the cell (x, y), then after triggering it will wipe out all walls in the row x and all walls in the column y. You are to determine if it is possible to wipe out all walls in the depot by placing and triggering exactly one bomb. The bomb can be laid both in an empty cell or in a cell occupied by a wall. Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 1000) β€” the number of rows and columns in the depot field. The next n lines contain m symbols "." and "*" each β€” the description of the field. j-th symbol in i-th of them stands for cell (i, j). If the symbol is equal to ".", then the corresponding cell is empty, otherwise it equals "*" and the corresponding cell is occupied by a wall. Output If it is impossible to wipe out all walls by placing and triggering exactly one bomb, then print "NO" in the first line (without quotes). Otherwise print "YES" (without quotes) in the first line and two integers in the second line β€” the coordinates of the cell at which the bomb should be laid. If there are multiple answers, print any of them. Examples Input 3 4 .*.. .... .*.. Output YES 1 2 Input 3 3 ..* .*. *.. Output NO Input 6 5 ..*.. ..*.. ***** ..*.. ..*.. ..*.. Output YES 3 3 Tags: implementation Correct Solution: ``` n,m=[int(x) for x in input().split()] depot=[] r=[] c=[] flag=True for i in range(n): row=input() r.append(row.count('*')) depot.append(row) for j in range(m): column=''.join([x[j] for x in depot]) c.append(column.count('*')) wall=sum(r) for i in range(n): for j in range(m): if depot[i][j]=='*': bomb=r[i]+c[j]-1 else: bomb=r[i]+c[j] if bomb==wall: print('YES') print(i+1,j+1) flag=False break if not flag: break if flag: print('NO') ```
99,106
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a description of a depot. It is a rectangular checkered field of n Γ— m size. Each cell in a field can be empty (".") or it can be occupied by a wall ("*"). You have one bomb. If you lay the bomb at the cell (x, y), then after triggering it will wipe out all walls in the row x and all walls in the column y. You are to determine if it is possible to wipe out all walls in the depot by placing and triggering exactly one bomb. The bomb can be laid both in an empty cell or in a cell occupied by a wall. Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 1000) β€” the number of rows and columns in the depot field. The next n lines contain m symbols "." and "*" each β€” the description of the field. j-th symbol in i-th of them stands for cell (i, j). If the symbol is equal to ".", then the corresponding cell is empty, otherwise it equals "*" and the corresponding cell is occupied by a wall. Output If it is impossible to wipe out all walls by placing and triggering exactly one bomb, then print "NO" in the first line (without quotes). Otherwise print "YES" (without quotes) in the first line and two integers in the second line β€” the coordinates of the cell at which the bomb should be laid. If there are multiple answers, print any of them. Examples Input 3 4 .*.. .... .*.. Output YES 1 2 Input 3 3 ..* .*. *.. Output NO Input 6 5 ..*.. ..*.. ***** ..*.. ..*.. ..*.. Output YES 3 3 Tags: implementation Correct Solution: ``` def bombs(array, rows, cols, walls, wallsInRows, wallsInCols): if walls == 0: print("YES") print(1, 1) return for i in range(0, rows): for j in range(0, cols): s = wallsInRows[i] + wallsInCols[j] if (array[i][j] == '*' and s - 1 == walls) or (array[i][j] == "." and s == walls): print("YES") print(i + 1, j + 1) return print("NO") return def readArray(): k = input().split(" ") rows, cols = int(k[0]), int(k[1]) array = [] wallsInRows = [] wallsInCols = [0 for i in range(0, cols)] walls = 0 for i in range(0, rows): array.append(list(input())) wallsInRows.append(0) for j in range(0, cols): if array[i][j] == "*": wallsInRows[i] += 1 wallsInCols[j] += 1 walls += 1 return array, rows, cols, walls, wallsInRows, wallsInCols array, rows, cols, walls, wallsInRows, wallsInCols = readArray() bombs(array, rows, cols, walls, wallsInRows, wallsInCols) ```
99,107
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a description of a depot. It is a rectangular checkered field of n Γ— m size. Each cell in a field can be empty (".") or it can be occupied by a wall ("*"). You have one bomb. If you lay the bomb at the cell (x, y), then after triggering it will wipe out all walls in the row x and all walls in the column y. You are to determine if it is possible to wipe out all walls in the depot by placing and triggering exactly one bomb. The bomb can be laid both in an empty cell or in a cell occupied by a wall. Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 1000) β€” the number of rows and columns in the depot field. The next n lines contain m symbols "." and "*" each β€” the description of the field. j-th symbol in i-th of them stands for cell (i, j). If the symbol is equal to ".", then the corresponding cell is empty, otherwise it equals "*" and the corresponding cell is occupied by a wall. Output If it is impossible to wipe out all walls by placing and triggering exactly one bomb, then print "NO" in the first line (without quotes). Otherwise print "YES" (without quotes) in the first line and two integers in the second line β€” the coordinates of the cell at which the bomb should be laid. If there are multiple answers, print any of them. Examples Input 3 4 .*.. .... .*.. Output YES 1 2 Input 3 3 ..* .*. *.. Output NO Input 6 5 ..*.. ..*.. ***** ..*.. ..*.. ..*.. Output YES 3 3 Tags: implementation Correct Solution: ``` n, m = map(int, input().split()) a = [input() for i in range(n)] x = [0] * n y = [0] * m cnt = 0 for i in range(n): for j in range(m): if a[i][j] == '*': x[i] += 1 y[j] += 1 cnt += 1 for i in range(n): for j in range(m): cur = x[i] + y[j] - (a[i][j] == '*') if cur == cnt: print('YES') print(i + 1, j + 1) exit() print('NO') ```
99,108
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a description of a depot. It is a rectangular checkered field of n Γ— m size. Each cell in a field can be empty (".") or it can be occupied by a wall ("*"). You have one bomb. If you lay the bomb at the cell (x, y), then after triggering it will wipe out all walls in the row x and all walls in the column y. You are to determine if it is possible to wipe out all walls in the depot by placing and triggering exactly one bomb. The bomb can be laid both in an empty cell or in a cell occupied by a wall. Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 1000) β€” the number of rows and columns in the depot field. The next n lines contain m symbols "." and "*" each β€” the description of the field. j-th symbol in i-th of them stands for cell (i, j). If the symbol is equal to ".", then the corresponding cell is empty, otherwise it equals "*" and the corresponding cell is occupied by a wall. Output If it is impossible to wipe out all walls by placing and triggering exactly one bomb, then print "NO" in the first line (without quotes). Otherwise print "YES" (without quotes) in the first line and two integers in the second line β€” the coordinates of the cell at which the bomb should be laid. If there are multiple answers, print any of them. Examples Input 3 4 .*.. .... .*.. Output YES 1 2 Input 3 3 ..* .*. *.. Output NO Input 6 5 ..*.. ..*.. ***** ..*.. ..*.. ..*.. Output YES 3 3 Tags: implementation Correct Solution: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- import sys from collections import Counter numrow, numcol = sys.stdin.readline().split(' ') numrow = int(numrow) numcol = int(numcol) #line = sys.stdin.readline() # stores the row and col indices of each * symbol row_index = [] col_index = [] row_counts = [0] * numrow col_counts = [0] * numcol row_highest = [] col_highest = [] row_highest_count = 0 col_highest_count = 0 for i in range(numrow): line = sys.stdin.readline().strip() for j in range(numcol): if line[j] == '*': row_counts[i] += 1 col_counts[j] += 1 row_index.append(i) col_index.append(j) if i == numrow-1: if (col_counts[j] > col_highest_count): col_highest_count = col_counts[j] col_highest = [j] elif(col_counts[j] == col_highest_count): col_highest.append(j) if (row_counts[i] > row_highest_count): row_highest_count = row_counts[i] row_highest = [i] elif (row_counts[i] == row_highest_count): row_highest.append(i) if (len(row_index) == 0): print ("YES") print ("1 1") elif (len(row_index) == 1): print ("YES") print (row_index[0]+1, col_index[0]+1) elif (len(row_index) == 2): print("YES") print (row_index[0]+1, col_index[1]+1) elif (row_highest_count >= 2 and len(row_highest) > 1): print ("NO") elif (col_highest_count >= 2 and len(col_highest) > 1): print ("NO") elif (len(row_index) > (numrow+numcol-1)): print ("NO") else: if (row_highest_count >= col_highest_count): for row_h in row_highest[:2]: goodCol = -1 for star in range(len(row_index)): if (row_index[star] != row_h and goodCol < 0): goodCol = col_index[star] elif (row_index[star] != row_h and goodCol != col_index[star]): print ("NO") sys.exit(0) print ("YES") print (row_h+1, max(goodCol+1, 1)) else: for col_h in col_highest[:2]: goodRow = -1 for star in range(len(row_index)): if (col_index[star] != col_h and goodRow < 0): goodRow = row_index[star] elif (col_index[star] != col_h and goodRow != row_index[star]): print ("NO") sys.exit(0) print ("YES") print (max(goodRow+1, 1), col_h+1) ```
99,109
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a description of a depot. It is a rectangular checkered field of n Γ— m size. Each cell in a field can be empty (".") or it can be occupied by a wall ("*"). You have one bomb. If you lay the bomb at the cell (x, y), then after triggering it will wipe out all walls in the row x and all walls in the column y. You are to determine if it is possible to wipe out all walls in the depot by placing and triggering exactly one bomb. The bomb can be laid both in an empty cell or in a cell occupied by a wall. Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 1000) β€” the number of rows and columns in the depot field. The next n lines contain m symbols "." and "*" each β€” the description of the field. j-th symbol in i-th of them stands for cell (i, j). If the symbol is equal to ".", then the corresponding cell is empty, otherwise it equals "*" and the corresponding cell is occupied by a wall. Output If it is impossible to wipe out all walls by placing and triggering exactly one bomb, then print "NO" in the first line (without quotes). Otherwise print "YES" (without quotes) in the first line and two integers in the second line β€” the coordinates of the cell at which the bomb should be laid. If there are multiple answers, print any of them. Examples Input 3 4 .*.. .... .*.. Output YES 1 2 Input 3 3 ..* .*. *.. Output NO Input 6 5 ..*.. ..*.. ***** ..*.. ..*.. ..*.. Output YES 3 3 Tags: implementation Correct Solution: ``` ##n = int(input()) ##a = list(map(int, input().split())) ##print(" ".join(map(str, res))) [n, m] = list(map(int, input().split())) s = [] for i in range(n): s.append(input()) r = [] c = [] tot = 0 for x in range(n): cnt = 0 for y in range(m): if s[x][y] == '*': cnt += 1 r.append(cnt) for y in range(m): cnt = 0 for x in range(n): if s[x][y] == '*': cnt += 1 c.append(cnt) for x in range(n): for y in range(m): if s[x][y] == '*': tot += 1 for x in range(n): for y in range(m): cnt = r[x]+c[y] if s[x][y] == '*': cnt -= 1 if cnt == tot: print('YES') print(' '.join(map(str, [x+1, y+1]))) exit(0) print('NO') ```
99,110
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a description of a depot. It is a rectangular checkered field of n Γ— m size. Each cell in a field can be empty (".") or it can be occupied by a wall ("*"). You have one bomb. If you lay the bomb at the cell (x, y), then after triggering it will wipe out all walls in the row x and all walls in the column y. You are to determine if it is possible to wipe out all walls in the depot by placing and triggering exactly one bomb. The bomb can be laid both in an empty cell or in a cell occupied by a wall. Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 1000) β€” the number of rows and columns in the depot field. The next n lines contain m symbols "." and "*" each β€” the description of the field. j-th symbol in i-th of them stands for cell (i, j). If the symbol is equal to ".", then the corresponding cell is empty, otherwise it equals "*" and the corresponding cell is occupied by a wall. Output If it is impossible to wipe out all walls by placing and triggering exactly one bomb, then print "NO" in the first line (without quotes). Otherwise print "YES" (without quotes) in the first line and two integers in the second line β€” the coordinates of the cell at which the bomb should be laid. If there are multiple answers, print any of them. Examples Input 3 4 .*.. .... .*.. Output YES 1 2 Input 3 3 ..* .*. *.. Output NO Input 6 5 ..*.. ..*.. ***** ..*.. ..*.. ..*.. Output YES 3 3 Submitted Solution: ``` t=input;p=print;r=range;s=sum;n,m=map(int,t().split());a=[t() for i in r(n)];g=[[a[j][i] for j in r(n)] for i in r(m)];x,y=[a[i].count("*") for i in r(n)],[g[i].count("*") for i in r(m)];c=(s(x)+s(y))//2 for i in r(n): for j in r(m): if x[i]+y[j]-(a[i][j] == "*")==c:p("YES\n",i+1," ",j+1,sep="");exit(0) p("NO") ``` Yes
99,111
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a description of a depot. It is a rectangular checkered field of n Γ— m size. Each cell in a field can be empty (".") or it can be occupied by a wall ("*"). You have one bomb. If you lay the bomb at the cell (x, y), then after triggering it will wipe out all walls in the row x and all walls in the column y. You are to determine if it is possible to wipe out all walls in the depot by placing and triggering exactly one bomb. The bomb can be laid both in an empty cell or in a cell occupied by a wall. Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 1000) β€” the number of rows and columns in the depot field. The next n lines contain m symbols "." and "*" each β€” the description of the field. j-th symbol in i-th of them stands for cell (i, j). If the symbol is equal to ".", then the corresponding cell is empty, otherwise it equals "*" and the corresponding cell is occupied by a wall. Output If it is impossible to wipe out all walls by placing and triggering exactly one bomb, then print "NO" in the first line (without quotes). Otherwise print "YES" (without quotes) in the first line and two integers in the second line β€” the coordinates of the cell at which the bomb should be laid. If there are multiple answers, print any of them. Examples Input 3 4 .*.. .... .*.. Output YES 1 2 Input 3 3 ..* .*. *.. Output NO Input 6 5 ..*.. ..*.. ***** ..*.. ..*.. ..*.. Output YES 3 3 Submitted Solution: ``` n,m=map(int,input().split()) if n==1 or m==1: print("YES") print("1 1") exit() count_2_walls_row=0 count_diff_col=0 pos_col=[None]*2 lines=[None]*n for i in range(n): lines[i]=input() if "*" in lines[i]: pos=lines[i].index("*") if pos not in pos_col: count_diff_col+=1 if count_diff_col==3: print("NO") exit() pos_col[count_diff_col-1]=pos count=lines[i].count("*") if count>=2: count_2_walls_row+=1 if count_2_walls_row==2: print("NO") exit() count_2_walls_col=0 for i in range(m): count=0 for j in range(n): if lines[j][i]=='*': count+=1 if count==2: count_2_walls_col+=1 if count_2_walls_col==2: print("NO") exit() print("YES") max_wall_row=0 row=0 last_row=0 count_1_wall_row=0 pos_1_wall_row=[None]*n for i in range(n): count=lines[i].count("*") if max_wall_row<count: max_wall_row=count row=i if count>=2: break if count==1: pos_1_wall_row[count_1_wall_row]=[i,lines[i].index("*")] count_1_wall_row+=1 max_wall_col=0 col=0 count_1_wall_col=0 pos_1_wall_col=[None]*m for i in range(m): count=0 pos=0 is_found=False for j in range(n): if lines[j][i]=='*': count+=1 pos=j if max_wall_col<count: max_wall_col=count col=i if count==2: is_found=True break if is_found: break if count==1: pos_1_wall_col[count_1_wall_col]=[i,pos] count_1_wall_col+=1 if max_wall_row==1 and max_wall_col>1: distinct=[None]*2 amount=[0]*2 count=0 for i in range(count_1_wall_row): if pos_1_wall_row[i][1] not in distinct: distinct[count]=pos_1_wall_row[i][1] count+=1 if distinct[1]!=None: break for i in range(count_1_wall_row): if pos_1_wall_row[i][1]==distinct[0]: amount[0]+=1 else: amount[1]+=1 pos=0 if amount[0]>amount[1]: pos=1 for i in range(count_1_wall_row): if pos_1_wall_row[i][1]==distinct[pos]: row=pos_1_wall_row[i][0] elif max_wall_row>1 and max_wall_col==1: distinct=[None]*2 amount=[0]*2 count=0 for i in range(count_1_wall_col): if pos_1_wall_col[i][1] not in distinct: distinct[count]=pos_1_wall_col[i][1] count+=1 if distinct[1]!=None: break for i in range(count_1_wall_col): if pos_1_wall_col[i][1]==distinct[0]: amount[0]+=1 else: amount[1]+=1 pos=0 if amount[0]>amount[1]: pos=1 for i in range(count_1_wall_col): if pos_1_wall_col[i][1]==distinct[pos]: col=pos_1_wall_col[i][0] elif max_wall_row==max_wall_col==1 and count_diff_col==2: row=pos_1_wall_row[0][0] col=pos_1_wall_row[1][1] print(row+1,col+1) ``` Yes
99,112
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a description of a depot. It is a rectangular checkered field of n Γ— m size. Each cell in a field can be empty (".") or it can be occupied by a wall ("*"). You have one bomb. If you lay the bomb at the cell (x, y), then after triggering it will wipe out all walls in the row x and all walls in the column y. You are to determine if it is possible to wipe out all walls in the depot by placing and triggering exactly one bomb. The bomb can be laid both in an empty cell or in a cell occupied by a wall. Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 1000) β€” the number of rows and columns in the depot field. The next n lines contain m symbols "." and "*" each β€” the description of the field. j-th symbol in i-th of them stands for cell (i, j). If the symbol is equal to ".", then the corresponding cell is empty, otherwise it equals "*" and the corresponding cell is occupied by a wall. Output If it is impossible to wipe out all walls by placing and triggering exactly one bomb, then print "NO" in the first line (without quotes). Otherwise print "YES" (without quotes) in the first line and two integers in the second line β€” the coordinates of the cell at which the bomb should be laid. If there are multiple answers, print any of them. Examples Input 3 4 .*.. .... .*.. Output YES 1 2 Input 3 3 ..* .*. *.. Output NO Input 6 5 ..*.. ..*.. ***** ..*.. ..*.. ..*.. Output YES 3 3 Submitted Solution: ``` import sys input= lambda:sys.stdin.readline() MOD = 1000000007 ii = lambda: int(input()) si = lambda: input() dgl = lambda: list(map(int, input())) f = lambda: list(map(int, input().split())) il = lambda: list(map(int, input().split())) ls = lambda: list(input()) lr=[] lc=[] l=[] n,m=f() cnt=0 for _ in range(n): x=si() cnt=x.count('*') lr.append(cnt) l.append(x) for i in range(m): cnt=0 for j in range(n): cnt+=(l[j][i]=='*') lc.append(cnt) tcnt=sum(lr) for i in range(n): for j in range(m): if (lr[i]+lc[j]-(l[i][j]=='*'))==tcnt: print('YES') print(i+1,j+1) exit() print('NO') ``` Yes
99,113
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a description of a depot. It is a rectangular checkered field of n Γ— m size. Each cell in a field can be empty (".") or it can be occupied by a wall ("*"). You have one bomb. If you lay the bomb at the cell (x, y), then after triggering it will wipe out all walls in the row x and all walls in the column y. You are to determine if it is possible to wipe out all walls in the depot by placing and triggering exactly one bomb. The bomb can be laid both in an empty cell or in a cell occupied by a wall. Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 1000) β€” the number of rows and columns in the depot field. The next n lines contain m symbols "." and "*" each β€” the description of the field. j-th symbol in i-th of them stands for cell (i, j). If the symbol is equal to ".", then the corresponding cell is empty, otherwise it equals "*" and the corresponding cell is occupied by a wall. Output If it is impossible to wipe out all walls by placing and triggering exactly one bomb, then print "NO" in the first line (without quotes). Otherwise print "YES" (without quotes) in the first line and two integers in the second line β€” the coordinates of the cell at which the bomb should be laid. If there are multiple answers, print any of them. Examples Input 3 4 .*.. .... .*.. Output YES 1 2 Input 3 3 ..* .*. *.. Output NO Input 6 5 ..*.. ..*.. ***** ..*.. ..*.. ..*.. Output YES 3 3 Submitted Solution: ``` #!/usr/bin/env pypy3 import array import itertools IMPOSSIBLE = (-1, -1) def place_bomb(height, width, is_wall): # zero-based walls_row = array.array("L", (sum(row) for row in is_wall)) walls_column = array.array("L") for column_idx in range(width): walls_column.append(sum(is_wall[r][column_idx] for r in range(height))) total_walls = sum(walls_row) for bomb_r, bomb_c in itertools.product(range(height), range(width)): wiped_walls = walls_row[bomb_r] + walls_column[bomb_c] wiped_walls -= is_wall[bomb_r][bomb_c] if wiped_walls == total_walls: # one-based return (bomb_r + 1, bomb_c + 1) else: return IMPOSSIBLE def main(): height, width = map(int, input().split()) is_wall = [array.array("B", map(lambda c: c == "*", input())) for _ in range(height)] ans = place_bomb(height, width, is_wall) if ans != IMPOSSIBLE: print("YES") print(*ans) else: print("NO") if __name__ == '__main__': main() ``` Yes
99,114
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a description of a depot. It is a rectangular checkered field of n Γ— m size. Each cell in a field can be empty (".") or it can be occupied by a wall ("*"). You have one bomb. If you lay the bomb at the cell (x, y), then after triggering it will wipe out all walls in the row x and all walls in the column y. You are to determine if it is possible to wipe out all walls in the depot by placing and triggering exactly one bomb. The bomb can be laid both in an empty cell or in a cell occupied by a wall. Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 1000) β€” the number of rows and columns in the depot field. The next n lines contain m symbols "." and "*" each β€” the description of the field. j-th symbol in i-th of them stands for cell (i, j). If the symbol is equal to ".", then the corresponding cell is empty, otherwise it equals "*" and the corresponding cell is occupied by a wall. Output If it is impossible to wipe out all walls by placing and triggering exactly one bomb, then print "NO" in the first line (without quotes). Otherwise print "YES" (without quotes) in the first line and two integers in the second line β€” the coordinates of the cell at which the bomb should be laid. If there are multiple answers, print any of them. Examples Input 3 4 .*.. .... .*.. Output YES 1 2 Input 3 3 ..* .*. *.. Output NO Input 6 5 ..*.. ..*.. ***** ..*.. ..*.. ..*.. Output YES 3 3 Submitted Solution: ``` def oneRowOneColumn(matrix): i = 0 row = -1 column = -1 while i<len(matrix): if matrix[i].count('*') > 1: if row == -1: row = i else: return ['NO'] elif matrix[i].count('*') == 1: if column == -1: column = matrix[i].index('*') elif column != matrix[i].index('*'): return ['NO'] i += 1 row = 1 if row == -1 else row + 1 column = 1 if column == -1 else column + 1 return ['YES',str(row) + ' ' + str(column)] i = input().split(' ') matrix = list() for e in range(int(i[0])): matrix.append(input()) for e in oneRowOneColumn(matrix): print(e) ``` No
99,115
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a description of a depot. It is a rectangular checkered field of n Γ— m size. Each cell in a field can be empty (".") or it can be occupied by a wall ("*"). You have one bomb. If you lay the bomb at the cell (x, y), then after triggering it will wipe out all walls in the row x and all walls in the column y. You are to determine if it is possible to wipe out all walls in the depot by placing and triggering exactly one bomb. The bomb can be laid both in an empty cell or in a cell occupied by a wall. Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 1000) β€” the number of rows and columns in the depot field. The next n lines contain m symbols "." and "*" each β€” the description of the field. j-th symbol in i-th of them stands for cell (i, j). If the symbol is equal to ".", then the corresponding cell is empty, otherwise it equals "*" and the corresponding cell is occupied by a wall. Output If it is impossible to wipe out all walls by placing and triggering exactly one bomb, then print "NO" in the first line (without quotes). Otherwise print "YES" (without quotes) in the first line and two integers in the second line β€” the coordinates of the cell at which the bomb should be laid. If there are multiple answers, print any of them. Examples Input 3 4 .*.. .... .*.. Output YES 1 2 Input 3 3 ..* .*. *.. Output NO Input 6 5 ..*.. ..*.. ***** ..*.. ..*.. ..*.. Output YES 3 3 Submitted Solution: ``` [n, m] = [int(x) for x in input().split()] t = 0 z = 0 row = col = 0 lst = [] special = [] counter = counter2 = counter3 = counter4 = 0 for i in range (n): t = input() counter3 += 1 if '*' in t: z = t.count('*') if z == m: counter4 += 1 if z == 1: lst.append(t.index('*')) elif z > 1: counter += 1 row = counter3 if counter4 == n: print("YES") print(1, 1) counter = 5 if counter <= 1: for i in range (len(lst)-1): if lst[i] == lst[i+1]: counter2 +=1 if counter2 == len(lst)-1: print("YES") print(max(1,row), lst[0]+1) else: print("NO") else: if counter4 != n: print("NO") ``` No
99,116
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a description of a depot. It is a rectangular checkered field of n Γ— m size. Each cell in a field can be empty (".") or it can be occupied by a wall ("*"). You have one bomb. If you lay the bomb at the cell (x, y), then after triggering it will wipe out all walls in the row x and all walls in the column y. You are to determine if it is possible to wipe out all walls in the depot by placing and triggering exactly one bomb. The bomb can be laid both in an empty cell or in a cell occupied by a wall. Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 1000) β€” the number of rows and columns in the depot field. The next n lines contain m symbols "." and "*" each β€” the description of the field. j-th symbol in i-th of them stands for cell (i, j). If the symbol is equal to ".", then the corresponding cell is empty, otherwise it equals "*" and the corresponding cell is occupied by a wall. Output If it is impossible to wipe out all walls by placing and triggering exactly one bomb, then print "NO" in the first line (without quotes). Otherwise print "YES" (without quotes) in the first line and two integers in the second line β€” the coordinates of the cell at which the bomb should be laid. If there are multiple answers, print any of them. Examples Input 3 4 .*.. .... .*.. Output YES 1 2 Input 3 3 ..* .*. *.. Output NO Input 6 5 ..*.. ..*.. ***** ..*.. ..*.. ..*.. Output YES 3 3 Submitted Solution: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- import sys from collections import Counter numrow, numcol = sys.stdin.readline().split(' ') numrow = int(numrow) numcol = int(numcol) #line = sys.stdin.readline() # stores the row and col indices of each * symbol row_index = [] col_index = [] for i in range(numrow): line = sys.stdin.readline().strip() for j in range(numcol): if line[j] == '*': row_index.append(i) col_index.append(j) if (len(row_index) > 0): maxrow_count = Counter(row_index).most_common(1)[0][1] row_choices = [] for i in Counter(row_index).most_common(): if (i[1] >= maxrow_count): row_choices.append(i[0]) else: break maxcol_count = Counter(col_index).most_common(1)[0][1] col_choices= [] for i in Counter(col_index).most_common(): if (i[1] >= maxcol_count): col_choices.append(i[0]) else: break for rtnrow in row_choices[:2]: for rtncol in col_choices[:2]: workable = True for i in range(len(row_index)): if (row_index[i] != rtnrow and col_index[i] != rtncol): workable = False; break if (workable): print ("YES") print (rtnrow+1, rtncol+1) sys.exit(0) print ("NO") else: print("YES") print("1 1") ``` No
99,117
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a description of a depot. It is a rectangular checkered field of n Γ— m size. Each cell in a field can be empty (".") or it can be occupied by a wall ("*"). You have one bomb. If you lay the bomb at the cell (x, y), then after triggering it will wipe out all walls in the row x and all walls in the column y. You are to determine if it is possible to wipe out all walls in the depot by placing and triggering exactly one bomb. The bomb can be laid both in an empty cell or in a cell occupied by a wall. Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 1000) β€” the number of rows and columns in the depot field. The next n lines contain m symbols "." and "*" each β€” the description of the field. j-th symbol in i-th of them stands for cell (i, j). If the symbol is equal to ".", then the corresponding cell is empty, otherwise it equals "*" and the corresponding cell is occupied by a wall. Output If it is impossible to wipe out all walls by placing and triggering exactly one bomb, then print "NO" in the first line (without quotes). Otherwise print "YES" (without quotes) in the first line and two integers in the second line β€” the coordinates of the cell at which the bomb should be laid. If there are multiple answers, print any of them. Examples Input 3 4 .*.. .... .*.. Output YES 1 2 Input 3 3 ..* .*. *.. Output NO Input 6 5 ..*.. ..*.. ***** ..*.. ..*.. ..*.. Output YES 3 3 Submitted Solution: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- import sys from collections import Counter numrow, numcol = sys.stdin.readline().split(' ') numrow = int(numrow) numcol = int(numcol) #line = sys.stdin.readline() # stores the row and col indices of each * symbol row_index = [] col_index = [] for i in range(numrow): line = sys.stdin.readline().strip() for j in range(numcol): if line[j] == '*': row_index.append(i) col_index.append(j) if (len(row_index) > 0): rtnrow = Counter(row_index).most_common(1)[0][0] rtncol = Counter(col_index).most_common(1)[0][0] else: print("NO") sys.exit(0) for i in range(len(row_index)): if (row_index[i] != rtnrow and col_index[i] != rtncol): print ("NO") sys.exit(0) print ("YES") print (rtnrow+1, rtncol+1) ``` No
99,118
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has a pack of 54 cards (52 standard cards and 2 distinct jokers). That is all he has at the moment. Not to die from boredom, Vasya plays Solitaire with them. Vasya lays out nm cards as a rectangle n Γ— m. If there are jokers among them, then Vasya should change them with some of the rest of 54 - nm cards (which are not layed out) so that there were no jokers left. Vasya can pick the cards to replace the jokers arbitrarily. Remember, that each card presents in pack exactly once (i. e. in a single copy). Vasya tries to perform the replacements so that the solitaire was solved. Vasya thinks that the solitaire is solved if after the jokers are replaced, there exist two non-overlapping squares 3 Γ— 3, inside each of which all the cards either have the same suit, or pairwise different ranks. Determine by the initial position whether the solitaire can be solved or not. If it can be solved, show the way in which it is possible. Input The first line contains integers n and m (3 ≀ n, m ≀ 17, n Γ— m ≀ 52). Next n lines contain m words each. Each word consists of two letters. The jokers are defined as "J1" and "J2" correspondingly. For the rest of the cards, the first letter stands for the rank and the second one β€” for the suit. The possible ranks are: "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K" and "A". The possible suits are: "C", "D", "H" and "S". All the cards are different. Output If the Solitaire can be solved, print on the first line "Solution exists." without the quotes. On the second line print in what way the jokers can be replaced. Three variants are possible: * "There are no jokers.", if there are no jokers in the input data. * "Replace Jx with y.", if there is one joker. x is its number, and y is the card it should be replaced with. * "Replace J1 with x and J2 with y.", if both jokers are present in the input data. x and y here represent distinct cards with which one should replace the first and the second jokers correspondingly. On the third line print the coordinates of the upper left corner of the first square 3 Γ— 3 in the format "Put the first square to (r, c).", where r and c are the row and the column correspondingly. In the same manner print on the fourth line the coordinates of the second square 3 Γ— 3 in the format "Put the second square to (r, c).". If there are several solutions to that problem, print any of them. If there are no solutions, print of the single line "No solution." without the quotes. See the samples to understand the output format better. Examples Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H 5S TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output No solution. Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H J1 TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. Replace J1 with 2H. Put the first square to (1, 1). Put the second square to (2, 4). Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H QC TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. There are no jokers. Put the first square to (1, 1). Put the second square to (2, 4). Note The pretests cover all the possible output formats. Tags: brute force, implementation Correct Solution: ``` n, m = map(int, input().split()) dignities = '23456789TJQKA' colors = 'CDHS' all_cards = [] for i in dignities: for j in colors: all_cards.append(i + j) my_cards = [[] for x in range(n)] joker1 = 0 joker2 = 0 for i in range(n): my_cards[i] = input().split() for j in range(m): if my_cards[i][j][1] == '1': joker1 = (i, j) elif my_cards[i][j][1] == '2': joker2 = (i, j) else: all_cards.remove(my_cards[i][j]) def intersect_segments(a, b, c, d): if a > b: a, b = b, a if c > d: c, d = d, c return a <= d and b >= c def intersect_squares(a, b): return intersect_segments(a[0], a[2], b[0], b[2]) and intersect_segments(a[1], a[3], b[1], b[3]) def suitable(cards, x, y): colors = set() dignities = set() for i in range(x, x + 3): for j in range(y, y + 3): colors.add(cards[i][j][1]) dignities.add(cards[i][j][0]) return len(colors) == 1 or len(dignities) == 9 def ok(cards, n, m): for a in range(n - 2): for b in range(m - 2): if suitable(cards, a, b): for c in range(n - 2): for d in range(m - 2): if not intersect_squares((a, b, a + 2, b + 2), (c, d, c + 2, d + 2)) and suitable(cards, c, d): return (a, b, c, d) return 0 for i in all_cards: for j in all_cards: if i != j: new_cards = my_cards if joker1 != 0: new_cards[joker1[0]][joker1[1]] = i if joker2 != 0: new_cards[joker2[0]][joker2[1]] = j if ok(new_cards, n, m): print('Solution exists.') if joker1 == 0 and joker2 == 0: print('There are no jokers.') elif joker1 != 0 and joker2 != 0: print('Replace J1 with %s and J2 with %s.' % (i, j)) elif joker1 != 0: print('Replace J1 with %s.' % (i)) else: print('Replace J2 with %s.' % (j)) tmp = ok(new_cards, n, m) print('Put the first square to (%d, %d).' % (tmp[0] + 1, tmp[1] + 1)) print('Put the second square to (%d, %d).' % (tmp[2] + 1, tmp[3] + 1)) quit() print('No solution.') ```
99,119
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has a pack of 54 cards (52 standard cards and 2 distinct jokers). That is all he has at the moment. Not to die from boredom, Vasya plays Solitaire with them. Vasya lays out nm cards as a rectangle n Γ— m. If there are jokers among them, then Vasya should change them with some of the rest of 54 - nm cards (which are not layed out) so that there were no jokers left. Vasya can pick the cards to replace the jokers arbitrarily. Remember, that each card presents in pack exactly once (i. e. in a single copy). Vasya tries to perform the replacements so that the solitaire was solved. Vasya thinks that the solitaire is solved if after the jokers are replaced, there exist two non-overlapping squares 3 Γ— 3, inside each of which all the cards either have the same suit, or pairwise different ranks. Determine by the initial position whether the solitaire can be solved or not. If it can be solved, show the way in which it is possible. Input The first line contains integers n and m (3 ≀ n, m ≀ 17, n Γ— m ≀ 52). Next n lines contain m words each. Each word consists of two letters. The jokers are defined as "J1" and "J2" correspondingly. For the rest of the cards, the first letter stands for the rank and the second one β€” for the suit. The possible ranks are: "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K" and "A". The possible suits are: "C", "D", "H" and "S". All the cards are different. Output If the Solitaire can be solved, print on the first line "Solution exists." without the quotes. On the second line print in what way the jokers can be replaced. Three variants are possible: * "There are no jokers.", if there are no jokers in the input data. * "Replace Jx with y.", if there is one joker. x is its number, and y is the card it should be replaced with. * "Replace J1 with x and J2 with y.", if both jokers are present in the input data. x and y here represent distinct cards with which one should replace the first and the second jokers correspondingly. On the third line print the coordinates of the upper left corner of the first square 3 Γ— 3 in the format "Put the first square to (r, c).", where r and c are the row and the column correspondingly. In the same manner print on the fourth line the coordinates of the second square 3 Γ— 3 in the format "Put the second square to (r, c).". If there are several solutions to that problem, print any of them. If there are no solutions, print of the single line "No solution." without the quotes. See the samples to understand the output format better. Examples Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H 5S TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output No solution. Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H J1 TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. Replace J1 with 2H. Put the first square to (1, 1). Put the second square to (2, 4). Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H QC TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. There are no jokers. Put the first square to (1, 1). Put the second square to (2, 4). Note The pretests cover all the possible output formats. Tags: brute force, implementation Correct Solution: ``` def get_cards(): n,m = map(int,input().split()) lis = [[]]*n for i in range(n): lis[i] = list(map(str,input().split())) return (n,m,lis) def find_remains(cards): remains = [] ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K","A"] suits = ["C", "D", "H","S"] for r in ranks: for s in suits: remains.append(r+s) remains += ["J1","J2"] for i in range(cards[0]): for j in range(cards[1]): remains.remove(cards[2][i][j]) return remains def condition_1(ranks): r = set(ranks) if len(r) < len(ranks): return 1 else: return 0 def condition_2(suits): r = set(suits) if len(r) == 1: return 0 else: return 1 def find_solution(cards): lis = cards[2] positions = [] result = 1 position = [] for i in range(cards[0]-2): for j in range(cards[1]-2): positions.append((i,j)) for p in positions: positions_2 = positions[:] if result == 0: break i = p[0] j = p[1] nine_1 = [lis[i][j],lis[i][j+1],lis[i][j+2],lis[i+1][j],lis[i+1][j+1],lis[i+1][j+2],lis[i+2][j],lis[i+2][j+1],lis[i+2][j+2]] nine_1_p = [] for a in range(-2,3): for b in range(-2,3): nine_1_p.append((i+a,j+b)) for c in nine_1_p: if c in positions_2: positions_2.remove(c) for q in positions_2: if result == 0: break i = q[0] j = q[1] nine_2 = [lis[i][j],lis[i][j+1],lis[i][j+2],lis[i+1][j],lis[i+1][j+1],lis[i+1][j+2],lis[i+2][j],lis[i+2][j+1],lis[i+2][j+2]] ranks_1,ranks_2 = [],[] suits_1,suits_2 = [],[] for card in nine_1: ranks_1.append(card[0]) suits_1.append(card[1]) result_1_1 = condition_1(ranks_1) result_1_2 = condition_2(suits_1) for card in nine_2: ranks_2.append(card[0]) suits_2.append(card[1]) result_2_1 = condition_1(ranks_2) result_2_2 = condition_2(suits_2) if result_1_1*result_1_2 == 0 and result_2_1*result_2_2 == 0: result = 0 position = [p,q] result = [result,position] return result def find_Jocker(cards): n = cards[0] m = cards[1] J1,J2 = 0,0 for i in range(n): for j in range(m): if cards[2][i][j] == "J1": J1 = (i,j) if cards[2][i][j] == "J2": J2 = (i,j) positions = (J1,J2) return positions cards = get_cards() if cards[0] < 3 or cards[1] < 3: result = [1] elif cards[0] < 6 and cards[1] < 6: result = [1] else: remains = find_remains(cards) jocker = find_Jocker(cards) changed = [0,0] if jocker[0] == 0 and jocker[1] == 0: result = find_solution(cards) elif jocker[0] != 0 and jocker[1] == 0: remains.remove("J2") for remain in remains: cards[2][jocker[0][0]][jocker[0][1]] = remain result = find_solution(cards) if result[0] == 0: changed = [remain,0] break elif jocker[1] != 0 and jocker[0] == 0: remains.remove("J1") for remain in remains: cards[2][jocker[1][0]][jocker[1][1]] = remain result = find_solution(cards) if result[0] == 0: changed = [0,remain] break else: remains_2 = remains[:] for remain_1 in remains: cards[2][jocker[1][0]][jocker[1][1]] = remain_1 remains_2.remove(remain_1) for remain_2 in remains_2: cards[2][jocker[0][0]][jocker[0][1]] = remain_2 result = find_solution(cards) if result[0] == 0: changed[0] = remain_2 break remains_2 = remains[:] if result[0] == 0: changed[1] = remain_1 break if result[0] == 1: print("No solution.") if result[0] == 0: print("Solution exists.") if changed[0] != 0 and changed[1] != 0: print("Replace J1 with "+changed[0]+" and J2 with "+changed[1]+".") elif changed[0] != 0: print("Replace J1 with "+changed[0]+".") elif changed[1] != 0: print("Replace J2 with "+changed[1]+".") else: print("There are no jokers.") print("Put the first square to ("+str(result[1][0][0]+1)+", "+str(result[1][0][1]+1)+").") print("Put the second square to ("+str(result[1][1][0]+1)+", "+str(result[1][1][1]+1)+").") ```
99,120
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has a pack of 54 cards (52 standard cards and 2 distinct jokers). That is all he has at the moment. Not to die from boredom, Vasya plays Solitaire with them. Vasya lays out nm cards as a rectangle n Γ— m. If there are jokers among them, then Vasya should change them with some of the rest of 54 - nm cards (which are not layed out) so that there were no jokers left. Vasya can pick the cards to replace the jokers arbitrarily. Remember, that each card presents in pack exactly once (i. e. in a single copy). Vasya tries to perform the replacements so that the solitaire was solved. Vasya thinks that the solitaire is solved if after the jokers are replaced, there exist two non-overlapping squares 3 Γ— 3, inside each of which all the cards either have the same suit, or pairwise different ranks. Determine by the initial position whether the solitaire can be solved or not. If it can be solved, show the way in which it is possible. Input The first line contains integers n and m (3 ≀ n, m ≀ 17, n Γ— m ≀ 52). Next n lines contain m words each. Each word consists of two letters. The jokers are defined as "J1" and "J2" correspondingly. For the rest of the cards, the first letter stands for the rank and the second one β€” for the suit. The possible ranks are: "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K" and "A". The possible suits are: "C", "D", "H" and "S". All the cards are different. Output If the Solitaire can be solved, print on the first line "Solution exists." without the quotes. On the second line print in what way the jokers can be replaced. Three variants are possible: * "There are no jokers.", if there are no jokers in the input data. * "Replace Jx with y.", if there is one joker. x is its number, and y is the card it should be replaced with. * "Replace J1 with x and J2 with y.", if both jokers are present in the input data. x and y here represent distinct cards with which one should replace the first and the second jokers correspondingly. On the third line print the coordinates of the upper left corner of the first square 3 Γ— 3 in the format "Put the first square to (r, c).", where r and c are the row and the column correspondingly. In the same manner print on the fourth line the coordinates of the second square 3 Γ— 3 in the format "Put the second square to (r, c).". If there are several solutions to that problem, print any of them. If there are no solutions, print of the single line "No solution." without the quotes. See the samples to understand the output format better. Examples Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H 5S TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output No solution. Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H J1 TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. Replace J1 with 2H. Put the first square to (1, 1). Put the second square to (2, 4). Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H QC TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. There are no jokers. Put the first square to (1, 1). Put the second square to (2, 4). Note The pretests cover all the possible output formats. Tags: brute force, implementation Correct Solution: ``` n, m = map(int, input().split()) dignities = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'] colors = ['C', 'D', 'H', 'S'] all_cards = [] for i in dignities: for j in colors: all_cards.append(i + j) my_cards = [[] for x in range(n)] joker1 = 0 joker2 = 0 for i in range(n): my_cards[i] = input().split() for j in range(m): if my_cards[i][j][1] == '1': joker1 = (i, j) elif my_cards[i][j][1] == '2': joker2 = (i, j) else: all_cards.remove(my_cards[i][j]) def intersect_segments(a, b, c, d): if a > b: a, b = b, a if c > d: c, d = d, c return a <= d and b >= c def intersect_squares(a, b): return intersect_segments(a[0], a[2], b[0], b[2]) and intersect_segments(a[1], a[3], b[1], b[3]) def suitable(cards, x, y): colors = set() dignities = set() for i in range(x, x + 3): for j in range(y, y + 3): colors.add(cards[i][j][1]) dignities.add(cards[i][j][0]) return len(colors) == 1 or len(dignities) == 9 def ok(cards, n, m): for a in range(n - 2): for b in range(m - 2): if suitable(cards, a, b): for c in range(n - 2): for d in range(m - 2): if not intersect_squares((a, b, a + 2, b + 2), (c, d, c + 2, d + 2)) and suitable(cards, c, d): return (a, b, c, d) return 0 for i in all_cards: for j in all_cards: if i != j: new_cards = my_cards if joker1 != 0: ans1 = i[0] + i[1] new_cards[joker1[0]][joker1[1]] = i if joker2 != 0: ans2 = j[0] + j[1] new_cards[joker2[0]][joker2[1]] = j if ok(new_cards, n, m): print('Solution exists.') if joker1 == 0 and joker2 == 0: print('There are no jokers.') elif joker1 != 0 and joker2 != 0: print('Replace J1 with %s and J2 with %s.' % (ans1, ans2)) elif joker1 != 0: print('Replace J1 with %s.' % (ans1)) else: print('Replace J2 with %s.' % (ans2)) tmp = ok(new_cards, n, m) print('Put the first square to (%d, %d).' % (tmp[0] + 1, tmp[1] + 1)) print('Put the second square to (%d, %d).' % (tmp[2] + 1, tmp[3] + 1)) quit() print('No solution.') ```
99,121
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has a pack of 54 cards (52 standard cards and 2 distinct jokers). That is all he has at the moment. Not to die from boredom, Vasya plays Solitaire with them. Vasya lays out nm cards as a rectangle n Γ— m. If there are jokers among them, then Vasya should change them with some of the rest of 54 - nm cards (which are not layed out) so that there were no jokers left. Vasya can pick the cards to replace the jokers arbitrarily. Remember, that each card presents in pack exactly once (i. e. in a single copy). Vasya tries to perform the replacements so that the solitaire was solved. Vasya thinks that the solitaire is solved if after the jokers are replaced, there exist two non-overlapping squares 3 Γ— 3, inside each of which all the cards either have the same suit, or pairwise different ranks. Determine by the initial position whether the solitaire can be solved or not. If it can be solved, show the way in which it is possible. Input The first line contains integers n and m (3 ≀ n, m ≀ 17, n Γ— m ≀ 52). Next n lines contain m words each. Each word consists of two letters. The jokers are defined as "J1" and "J2" correspondingly. For the rest of the cards, the first letter stands for the rank and the second one β€” for the suit. The possible ranks are: "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K" and "A". The possible suits are: "C", "D", "H" and "S". All the cards are different. Output If the Solitaire can be solved, print on the first line "Solution exists." without the quotes. On the second line print in what way the jokers can be replaced. Three variants are possible: * "There are no jokers.", if there are no jokers in the input data. * "Replace Jx with y.", if there is one joker. x is its number, and y is the card it should be replaced with. * "Replace J1 with x and J2 with y.", if both jokers are present in the input data. x and y here represent distinct cards with which one should replace the first and the second jokers correspondingly. On the third line print the coordinates of the upper left corner of the first square 3 Γ— 3 in the format "Put the first square to (r, c).", where r and c are the row and the column correspondingly. In the same manner print on the fourth line the coordinates of the second square 3 Γ— 3 in the format "Put the second square to (r, c).". If there are several solutions to that problem, print any of them. If there are no solutions, print of the single line "No solution." without the quotes. See the samples to understand the output format better. Examples Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H 5S TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output No solution. Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H J1 TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. Replace J1 with 2H. Put the first square to (1, 1). Put the second square to (2, 4). Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H QC TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. There are no jokers. Put the first square to (1, 1). Put the second square to (2, 4). Note The pretests cover all the possible output formats. Tags: brute force, implementation Correct Solution: ``` n, m = map(int, input().split()) dignities = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'] colors = ['C', 'D', 'H', 'S'] all_cards = [] for i in dignities: for j in colors: all_cards.append(i + j) my_cards = [[] for x in range(n)] joker1 = 0 joker2 = 0 for i in range(n): my_cards[i] = input().split() for j in range(m): if my_cards[i][j][1] == '1': joker1 = (i, j) elif my_cards[i][j][1] == '2': joker2 = (i, j) else: all_cards.remove(my_cards[i][j]) def intersect_segments(a, b, c, d): if a > b: a, b = b, a if c > d: c, d = d, c return a <= d and b >= c def intersect_squares(a, b): return intersect_segments(a[0], a[2], b[0], b[2]) and intersect_segments(a[1], a[3], b[1], b[3]) def suitable(cards, x, y): colors = set() dignities = set() for i in range(x, x + 3): for j in range(y, y + 3): colors.add(cards[i][j][1]) dignities.add(cards[i][j][0]) return len(colors) == 1 or len(dignities) == 9 def ok(cards, n, m): for a in range(n - 2): for b in range(m - 2): if suitable(cards, a, b): for c in range(n - 2): for d in range(m - 2): if not intersect_squares((a, b, a + 2, b + 2), (c, d, c + 2, d + 2)) and suitable(cards, c, d): return (a, b, c, d) return 0 for i in all_cards: for j in all_cards: if i != j: new_cards = my_cards if joker1 != 0: new_cards[joker1[0]][joker1[1]] = i if joker2 != 0: new_cards[joker2[0]][joker2[1]] = j if ok(new_cards, n, m): print('Solution exists.') if joker1 == 0 and joker2 == 0: print('There are no jokers.') elif joker1 != 0 and joker2 != 0: print('Replace J1 with %s and J2 with %s.' % (i, j)) elif joker1 != 0: print('Replace J1 with %s.' % (i)) else: print('Replace J2 with %s.' % (j)) tmp = ok(new_cards, n, m) print('Put the first square to (%d, %d).' % (tmp[0] + 1, tmp[1] + 1)) print('Put the second square to (%d, %d).' % (tmp[2] + 1, tmp[3] + 1)) quit() print('No solution.') ```
99,122
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has a pack of 54 cards (52 standard cards and 2 distinct jokers). That is all he has at the moment. Not to die from boredom, Vasya plays Solitaire with them. Vasya lays out nm cards as a rectangle n Γ— m. If there are jokers among them, then Vasya should change them with some of the rest of 54 - nm cards (which are not layed out) so that there were no jokers left. Vasya can pick the cards to replace the jokers arbitrarily. Remember, that each card presents in pack exactly once (i. e. in a single copy). Vasya tries to perform the replacements so that the solitaire was solved. Vasya thinks that the solitaire is solved if after the jokers are replaced, there exist two non-overlapping squares 3 Γ— 3, inside each of which all the cards either have the same suit, or pairwise different ranks. Determine by the initial position whether the solitaire can be solved or not. If it can be solved, show the way in which it is possible. Input The first line contains integers n and m (3 ≀ n, m ≀ 17, n Γ— m ≀ 52). Next n lines contain m words each. Each word consists of two letters. The jokers are defined as "J1" and "J2" correspondingly. For the rest of the cards, the first letter stands for the rank and the second one β€” for the suit. The possible ranks are: "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K" and "A". The possible suits are: "C", "D", "H" and "S". All the cards are different. Output If the Solitaire can be solved, print on the first line "Solution exists." without the quotes. On the second line print in what way the jokers can be replaced. Three variants are possible: * "There are no jokers.", if there are no jokers in the input data. * "Replace Jx with y.", if there is one joker. x is its number, and y is the card it should be replaced with. * "Replace J1 with x and J2 with y.", if both jokers are present in the input data. x and y here represent distinct cards with which one should replace the first and the second jokers correspondingly. On the third line print the coordinates of the upper left corner of the first square 3 Γ— 3 in the format "Put the first square to (r, c).", where r and c are the row and the column correspondingly. In the same manner print on the fourth line the coordinates of the second square 3 Γ— 3 in the format "Put the second square to (r, c).". If there are several solutions to that problem, print any of them. If there are no solutions, print of the single line "No solution." without the quotes. See the samples to understand the output format better. Examples Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H 5S TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output No solution. Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H J1 TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. Replace J1 with 2H. Put the first square to (1, 1). Put the second square to (2, 4). Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H QC TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. There are no jokers. Put the first square to (1, 1). Put the second square to (2, 4). Note The pretests cover all the possible output formats. Tags: brute force, implementation Correct Solution: ``` allCards = [value + suit for value in ["2","3","4","5","6","7","8","9","T","J","Q","K","A"] for suit in ["C","D","H","S"]] n, m = map(lambda x: int(x), input().split(" ")) cards = [] for i in range(n): cards.append(input().split(" ")) availableCards = allCards for arr in cards: for card in arr: if card != "J1" and card != "J2": availableCards.remove(card) def joker2(i: int, j: int) -> [bool, bool, bool, set]: usedValues = set() didFoundJoker1 = False didFoundJoker2 = False for i1 in range(i, i + 3): for j1 in range(j, j + 3): if cards[i1][j1] == "J1": didFoundJoker1 = True elif cards[i1][j1] == "J2": didFoundJoker2 = True elif cards[i1][j1][0] not in usedValues: usedValues.add(cards[i1][j1][0]) else: return [False, False, False, set()] res = set() for card in availableCards: if card[0] not in usedValues: res.add(card) isTrue = True if didFoundJoker1 or didFoundJoker2: isTrue = False for card in res: if isTrue: break for i1 in range(i, i + 3): if isTrue: break for j1 in range(j, j + 3): if cards[i1][j1] not in ["J1","J2"] and cards[i1][j1][0] != card[0]: isTrue = True break return [isTrue, didFoundJoker1, didFoundJoker2, res] ansi1, ansj1, ansi2, ansj2 = 0, 0, 0, 0 replaceJoker1 = None replaceJoker2 = None def joker1(i: int, j: int) -> bool: global replaceJoker1 global replaceJoker2 global ansi1, ansj1, ansi2, ansj2 if not (i + 2 < n and j + 2 < m): return False didFound1, didFindJoker1, didFindJoker2, strings = joker2(i, j) if not didFound1: return False for i1 in range(n): for j1 in range(m): if (i1 > i + 2 or j1 > j + 2) and i1 + 2 < n and j1 + 2 < m: didFound2, didFindJoker21, didFindJoker22, strings2 = joker2(i1, j1) if (didFindJoker1 or didFindJoker2) and (didFindJoker21 or didFindJoker22): xor = (strings2 ^ strings) x1 = xor & strings x2 = xor & strings2 if x1 and x2: if didFindJoker1 and didFindJoker22: replaceJoker1 = x1.pop() replaceJoker2 = x2.pop() else: replaceJoker1 = x2.pop() replaceJoker2 = x1.pop() ansi1, ansj1, ansi2, ansj2 = i, j, i1, j1 return True elif didFindJoker21 and didFindJoker22: if len(strings2) >= 2: replaceJoker1 = strings2.pop() replaceJoker2 = strings2.pop() ansi1, ansj1, ansi2, ansj2 = i, j, i1, j1 return True elif didFound2 and didFindJoker1 and didFindJoker2: stringsx = list(strings) ansi1, ansj1, ansi2, ansj2 = i, j, i1, j1 for i in range(len(stringsx)): for j in range(i + 1, len(stringsx)): if stringsx[i][0] != stringsx[j][0]: replaceJoker1 = stringsx[i] replaceJoker2 = stringsx[j] return True continue elif didFound2 and didFindJoker21 and didFindJoker22: stringsx = list(strings2) ansi1, ansj1, ansi2, ansj2 = i, j, i1, j1 for i in range(len(stringsx)): for j in range(i + 1, len(stringsx)): if stringsx[i][0] != stringsx[j][0]: replaceJoker1 = stringsx[i] replaceJoker2 = stringsx[j] return True continue elif didFound2: if didFindJoker1: if not strings: continue replaceJoker1 = strings.pop() if didFindJoker2: if not strings: continue replaceJoker2 = strings.pop() if didFindJoker21: if not strings2: continue replaceJoker1 = strings2.pop() if didFindJoker22: if not strings2: continue replaceJoker2 = strings2.pop() ansi1, ansj1, ansi2, ansj2 = i, j, i1, j1 return True return False didFound = False for i in range(n): if didFound: break for j in range(m): res = joker1(i, j) if res: print("Solution exists.") j1f, j2f = False, False for c in cards: for card in c: if card == "J1": j1f = True elif card == "J2": j2f = True if j1f and not replaceJoker1: replaceJoker1 = availableCards.pop() while availableCards and replaceJoker1 == replaceJoker2: replaceJoker1 = availableCards.pop() if j2f and not replaceJoker2: replaceJoker2 = availableCards.pop() if replaceJoker2 and replaceJoker1: print(f"Replace J1 with {replaceJoker1} and J2 with {replaceJoker2}.") elif replaceJoker1: print(f"Replace J1 with {replaceJoker1}.") elif replaceJoker2: print(f"Replace J2 with {replaceJoker2}.") else: print("There are no jokers.") print(f"Put the first square to ({ansi1+1}, {ansj1+1}).") print(f"Put the second square to ({ansi2+1}, {ansj2+1}).") didFound = True break if not didFound: print("No solution.") ```
99,123
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has a pack of 54 cards (52 standard cards and 2 distinct jokers). That is all he has at the moment. Not to die from boredom, Vasya plays Solitaire with them. Vasya lays out nm cards as a rectangle n Γ— m. If there are jokers among them, then Vasya should change them with some of the rest of 54 - nm cards (which are not layed out) so that there were no jokers left. Vasya can pick the cards to replace the jokers arbitrarily. Remember, that each card presents in pack exactly once (i. e. in a single copy). Vasya tries to perform the replacements so that the solitaire was solved. Vasya thinks that the solitaire is solved if after the jokers are replaced, there exist two non-overlapping squares 3 Γ— 3, inside each of which all the cards either have the same suit, or pairwise different ranks. Determine by the initial position whether the solitaire can be solved or not. If it can be solved, show the way in which it is possible. Input The first line contains integers n and m (3 ≀ n, m ≀ 17, n Γ— m ≀ 52). Next n lines contain m words each. Each word consists of two letters. The jokers are defined as "J1" and "J2" correspondingly. For the rest of the cards, the first letter stands for the rank and the second one β€” for the suit. The possible ranks are: "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K" and "A". The possible suits are: "C", "D", "H" and "S". All the cards are different. Output If the Solitaire can be solved, print on the first line "Solution exists." without the quotes. On the second line print in what way the jokers can be replaced. Three variants are possible: * "There are no jokers.", if there are no jokers in the input data. * "Replace Jx with y.", if there is one joker. x is its number, and y is the card it should be replaced with. * "Replace J1 with x and J2 with y.", if both jokers are present in the input data. x and y here represent distinct cards with which one should replace the first and the second jokers correspondingly. On the third line print the coordinates of the upper left corner of the first square 3 Γ— 3 in the format "Put the first square to (r, c).", where r and c are the row and the column correspondingly. In the same manner print on the fourth line the coordinates of the second square 3 Γ— 3 in the format "Put the second square to (r, c).". If there are several solutions to that problem, print any of them. If there are no solutions, print of the single line "No solution." without the quotes. See the samples to understand the output format better. Examples Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H 5S TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output No solution. Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H J1 TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. Replace J1 with 2H. Put the first square to (1, 1). Put the second square to (2, 4). Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H QC TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. There are no jokers. Put the first square to (1, 1). Put the second square to (2, 4). Note The pretests cover all the possible output formats. Tags: brute force, implementation Correct Solution: ``` n, m = map(int, input().split()) num = '23456789TJQKA' col = 'CDHS' all = [] for i in num: for j in col: all.append(i + j) my = [[] for x in range(n)] joker1 = 0 joker2 = 0 for i in range(n): my[i] = input().split() for j in range(m): if my[i][j][1] == '1': joker1 = (i, j) elif my[i][j][1] == '2': joker2 = (i, j) else: all.remove(my[i][j]) def intersect_segments(a, b, c, d): return a <= d and b >= c def intersect_squares(a, b): return intersect_segments(a[0], a[2], b[0], b[2]) and intersect_segments(a[1], a[3], b[1], b[3]) def suitable(cards, x, y): col = set() num = set() for i in range(x, x + 3): for j in range(y, y + 3): col.add(cards[i][j][1]) num.add(cards[i][j][0]) return len(col) == 1 or len(num) == 9 def ok(cards, n, m): for a in range(n - 2): for b in range(m - 2): if suitable(cards, a, b): for c in range(n - 2): for d in range(m - 2): if not intersect_squares((a, b, a + 2, b + 2), (c, d, c + 2, d + 2)) and suitable(cards, c, d): return (a, b, c, d) return 0 for i in all: for j in all: if i != j: new = my if joker1 != 0: new[joker1[0]][joker1[1]] = i if joker2 != 0: new[joker2[0]][joker2[1]] = j q = ok(new, n, m) if q: print('Solution exists.') if joker1 == 0 and joker2 == 0: print('There are no jokers.') elif joker1 != 0 and joker2 != 0: print('Replace J1 with %s and J2 with %s.' % (i, j)) elif joker1 != 0: print('Replace J1 with %s.' % (i)) else: print('Replace J2 with %s.' % (j)) print('Put the first square to (%d, %d).' % (q[0] + 1, q[1] + 1)) print('Put the second square to (%d, %d).' % (q[2] + 1, q[3] + 1)) quit() print('No solution.') ```
99,124
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has a pack of 54 cards (52 standard cards and 2 distinct jokers). That is all he has at the moment. Not to die from boredom, Vasya plays Solitaire with them. Vasya lays out nm cards as a rectangle n Γ— m. If there are jokers among them, then Vasya should change them with some of the rest of 54 - nm cards (which are not layed out) so that there were no jokers left. Vasya can pick the cards to replace the jokers arbitrarily. Remember, that each card presents in pack exactly once (i. e. in a single copy). Vasya tries to perform the replacements so that the solitaire was solved. Vasya thinks that the solitaire is solved if after the jokers are replaced, there exist two non-overlapping squares 3 Γ— 3, inside each of which all the cards either have the same suit, or pairwise different ranks. Determine by the initial position whether the solitaire can be solved or not. If it can be solved, show the way in which it is possible. Input The first line contains integers n and m (3 ≀ n, m ≀ 17, n Γ— m ≀ 52). Next n lines contain m words each. Each word consists of two letters. The jokers are defined as "J1" and "J2" correspondingly. For the rest of the cards, the first letter stands for the rank and the second one β€” for the suit. The possible ranks are: "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K" and "A". The possible suits are: "C", "D", "H" and "S". All the cards are different. Output If the Solitaire can be solved, print on the first line "Solution exists." without the quotes. On the second line print in what way the jokers can be replaced. Three variants are possible: * "There are no jokers.", if there are no jokers in the input data. * "Replace Jx with y.", if there is one joker. x is its number, and y is the card it should be replaced with. * "Replace J1 with x and J2 with y.", if both jokers are present in the input data. x and y here represent distinct cards with which one should replace the first and the second jokers correspondingly. On the third line print the coordinates of the upper left corner of the first square 3 Γ— 3 in the format "Put the first square to (r, c).", where r and c are the row and the column correspondingly. In the same manner print on the fourth line the coordinates of the second square 3 Γ— 3 in the format "Put the second square to (r, c).". If there are several solutions to that problem, print any of them. If there are no solutions, print of the single line "No solution." without the quotes. See the samples to understand the output format better. Examples Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H 5S TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output No solution. Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H J1 TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. Replace J1 with 2H. Put the first square to (1, 1). Put the second square to (2, 4). Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H QC TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. There are no jokers. Put the first square to (1, 1). Put the second square to (2, 4). Note The pretests cover all the possible output formats. Tags: brute force, implementation Correct Solution: ``` ranks = '23456789TJQKA' suits = 'CDHS' n, m = [int(i) for i in input().split()] b = [input().split() for _ in range(n)] p = [r + s for r in ranks for s in suits] j1, j2 = False, False for r in b: for c in r: if c == 'J1': j1 = True elif c == 'J2': j2 = True else: p.remove(c) def valid(n, m): r = set() s = set() for ni in range(n, n + 3): for mi in range(m, m + 3): c = b[ni][mi] if c == 'J1': c = j1v if c == 'J2': c = j2v r.add(c[0]) s.add(c[1]) return len(r) == 9 or len(s) == 1 def solve(): global j1v, j2v, n0, m0, n1, m1 for j1v in p: for j2v in p: if j1v == j2v: continue for n0 in range(n-2): for m0 in range(m-2): if not valid(n0, m0): continue for n1 in range(n-2): for m1 in range(m-2): if (n0 + 2 < n1 or n1 + 2 < n0 or m0 + 2 < m1 or m1 + 2 < m0): if valid(n1, m1): return True return False if solve(): print('Solution exists.') if j1 and j2: print('Replace J1 with {} and J2 with {}.'.format(j1v, j2v)) elif j1: print('Replace J1 with {}.'.format(j1v)) elif j2: print('Replace J2 with {}.'.format(j2v)) else: print('There are no jokers.') print('Put the first square to ({}, {}).'.format(n0+1, m0+1)) print('Put the second square to ({}, {}).'.format(n1+1, m1+1)) else: print('No solution.') ```
99,125
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has a pack of 54 cards (52 standard cards and 2 distinct jokers). That is all he has at the moment. Not to die from boredom, Vasya plays Solitaire with them. Vasya lays out nm cards as a rectangle n Γ— m. If there are jokers among them, then Vasya should change them with some of the rest of 54 - nm cards (which are not layed out) so that there were no jokers left. Vasya can pick the cards to replace the jokers arbitrarily. Remember, that each card presents in pack exactly once (i. e. in a single copy). Vasya tries to perform the replacements so that the solitaire was solved. Vasya thinks that the solitaire is solved if after the jokers are replaced, there exist two non-overlapping squares 3 Γ— 3, inside each of which all the cards either have the same suit, or pairwise different ranks. Determine by the initial position whether the solitaire can be solved or not. If it can be solved, show the way in which it is possible. Input The first line contains integers n and m (3 ≀ n, m ≀ 17, n Γ— m ≀ 52). Next n lines contain m words each. Each word consists of two letters. The jokers are defined as "J1" and "J2" correspondingly. For the rest of the cards, the first letter stands for the rank and the second one β€” for the suit. The possible ranks are: "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K" and "A". The possible suits are: "C", "D", "H" and "S". All the cards are different. Output If the Solitaire can be solved, print on the first line "Solution exists." without the quotes. On the second line print in what way the jokers can be replaced. Three variants are possible: * "There are no jokers.", if there are no jokers in the input data. * "Replace Jx with y.", if there is one joker. x is its number, and y is the card it should be replaced with. * "Replace J1 with x and J2 with y.", if both jokers are present in the input data. x and y here represent distinct cards with which one should replace the first and the second jokers correspondingly. On the third line print the coordinates of the upper left corner of the first square 3 Γ— 3 in the format "Put the first square to (r, c).", where r and c are the row and the column correspondingly. In the same manner print on the fourth line the coordinates of the second square 3 Γ— 3 in the format "Put the second square to (r, c).". If there are several solutions to that problem, print any of them. If there are no solutions, print of the single line "No solution." without the quotes. See the samples to understand the output format better. Examples Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H 5S TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output No solution. Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H J1 TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. Replace J1 with 2H. Put the first square to (1, 1). Put the second square to (2, 4). Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H QC TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. There are no jokers. Put the first square to (1, 1). Put the second square to (2, 4). Note The pretests cover all the possible output formats. Tags: brute force, implementation Correct Solution: ``` n, m = map(int, input().split()) num = '23456789TJQKA' col = 'CDHS' all = [] for i in num: for j in col: all.append(i + j) my = [[] for x in range(n)] j1 = 0 j2 = 0 for i in range(n): my[i] = input().split() for j in range(m): if my[i][j][1] == '1': j1 = (i, j) elif my[i][j][1] == '2': j2 = (i, j) else: all.remove(my[i][j]) def i_seg(a, b, c, d): return a <= d and b >= c def i_sq(a, b): return i_seg(a[0], a[2], b[0], b[2]) and i_seg(a[1], a[3], b[1], b[3]) def suit(cards, x, y): col = set() num = set() for i in range(x, x + 3): for j in range(y, y + 3): col.add(cards[i][j][1]) num.add(cards[i][j][0]) return len(col) == 1 or len(num) == 9 def ok(cards, n, m): for a in range(n - 2): for b in range(m - 2): if suit(cards, a, b): for c in range(n - 2): for d in range(m - 2): if not i_sq((a, b, a + 2, b + 2), (c, d, c + 2, d + 2)) and suit(cards, c, d): return (a, b, c, d) return 0 for i in all: for j in all: if i != j: new = my if j1 != 0: new[j1[0]][j1[1]] = i if j2 != 0: new[j2[0]][j2[1]] = j q = ok(new, n, m) if q: print('Solution exists.') if j1 == 0 and j2 == 0: print('There are no jokers.') elif j1 != 0 and j2 != 0: print('Replace J1 with %s and J2 with %s.' % (i, j)) elif j1 != 0: print('Replace J1 with %s.' % (i)) else: print('Replace J2 with %s.' % (j)) print('Put the first square to (%d, %d).' % (q[0] + 1, q[1] + 1)) print('Put the second square to (%d, %d).' % (q[2] + 1, q[3] + 1)) quit() print('No solution.') ```
99,126
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has a pack of 54 cards (52 standard cards and 2 distinct jokers). That is all he has at the moment. Not to die from boredom, Vasya plays Solitaire with them. Vasya lays out nm cards as a rectangle n Γ— m. If there are jokers among them, then Vasya should change them with some of the rest of 54 - nm cards (which are not layed out) so that there were no jokers left. Vasya can pick the cards to replace the jokers arbitrarily. Remember, that each card presents in pack exactly once (i. e. in a single copy). Vasya tries to perform the replacements so that the solitaire was solved. Vasya thinks that the solitaire is solved if after the jokers are replaced, there exist two non-overlapping squares 3 Γ— 3, inside each of which all the cards either have the same suit, or pairwise different ranks. Determine by the initial position whether the solitaire can be solved or not. If it can be solved, show the way in which it is possible. Input The first line contains integers n and m (3 ≀ n, m ≀ 17, n Γ— m ≀ 52). Next n lines contain m words each. Each word consists of two letters. The jokers are defined as "J1" and "J2" correspondingly. For the rest of the cards, the first letter stands for the rank and the second one β€” for the suit. The possible ranks are: "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K" and "A". The possible suits are: "C", "D", "H" and "S". All the cards are different. Output If the Solitaire can be solved, print on the first line "Solution exists." without the quotes. On the second line print in what way the jokers can be replaced. Three variants are possible: * "There are no jokers.", if there are no jokers in the input data. * "Replace Jx with y.", if there is one joker. x is its number, and y is the card it should be replaced with. * "Replace J1 with x and J2 with y.", if both jokers are present in the input data. x and y here represent distinct cards with which one should replace the first and the second jokers correspondingly. On the third line print the coordinates of the upper left corner of the first square 3 Γ— 3 in the format "Put the first square to (r, c).", where r and c are the row and the column correspondingly. In the same manner print on the fourth line the coordinates of the second square 3 Γ— 3 in the format "Put the second square to (r, c).". If there are several solutions to that problem, print any of them. If there are no solutions, print of the single line "No solution." without the quotes. See the samples to understand the output format better. Examples Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H 5S TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output No solution. Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H J1 TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. Replace J1 with 2H. Put the first square to (1, 1). Put the second square to (2, 4). Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H QC TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. There are no jokers. Put the first square to (1, 1). Put the second square to (2, 4). Note The pretests cover all the possible output formats. Submitted Solution: ``` #!/usr/bin/env python3 import itertools class Solitaire: def __init__(self): # Read inputs (self.n,self.m) = map(int,input().split()) self.table = [input().split() for i in range(self.n)] # Determine the unused cards and the positions of the jokers ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"] suits = ["C", "D", "H", "S"] deck = set(("%s%s" % card) for card in itertools.product(ranks,suits)) self.J1_position = None self.J2_position = None for (r,c) in itertools.product(range(self.n), range(self.m)): card = self.table[r][c] deck.discard(card) if (card == "J1"): self.J1_position = (r,c) elif (card == "J2"): self.J2_position = (r,c) self.unused_cards = list(deck) self.unused_cards.sort() # Sort to make things deterministic (easier for testing) def is_solved_square(self, r, c): cards = [self.table[r+ro][c+co] for (ro, co) in itertools.product(range(3), range(3))] suits = set(card[1] for card in cards) ranks = set(card[0] for card in cards) solved = (len(suits) == 1) or (len(ranks) == 9) return solved def is_solved(self): all_positions = itertools.product(range(self.n-2), range(self.m-2)) all_solved_squares = [(r,c) for (r,c) in all_positions if self.is_solved_square(r,c)] for ((r1, c1), (r2,c2)) in itertools.combinations(all_solved_squares, 2): if (abs(r1-r2) >= 3) or (abs(c1-c2) >= 3): return ((r1,c1),(r2,c2)) return None def replace_card(self, position, card): (r,c) = position self.table[r][c] = card def print_solution(self, joker_line, solution): if (solution == None): print("No solution.") else: ((r1,c1),(r2,c2)) = solution print("Solution exists.") print(joker_line) print("Put the first square to (%d, %d)." % (r1+1,c1+1)) print("Put the second square to (%d, %d)." % (r2+1,c2+1)) exit() def solve(self): if (self.J1_position != None) and (self.J2_position != None): for (replacement1, replacement2) in itertools.permutations(self.unused_cards,2): self.replace_card(self.J1_position, replacement1) self.replace_card(self.J2_position, replacement2) solution = self.is_solved() if (solution): self.print_solution("Replace J1 with %s and J2 with %s." % (replacement1, replacement2), solution) elif (self.J1_position != None): for replacement in self.unused_cards: self.replace_card(self.J1_position, replacement) solution = self.is_solved() if (solution): self.print_solution("Replace J1 with %s." % replacement, solution) elif (self.J2_position != None): for replacement in self.unused_cards: self.replace_card(self.J2_position, replacement) solution = self.is_solved() if (solution): self.print_solution("Replace J2 with %s." % replacement, solution) else: solution = self.is_solved() self.print_solution("There are no jokers.", solution) self.print_solution("", None) Solitaire().solve() ``` Yes
99,127
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has a pack of 54 cards (52 standard cards and 2 distinct jokers). That is all he has at the moment. Not to die from boredom, Vasya plays Solitaire with them. Vasya lays out nm cards as a rectangle n Γ— m. If there are jokers among them, then Vasya should change them with some of the rest of 54 - nm cards (which are not layed out) so that there were no jokers left. Vasya can pick the cards to replace the jokers arbitrarily. Remember, that each card presents in pack exactly once (i. e. in a single copy). Vasya tries to perform the replacements so that the solitaire was solved. Vasya thinks that the solitaire is solved if after the jokers are replaced, there exist two non-overlapping squares 3 Γ— 3, inside each of which all the cards either have the same suit, or pairwise different ranks. Determine by the initial position whether the solitaire can be solved or not. If it can be solved, show the way in which it is possible. Input The first line contains integers n and m (3 ≀ n, m ≀ 17, n Γ— m ≀ 52). Next n lines contain m words each. Each word consists of two letters. The jokers are defined as "J1" and "J2" correspondingly. For the rest of the cards, the first letter stands for the rank and the second one β€” for the suit. The possible ranks are: "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K" and "A". The possible suits are: "C", "D", "H" and "S". All the cards are different. Output If the Solitaire can be solved, print on the first line "Solution exists." without the quotes. On the second line print in what way the jokers can be replaced. Three variants are possible: * "There are no jokers.", if there are no jokers in the input data. * "Replace Jx with y.", if there is one joker. x is its number, and y is the card it should be replaced with. * "Replace J1 with x and J2 with y.", if both jokers are present in the input data. x and y here represent distinct cards with which one should replace the first and the second jokers correspondingly. On the third line print the coordinates of the upper left corner of the first square 3 Γ— 3 in the format "Put the first square to (r, c).", where r and c are the row and the column correspondingly. In the same manner print on the fourth line the coordinates of the second square 3 Γ— 3 in the format "Put the second square to (r, c).". If there are several solutions to that problem, print any of them. If there are no solutions, print of the single line "No solution." without the quotes. See the samples to understand the output format better. Examples Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H 5S TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output No solution. Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H J1 TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. Replace J1 with 2H. Put the first square to (1, 1). Put the second square to (2, 4). Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H QC TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. There are no jokers. Put the first square to (1, 1). Put the second square to (2, 4). Note The pretests cover all the possible output formats. Submitted Solution: ``` '''input 3 6 2H 3H 4H 5H 2S 3S 6H 7H 8H 9H 4S 5S TH JH QH KH 6S 7S ''' from sys import stdin import math from copy import deepcopy def find_jokers(grid, n, m): jokers = [] for i in range(n): for j in range(m): if grid[i][j] == 'J1' and len(jokers) > 0: jokers.insert(0, [i, j]) elif (grid[i][j] == 'J1' or grid[i][j] == 'J2'): jokers.append([i, j]) return jokers def get_remain(grid, n, m): total = set() for typ in ['D', 'S', 'H', 'C']: for rank in ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A']: total.add(rank + typ) grid_set = set() for i in range(n): for j in range(m): grid_set.add(grid[i][j]) r = total.difference(grid_set) r = list(r) return r def replace(cgrid, x, y, item): cgrid[x][y] = item def first_condition(grid, x, y): suit = set() for i in range(x, x + 3): for j in range(y, y + 3): suit.add(grid[i][j][1]) if len(suit) == 1: return True else: return False def second_condition(grid, x, y): rank = set() for i in range(x, x + 3): for j in range(y, y + 3): rank.add(grid[i][j][0]) if len(rank) == 9: return True else: return False def check_mark(mark, x, y): for i in range(x, x + 3): for j in range(y, y + 3): if mark[i][j] == True: return False else: return True def make_mark(mark, x, y): for i in range(x, x + 3): for j in range(y, y + 3): mark[i][j] = True def check(grid, n, m): count = 0 mark = [[False for x in range(m)] for y in range(n)] for i in range(n): if i + 3 <= n: for j in range(m): if j + 3 <= m: if check_mark(mark, i, j): if first_condition(grid, i, j) or second_condition(grid, i, j): count += 1 make_mark(mark, i, j) #print(mark) if count >= 2: return True else: return False def get_ans(grid, n, m): ans = [] mark = [[False for x in range(m)] for y in range(n)] for i in range(n): if i + 3 <= n: for j in range(m): if j + 3 <= m: if check_mark(mark, i, j): if first_condition(grid, i, j) or second_condition(grid, i, j): ans.append([i, j]) make_mark(mark, i, j) return ans # main starts n, m = list(map(int, stdin.readline().split())) grid = [] for _ in range(n): grid.append(list(stdin.readline().split())) jokers = find_jokers(grid, n, m) remaining = get_remain(grid, n, m) #print(remaining) if len(jokers) == 2: for i in range(len(remaining) - 1): for j in range(i + 1, len(remaining)): cgrid = deepcopy(grid) fx, fy = jokers[0] sx, sy = jokers[1] replace(cgrid, fx, fy, remaining[i]) replace(cgrid, sx, sy, remaining[j]) if check(cgrid, n, m): print('Solution exists.') print('Replace J1 with ' + str(remaining[i])+ ' and J2 with '+ str(remaining[j])+ '.') ans = get_ans(cgrid, n, m) print('Put the first square to ' + '(' + str(ans[0][0] + 1) + ', ' + str(ans[0][1] + 1) + ').') print('Put the second square to ' + '(' + str(ans[1][0] + 1) + ', ' + str(ans[1][1] + 1) + ').') exit() else: cgrid = deepcopy(grid) replace(cgrid, sx, sy, remaining[i]) replace(cgrid, fx, fy, remaining[j]) if check(cgrid, n, m, ): print('Solution exists.') print('Replace J1 with ' + str(remaining[j])+ ' and J2 with '+ str(remaining[i])+ '.') ans = get_ans(cgrid, n, m) print('Put the first square to ' + '(' + str(ans[0][0] + 1) + ', ' + str(ans[0][1] + 1) + ').') print('Put the second square to ' + '(' + str(ans[1][0] + 1) + ', ' + str(ans[1][1] + 1) + ').') exit() else: pass elif len(jokers) == 1: for i in range(len(remaining)): cgrid = deepcopy(grid) fx, fy = jokers[0] replace(cgrid, fx, fy, remaining[i]) if check(cgrid, n, m): print('Solution exists.') print('Replace '+ str(grid[fx][fy]) +' with ' + str(remaining[i]) +'.') ans = get_ans(cgrid, n, m) print('Put the first square to ' + '(' + str(ans[0][0] + 1) + ', ' + str(ans[0][1] + 1) + ').') print('Put the second square to ' + '(' + str(ans[1][0] + 1) + ', ' + str(ans[1][1] + 1) + ').') exit() else: continue else: if check(grid, n, m): print('Solution exists.') print("There are no jokers.") ans = get_ans(grid, n, m) print('Put the first square to ' + '(' + str(ans[0][0] + 1) + ', ' + str(ans[0][1] + 1) + ').') print('Put the second square to ' + '(' + str(ans[1][0] + 1) + ', ' + str(ans[1][1] + 1) + ').') exit() else: pass print("No solution.") ``` Yes
99,128
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has a pack of 54 cards (52 standard cards and 2 distinct jokers). That is all he has at the moment. Not to die from boredom, Vasya plays Solitaire with them. Vasya lays out nm cards as a rectangle n Γ— m. If there are jokers among them, then Vasya should change them with some of the rest of 54 - nm cards (which are not layed out) so that there were no jokers left. Vasya can pick the cards to replace the jokers arbitrarily. Remember, that each card presents in pack exactly once (i. e. in a single copy). Vasya tries to perform the replacements so that the solitaire was solved. Vasya thinks that the solitaire is solved if after the jokers are replaced, there exist two non-overlapping squares 3 Γ— 3, inside each of which all the cards either have the same suit, or pairwise different ranks. Determine by the initial position whether the solitaire can be solved or not. If it can be solved, show the way in which it is possible. Input The first line contains integers n and m (3 ≀ n, m ≀ 17, n Γ— m ≀ 52). Next n lines contain m words each. Each word consists of two letters. The jokers are defined as "J1" and "J2" correspondingly. For the rest of the cards, the first letter stands for the rank and the second one β€” for the suit. The possible ranks are: "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K" and "A". The possible suits are: "C", "D", "H" and "S". All the cards are different. Output If the Solitaire can be solved, print on the first line "Solution exists." without the quotes. On the second line print in what way the jokers can be replaced. Three variants are possible: * "There are no jokers.", if there are no jokers in the input data. * "Replace Jx with y.", if there is one joker. x is its number, and y is the card it should be replaced with. * "Replace J1 with x and J2 with y.", if both jokers are present in the input data. x and y here represent distinct cards with which one should replace the first and the second jokers correspondingly. On the third line print the coordinates of the upper left corner of the first square 3 Γ— 3 in the format "Put the first square to (r, c).", where r and c are the row and the column correspondingly. In the same manner print on the fourth line the coordinates of the second square 3 Γ— 3 in the format "Put the second square to (r, c).". If there are several solutions to that problem, print any of them. If there are no solutions, print of the single line "No solution." without the quotes. See the samples to understand the output format better. Examples Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H 5S TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output No solution. Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H J1 TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. Replace J1 with 2H. Put the first square to (1, 1). Put the second square to (2, 4). Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H QC TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. There are no jokers. Put the first square to (1, 1). Put the second square to (2, 4). Note The pretests cover all the possible output formats. Submitted Solution: ``` suits = ['C', 'D', 'H', 'S', 'W'] ranks = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'] def parse(c): if c == 'J1': return 52 if c == 'J2': return 53 return 13 * suits.index(c[1]) + ranks.index(c[0]) def summarize(cards): s = [0] * 4 r = [0] * 13 j1, j2 = False, False for i in cards: if i < 52: s[i // 13] += 1 r[i % 13] += 1 elif i == 52: j1 = True else: j2 = True return s, r, j1, j2 n, m = map(int, input().split()) board = [ [parse(c) for c in input().split()] for _ in range(n) ] pack = set(range(54)) for r in board: pack -= set(r) ps, pr, pj1, pj2 = summarize(pack) jc = [[0] * (m - 2) for _ in range(n - 2)] ji = [[False] * (m - 2) for _ in range(n - 2)] valid = [[False] * (m - 2) for _ in range(n - 2)] subs = [[None] * (m - 2) for _ in range(n - 2)] for ni in range(n - 2): for mi in range(m - 2): ss, sr, sj1, sj2 = summarize( board[ni + nj][mi + mj] for nj in range(3) for mj in range(3)) if not sj1 and not sj2: if max(ss) == 9 or max(sr) == 1: valid[ni][mi] = True elif sj1 and sj2: jc[ni][mi] = 2 if max(ss) == 7: ssi = ss.index(7) for pi in pack: if pi // 13 != ssi: continue for pj in pack: if pj == pi: continue if pj // 13 != ssi: continue subs[ni][mi] = [pi, pj] valid[ni][mi] = True if max(sr) == 1: for pi in pack: if sr[pi % 13] == 1: continue for pj in pack: if pj % 13 == pi % 13: continue if sr[pj % 13] == 1: continue subs[ni][mi] = [pi, pj] valid[ni][mi] = True else: jc[ni][mi] = 1 ji[ni][mi] = 0 if sj1 else 1 pc = set() if max(ss) == 8: ssi = ss.index(8) for p in pack: if p // 13 == ssi: pc.add(p) if max(sr) == 1: for p in pack: if sr[p % 13] == 0: pc.add(p) if len(pc) > 0: valid[ni][mi] = True subs[ni][mi] = pc def solve(): for ni0 in range(n - 2): for mi0 in range(m - 2): if not valid[ni0][mi0]: continue for ni1 in range(n - 2): for mi1 in range(m - 2): if not valid[ni1][mi1]: continue if (((ni1 >= ni0 and ni1 <= ni0 + 2) or (ni0 >= ni1 and ni0 <= ni1 + 2)) and ((mi1 >= mi0 and mi1 <= mi0 + 2) or (mi0 >= mi1 and mi0 <= mi1 + 2))): continue ja = [None, None] if jc[ni0][mi0] == 0 and jc[ni1][mi1] == 0: return True, (0, 0), ja, ((ni0, mi0), (ni1, mi1)) elif jc[ni0][mi0] == 1 and jc[ni1][mi1] == 1: s0 = list(subs[ni0][mi0]) s1 = list(subs[ni1][mi1]) if len(s1) == 1 and s1[0] in s0: s0.remove(s1[0]) if len(s0) == 0: continue ja[ji[ni0][mi0]] = s0[0] if s0[0] in s1: s1.remove(s0[0]) ja[ji[ni1][mi1]] = s1[0] return True, (1, 1), ja, ((ni0, mi0), (ni1, mi1)) elif jc[ni0][mi0] == 2: ja = subs[ni0][mi0] elif jc[ni1][mi1] == 2: ja = subs[ni1][mi1] elif jc[ni0][mi0] == 1: ja[ji[ni0][mi0]] = list(subs[ni0][mi0])[0] else: ja[ji[ni1][mi1]] = list(subs[ni1][mi1])[0] return True, (jc[ni0][mi0], jc[ni1][mi1]), ja, ((ni0, mi0), (ni1, mi1)) return False, 0, [None, None], None v, jc, j, c = solve() if 52 in pack: pack.remove(52) if 53 in pack: pack.remove(53) if j[0] is not None: pack.remove(j[0]) if j[1] is not None: pack.remove(j[1]) if not pj1 and j[0] is None: j[0] = pack.pop() if not pj2 and j[1] is None: j[1] = pack.pop() for i in range(2): if j[i] is not None: j[i] = ranks[j[i] % 13] + suits[j[i] // 13] if not v: print('No solution.') else: print('Solution exists.') if pj1 and pj2: print('There are no jokers.') elif not pj1 and not pj2: print('Replace J1 with {} and J2 with {}.'.format(j[0], j[1])) elif not pj1: print('Replace J1 with {}.'.format(j[0])) else: print('Replace J2 with {}.'.format(j[1])) print('Put the first square to ({}, {}).'.format(c[0][0]+1, c[0][1]+1)) print('Put the second square to ({}, {}).'.format(c[1][0]+1, c[1][1]+1)) ``` Yes
99,129
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has a pack of 54 cards (52 standard cards and 2 distinct jokers). That is all he has at the moment. Not to die from boredom, Vasya plays Solitaire with them. Vasya lays out nm cards as a rectangle n Γ— m. If there are jokers among them, then Vasya should change them with some of the rest of 54 - nm cards (which are not layed out) so that there were no jokers left. Vasya can pick the cards to replace the jokers arbitrarily. Remember, that each card presents in pack exactly once (i. e. in a single copy). Vasya tries to perform the replacements so that the solitaire was solved. Vasya thinks that the solitaire is solved if after the jokers are replaced, there exist two non-overlapping squares 3 Γ— 3, inside each of which all the cards either have the same suit, or pairwise different ranks. Determine by the initial position whether the solitaire can be solved or not. If it can be solved, show the way in which it is possible. Input The first line contains integers n and m (3 ≀ n, m ≀ 17, n Γ— m ≀ 52). Next n lines contain m words each. Each word consists of two letters. The jokers are defined as "J1" and "J2" correspondingly. For the rest of the cards, the first letter stands for the rank and the second one β€” for the suit. The possible ranks are: "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K" and "A". The possible suits are: "C", "D", "H" and "S". All the cards are different. Output If the Solitaire can be solved, print on the first line "Solution exists." without the quotes. On the second line print in what way the jokers can be replaced. Three variants are possible: * "There are no jokers.", if there are no jokers in the input data. * "Replace Jx with y.", if there is one joker. x is its number, and y is the card it should be replaced with. * "Replace J1 with x and J2 with y.", if both jokers are present in the input data. x and y here represent distinct cards with which one should replace the first and the second jokers correspondingly. On the third line print the coordinates of the upper left corner of the first square 3 Γ— 3 in the format "Put the first square to (r, c).", where r and c are the row and the column correspondingly. In the same manner print on the fourth line the coordinates of the second square 3 Γ— 3 in the format "Put the second square to (r, c).". If there are several solutions to that problem, print any of them. If there are no solutions, print of the single line "No solution." without the quotes. See the samples to understand the output format better. Examples Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H 5S TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output No solution. Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H J1 TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. Replace J1 with 2H. Put the first square to (1, 1). Put the second square to (2, 4). Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H QC TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. There are no jokers. Put the first square to (1, 1). Put the second square to (2, 4). Note The pretests cover all the possible output formats. Submitted Solution: ``` suits = ['C', 'D', 'H', 'S', 'W'] ranks = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'] def parse(c): if c == 'J1': return 52 if c == 'J2': return 53 return 13 * suits.index(c[1]) + ranks.index(c[0]) def summarize(cards): s = [0] * 4 r = [0] * 13 j1, j2 = False, False for i in cards: if i < 52: s[i // 13] += 1 r[i % 13] += 1 elif i == 52: j1 = True else: j2 = True return s, r, j1, j2 n, m = map(int, input().split()) board = [ [parse(c) for c in input().split()] for _ in range(n) ] pack = set(range(54)) for r in board: pack -= set(r) ps, pr, pj1, pj2 = summarize(pack) jc = [[0] * (m - 2) for _ in range(n - 2)] ji = [[False] * (m - 2) for _ in range(n - 2)] valid = [[False] * (m - 2) for _ in range(n - 2)] subs = [[None] * (m - 2) for _ in range(n - 2)] for ni in range(n - 2): for mi in range(m - 2): ss, sr, sj1, sj2 = summarize( board[ni + nj][mi + mj] for nj in range(3) for mj in range(3)) if not sj1 and not sj2: if max(ss) == 9 or max(sr) == 1: valid[ni][mi] = True elif sj1 and sj2: jc[ni][mi] = 2 if max(ss) == 7: ssi = ss.index(7) for pi in pack: if pi // 13 != ssi: continue for pj in pack: if pj == pi: continue if pj // 13 != ssi: continue subs[ni][mi] = [pi, pj] valid[ni][mi] = True if max(sr) == 1: for pi in pack: if sr[pi % 13] == 1: continue for pj in pack: if pj % 13 == pi % 13: continue subs[ni][mi] = [pi, pj] valid[ni][mi] = True else: jc[ni][mi] = 1 ji[ni][mi] = 0 if sj1 else 1 pc = set() if max(ss) == 8: ssi = ss.index(8) for p in pack: if p // 13 == ssi: pc.add(p) if max(sr) == 1: for p in pack: if sr[p % 13] == 0: pc.add(p) if len(pc) > 0: valid[ni][mi] = True subs[ni][mi] = pc def solve(): for ni0 in range(n - 2): for mi0 in range(m - 2): if not valid[ni0][mi0]: continue for ni1 in range(n - 2): for mi1 in range(m - 2): if not valid[ni1][mi1]: continue if (((ni1 >= ni0 and ni1 < ni0 + 2) or (ni0 >= ni1 and ni0 < ni1 + 2)) and ((mi1 >= mi0 and mi1 < mi0 + 2) or (mi0 >= mi1 and mi0 < mi1 + 2))): continue ja = [None, None] if jc[ni0][mi0] == 0 and jc[ni1][mi1] == 0: return True, (0, 0), ja, ((ni0, mi0), (ni1, mi1)) elif jc[ni0][mi0] == 1 and jc[ni1][mi1] == 1: s0 = list(subs[ni0][mi0]) s1 = list(subs[ni1][mi1]) if len(s1) == 1 and s1[0] in s0: s0.remove(s1[0]) if len(s0) == 0: continue ja[ji[ni0][mi0]] = s0[0] if s0[0] in s1: s1.remove(s0[0]) ja[ji[ni1][mi1]] = s1[0] return True, (1, 1), ja, ((ni0, mi0), (ni1, mi1)) elif jc[ni0][mi0] == 2: ja = subs[ni0][mi0] elif jc[ni1][mi1] == 2: ja = subs[ni1][mi1] elif jc[ni0][mi0] == 1: ja[ji[ni0][mi0]] = list(subs[ni0][mi0])[0] else: ja[ji[ni1][mi1]] = list(subs[ni1][mi1])[0] return True, (jc[ni0][mi0], jc[ni1][mi1]), ja, ((ni0, mi0), (ni1, mi1)) return False, None, None, None v, jc, j, c = solve() if j is not None: for i in range(2): if j[i] is not None: j[i] = ranks[j[i] % 13] + suits[j[i] // 13] if not v: print('No solution.') else: print('Solution exists.') if pj1 and pj2: print('There are no jokers.') elif not pj1 and not pj2: print('Replace J1 with {} and J2 with {}.'.format(j[0], j[1])) elif not pj1: print('Replace J1 with {}.'.format(j[0])) else: print('Replace J2 with {}.'.format(j[1])) print('Put the first square to ({}, {}).'.format(c[0][0]+1, c[0][1]+1)) print('Put the second square to ({}, {}).'.format(c[1][0]+1, c[1][1]+1)) ``` No
99,130
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has a pack of 54 cards (52 standard cards and 2 distinct jokers). That is all he has at the moment. Not to die from boredom, Vasya plays Solitaire with them. Vasya lays out nm cards as a rectangle n Γ— m. If there are jokers among them, then Vasya should change them with some of the rest of 54 - nm cards (which are not layed out) so that there were no jokers left. Vasya can pick the cards to replace the jokers arbitrarily. Remember, that each card presents in pack exactly once (i. e. in a single copy). Vasya tries to perform the replacements so that the solitaire was solved. Vasya thinks that the solitaire is solved if after the jokers are replaced, there exist two non-overlapping squares 3 Γ— 3, inside each of which all the cards either have the same suit, or pairwise different ranks. Determine by the initial position whether the solitaire can be solved or not. If it can be solved, show the way in which it is possible. Input The first line contains integers n and m (3 ≀ n, m ≀ 17, n Γ— m ≀ 52). Next n lines contain m words each. Each word consists of two letters. The jokers are defined as "J1" and "J2" correspondingly. For the rest of the cards, the first letter stands for the rank and the second one β€” for the suit. The possible ranks are: "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K" and "A". The possible suits are: "C", "D", "H" and "S". All the cards are different. Output If the Solitaire can be solved, print on the first line "Solution exists." without the quotes. On the second line print in what way the jokers can be replaced. Three variants are possible: * "There are no jokers.", if there are no jokers in the input data. * "Replace Jx with y.", if there is one joker. x is its number, and y is the card it should be replaced with. * "Replace J1 with x and J2 with y.", if both jokers are present in the input data. x and y here represent distinct cards with which one should replace the first and the second jokers correspondingly. On the third line print the coordinates of the upper left corner of the first square 3 Γ— 3 in the format "Put the first square to (r, c).", where r and c are the row and the column correspondingly. In the same manner print on the fourth line the coordinates of the second square 3 Γ— 3 in the format "Put the second square to (r, c).". If there are several solutions to that problem, print any of them. If there are no solutions, print of the single line "No solution." without the quotes. See the samples to understand the output format better. Examples Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H 5S TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output No solution. Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H J1 TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. Replace J1 with 2H. Put the first square to (1, 1). Put the second square to (2, 4). Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H QC TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. There are no jokers. Put the first square to (1, 1). Put the second square to (2, 4). Note The pretests cover all the possible output formats. Submitted Solution: ``` def init_cards(): result = {} for suit in ('C', 'D', 'H', 'S'): for price in ('2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'): result[price + suit] = True return result def main(stdin): cards = init_cards() user_cards = [] n, m = next(stdin).split() n, m = int(n), int(m) for row in stdin: cards_row = [] for card in row.split(): cards_row.append(card) if card in cards: del cards[card] user_cards.append(cards_row) founded = [] jockers = set() row = 0 while row + 3 <= n: col = 0 if len(founded) == 1: if row < founded[0][0] + 2: col = founded[0][1] + 2 while col + 3 <= m: check_price = set() for i in range(row, row + 3): for j in range(col, col + 3): if user_cards[i][j] in ('J1', 'J2'): check_price.add(user_cards[i][j]) jockers.add(user_cards[i][j]) else: check_price.add(user_cards[i][j][0]) if len(check_price) == 9: founded.append((row + 1, col + 1)) col += 3 break else: col += 1 row += 1 jockers_founded = [] for i, jocker in enumerate(jockers): item = cards.popitem() jockers_founded.append((jocker, item[0])) if len(founded) > 1: print('Solution exists.') if len(jockers_founded): jockers_founded.sort(key=lambda x: x[0]) print('Replace ' + ' and '.join('%s with %s' % f for f in jockers_founded) + '.') else: print('There are no jokers.') print('Put the first square to %s.' % repr(founded[0])) print('Put the second square to %s.' % repr(founded[1])) else: print('No solution.') if __name__ == '__main__': import sys main(sys.stdin) ``` No
99,131
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has a pack of 54 cards (52 standard cards and 2 distinct jokers). That is all he has at the moment. Not to die from boredom, Vasya plays Solitaire with them. Vasya lays out nm cards as a rectangle n Γ— m. If there are jokers among them, then Vasya should change them with some of the rest of 54 - nm cards (which are not layed out) so that there were no jokers left. Vasya can pick the cards to replace the jokers arbitrarily. Remember, that each card presents in pack exactly once (i. e. in a single copy). Vasya tries to perform the replacements so that the solitaire was solved. Vasya thinks that the solitaire is solved if after the jokers are replaced, there exist two non-overlapping squares 3 Γ— 3, inside each of which all the cards either have the same suit, or pairwise different ranks. Determine by the initial position whether the solitaire can be solved or not. If it can be solved, show the way in which it is possible. Input The first line contains integers n and m (3 ≀ n, m ≀ 17, n Γ— m ≀ 52). Next n lines contain m words each. Each word consists of two letters. The jokers are defined as "J1" and "J2" correspondingly. For the rest of the cards, the first letter stands for the rank and the second one β€” for the suit. The possible ranks are: "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K" and "A". The possible suits are: "C", "D", "H" and "S". All the cards are different. Output If the Solitaire can be solved, print on the first line "Solution exists." without the quotes. On the second line print in what way the jokers can be replaced. Three variants are possible: * "There are no jokers.", if there are no jokers in the input data. * "Replace Jx with y.", if there is one joker. x is its number, and y is the card it should be replaced with. * "Replace J1 with x and J2 with y.", if both jokers are present in the input data. x and y here represent distinct cards with which one should replace the first and the second jokers correspondingly. On the third line print the coordinates of the upper left corner of the first square 3 Γ— 3 in the format "Put the first square to (r, c).", where r and c are the row and the column correspondingly. In the same manner print on the fourth line the coordinates of the second square 3 Γ— 3 in the format "Put the second square to (r, c).". If there are several solutions to that problem, print any of them. If there are no solutions, print of the single line "No solution." without the quotes. See the samples to understand the output format better. Examples Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H 5S TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output No solution. Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H J1 TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. Replace J1 with 2H. Put the first square to (1, 1). Put the second square to (2, 4). Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H QC TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. There are no jokers. Put the first square to (1, 1). Put the second square to (2, 4). Note The pretests cover all the possible output formats. Submitted Solution: ``` def init_cards(): result = {} for suit in ('C', 'D', 'H', 'S'): for price in ('2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'): result[price + suit] = True return result def main(stdin): cards = init_cards() user_cards = [] n, m = next(stdin).split() n, m = int(n), int(m) for row in stdin: cards_row = [] for card in row.split(): cards_row.append(card) if card in cards: del cards[card] user_cards.append(cards_row) founded = [] jockers_founded = [] row = 0 while row + 3 <= n: if len(founded) > 2: break col = 0 if len(founded) == 1: if row < founded[0][0] + 2: col = founded[0][1] + 2 while col + 3 <= m: check_price = set() jockers = [] for i in range(row, row + 3): for j in range(col, col + 3): if user_cards[i][j] in ('J1', 'J2'): jockers.append(user_cards[i][j]) else: check_price.add(user_cards[i][j][0]) for i, jocker in enumerate(jockers): for card in cards: if card[0] not in check_price: check_price.add(card[0]) jockers[i] = (jocker, card) del cards[card] break if len(check_price) == 9: founded.append((row + 1, col + 1)) for jocker in jockers: jockers_founded.append(jocker) col += 3 break else: col += 1 row += 1 if len(founded) > 1: print('Solution exists.') if len(jockers_founded): jockers_founded.sort(key=lambda x: x[0]) print('Replace ' + ' and '.join('%s with %s' % f for f in jockers_founded) + '.') else: print('There are no jokers.') print('Put the first square to %s.' % repr(founded[0])) print('Put the second square to %s.' % repr(founded[1])) else: print('No solution.') if __name__ == '__main__': import sys main(sys.stdin) ``` No
99,132
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has a pack of 54 cards (52 standard cards and 2 distinct jokers). That is all he has at the moment. Not to die from boredom, Vasya plays Solitaire with them. Vasya lays out nm cards as a rectangle n Γ— m. If there are jokers among them, then Vasya should change them with some of the rest of 54 - nm cards (which are not layed out) so that there were no jokers left. Vasya can pick the cards to replace the jokers arbitrarily. Remember, that each card presents in pack exactly once (i. e. in a single copy). Vasya tries to perform the replacements so that the solitaire was solved. Vasya thinks that the solitaire is solved if after the jokers are replaced, there exist two non-overlapping squares 3 Γ— 3, inside each of which all the cards either have the same suit, or pairwise different ranks. Determine by the initial position whether the solitaire can be solved or not. If it can be solved, show the way in which it is possible. Input The first line contains integers n and m (3 ≀ n, m ≀ 17, n Γ— m ≀ 52). Next n lines contain m words each. Each word consists of two letters. The jokers are defined as "J1" and "J2" correspondingly. For the rest of the cards, the first letter stands for the rank and the second one β€” for the suit. The possible ranks are: "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K" and "A". The possible suits are: "C", "D", "H" and "S". All the cards are different. Output If the Solitaire can be solved, print on the first line "Solution exists." without the quotes. On the second line print in what way the jokers can be replaced. Three variants are possible: * "There are no jokers.", if there are no jokers in the input data. * "Replace Jx with y.", if there is one joker. x is its number, and y is the card it should be replaced with. * "Replace J1 with x and J2 with y.", if both jokers are present in the input data. x and y here represent distinct cards with which one should replace the first and the second jokers correspondingly. On the third line print the coordinates of the upper left corner of the first square 3 Γ— 3 in the format "Put the first square to (r, c).", where r and c are the row and the column correspondingly. In the same manner print on the fourth line the coordinates of the second square 3 Γ— 3 in the format "Put the second square to (r, c).". If there are several solutions to that problem, print any of them. If there are no solutions, print of the single line "No solution." without the quotes. See the samples to understand the output format better. Examples Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H 5S TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output No solution. Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H J1 TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. Replace J1 with 2H. Put the first square to (1, 1). Put the second square to (2, 4). Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H QC TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. There are no jokers. Put the first square to (1, 1). Put the second square to (2, 4). Note The pretests cover all the possible output formats. Submitted Solution: ``` '''input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H QC TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C ''' from sys import stdin import math from copy import deepcopy def find_jokers(grid, n, m): jokers = [] for i in range(n): for j in range(m): if grid[i][j] == 'J1' and len(jokers) > 0: jokers.insert(0, [i, j]) elif (grid[i][j] == 'J1' or grid[i][j] == 'J2'): jokers.append([i, j]) return jokers def get_remain(grid, n, m): total = set() for typ in ['D', 'S', 'H', 'C']: for rank in ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A']: total.add(rank + typ) grid_set = set() for i in range(n): for j in range(m): grid_set.add(grid[i][j]) r = total.difference(grid_set) r = list(r) return r def replace(cgrid, x, y, item): cgrid[x][y] = item def first_condition(grid, x, y): suit = set() for i in range(x, x + 3): for j in range(y, y + 3): suit.add(grid[i][j][1]) if len(suit) == 1: return True else: return False def second_condition(grid, x, y): rank = set() for i in range(x, x + 3): for j in range(y, y + 3): rank.add(grid[i][j][0]) if len(rank) == 9: return True else: return False def check_mark(mark, x, y): for i in range(x, x + 3): for j in range(y, y + 3): if mark[i][j] == True: return False else: return True def make_mark(mark, x, y): for i in range(x, x + 3): for j in range(y, y + 3): mark[i][j] == True def check(grid, n, m): count = 0 mark = [[False for x in range(m)] for y in range(n)] for i in range(n): if i + 3 <= n: for j in range(m): if j + 3 <= m: if check_mark(mark, i, j): if first_condition(grid, i, j) or second_condition(grid, i, j): count += 1 make_mark(mark, i, j) if count >= 2: return True else: return False def get_ans(grid, n, m): ans = [] mark = [[False for x in range(m)] for y in range(n)] for i in range(n): if i + 3 <= n: for j in range(m): if j + 3 <= m: if check_mark(mark, i, j): if first_condition(grid, i, j) or second_condition(grid, i, j): ans.append([i, j]) return ans # main starts n, m = list(map(int, stdin.readline().split())) grid = [] for _ in range(n): grid.append(list(stdin.readline().split())) jokers = find_jokers(grid, n, m) remaining = get_remain(grid, n, m) #print(remaining) if len(jokers) == 2: for i in range(len(remaining) - 1): for j in range(i + 1, len(remaining)): cgrid = deepcopy(grid) fx, fy = jokers[0] sx, sy = jokers[1] replace(cgrid, fx, fy, remaining[i]) replace(cgrid, sx, sy, remaining[j]) if check(cgrid, n, m): print('Solution exists.') print('Replace J1 with ' + str(remaining[i])+ ' and J2 with '+ str(remaining[j])+ '.') ans = get_ans(grid, n, m) print('Put the first square to ' + '(' + str(ans[0][0] + 1) + ', ' + str(ans[0][1] + 1) + ').') print('Put the second square to ' + '(' + str(ans[1][0] + 1) + ', ' + str(ans[1][1] + 1) + ').') exit() else: cgrid = deepcopy(grid) replace(cgrid, sx, sy, remaining[i]) replace(cgrid, fx, fy, remaining[j]) if check(cgrid, n, m, ): print('Solution exists.') print('Replace J1 with ' + str(remaining[i])+ ' and J2 with '+ str(remaining[j])+ '.') ans = get_ans(grid, n, m) print('Put the first square to ' + '(' + str(ans[0][0] + 1) + ', ' + str(ans[0][1] + 1) + ').') print('Put the second square to ' + '(' + str(ans[1][0] + 1) + ', ' + str(ans[1][1] + 1) + ').') exit() else: pass elif len(jokers) == 1: for i in range(len(remaining)): cgrid = deepcopy(grid) fx, fy = jokers[0] replace(cgrid, fx, fy, remaining[i]) if check(grid, n, m): print('Solution exists.') print('Replace J1 with ' + str(remaining[i]) +'.') ans = get_ans(grid, n, m) print('Put the first square to ' + '(' + str(ans[0][0] + 1) + ', ' + str(ans[0][1] + 1) + ').') print('Put the second square to ' + '(' + str(ans[1][0] + 1) + ', ' + str(ans[1][1] + 1) + ').') exit() else: continue else: if check(grid, n, m): print('Solution exists.') print("There are no jokers.") ans = get_ans(grid, n, m) print('Put the first square to ' + '(' + str(ans[0][0] + 1) + ', ' + str(ans[0][1] + 1) + ').') print('Put the second square to ' + '(' + str(ans[1][0] + 1) + ', ' + str(ans[1][1] + 1) + ').') exit() else: pass print("No solution.") ``` No
99,133
Provide tags and a correct Python 3 solution for this coding contest problem. As you have noticed, there are lovely girls in Arpa’s land. People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crushi. <image> Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are as follows. The game consists of rounds. Assume person x wants to start a round, he calls crushx and says: "Oww...wwf" (the letter w is repeated t times) and cuts off the phone immediately. If t > 1 then crushx calls crushcrushx and says: "Oww...wwf" (the letter w is repeated t - 1 times) and cuts off the phone immediately. The round continues until some person receives an "Owf" (t = 1). This person is called the Joon-Joon of the round. There can't be two rounds at the same time. Mehrdad has an evil plan to make the game more funny, he wants to find smallest t (t β‰₯ 1) such that for each person x, if x starts some round and y becomes the Joon-Joon of the round, then by starting from y, x would become the Joon-Joon of the round. Find such t for Mehrdad if it's possible. Some strange fact in Arpa's land is that someone can be himself's crush (i.e. crushi = i). Input The first line of input contains integer n (1 ≀ n ≀ 100) β€” the number of people in Arpa's land. The second line contains n integers, i-th of them is crushi (1 ≀ crushi ≀ n) β€” the number of i-th person's crush. Output If there is no t satisfying the condition, print -1. Otherwise print such smallest t. Examples Input 4 2 3 1 4 Output 3 Input 4 4 4 4 4 Output -1 Input 4 2 1 4 3 Output 1 Note In the first sample suppose t = 3. If the first person starts some round: The first person calls the second person and says "Owwwf", then the second person calls the third person and says "Owwf", then the third person calls the first person and says "Owf", so the first person becomes Joon-Joon of the round. So the condition is satisfied if x is 1. The process is similar for the second and the third person. If the fourth person starts some round: The fourth person calls himself and says "Owwwf", then he calls himself again and says "Owwf", then he calls himself for another time and says "Owf", so the fourth person becomes Joon-Joon of the round. So the condition is satisfied when x is 4. In the last example if the first person starts a round, then the second person becomes the Joon-Joon, and vice versa. Tags: dfs and similar, math Correct Solution: ``` ###### ### ####### ####### ## # ##### ### ##### # # # # # # # # # # # # # ### # # # # # # # # # # # # # ### ###### ######### # # # # # # ######### # ###### ######### # # # # # # ######### # # # # # # # # # # # #### # # # # # # # # # # ## # # # # # ###### # # ####### ####### # # ##### # # # # from __future__ import print_function # for PyPy2 # from itertools import permutations # from functools import cmp_to_key # for adding custom comparator # from fractions import Fraction from collections import * from sys import stdin # from bisect import * from heapq import * from math import * g = lambda : stdin.readline().strip() gl = lambda : g().split() gil = lambda : [int(var) for var in gl()] gfl = lambda : [float(var) for var in gl()] gcl = lambda : list(g()) gbs = lambda : [int(var) for var in g()] rr = lambda x : reversed(range(x)) mod = int(1e9)+7 inf = float("inf") n, = gil() nxt = [0] + gil() vis = [0]*(n+1) c = set() def cycle(p): tt = 0 start = p while vis[p] == 0: tt += 1 vis[p] = 1 p = nxt[p] if p != start: print(-1) exit() return tt for p in range(1, n+1): if vis[p] : continue tt = cycle(p) if tt&1 : c.add(tt) else: c.add(tt//2) if 1 in c:c.remove(1) c = list(c) # print(c) if len(c) <= 1: print(c[0] if c else 1) exit() pr = {} def getPrime(x): ppr = {} for i in range(2, int(sqrt(x))+1): po = 0 while x%i == 0: x //= i po += 1 if po:ppr[i] = po if x > 1: ppr[x] = 1 return ppr for v in c: for pi, po in getPrime(v).items(): pr[pi] = max(pr.get(pi, 0), po) ans = 1 for pi, po in pr.items(): ans *= pi**po print(ans) ```
99,134
Provide tags and a correct Python 3 solution for this coding contest problem. As you have noticed, there are lovely girls in Arpa’s land. People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crushi. <image> Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are as follows. The game consists of rounds. Assume person x wants to start a round, he calls crushx and says: "Oww...wwf" (the letter w is repeated t times) and cuts off the phone immediately. If t > 1 then crushx calls crushcrushx and says: "Oww...wwf" (the letter w is repeated t - 1 times) and cuts off the phone immediately. The round continues until some person receives an "Owf" (t = 1). This person is called the Joon-Joon of the round. There can't be two rounds at the same time. Mehrdad has an evil plan to make the game more funny, he wants to find smallest t (t β‰₯ 1) such that for each person x, if x starts some round and y becomes the Joon-Joon of the round, then by starting from y, x would become the Joon-Joon of the round. Find such t for Mehrdad if it's possible. Some strange fact in Arpa's land is that someone can be himself's crush (i.e. crushi = i). Input The first line of input contains integer n (1 ≀ n ≀ 100) β€” the number of people in Arpa's land. The second line contains n integers, i-th of them is crushi (1 ≀ crushi ≀ n) β€” the number of i-th person's crush. Output If there is no t satisfying the condition, print -1. Otherwise print such smallest t. Examples Input 4 2 3 1 4 Output 3 Input 4 4 4 4 4 Output -1 Input 4 2 1 4 3 Output 1 Note In the first sample suppose t = 3. If the first person starts some round: The first person calls the second person and says "Owwwf", then the second person calls the third person and says "Owwf", then the third person calls the first person and says "Owf", so the first person becomes Joon-Joon of the round. So the condition is satisfied if x is 1. The process is similar for the second and the third person. If the fourth person starts some round: The fourth person calls himself and says "Owwwf", then he calls himself again and says "Owwf", then he calls himself for another time and says "Owf", so the fourth person becomes Joon-Joon of the round. So the condition is satisfied when x is 4. In the last example if the first person starts a round, then the second person becomes the Joon-Joon, and vice versa. Tags: dfs and similar, math Correct Solution: ``` from math import gcd n = int(input()) crush = list(map(int,input().split())) crush = [0] + crush vis,dis,cyc,flag = [0]*(n+1), [-1]*(n+1), [], 1 def dfs(u,d): dis[u] = d vis[u] = 1 global flag v = crush[u] if vis[v]==0: dfs(v,d+1) else: if dis[v]==1: cyc.append(d) else: flag = 0 dis[u] = -1 for i in range(1,n+1): if not flag: break if vis[i]==0: dfs(i,1) if not flag or len(cyc)==0: print(-1) else: def lcm(a,b): return a*b//gcd(a,b) L = cyc[0] if not L%2: L //= 2 for i in range(1,len(cyc)): s = cyc[i] if not s%2: s //= 2 L = lcm(L,s) print(L) # C:\Users\Usuario\HOME2\Programacion\ACM ```
99,135
Provide tags and a correct Python 3 solution for this coding contest problem. As you have noticed, there are lovely girls in Arpa’s land. People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crushi. <image> Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are as follows. The game consists of rounds. Assume person x wants to start a round, he calls crushx and says: "Oww...wwf" (the letter w is repeated t times) and cuts off the phone immediately. If t > 1 then crushx calls crushcrushx and says: "Oww...wwf" (the letter w is repeated t - 1 times) and cuts off the phone immediately. The round continues until some person receives an "Owf" (t = 1). This person is called the Joon-Joon of the round. There can't be two rounds at the same time. Mehrdad has an evil plan to make the game more funny, he wants to find smallest t (t β‰₯ 1) such that for each person x, if x starts some round and y becomes the Joon-Joon of the round, then by starting from y, x would become the Joon-Joon of the round. Find such t for Mehrdad if it's possible. Some strange fact in Arpa's land is that someone can be himself's crush (i.e. crushi = i). Input The first line of input contains integer n (1 ≀ n ≀ 100) β€” the number of people in Arpa's land. The second line contains n integers, i-th of them is crushi (1 ≀ crushi ≀ n) β€” the number of i-th person's crush. Output If there is no t satisfying the condition, print -1. Otherwise print such smallest t. Examples Input 4 2 3 1 4 Output 3 Input 4 4 4 4 4 Output -1 Input 4 2 1 4 3 Output 1 Note In the first sample suppose t = 3. If the first person starts some round: The first person calls the second person and says "Owwwf", then the second person calls the third person and says "Owwf", then the third person calls the first person and says "Owf", so the first person becomes Joon-Joon of the round. So the condition is satisfied if x is 1. The process is similar for the second and the third person. If the fourth person starts some round: The fourth person calls himself and says "Owwwf", then he calls himself again and says "Owwf", then he calls himself for another time and says "Owf", so the fourth person becomes Joon-Joon of the round. So the condition is satisfied when x is 4. In the last example if the first person starts a round, then the second person becomes the Joon-Joon, and vice versa. Tags: dfs and similar, math Correct Solution: ``` def gcd(a, b): while b: a, b = b, a % b return a def lcm(a, b): return a * b // gcd(a, b) n = int(input()) a = list(map(int, input().split())) if sorted(a) != [i + 1 for i in range(n)]: print(-1) else: ans = 1 used = [0 for i in range(n)] for i in range(n): if used[i] == 0: j = i am = 0 while used[j] == 0: am += 1 used[j] = 1 j = a[j] - 1 if am % 2: ans = lcm(ans, am) else: ans = lcm(ans, am // 2) print(ans) ```
99,136
Provide tags and a correct Python 3 solution for this coding contest problem. As you have noticed, there are lovely girls in Arpa’s land. People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crushi. <image> Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are as follows. The game consists of rounds. Assume person x wants to start a round, he calls crushx and says: "Oww...wwf" (the letter w is repeated t times) and cuts off the phone immediately. If t > 1 then crushx calls crushcrushx and says: "Oww...wwf" (the letter w is repeated t - 1 times) and cuts off the phone immediately. The round continues until some person receives an "Owf" (t = 1). This person is called the Joon-Joon of the round. There can't be two rounds at the same time. Mehrdad has an evil plan to make the game more funny, he wants to find smallest t (t β‰₯ 1) such that for each person x, if x starts some round and y becomes the Joon-Joon of the round, then by starting from y, x would become the Joon-Joon of the round. Find such t for Mehrdad if it's possible. Some strange fact in Arpa's land is that someone can be himself's crush (i.e. crushi = i). Input The first line of input contains integer n (1 ≀ n ≀ 100) β€” the number of people in Arpa's land. The second line contains n integers, i-th of them is crushi (1 ≀ crushi ≀ n) β€” the number of i-th person's crush. Output If there is no t satisfying the condition, print -1. Otherwise print such smallest t. Examples Input 4 2 3 1 4 Output 3 Input 4 4 4 4 4 Output -1 Input 4 2 1 4 3 Output 1 Note In the first sample suppose t = 3. If the first person starts some round: The first person calls the second person and says "Owwwf", then the second person calls the third person and says "Owwf", then the third person calls the first person and says "Owf", so the first person becomes Joon-Joon of the round. So the condition is satisfied if x is 1. The process is similar for the second and the third person. If the fourth person starts some round: The fourth person calls himself and says "Owwwf", then he calls himself again and says "Owwf", then he calls himself for another time and says "Owf", so the fourth person becomes Joon-Joon of the round. So the condition is satisfied when x is 4. In the last example if the first person starts a round, then the second person becomes the Joon-Joon, and vice versa. Tags: dfs and similar, math Correct Solution: ``` import sys #sys.stdin=open("data.txt") input=sys.stdin.readline n=int(input()) l=list(map(lambda x:int(x)-1,input().split())) use=[] valid=1 for i in range(n): t=i for j in range(n+5): t=l[t] if t==i: if (j+1)%2==0: use.append((j+1)//2) else: use.append(j+1) break else: valid=0 if not valid: print("-1") else: # get lcm ans=1 for i in use: t=ans while ans%i: ans+=t print(ans) ```
99,137
Provide tags and a correct Python 3 solution for this coding contest problem. As you have noticed, there are lovely girls in Arpa’s land. People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crushi. <image> Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are as follows. The game consists of rounds. Assume person x wants to start a round, he calls crushx and says: "Oww...wwf" (the letter w is repeated t times) and cuts off the phone immediately. If t > 1 then crushx calls crushcrushx and says: "Oww...wwf" (the letter w is repeated t - 1 times) and cuts off the phone immediately. The round continues until some person receives an "Owf" (t = 1). This person is called the Joon-Joon of the round. There can't be two rounds at the same time. Mehrdad has an evil plan to make the game more funny, he wants to find smallest t (t β‰₯ 1) such that for each person x, if x starts some round and y becomes the Joon-Joon of the round, then by starting from y, x would become the Joon-Joon of the round. Find such t for Mehrdad if it's possible. Some strange fact in Arpa's land is that someone can be himself's crush (i.e. crushi = i). Input The first line of input contains integer n (1 ≀ n ≀ 100) β€” the number of people in Arpa's land. The second line contains n integers, i-th of them is crushi (1 ≀ crushi ≀ n) β€” the number of i-th person's crush. Output If there is no t satisfying the condition, print -1. Otherwise print such smallest t. Examples Input 4 2 3 1 4 Output 3 Input 4 4 4 4 4 Output -1 Input 4 2 1 4 3 Output 1 Note In the first sample suppose t = 3. If the first person starts some round: The first person calls the second person and says "Owwwf", then the second person calls the third person and says "Owwf", then the third person calls the first person and says "Owf", so the first person becomes Joon-Joon of the round. So the condition is satisfied if x is 1. The process is similar for the second and the third person. If the fourth person starts some round: The fourth person calls himself and says "Owwwf", then he calls himself again and says "Owwf", then he calls himself for another time and says "Owf", so the fourth person becomes Joon-Joon of the round. So the condition is satisfied when x is 4. In the last example if the first person starts a round, then the second person becomes the Joon-Joon, and vice versa. Tags: dfs and similar, math Correct Solution: ``` from math import gcd n = int(input()) arr = map(int, input().split()) arr = list(map(lambda x: x-1, arr)) res = 1 for i in range(n): p, k = 0, i for j in range(n): k = arr[k] if k == i: p = j break if k != i: print(-1) exit() p += 1 if p % 2 == 0: p //= 2 res = res * p // gcd(res, p) print(res) ```
99,138
Provide tags and a correct Python 3 solution for this coding contest problem. As you have noticed, there are lovely girls in Arpa’s land. People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crushi. <image> Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are as follows. The game consists of rounds. Assume person x wants to start a round, he calls crushx and says: "Oww...wwf" (the letter w is repeated t times) and cuts off the phone immediately. If t > 1 then crushx calls crushcrushx and says: "Oww...wwf" (the letter w is repeated t - 1 times) and cuts off the phone immediately. The round continues until some person receives an "Owf" (t = 1). This person is called the Joon-Joon of the round. There can't be two rounds at the same time. Mehrdad has an evil plan to make the game more funny, he wants to find smallest t (t β‰₯ 1) such that for each person x, if x starts some round and y becomes the Joon-Joon of the round, then by starting from y, x would become the Joon-Joon of the round. Find such t for Mehrdad if it's possible. Some strange fact in Arpa's land is that someone can be himself's crush (i.e. crushi = i). Input The first line of input contains integer n (1 ≀ n ≀ 100) β€” the number of people in Arpa's land. The second line contains n integers, i-th of them is crushi (1 ≀ crushi ≀ n) β€” the number of i-th person's crush. Output If there is no t satisfying the condition, print -1. Otherwise print such smallest t. Examples Input 4 2 3 1 4 Output 3 Input 4 4 4 4 4 Output -1 Input 4 2 1 4 3 Output 1 Note In the first sample suppose t = 3. If the first person starts some round: The first person calls the second person and says "Owwwf", then the second person calls the third person and says "Owwf", then the third person calls the first person and says "Owf", so the first person becomes Joon-Joon of the round. So the condition is satisfied if x is 1. The process is similar for the second and the third person. If the fourth person starts some round: The fourth person calls himself and says "Owwwf", then he calls himself again and says "Owwf", then he calls himself for another time and says "Owf", so the fourth person becomes Joon-Joon of the round. So the condition is satisfied when x is 4. In the last example if the first person starts a round, then the second person becomes the Joon-Joon, and vice versa. Tags: dfs and similar, math Correct Solution: ``` input() crush = [0] + [int(x) for x in input().split()] visited = set() circle_sizes = [] def gcd(a, b): return a if b == 0 else gcd(b, a%b) def lcm(a, b): return a * b // gcd(a, b) def solve(): for i in range(len(crush)): if i not in visited: start, cur, count = i, i, 0 while cur not in visited: visited.add(cur) count += 1 cur = crush[cur] if cur != start: return -1 circle_sizes.append(count if count % 2 else count // 2) if len(circle_sizes) == 1: return circle_sizes[0] ans = lcm(circle_sizes[0], circle_sizes[1]) for size in circle_sizes[2:]: ans = lcm(ans, size) return ans print(solve()) ```
99,139
Provide tags and a correct Python 3 solution for this coding contest problem. As you have noticed, there are lovely girls in Arpa’s land. People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crushi. <image> Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are as follows. The game consists of rounds. Assume person x wants to start a round, he calls crushx and says: "Oww...wwf" (the letter w is repeated t times) and cuts off the phone immediately. If t > 1 then crushx calls crushcrushx and says: "Oww...wwf" (the letter w is repeated t - 1 times) and cuts off the phone immediately. The round continues until some person receives an "Owf" (t = 1). This person is called the Joon-Joon of the round. There can't be two rounds at the same time. Mehrdad has an evil plan to make the game more funny, he wants to find smallest t (t β‰₯ 1) such that for each person x, if x starts some round and y becomes the Joon-Joon of the round, then by starting from y, x would become the Joon-Joon of the round. Find such t for Mehrdad if it's possible. Some strange fact in Arpa's land is that someone can be himself's crush (i.e. crushi = i). Input The first line of input contains integer n (1 ≀ n ≀ 100) β€” the number of people in Arpa's land. The second line contains n integers, i-th of them is crushi (1 ≀ crushi ≀ n) β€” the number of i-th person's crush. Output If there is no t satisfying the condition, print -1. Otherwise print such smallest t. Examples Input 4 2 3 1 4 Output 3 Input 4 4 4 4 4 Output -1 Input 4 2 1 4 3 Output 1 Note In the first sample suppose t = 3. If the first person starts some round: The first person calls the second person and says "Owwwf", then the second person calls the third person and says "Owwf", then the third person calls the first person and says "Owf", so the first person becomes Joon-Joon of the round. So the condition is satisfied if x is 1. The process is similar for the second and the third person. If the fourth person starts some round: The fourth person calls himself and says "Owwwf", then he calls himself again and says "Owwf", then he calls himself for another time and says "Owf", so the fourth person becomes Joon-Joon of the round. So the condition is satisfied when x is 4. In the last example if the first person starts a round, then the second person becomes the Joon-Joon, and vice versa. Tags: dfs and similar, math Correct Solution: ``` from fractions import gcd n = int(input()) crush = list(map(int,input().split())) was = [0] * n ans = 1 for i in range(n): if was[i]: continue num = i j = 0 while not was[num]: was[num] = 1 num = crush[num] - 1 j += 1 if i != num: ans = -1 break else: if j % 2 == 0: j //= 2 ans = ans * j // gcd(ans,j) print(ans) ```
99,140
Provide tags and a correct Python 3 solution for this coding contest problem. As you have noticed, there are lovely girls in Arpa’s land. People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crushi. <image> Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are as follows. The game consists of rounds. Assume person x wants to start a round, he calls crushx and says: "Oww...wwf" (the letter w is repeated t times) and cuts off the phone immediately. If t > 1 then crushx calls crushcrushx and says: "Oww...wwf" (the letter w is repeated t - 1 times) and cuts off the phone immediately. The round continues until some person receives an "Owf" (t = 1). This person is called the Joon-Joon of the round. There can't be two rounds at the same time. Mehrdad has an evil plan to make the game more funny, he wants to find smallest t (t β‰₯ 1) such that for each person x, if x starts some round and y becomes the Joon-Joon of the round, then by starting from y, x would become the Joon-Joon of the round. Find such t for Mehrdad if it's possible. Some strange fact in Arpa's land is that someone can be himself's crush (i.e. crushi = i). Input The first line of input contains integer n (1 ≀ n ≀ 100) β€” the number of people in Arpa's land. The second line contains n integers, i-th of them is crushi (1 ≀ crushi ≀ n) β€” the number of i-th person's crush. Output If there is no t satisfying the condition, print -1. Otherwise print such smallest t. Examples Input 4 2 3 1 4 Output 3 Input 4 4 4 4 4 Output -1 Input 4 2 1 4 3 Output 1 Note In the first sample suppose t = 3. If the first person starts some round: The first person calls the second person and says "Owwwf", then the second person calls the third person and says "Owwf", then the third person calls the first person and says "Owf", so the first person becomes Joon-Joon of the round. So the condition is satisfied if x is 1. The process is similar for the second and the third person. If the fourth person starts some round: The fourth person calls himself and says "Owwwf", then he calls himself again and says "Owwf", then he calls himself for another time and says "Owf", so the fourth person becomes Joon-Joon of the round. So the condition is satisfied when x is 4. In the last example if the first person starts a round, then the second person becomes the Joon-Joon, and vice versa. Tags: dfs and similar, math Correct Solution: ``` def gcd(a, b): return a if b == 0 else gcd(b, a % b) def lcm(a, b): return a * b // gcd(a, b) n = int(input()) c = [int(v)-1 for v in input().split(' ')] t = 1 for i in range(n): k = i for j in range(1, n+2): k = c[k] if k == i: break if j > n: print(-1) exit() t = lcm(t, j if j % 2 != 0 else j // 2) print(t) # Made By Mostafa_Khaled ```
99,141
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As you have noticed, there are lovely girls in Arpa’s land. People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crushi. <image> Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are as follows. The game consists of rounds. Assume person x wants to start a round, he calls crushx and says: "Oww...wwf" (the letter w is repeated t times) and cuts off the phone immediately. If t > 1 then crushx calls crushcrushx and says: "Oww...wwf" (the letter w is repeated t - 1 times) and cuts off the phone immediately. The round continues until some person receives an "Owf" (t = 1). This person is called the Joon-Joon of the round. There can't be two rounds at the same time. Mehrdad has an evil plan to make the game more funny, he wants to find smallest t (t β‰₯ 1) such that for each person x, if x starts some round and y becomes the Joon-Joon of the round, then by starting from y, x would become the Joon-Joon of the round. Find such t for Mehrdad if it's possible. Some strange fact in Arpa's land is that someone can be himself's crush (i.e. crushi = i). Input The first line of input contains integer n (1 ≀ n ≀ 100) β€” the number of people in Arpa's land. The second line contains n integers, i-th of them is crushi (1 ≀ crushi ≀ n) β€” the number of i-th person's crush. Output If there is no t satisfying the condition, print -1. Otherwise print such smallest t. Examples Input 4 2 3 1 4 Output 3 Input 4 4 4 4 4 Output -1 Input 4 2 1 4 3 Output 1 Note In the first sample suppose t = 3. If the first person starts some round: The first person calls the second person and says "Owwwf", then the second person calls the third person and says "Owwf", then the third person calls the first person and says "Owf", so the first person becomes Joon-Joon of the round. So the condition is satisfied if x is 1. The process is similar for the second and the third person. If the fourth person starts some round: The fourth person calls himself and says "Owwwf", then he calls himself again and says "Owwf", then he calls himself for another time and says "Owf", so the fourth person becomes Joon-Joon of the round. So the condition is satisfied when x is 4. In the last example if the first person starts a round, then the second person becomes the Joon-Joon, and vice versa. Submitted Solution: ``` import math n=int(input()) a=list(map(int,input().split())) if len(set(a))!=len(a): print(-1) else: ans,cycle=None,None visited=[False]*(n+1) for i in range(n): if visited[i+1]: continue count,v=0,[] index,value=i+1,-1 while value!=i+1: visited[index]=True v.append(index) value=a[index-1] index=value cycle=[len(v)//2,len(v)][len(v)%2] if i==0: ans=cycle else: ans=(ans*cycle)//math.gcd(ans,cycle) print(ans) ``` Yes
99,142
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As you have noticed, there are lovely girls in Arpa’s land. People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crushi. <image> Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are as follows. The game consists of rounds. Assume person x wants to start a round, he calls crushx and says: "Oww...wwf" (the letter w is repeated t times) and cuts off the phone immediately. If t > 1 then crushx calls crushcrushx and says: "Oww...wwf" (the letter w is repeated t - 1 times) and cuts off the phone immediately. The round continues until some person receives an "Owf" (t = 1). This person is called the Joon-Joon of the round. There can't be two rounds at the same time. Mehrdad has an evil plan to make the game more funny, he wants to find smallest t (t β‰₯ 1) such that for each person x, if x starts some round and y becomes the Joon-Joon of the round, then by starting from y, x would become the Joon-Joon of the round. Find such t for Mehrdad if it's possible. Some strange fact in Arpa's land is that someone can be himself's crush (i.e. crushi = i). Input The first line of input contains integer n (1 ≀ n ≀ 100) β€” the number of people in Arpa's land. The second line contains n integers, i-th of them is crushi (1 ≀ crushi ≀ n) β€” the number of i-th person's crush. Output If there is no t satisfying the condition, print -1. Otherwise print such smallest t. Examples Input 4 2 3 1 4 Output 3 Input 4 4 4 4 4 Output -1 Input 4 2 1 4 3 Output 1 Note In the first sample suppose t = 3. If the first person starts some round: The first person calls the second person and says "Owwwf", then the second person calls the third person and says "Owwf", then the third person calls the first person and says "Owf", so the first person becomes Joon-Joon of the round. So the condition is satisfied if x is 1. The process is similar for the second and the third person. If the fourth person starts some round: The fourth person calls himself and says "Owwwf", then he calls himself again and says "Owwf", then he calls himself for another time and says "Owf", so the fourth person becomes Joon-Joon of the round. So the condition is satisfied when x is 4. In the last example if the first person starts a round, then the second person becomes the Joon-Joon, and vice versa. Submitted Solution: ``` from fractions import gcd def dfs(node): if (vis[node] == idd[0]): return node cycleLen[0] += 1 vis[node] = idd[0] return dfs(crush[node]) n = int(input()) crush = list(map(int, input().split())) for i in range(n): crush[i] -= 1 vis = [0] * n ans = 10**100 idd = [0] V = [] for i in range(n): idd[0] += 1 cycleLen = [0] if (dfs(i) != i): ans = -1 V.append(cycleLen[0]) V.sort() def lcm(x, y): return x * y // gcd(x, y) if (ans == -1): print(ans) else: ans = 1 inc = 1 for item in V: mem = {} bad = False while (True): if (ans % item == 0): break if (item % 2 == 0 and ans % item == item // 2): break if (ans % item in mem): bad = True break mem[ans % item] = 1 ans += inc if (bad): ans = -1 break inc = lcm(inc, ans) print(ans) ``` Yes
99,143
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As you have noticed, there are lovely girls in Arpa’s land. People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crushi. <image> Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are as follows. The game consists of rounds. Assume person x wants to start a round, he calls crushx and says: "Oww...wwf" (the letter w is repeated t times) and cuts off the phone immediately. If t > 1 then crushx calls crushcrushx and says: "Oww...wwf" (the letter w is repeated t - 1 times) and cuts off the phone immediately. The round continues until some person receives an "Owf" (t = 1). This person is called the Joon-Joon of the round. There can't be two rounds at the same time. Mehrdad has an evil plan to make the game more funny, he wants to find smallest t (t β‰₯ 1) such that for each person x, if x starts some round and y becomes the Joon-Joon of the round, then by starting from y, x would become the Joon-Joon of the round. Find such t for Mehrdad if it's possible. Some strange fact in Arpa's land is that someone can be himself's crush (i.e. crushi = i). Input The first line of input contains integer n (1 ≀ n ≀ 100) β€” the number of people in Arpa's land. The second line contains n integers, i-th of them is crushi (1 ≀ crushi ≀ n) β€” the number of i-th person's crush. Output If there is no t satisfying the condition, print -1. Otherwise print such smallest t. Examples Input 4 2 3 1 4 Output 3 Input 4 4 4 4 4 Output -1 Input 4 2 1 4 3 Output 1 Note In the first sample suppose t = 3. If the first person starts some round: The first person calls the second person and says "Owwwf", then the second person calls the third person and says "Owwf", then the third person calls the first person and says "Owf", so the first person becomes Joon-Joon of the round. So the condition is satisfied if x is 1. The process is similar for the second and the third person. If the fourth person starts some round: The fourth person calls himself and says "Owwwf", then he calls himself again and says "Owwf", then he calls himself for another time and says "Owf", so the fourth person becomes Joon-Joon of the round. So the condition is satisfied when x is 4. In the last example if the first person starts a round, then the second person becomes the Joon-Joon, and vice versa. Submitted Solution: ``` from sys import stdin, stdout, setrecursionlimit input = stdin.readline # setrecursionlimit(int(1e6)) inf = float('inf') from collections import defaultdict as dd from collections import Counter, deque from heapq import * import math from math import floor, ceil, sqrt def geti(): return map(int, input().strip().split()) def getl(): return list(map(int, input().strip().split())) def getis(): return map(str, input().strip().split()) def getls(): return list(map(str, input().strip().split())) def gets(): return input().strip() def geta(): return int(input()) def print_s(s): stdout.write(s+'\n') def solve(): n = geta() a = getl() edges = dd(list) for i in range(n): edges[i].append(a[i]-1) dist = [[inf]*n for _ in range(n)] def dfs(root, par, temp = 0): vis[root] = True for node in edges[root]: dist[par][node] = temp + 1 if node not in vis: dfs(node, par, temp+1) ans = [] vis = dd(int) ok = dd(int) def dfs(root, par, dist = 0): if root == par and dist: ok[par] = True if dist&1: ans.append(dist) else: ans.append(dist//2) return if root in vis: return vis[root] = True for node in edges[root]: dfs(node, par, dist+1) need = [] for i in range(n): if i not in vis: need.append(i) dfs(i, i) # print(ans) for i in need: if i not in ok: print(-1) break else: ans = Counter(ans) ans = sorted(ans) # print(ans) vis = [False]*(len(ans)+1) ok = [] for i in range(len(ans)): if ans[i] == 1 or vis[i]: continue temp = [] for j in range(i, len(ans)): if ans[j] % ans[i] == 0: temp.append(ans[j]) vis[j] = True now = temp[0] g = temp[0] # print(temp) for k in range(1, len(temp)): now *= temp[k] g = math.gcd(g, temp[k]) now = now//g g = now if g!=now: ok.append(now//g) else: ok.append(now) # print(ok) now = 1 if ok: now = ok[0] g = ok[0] for k in range(1, len(ok)): now *= ok[k] g = math.gcd(g, ok[k]) now = now//g g = now print(now) if __name__=='__main__': solve() ``` Yes
99,144
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As you have noticed, there are lovely girls in Arpa’s land. People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crushi. <image> Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are as follows. The game consists of rounds. Assume person x wants to start a round, he calls crushx and says: "Oww...wwf" (the letter w is repeated t times) and cuts off the phone immediately. If t > 1 then crushx calls crushcrushx and says: "Oww...wwf" (the letter w is repeated t - 1 times) and cuts off the phone immediately. The round continues until some person receives an "Owf" (t = 1). This person is called the Joon-Joon of the round. There can't be two rounds at the same time. Mehrdad has an evil plan to make the game more funny, he wants to find smallest t (t β‰₯ 1) such that for each person x, if x starts some round and y becomes the Joon-Joon of the round, then by starting from y, x would become the Joon-Joon of the round. Find such t for Mehrdad if it's possible. Some strange fact in Arpa's land is that someone can be himself's crush (i.e. crushi = i). Input The first line of input contains integer n (1 ≀ n ≀ 100) β€” the number of people in Arpa's land. The second line contains n integers, i-th of them is crushi (1 ≀ crushi ≀ n) β€” the number of i-th person's crush. Output If there is no t satisfying the condition, print -1. Otherwise print such smallest t. Examples Input 4 2 3 1 4 Output 3 Input 4 4 4 4 4 Output -1 Input 4 2 1 4 3 Output 1 Note In the first sample suppose t = 3. If the first person starts some round: The first person calls the second person and says "Owwwf", then the second person calls the third person and says "Owwf", then the third person calls the first person and says "Owf", so the first person becomes Joon-Joon of the round. So the condition is satisfied if x is 1. The process is similar for the second and the third person. If the fourth person starts some round: The fourth person calls himself and says "Owwwf", then he calls himself again and says "Owwf", then he calls himself for another time and says "Owf", so the fourth person becomes Joon-Joon of the round. So the condition is satisfied when x is 4. In the last example if the first person starts a round, then the second person becomes the Joon-Joon, and vice versa. Submitted Solution: ``` #from collections import deque from functools import reduce n = int(input()) crush = [int(i) - 1 for i in input().split()] def parity_treat(n): if n%2 == 0: return n//2 else: return n def gcd(a,b): while b: a, b = b, a%b return a def lcm(a,b): return a * b // gcd(a,b) def lcmm(*args): return reduce(lcm, args) if len(set(crush)) < n: print(-1) else: component_size = [] visited = set() for i in range(n): if i not in visited: tmp = 1 start = i visited.add(start) j = crush[start] while j != start: visited.add(j) j = crush[j] tmp+=1 component_size.append(tmp) component_size = [parity_treat(i) for i in component_size] print(lcmm(*component_size)) ``` Yes
99,145
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As you have noticed, there are lovely girls in Arpa’s land. People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crushi. <image> Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are as follows. The game consists of rounds. Assume person x wants to start a round, he calls crushx and says: "Oww...wwf" (the letter w is repeated t times) and cuts off the phone immediately. If t > 1 then crushx calls crushcrushx and says: "Oww...wwf" (the letter w is repeated t - 1 times) and cuts off the phone immediately. The round continues until some person receives an "Owf" (t = 1). This person is called the Joon-Joon of the round. There can't be two rounds at the same time. Mehrdad has an evil plan to make the game more funny, he wants to find smallest t (t β‰₯ 1) such that for each person x, if x starts some round and y becomes the Joon-Joon of the round, then by starting from y, x would become the Joon-Joon of the round. Find such t for Mehrdad if it's possible. Some strange fact in Arpa's land is that someone can be himself's crush (i.e. crushi = i). Input The first line of input contains integer n (1 ≀ n ≀ 100) β€” the number of people in Arpa's land. The second line contains n integers, i-th of them is crushi (1 ≀ crushi ≀ n) β€” the number of i-th person's crush. Output If there is no t satisfying the condition, print -1. Otherwise print such smallest t. Examples Input 4 2 3 1 4 Output 3 Input 4 4 4 4 4 Output -1 Input 4 2 1 4 3 Output 1 Note In the first sample suppose t = 3. If the first person starts some round: The first person calls the second person and says "Owwwf", then the second person calls the third person and says "Owwf", then the third person calls the first person and says "Owf", so the first person becomes Joon-Joon of the round. So the condition is satisfied if x is 1. The process is similar for the second and the third person. If the fourth person starts some round: The fourth person calls himself and says "Owwwf", then he calls himself again and says "Owwf", then he calls himself for another time and says "Owf", so the fourth person becomes Joon-Joon of the round. So the condition is satisfied when x is 4. In the last example if the first person starts a round, then the second person becomes the Joon-Joon, and vice versa. Submitted Solution: ``` def gcd(a,b): while b > 0: a, b = b, a % b return a def lcm(a, b): return int(a * b / gcd(a, b)) def run(n, crush): visited = [False] * n cycle_size = 1 for i in range(0, n): if visited[i]: continue x = i c = 0 while (not visited[x]): visited[x] = True x = crush[x] - 1 c += 1 if x != i: return -1 cycle_size = lcm(cycle_size, c) if cycle_size % 2 == 0: cycle_size /= 2 return cycle_size n = int(input()) crush = [int(x) for x in input().split()] print(run(n,crush)) ``` No
99,146
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As you have noticed, there are lovely girls in Arpa’s land. People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crushi. <image> Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are as follows. The game consists of rounds. Assume person x wants to start a round, he calls crushx and says: "Oww...wwf" (the letter w is repeated t times) and cuts off the phone immediately. If t > 1 then crushx calls crushcrushx and says: "Oww...wwf" (the letter w is repeated t - 1 times) and cuts off the phone immediately. The round continues until some person receives an "Owf" (t = 1). This person is called the Joon-Joon of the round. There can't be two rounds at the same time. Mehrdad has an evil plan to make the game more funny, he wants to find smallest t (t β‰₯ 1) such that for each person x, if x starts some round and y becomes the Joon-Joon of the round, then by starting from y, x would become the Joon-Joon of the round. Find such t for Mehrdad if it's possible. Some strange fact in Arpa's land is that someone can be himself's crush (i.e. crushi = i). Input The first line of input contains integer n (1 ≀ n ≀ 100) β€” the number of people in Arpa's land. The second line contains n integers, i-th of them is crushi (1 ≀ crushi ≀ n) β€” the number of i-th person's crush. Output If there is no t satisfying the condition, print -1. Otherwise print such smallest t. Examples Input 4 2 3 1 4 Output 3 Input 4 4 4 4 4 Output -1 Input 4 2 1 4 3 Output 1 Note In the first sample suppose t = 3. If the first person starts some round: The first person calls the second person and says "Owwwf", then the second person calls the third person and says "Owwf", then the third person calls the first person and says "Owf", so the first person becomes Joon-Joon of the round. So the condition is satisfied if x is 1. The process is similar for the second and the third person. If the fourth person starts some round: The fourth person calls himself and says "Owwwf", then he calls himself again and says "Owwf", then he calls himself for another time and says "Owf", so the fourth person becomes Joon-Joon of the round. So the condition is satisfied when x is 4. In the last example if the first person starts a round, then the second person becomes the Joon-Joon, and vice versa. Submitted Solution: ``` ###### ### ####### ####### ## # ##### ### ##### # # # # # # # # # # # # # ### # # # # # # # # # # # # # ### ###### ######### # # # # # # ######### # ###### ######### # # # # # # ######### # # # # # # # # # # # #### # # # # # # # # # # ## # # # # # ###### # # ####### ####### # # ##### # # # # from __future__ import print_function # for PyPy2 # from itertools import permutations # from functools import cmp_to_key # for adding custom comparator # from fractions import Fraction from collections import * from sys import stdin # from bisect import * from heapq import * from math import * g = lambda : stdin.readline().strip() gl = lambda : g().split() gil = lambda : [int(var) for var in gl()] gfl = lambda : [float(var) for var in gl()] gcl = lambda : list(g()) gbs = lambda : [int(var) for var in g()] rr = lambda x : reversed(range(x)) mod = int(1e9)+7 inf = float("inf") n, = gil() nxt = [0] + gil() vis = [0]*(n+1) c = set() def cycle(p): tt = 0 start = p while vis[p] == 0: tt += 1 vis[p] = 1 p = nxt[p] if p != start: print(-1) exit() return tt for p in range(1, n+1): if vis[p] : continue tt = cycle(p) if tt&1 : c.add(tt) else: c.add(tt//2) if 1 in c:c.remove(1) c = list(c) if len(c) <= 1: print(c[0] if c else 1) exit() p = 1 gc = c[0] if c else 1 for ci in c: gc = gcd(gc, ci) p *= ci # print(p, gc) print(p//gc) ``` No
99,147
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As you have noticed, there are lovely girls in Arpa’s land. People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crushi. <image> Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are as follows. The game consists of rounds. Assume person x wants to start a round, he calls crushx and says: "Oww...wwf" (the letter w is repeated t times) and cuts off the phone immediately. If t > 1 then crushx calls crushcrushx and says: "Oww...wwf" (the letter w is repeated t - 1 times) and cuts off the phone immediately. The round continues until some person receives an "Owf" (t = 1). This person is called the Joon-Joon of the round. There can't be two rounds at the same time. Mehrdad has an evil plan to make the game more funny, he wants to find smallest t (t β‰₯ 1) such that for each person x, if x starts some round and y becomes the Joon-Joon of the round, then by starting from y, x would become the Joon-Joon of the round. Find such t for Mehrdad if it's possible. Some strange fact in Arpa's land is that someone can be himself's crush (i.e. crushi = i). Input The first line of input contains integer n (1 ≀ n ≀ 100) β€” the number of people in Arpa's land. The second line contains n integers, i-th of them is crushi (1 ≀ crushi ≀ n) β€” the number of i-th person's crush. Output If there is no t satisfying the condition, print -1. Otherwise print such smallest t. Examples Input 4 2 3 1 4 Output 3 Input 4 4 4 4 4 Output -1 Input 4 2 1 4 3 Output 1 Note In the first sample suppose t = 3. If the first person starts some round: The first person calls the second person and says "Owwwf", then the second person calls the third person and says "Owwf", then the third person calls the first person and says "Owf", so the first person becomes Joon-Joon of the round. So the condition is satisfied if x is 1. The process is similar for the second and the third person. If the fourth person starts some round: The fourth person calls himself and says "Owwwf", then he calls himself again and says "Owwf", then he calls himself for another time and says "Owf", so the fourth person becomes Joon-Joon of the round. So the condition is satisfied when x is 4. In the last example if the first person starts a round, then the second person becomes the Joon-Joon, and vice versa. Submitted Solution: ``` input() crush = [0] + [int(x) for x in input().split()] visited = set() circle_sizes = [] def solve(): for i in range(len(crush)): if i not in visited: start, cur, count = i, i, 0 while cur not in visited: visited.add(cur) count += 1 cur = crush[cur] if cur != start: return -1 circle_sizes.append(count if count % 2 else count // 2) ans = max(circle_sizes) for size in circle_sizes: if ans % size != 0: return -1 return ans print(solve()) ``` No
99,148
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As you have noticed, there are lovely girls in Arpa’s land. People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crushi. <image> Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are as follows. The game consists of rounds. Assume person x wants to start a round, he calls crushx and says: "Oww...wwf" (the letter w is repeated t times) and cuts off the phone immediately. If t > 1 then crushx calls crushcrushx and says: "Oww...wwf" (the letter w is repeated t - 1 times) and cuts off the phone immediately. The round continues until some person receives an "Owf" (t = 1). This person is called the Joon-Joon of the round. There can't be two rounds at the same time. Mehrdad has an evil plan to make the game more funny, he wants to find smallest t (t β‰₯ 1) such that for each person x, if x starts some round and y becomes the Joon-Joon of the round, then by starting from y, x would become the Joon-Joon of the round. Find such t for Mehrdad if it's possible. Some strange fact in Arpa's land is that someone can be himself's crush (i.e. crushi = i). Input The first line of input contains integer n (1 ≀ n ≀ 100) β€” the number of people in Arpa's land. The second line contains n integers, i-th of them is crushi (1 ≀ crushi ≀ n) β€” the number of i-th person's crush. Output If there is no t satisfying the condition, print -1. Otherwise print such smallest t. Examples Input 4 2 3 1 4 Output 3 Input 4 4 4 4 4 Output -1 Input 4 2 1 4 3 Output 1 Note In the first sample suppose t = 3. If the first person starts some round: The first person calls the second person and says "Owwwf", then the second person calls the third person and says "Owwf", then the third person calls the first person and says "Owf", so the first person becomes Joon-Joon of the round. So the condition is satisfied if x is 1. The process is similar for the second and the third person. If the fourth person starts some round: The fourth person calls himself and says "Owwwf", then he calls himself again and says "Owwf", then he calls himself for another time and says "Owf", so the fourth person becomes Joon-Joon of the round. So the condition is satisfied when x is 4. In the last example if the first person starts a round, then the second person becomes the Joon-Joon, and vice versa. Submitted Solution: ``` def read_int(): return int(input()) def read_ints(): return map(int, input().split(' ')) def gcd(x, y): return x if y == 0 else gcd(y, x % y) n = read_int() a = list(read_ints()) vis = [False for i in range(n)] loop = 0 ok = True for i in range(n): if vis[i]: continue current = i length = 0 while not vis[current]: vis[current] = True current = a[current] - 1 length += 1 if current != i: ok = False print(-1) break if loop == 0: loop = length else: loop = loop * length // gcd(loop, length) if ok: print(loop if loop > 2 else 1) ``` No
99,149
Provide tags and a correct Python 3 solution for this coding contest problem. Little Timofey likes integers a lot. Unfortunately, he is very young and can't work with very big integers, so he does all the operations modulo his favorite prime m. Also, Timofey likes to look for arithmetical progressions everywhere. One of his birthday presents was a sequence of distinct integers a1, a2, ..., an. Timofey wants to know whether he can rearrange the elements of the sequence so that is will be an arithmetical progression modulo m, or not. Arithmetical progression modulo m of length n with first element x and difference d is sequence of integers x, x + d, x + 2d, ..., x + (n - 1)Β·d, each taken modulo m. Input The first line contains two integers m and n (2 ≀ m ≀ 109 + 7, 1 ≀ n ≀ 105, m is prime) β€” Timofey's favorite prime module and the length of the sequence. The second line contains n distinct integers a1, a2, ..., an (0 ≀ ai < m) β€” the elements of the sequence. Output Print -1 if it is not possible to rearrange the elements of the sequence so that is will be an arithmetical progression modulo m. Otherwise, print two integers β€” the first element of the obtained progression x (0 ≀ x < m) and its difference d (0 ≀ d < m). If there are multiple answers, print any of them. Examples Input 17 5 0 2 4 13 15 Output 13 2 Input 17 5 0 2 4 13 14 Output -1 Input 5 3 1 2 3 Output 3 4 Tags: brute force, implementation, math, number theory Correct Solution: ``` from functools import reduce def gcd_extended(bigger, less): if less == 0: return(bigger, 1, 0) mod = bigger % less div = bigger // less gcd, c_less, c_mod = gcd_extended(less, mod) #gcd == c_less * less + c_mod * mod #mod == bigger - div * less #gcd = (c_less - c_mod * div) * less # + c_mod * bigger c_bigger = c_mod c_less = c_less - c_mod * div return(gcd, c_bigger, c_less) def mlp_inverse(x, p): one, c_p, c_x = gcd_extended(p, x) #one == c_x * x + c_p * p return (c_x + p) % p def tests(x, d, p, row): _row = set(row) n = len(row) if d == 0: return False for i in range(n): elem = x + i * d elem = (elem % p + p) % p if elem not in _row: return False return True p, n = (int(x) for x in input().split()) row = [int(x) for x in input().split()] if p == n: print(1, 1) exit() if n == 1: print(row[0], 0) exit() #precounting constants c1 = reduce(lambda x, y: (x + y) % p, row, 0) c2 = reduce(lambda x, y: (x + y * y) % p, row, 0) sum_i = reduce(lambda x, y: (x + y) % p, range(0, n), 0) sum_i_sq = reduce(lambda x, y: (x + y * y) % p, range(0, n), 0) inv_sum_i = mlp_inverse(sum_i, p) inv_sum_i_sq = mlp_inverse(sum_i_sq, p) #algorythm for x in row: # d = (c1 - n * x) * inv_sum_i d = (d % p + p) % p equasion = n * x * x + 2 * d * x * sum_i + d * d * sum_i_sq equasion = (equasion % p + p) % p # print(x, d) # print(c2, equasion) if (equasion == c2 and tests(x, d, p, row) ): print(x, d) exit() print(-1) ```
99,150
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Little Timofey likes integers a lot. Unfortunately, he is very young and can't work with very big integers, so he does all the operations modulo his favorite prime m. Also, Timofey likes to look for arithmetical progressions everywhere. One of his birthday presents was a sequence of distinct integers a1, a2, ..., an. Timofey wants to know whether he can rearrange the elements of the sequence so that is will be an arithmetical progression modulo m, or not. Arithmetical progression modulo m of length n with first element x and difference d is sequence of integers x, x + d, x + 2d, ..., x + (n - 1)Β·d, each taken modulo m. Input The first line contains two integers m and n (2 ≀ m ≀ 109 + 7, 1 ≀ n ≀ 105, m is prime) β€” Timofey's favorite prime module and the length of the sequence. The second line contains n distinct integers a1, a2, ..., an (0 ≀ ai < m) β€” the elements of the sequence. Output Print -1 if it is not possible to rearrange the elements of the sequence so that is will be an arithmetical progression modulo m. Otherwise, print two integers β€” the first element of the obtained progression x (0 ≀ x < m) and its difference d (0 ≀ d < m). If there are multiple answers, print any of them. Examples Input 17 5 0 2 4 13 15 Output 13 2 Input 17 5 0 2 4 13 14 Output -1 Input 5 3 1 2 3 Output 3 4 Submitted Solution: ``` from functools import reduce def gcd_extended(bigger, less): if less == 0: return(bigger, 1, 0) mod = bigger % less div = bigger // less gcd, c_less, c_mod = gcd_extended(less, mod) #gcd == c_less * less + c_mod * mod #mod == bigger - div * less #gcd = (c_less - c_mod * div) * less # + c_mod * bigger c_bigger = c_mod c_less = c_less - c_mod * div return(gcd, c_bigger, c_less) def mlp_inverse(x, p): one, c_p, c_x = gcd_extended(p, x) #one == c_x * x + c_p * p return (c_x + p) % p def tests(x, d, p, row): _row = set(row) n = len(row) if d == 0: return False for i in range(n): elem = x + i * d elem = (elem % p + p) % p if elem not in _row: return False return True p, n = (int(x) for x in input().split()) row = [int(x) for x in input().split()] #precounting constants c1 = reduce(lambda x, y: (x + y) % p, row, 0) c2 = reduce(lambda x, y: (x + y * y) % p, row, 0) sum_i = reduce(lambda x, y: (x + y) % p, range(0, n), 0) sum_i_sq = reduce(lambda x, y: (x + y * y) % p, range(0, n), 0) inv_sum_i = mlp_inverse(sum_i, p) inv_sum_i_sq = mlp_inverse(sum_i_sq, p) #algorythm for x in row: # d = (c1 - n * x) * inv_sum_i d = (d % p + p) % p equasion = n * x * x + 2 * d * sum_i + d * d * sum_i_sq equasion = (equasion % p + p) % p if (equasion == c2 and tests(x, d, p, row) ): print(x, d) break print(-1) ``` No
99,151
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Little boy Igor wants to become a traveller. At first, he decided to visit all the cities of his motherland β€” Uzhlyandia. It is widely known that Uzhlyandia has n cities connected with m bidirectional roads. Also, there are no two roads in the country that connect the same pair of cities, but roads starting and ending in the same city can exist. Igor wants to plan his journey beforehand. Boy thinks a path is good if the path goes over m - 2 roads twice, and over the other 2 exactly once. The good path can start and finish in any city of Uzhlyandia. Now he wants to know how many different good paths are in Uzhlyandia. Two paths are considered different if the sets of roads the paths goes over exactly once differ. Help Igor β€” calculate the number of good paths. Input The first line contains two integers n, m (1 ≀ n, m ≀ 106) β€” the number of cities and roads in Uzhlyandia, respectively. Each of the next m lines contains two integers u and v (1 ≀ u, v ≀ n) that mean that there is road between cities u and v. It is guaranteed that no road will be given in the input twice. That also means that for every city there is no more than one road that connects the city to itself. Output Print out the only integer β€” the number of good paths in Uzhlyandia. Examples Input 5 4 1 2 1 3 1 4 1 5 Output 6 Input 5 3 1 2 2 3 4 5 Output 0 Input 2 2 1 1 1 2 Output 1 Note In first sample test case the good paths are: * 2 β†’ 1 β†’ 3 β†’ 1 β†’ 4 β†’ 1 β†’ 5, * 2 β†’ 1 β†’ 3 β†’ 1 β†’ 5 β†’ 1 β†’ 4, * 2 β†’ 1 β†’ 4 β†’ 1 β†’ 5 β†’ 1 β†’ 3, * 3 β†’ 1 β†’ 2 β†’ 1 β†’ 4 β†’ 1 β†’ 5, * 3 β†’ 1 β†’ 2 β†’ 1 β†’ 5 β†’ 1 β†’ 4, * 4 β†’ 1 β†’ 2 β†’ 1 β†’ 3 β†’ 1 β†’ 5. There are good paths that are same with displayed above, because the sets of roads they pass over once are same: * 2 β†’ 1 β†’ 4 β†’ 1 β†’ 3 β†’ 1 β†’ 5, * 2 β†’ 1 β†’ 5 β†’ 1 β†’ 3 β†’ 1 β†’ 4, * 2 β†’ 1 β†’ 5 β†’ 1 β†’ 4 β†’ 1 β†’ 3, * 3 β†’ 1 β†’ 4 β†’ 1 β†’ 2 β†’ 1 β†’ 5, * 3 β†’ 1 β†’ 5 β†’ 1 β†’ 2 β†’ 1 β†’ 4, * 4 β†’ 1 β†’ 3 β†’ 1 β†’ 2 β†’ 1 β†’ 5, * and all the paths in the other direction. Thus, the answer is 6. In the second test case, Igor simply can not walk by all the roads. In the third case, Igor walks once over every road. Submitted Solution: ``` n, m = map(int, input().split()) ranks = [0]*(n+1) rep = list(range(0, n+1)) for _ in range(0, m): a, b = map(int, input().split()) ranks[a] += 1 ranks[b] += 1 mab = min(a, b) rep[a] = mab rep[b] = mab #print(rep) if max(rep) > 1: print(0) else: odd = len([x for x in ranks if x % 2 != 0]) print(odd * (odd - 1) // 2) ``` No
99,152
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Little boy Igor wants to become a traveller. At first, he decided to visit all the cities of his motherland β€” Uzhlyandia. It is widely known that Uzhlyandia has n cities connected with m bidirectional roads. Also, there are no two roads in the country that connect the same pair of cities, but roads starting and ending in the same city can exist. Igor wants to plan his journey beforehand. Boy thinks a path is good if the path goes over m - 2 roads twice, and over the other 2 exactly once. The good path can start and finish in any city of Uzhlyandia. Now he wants to know how many different good paths are in Uzhlyandia. Two paths are considered different if the sets of roads the paths goes over exactly once differ. Help Igor β€” calculate the number of good paths. Input The first line contains two integers n, m (1 ≀ n, m ≀ 106) β€” the number of cities and roads in Uzhlyandia, respectively. Each of the next m lines contains two integers u and v (1 ≀ u, v ≀ n) that mean that there is road between cities u and v. It is guaranteed that no road will be given in the input twice. That also means that for every city there is no more than one road that connects the city to itself. Output Print out the only integer β€” the number of good paths in Uzhlyandia. Examples Input 5 4 1 2 1 3 1 4 1 5 Output 6 Input 5 3 1 2 2 3 4 5 Output 0 Input 2 2 1 1 1 2 Output 1 Note In first sample test case the good paths are: * 2 β†’ 1 β†’ 3 β†’ 1 β†’ 4 β†’ 1 β†’ 5, * 2 β†’ 1 β†’ 3 β†’ 1 β†’ 5 β†’ 1 β†’ 4, * 2 β†’ 1 β†’ 4 β†’ 1 β†’ 5 β†’ 1 β†’ 3, * 3 β†’ 1 β†’ 2 β†’ 1 β†’ 4 β†’ 1 β†’ 5, * 3 β†’ 1 β†’ 2 β†’ 1 β†’ 5 β†’ 1 β†’ 4, * 4 β†’ 1 β†’ 2 β†’ 1 β†’ 3 β†’ 1 β†’ 5. There are good paths that are same with displayed above, because the sets of roads they pass over once are same: * 2 β†’ 1 β†’ 4 β†’ 1 β†’ 3 β†’ 1 β†’ 5, * 2 β†’ 1 β†’ 5 β†’ 1 β†’ 3 β†’ 1 β†’ 4, * 2 β†’ 1 β†’ 5 β†’ 1 β†’ 4 β†’ 1 β†’ 3, * 3 β†’ 1 β†’ 4 β†’ 1 β†’ 2 β†’ 1 β†’ 5, * 3 β†’ 1 β†’ 5 β†’ 1 β†’ 2 β†’ 1 β†’ 4, * 4 β†’ 1 β†’ 3 β†’ 1 β†’ 2 β†’ 1 β†’ 5, * and all the paths in the other direction. Thus, the answer is 6. In the second test case, Igor simply can not walk by all the roads. In the third case, Igor walks once over every road. Submitted Solution: ``` from collections import defaultdict n, m = map(int, input().split()) g = defaultdict(list) for i in range(m): a, b = map(int, input().split()) if a != b: g[a].append(b) g[b].append(a) else: g[a].append(b) color = [0]*(1 + n) stack = [] number_of_anj_comp = 0 for i in range(1, n + 1): if color[i] == 0: stack.append(i) edges = 0 while stack: v = stack.pop() if color[v] == 0: color[v] = 1 for u in g[v]: edges += 1 stack.append(u) color[v] = 2 if edges > 0: number_of_anj_comp += 1 if number_of_anj_comp > 1: print(0) else: ans = 0 for i in range(len(g)): k = len(g[i]) ans += k * (k - 1) // 2 print(ans) ``` No
99,153
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Little boy Igor wants to become a traveller. At first, he decided to visit all the cities of his motherland β€” Uzhlyandia. It is widely known that Uzhlyandia has n cities connected with m bidirectional roads. Also, there are no two roads in the country that connect the same pair of cities, but roads starting and ending in the same city can exist. Igor wants to plan his journey beforehand. Boy thinks a path is good if the path goes over m - 2 roads twice, and over the other 2 exactly once. The good path can start and finish in any city of Uzhlyandia. Now he wants to know how many different good paths are in Uzhlyandia. Two paths are considered different if the sets of roads the paths goes over exactly once differ. Help Igor β€” calculate the number of good paths. Input The first line contains two integers n, m (1 ≀ n, m ≀ 106) β€” the number of cities and roads in Uzhlyandia, respectively. Each of the next m lines contains two integers u and v (1 ≀ u, v ≀ n) that mean that there is road between cities u and v. It is guaranteed that no road will be given in the input twice. That also means that for every city there is no more than one road that connects the city to itself. Output Print out the only integer β€” the number of good paths in Uzhlyandia. Examples Input 5 4 1 2 1 3 1 4 1 5 Output 6 Input 5 3 1 2 2 3 4 5 Output 0 Input 2 2 1 1 1 2 Output 1 Note In first sample test case the good paths are: * 2 β†’ 1 β†’ 3 β†’ 1 β†’ 4 β†’ 1 β†’ 5, * 2 β†’ 1 β†’ 3 β†’ 1 β†’ 5 β†’ 1 β†’ 4, * 2 β†’ 1 β†’ 4 β†’ 1 β†’ 5 β†’ 1 β†’ 3, * 3 β†’ 1 β†’ 2 β†’ 1 β†’ 4 β†’ 1 β†’ 5, * 3 β†’ 1 β†’ 2 β†’ 1 β†’ 5 β†’ 1 β†’ 4, * 4 β†’ 1 β†’ 2 β†’ 1 β†’ 3 β†’ 1 β†’ 5. There are good paths that are same with displayed above, because the sets of roads they pass over once are same: * 2 β†’ 1 β†’ 4 β†’ 1 β†’ 3 β†’ 1 β†’ 5, * 2 β†’ 1 β†’ 5 β†’ 1 β†’ 3 β†’ 1 β†’ 4, * 2 β†’ 1 β†’ 5 β†’ 1 β†’ 4 β†’ 1 β†’ 3, * 3 β†’ 1 β†’ 4 β†’ 1 β†’ 2 β†’ 1 β†’ 5, * 3 β†’ 1 β†’ 5 β†’ 1 β†’ 2 β†’ 1 β†’ 4, * 4 β†’ 1 β†’ 3 β†’ 1 β†’ 2 β†’ 1 β†’ 5, * and all the paths in the other direction. Thus, the answer is 6. In the second test case, Igor simply can not walk by all the roads. In the third case, Igor walks once over every road. Submitted Solution: ``` from collections import defaultdict n, m = map(int, input().split()) g = defaultdict(list) for i in range(m): a, b = map(int, input().split()) if a != b: g[a].append(b) g[b].append(a) else: g[a].append(b) color = [0]*(1 + n) stack = [] number_of_anj_comp = 0 for i in range(1, n + 1): if color[i] == 0: stack.append(i) edges = 0 while stack: v = stack.pop() if color[v] == 0: color[v] = 1 for u in g[v]: edges += 1 stack.append(u) color[v] = 2 if edges > 0: number_of_anj_comp += 1 if number_of_anj_comp > 1: print(0) else: ans = 0 for i in range(1, n): k = len(g[i]) ans += k * (k - 1) // 2 print(ans) ``` No
99,154
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Little boy Igor wants to become a traveller. At first, he decided to visit all the cities of his motherland β€” Uzhlyandia. It is widely known that Uzhlyandia has n cities connected with m bidirectional roads. Also, there are no two roads in the country that connect the same pair of cities, but roads starting and ending in the same city can exist. Igor wants to plan his journey beforehand. Boy thinks a path is good if the path goes over m - 2 roads twice, and over the other 2 exactly once. The good path can start and finish in any city of Uzhlyandia. Now he wants to know how many different good paths are in Uzhlyandia. Two paths are considered different if the sets of roads the paths goes over exactly once differ. Help Igor β€” calculate the number of good paths. Input The first line contains two integers n, m (1 ≀ n, m ≀ 106) β€” the number of cities and roads in Uzhlyandia, respectively. Each of the next m lines contains two integers u and v (1 ≀ u, v ≀ n) that mean that there is road between cities u and v. It is guaranteed that no road will be given in the input twice. That also means that for every city there is no more than one road that connects the city to itself. Output Print out the only integer β€” the number of good paths in Uzhlyandia. Examples Input 5 4 1 2 1 3 1 4 1 5 Output 6 Input 5 3 1 2 2 3 4 5 Output 0 Input 2 2 1 1 1 2 Output 1 Note In first sample test case the good paths are: * 2 β†’ 1 β†’ 3 β†’ 1 β†’ 4 β†’ 1 β†’ 5, * 2 β†’ 1 β†’ 3 β†’ 1 β†’ 5 β†’ 1 β†’ 4, * 2 β†’ 1 β†’ 4 β†’ 1 β†’ 5 β†’ 1 β†’ 3, * 3 β†’ 1 β†’ 2 β†’ 1 β†’ 4 β†’ 1 β†’ 5, * 3 β†’ 1 β†’ 2 β†’ 1 β†’ 5 β†’ 1 β†’ 4, * 4 β†’ 1 β†’ 2 β†’ 1 β†’ 3 β†’ 1 β†’ 5. There are good paths that are same with displayed above, because the sets of roads they pass over once are same: * 2 β†’ 1 β†’ 4 β†’ 1 β†’ 3 β†’ 1 β†’ 5, * 2 β†’ 1 β†’ 5 β†’ 1 β†’ 3 β†’ 1 β†’ 4, * 2 β†’ 1 β†’ 5 β†’ 1 β†’ 4 β†’ 1 β†’ 3, * 3 β†’ 1 β†’ 4 β†’ 1 β†’ 2 β†’ 1 β†’ 5, * 3 β†’ 1 β†’ 5 β†’ 1 β†’ 2 β†’ 1 β†’ 4, * 4 β†’ 1 β†’ 3 β†’ 1 β†’ 2 β†’ 1 β†’ 5, * and all the paths in the other direction. Thus, the answer is 6. In the second test case, Igor simply can not walk by all the roads. In the third case, Igor walks once over every road. Submitted Solution: ``` n, m = map(int, input().split()) ranks = [0]*(n+1) rep = list(range(0, n+1)) for _ in range(0, m): a, b = map(int, input().split()) ranks[a] += 1 ranks[b] += 1 mab = min(a, b) rep[a] = mab rep[b] = mab print(rep) if max(rep) > 1: print(0) else: odd = len([x for x in ranks if x % 2 != 0]) print(odd * (odd - 1) // 2) ``` No
99,155
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Leha and Noora decided to go on a trip in the Baltic States. As you know from the previous problem, Leha has lost his car on the parking of the restaurant. Unfortunately, requests to the watchman didn't helped hacker find the car, so friends decided to go hitchhiking. In total, they intended to visit n towns. However it turned out that sights in i-th town are open for visitors only on days from li to ri. What to do? Leha proposed to choose for each town i a day, when they will visit this town, i.e any integer xi in interval [li, ri]. After that Noora choses some subsequence of towns id1, id2, ..., idk, which friends are going to visit, that at first they are strictly increasing, i.e idi < idi + 1 is for all integers i from 1 to k - 1, but also the dates of the friends visits are strictly increasing, i.e xidi < xidi + 1 is true for all integers i from 1 to k - 1. Please help Leha and Noora in choosing such xi for each town i, and such subsequence of towns id1, id2, ..., idk, so that friends can visit maximal number of towns. You may assume, that Leha and Noora can start the trip any day. Input The first line contains a single integer n (1 ≀ n ≀ 3Β·105) denoting the number of towns Leha and Noora intended to visit. Each line i of the n subsequent lines contains two integers li, ri (1 ≀ li ≀ ri ≀ 109), denoting that sights in i-th town are open for visitors on any day <image>. Output Print a single integer denoting the maximal number of towns, that Leha and Noora can visit. Example Input 5 6 6 1 2 3 4 2 2 1 4 Output 3 Note Consider the first example. Let's take this plan: let's visit the sight in the second town on the first day, in the third town on the third day and in the fifth town on the fourth. That's would be the optimal answer. Submitted Solution: ``` # Find largest increasing subsequence def solve(): global dyn global towns for i in range(0, n)[::-1]: dyn[i] = [1, towns[i][1]] for j in range(i + 1, n): if towns[j][1] > towns[i][0] and dyn[i][0] < dyn[j][0] + 1: dyn[i][0] = dyn[j][0] + 1 return dyn[0][0] - 1 n = int(input())+1 towns = [[-500, 10e9]] for i in range(1, n): l, r = [int(x) for x in input().split()] towns.append([l, r]) # Memoization dyn = [[0, 10e9] for _ in range(len(towns))] print(solve()) print() ``` No
99,156
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Leha and Noora decided to go on a trip in the Baltic States. As you know from the previous problem, Leha has lost his car on the parking of the restaurant. Unfortunately, requests to the watchman didn't helped hacker find the car, so friends decided to go hitchhiking. In total, they intended to visit n towns. However it turned out that sights in i-th town are open for visitors only on days from li to ri. What to do? Leha proposed to choose for each town i a day, when they will visit this town, i.e any integer xi in interval [li, ri]. After that Noora choses some subsequence of towns id1, id2, ..., idk, which friends are going to visit, that at first they are strictly increasing, i.e idi < idi + 1 is for all integers i from 1 to k - 1, but also the dates of the friends visits are strictly increasing, i.e xidi < xidi + 1 is true for all integers i from 1 to k - 1. Please help Leha and Noora in choosing such xi for each town i, and such subsequence of towns id1, id2, ..., idk, so that friends can visit maximal number of towns. You may assume, that Leha and Noora can start the trip any day. Input The first line contains a single integer n (1 ≀ n ≀ 3Β·105) denoting the number of towns Leha and Noora intended to visit. Each line i of the n subsequent lines contains two integers li, ri (1 ≀ li ≀ ri ≀ 109), denoting that sights in i-th town are open for visitors on any day <image>. Output Print a single integer denoting the maximal number of towns, that Leha and Noora can visit. Example Input 5 6 6 1 2 3 4 2 2 1 4 Output 3 Note Consider the first example. Let's take this plan: let's visit the sight in the second town on the first day, in the third town on the third day and in the fifth town on the fourth. That's would be the optimal answer. Submitted Solution: ``` # Find largest increasing subsequence def solve_rec(i, n): global dyn global towns if dyn[i] != 0: return dyn[i] dyn[i] = 1 for j in range(i + 1, n): if towns[j][1] > towns[i][0]: dyn[i] = max(dyn[i], solve_rec(j, n) + 1) return dyn[i] n = int(input()) towns = [(0, 0)] * n for i in range(n): l, r = [int(x) for x in input().split()] towns[i] = (l, r) # Memoization dyn = [0] * len(towns) max_t = 0 for t in range(len(towns)): max_t = max(max_t, solve_rec(t, n)) print(max_t) ``` No
99,157
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Leha and Noora decided to go on a trip in the Baltic States. As you know from the previous problem, Leha has lost his car on the parking of the restaurant. Unfortunately, requests to the watchman didn't helped hacker find the car, so friends decided to go hitchhiking. In total, they intended to visit n towns. However it turned out that sights in i-th town are open for visitors only on days from li to ri. What to do? Leha proposed to choose for each town i a day, when they will visit this town, i.e any integer xi in interval [li, ri]. After that Noora choses some subsequence of towns id1, id2, ..., idk, which friends are going to visit, that at first they are strictly increasing, i.e idi < idi + 1 is for all integers i from 1 to k - 1, but also the dates of the friends visits are strictly increasing, i.e xidi < xidi + 1 is true for all integers i from 1 to k - 1. Please help Leha and Noora in choosing such xi for each town i, and such subsequence of towns id1, id2, ..., idk, so that friends can visit maximal number of towns. You may assume, that Leha and Noora can start the trip any day. Input The first line contains a single integer n (1 ≀ n ≀ 3Β·105) denoting the number of towns Leha and Noora intended to visit. Each line i of the n subsequent lines contains two integers li, ri (1 ≀ li ≀ ri ≀ 109), denoting that sights in i-th town are open for visitors on any day <image>. Output Print a single integer denoting the maximal number of towns, that Leha and Noora can visit. Example Input 5 6 6 1 2 3 4 2 2 1 4 Output 3 Note Consider the first example. Let's take this plan: let's visit the sight in the second town on the first day, in the third town on the third day and in the fifth town on the fourth. That's would be the optimal answer. Submitted Solution: ``` # Find largest increasing subsequence def solve_rec(i, day, n): global dyn global towns if dyn[i] != 0: return dyn[i] dyn[i] = 1 for j in range(i + 1, n): if towns[j][1] > day: for next_day in range(day + 1, towns[j][1] + 1): dyn[i] = max(dyn[i], solve_rec(j, next_day, n) + 1) return dyn[i] n = int(input()) towns = [(0, 0)] * n for i in range(n): l, r = [int(x) for x in input().split()] towns[i] = (l, r) # Memoization dyn = [0] * len(towns) max_t = 0 for t in range(len(towns)): for day in range(towns[t][0], towns[t][1] + 1): max_t = max(max_t, solve_rec(t, day, n)) print(max_t) ``` No
99,158
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Leha and Noora decided to go on a trip in the Baltic States. As you know from the previous problem, Leha has lost his car on the parking of the restaurant. Unfortunately, requests to the watchman didn't helped hacker find the car, so friends decided to go hitchhiking. In total, they intended to visit n towns. However it turned out that sights in i-th town are open for visitors only on days from li to ri. What to do? Leha proposed to choose for each town i a day, when they will visit this town, i.e any integer xi in interval [li, ri]. After that Noora choses some subsequence of towns id1, id2, ..., idk, which friends are going to visit, that at first they are strictly increasing, i.e idi < idi + 1 is for all integers i from 1 to k - 1, but also the dates of the friends visits are strictly increasing, i.e xidi < xidi + 1 is true for all integers i from 1 to k - 1. Please help Leha and Noora in choosing such xi for each town i, and such subsequence of towns id1, id2, ..., idk, so that friends can visit maximal number of towns. You may assume, that Leha and Noora can start the trip any day. Input The first line contains a single integer n (1 ≀ n ≀ 3Β·105) denoting the number of towns Leha and Noora intended to visit. Each line i of the n subsequent lines contains two integers li, ri (1 ≀ li ≀ ri ≀ 109), denoting that sights in i-th town are open for visitors on any day <image>. Output Print a single integer denoting the maximal number of towns, that Leha and Noora can visit. Example Input 5 6 6 1 2 3 4 2 2 1 4 Output 3 Note Consider the first example. Let's take this plan: let's visit the sight in the second town on the first day, in the third town on the third day and in the fifth town on the fourth. That's would be the optimal answer. Submitted Solution: ``` # Find largest increasing subsequence def solve_rec(i, day, n): global dyn global towns if dyn[i] != 0: return dyn[i] dyn[i] = 1 for j in range(i + 1, n): if towns[j][1] > day: max_day = dyn[i] for next_day in range(max(day + 1, towns[j][0]), towns[j][1] + 1): max_day = max(max_day, solve_rec(j, next_day, n) + 1) dyn[i] = max(dyn[i], max_day) return dyn[i] n = int(input()) towns = [(0, 0)] * n for i in range(n): l, r = [int(x) for x in input().split()] towns[i] = (l, r) # Memoization dyn = [0] * len(towns) max_t = 0 for t in range(len(towns)): for day in range(towns[t][0], towns[t][1] + 1): max_t = max(max_t, solve_rec(t, day, n)) print(max_t) ``` No
99,159
Provide tags and a correct Python 3 solution for this coding contest problem. <image> It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in the kingdom of Sweetland in case it turns out to reach the wrong hands. So it's a necessity to not let any uninvited guests in. There are 26 entrances in Jelly Castle, enumerated with uppercase English letters from A to Z. Because of security measures, each guest is known to be assigned an entrance he should enter the castle through. The door of each entrance is opened right before the first guest's arrival and closed right after the arrival of the last guest that should enter the castle through this entrance. No two guests can enter the castle simultaneously. For an entrance to be protected from possible intrusion, a candy guard should be assigned to it. There are k such guards in the castle, so if there are more than k opened doors, one of them is going to be left unguarded! Notice that a guard can't leave his post until the door he is assigned to is closed. Slastyona had a suspicion that there could be uninvited guests at the evening. She knows the order in which the invited guests entered the castle, and wants you to help her check whether there was a moment when more than k doors were opened. Input Two integers are given in the first string: the number of guests n and the number of guards k (1 ≀ n ≀ 106, 1 ≀ k ≀ 26). In the second string, n uppercase English letters s1s2... sn are given, where si is the entrance used by the i-th guest. Output Output Β«YESΒ» if at least one door was unguarded during some time, and Β«NOΒ» otherwise. You can output each letter in arbitrary case (upper or lower). Examples Input 5 1 AABBB Output NO Input 5 1 ABABB Output YES Note In the first sample case, the door A is opened right before the first guest's arrival and closed when the second guest enters the castle. The door B is opened right before the arrival of the third guest, and closed after the fifth one arrives. One guard can handle both doors, as the first one is closed before the second one is opened. In the second sample case, the door B is opened before the second guest's arrival, but the only guard can't leave the door A unattended, as there is still one more guest that should enter the castle through this door. Tags: data structures, implementation Correct Solution: ``` string_len, condition_value = (int(x) for x in input().split()) idx___letter = list(input()) letter___start__finish = {} for idx, letter in enumerate(idx___letter): if letter not in letter___start__finish: letter___start__finish[letter] = [idx, idx] if letter___start__finish[letter][1] < idx: letter___start__finish[letter][1] = idx max_events_open = 0 curr_events_open = 0 for idx, letter in enumerate(idx___letter): start, close = letter___start__finish[letter] if idx == start: curr_events_open += 1 max_events_open = max(max_events_open, curr_events_open) if idx == close: curr_events_open -= 1 if max_events_open > condition_value: print('YES') else: print('NO') ```
99,160
Provide tags and a correct Python 3 solution for this coding contest problem. <image> It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in the kingdom of Sweetland in case it turns out to reach the wrong hands. So it's a necessity to not let any uninvited guests in. There are 26 entrances in Jelly Castle, enumerated with uppercase English letters from A to Z. Because of security measures, each guest is known to be assigned an entrance he should enter the castle through. The door of each entrance is opened right before the first guest's arrival and closed right after the arrival of the last guest that should enter the castle through this entrance. No two guests can enter the castle simultaneously. For an entrance to be protected from possible intrusion, a candy guard should be assigned to it. There are k such guards in the castle, so if there are more than k opened doors, one of them is going to be left unguarded! Notice that a guard can't leave his post until the door he is assigned to is closed. Slastyona had a suspicion that there could be uninvited guests at the evening. She knows the order in which the invited guests entered the castle, and wants you to help her check whether there was a moment when more than k doors were opened. Input Two integers are given in the first string: the number of guests n and the number of guards k (1 ≀ n ≀ 106, 1 ≀ k ≀ 26). In the second string, n uppercase English letters s1s2... sn are given, where si is the entrance used by the i-th guest. Output Output Β«YESΒ» if at least one door was unguarded during some time, and Β«NOΒ» otherwise. You can output each letter in arbitrary case (upper or lower). Examples Input 5 1 AABBB Output NO Input 5 1 ABABB Output YES Note In the first sample case, the door A is opened right before the first guest's arrival and closed when the second guest enters the castle. The door B is opened right before the arrival of the third guest, and closed after the fifth one arrives. One guard can handle both doors, as the first one is closed before the second one is opened. In the second sample case, the door B is opened before the second guest's arrival, but the only guard can't leave the door A unattended, as there is still one more guest that should enter the castle through this door. Tags: data structures, implementation Correct Solution: ``` import sys def func(dic1,dic2,s,alot): for i in s: if dic2[i] == 0: alot += 1 dic2[i] += 1 else: dic2[i] += 1 if alot>guards: return False if dic2[i]==dic1[i]: alot -= 1 return True dic1 = {} dic2 = {} guests,guards = [int(x) for x in sys.stdin.readline().split()] s = sys.stdin.readline().strip() alp = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' for i in alp: dic1[i] = 0 dic2[i] = 0 for i in s: dic1[i] += 1 alot = 0 if func(dic1,dic2,s,alot): sys.stdout.write('NO') else: sys.stdout.write('YES') ```
99,161
Provide tags and a correct Python 3 solution for this coding contest problem. <image> It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in the kingdom of Sweetland in case it turns out to reach the wrong hands. So it's a necessity to not let any uninvited guests in. There are 26 entrances in Jelly Castle, enumerated with uppercase English letters from A to Z. Because of security measures, each guest is known to be assigned an entrance he should enter the castle through. The door of each entrance is opened right before the first guest's arrival and closed right after the arrival of the last guest that should enter the castle through this entrance. No two guests can enter the castle simultaneously. For an entrance to be protected from possible intrusion, a candy guard should be assigned to it. There are k such guards in the castle, so if there are more than k opened doors, one of them is going to be left unguarded! Notice that a guard can't leave his post until the door he is assigned to is closed. Slastyona had a suspicion that there could be uninvited guests at the evening. She knows the order in which the invited guests entered the castle, and wants you to help her check whether there was a moment when more than k doors were opened. Input Two integers are given in the first string: the number of guests n and the number of guards k (1 ≀ n ≀ 106, 1 ≀ k ≀ 26). In the second string, n uppercase English letters s1s2... sn are given, where si is the entrance used by the i-th guest. Output Output Β«YESΒ» if at least one door was unguarded during some time, and Β«NOΒ» otherwise. You can output each letter in arbitrary case (upper or lower). Examples Input 5 1 AABBB Output NO Input 5 1 ABABB Output YES Note In the first sample case, the door A is opened right before the first guest's arrival and closed when the second guest enters the castle. The door B is opened right before the arrival of the third guest, and closed after the fifth one arrives. One guard can handle both doors, as the first one is closed before the second one is opened. In the second sample case, the door B is opened before the second guest's arrival, but the only guard can't leave the door A unattended, as there is still one more guest that should enter the castle through this door. Tags: data structures, implementation Correct Solution: ``` n,k=(int(i )for i in input().split()) s=input() a=[0]*n b=[] x=k y=0 alf='ABCDEFGHIJKLMNOPQRSTUVWXYZ' end=[s.rfind(i) for i in alf] begin=[s.find(i) for i in alf] f=False ans=False for i in range(n): find=alf.find(s[i]) if ((i!=end[find]) and not(s[i] in b)) or ((begin[find]==end[find])): b.append(s[i]) x-=1; elif (i==end[find]) and (i!=begin[find]): x+=1 if x<0: ans=True break if begin[find]==end[find]: x+=1 print('YES' if ans else 'NO') ```
99,162
Provide tags and a correct Python 3 solution for this coding contest problem. <image> It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in the kingdom of Sweetland in case it turns out to reach the wrong hands. So it's a necessity to not let any uninvited guests in. There are 26 entrances in Jelly Castle, enumerated with uppercase English letters from A to Z. Because of security measures, each guest is known to be assigned an entrance he should enter the castle through. The door of each entrance is opened right before the first guest's arrival and closed right after the arrival of the last guest that should enter the castle through this entrance. No two guests can enter the castle simultaneously. For an entrance to be protected from possible intrusion, a candy guard should be assigned to it. There are k such guards in the castle, so if there are more than k opened doors, one of them is going to be left unguarded! Notice that a guard can't leave his post until the door he is assigned to is closed. Slastyona had a suspicion that there could be uninvited guests at the evening. She knows the order in which the invited guests entered the castle, and wants you to help her check whether there was a moment when more than k doors were opened. Input Two integers are given in the first string: the number of guests n and the number of guards k (1 ≀ n ≀ 106, 1 ≀ k ≀ 26). In the second string, n uppercase English letters s1s2... sn are given, where si is the entrance used by the i-th guest. Output Output Β«YESΒ» if at least one door was unguarded during some time, and Β«NOΒ» otherwise. You can output each letter in arbitrary case (upper or lower). Examples Input 5 1 AABBB Output NO Input 5 1 ABABB Output YES Note In the first sample case, the door A is opened right before the first guest's arrival and closed when the second guest enters the castle. The door B is opened right before the arrival of the third guest, and closed after the fifth one arrives. One guard can handle both doors, as the first one is closed before the second one is opened. In the second sample case, the door B is opened before the second guest's arrival, but the only guard can't leave the door A unattended, as there is still one more guest that should enter the castle through this door. Tags: data structures, implementation Correct Solution: ``` from collections import deque n, k = list(map(int, input().split())) s = input() rs = s[::-1] alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' last = {} for c in alpha: p = rs.find(c) if p != -1: last.update({c: n - p - 1}) amount = 0 o = deque() c = 0 for i in range(len(s)): if s[i] not in o: o.append(s[i]) c += 1 if c > k: print('YES') break if i == last[s[i]]: c -= 1 else: print('NO') ```
99,163
Provide tags and a correct Python 3 solution for this coding contest problem. <image> It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in the kingdom of Sweetland in case it turns out to reach the wrong hands. So it's a necessity to not let any uninvited guests in. There are 26 entrances in Jelly Castle, enumerated with uppercase English letters from A to Z. Because of security measures, each guest is known to be assigned an entrance he should enter the castle through. The door of each entrance is opened right before the first guest's arrival and closed right after the arrival of the last guest that should enter the castle through this entrance. No two guests can enter the castle simultaneously. For an entrance to be protected from possible intrusion, a candy guard should be assigned to it. There are k such guards in the castle, so if there are more than k opened doors, one of them is going to be left unguarded! Notice that a guard can't leave his post until the door he is assigned to is closed. Slastyona had a suspicion that there could be uninvited guests at the evening. She knows the order in which the invited guests entered the castle, and wants you to help her check whether there was a moment when more than k doors were opened. Input Two integers are given in the first string: the number of guests n and the number of guards k (1 ≀ n ≀ 106, 1 ≀ k ≀ 26). In the second string, n uppercase English letters s1s2... sn are given, where si is the entrance used by the i-th guest. Output Output Β«YESΒ» if at least one door was unguarded during some time, and Β«NOΒ» otherwise. You can output each letter in arbitrary case (upper or lower). Examples Input 5 1 AABBB Output NO Input 5 1 ABABB Output YES Note In the first sample case, the door A is opened right before the first guest's arrival and closed when the second guest enters the castle. The door B is opened right before the arrival of the third guest, and closed after the fifth one arrives. One guard can handle both doors, as the first one is closed before the second one is opened. In the second sample case, the door B is opened before the second guest's arrival, but the only guard can't leave the door A unattended, as there is still one more guest that should enter the castle through this door. Tags: data structures, implementation Correct Solution: ``` from collections import defaultdict n,k=map(int,input().split()) s=input() d=defaultdict(lambda:[-1,-1]) s1=s[::-1] for x in range(65,91): if s.find(chr(x))!=-1: d[chr(x)][0]=s.find(chr(x)) d[chr(x)][1]=(n-1)-s1.find(chr(x)) t=s[0] k1=1 f=0 for x in range(1,n): if s[x]!=t and d[s[x-1]][1]!=x-1 and d[s[x]][0]==x: k1+=1 if k1>k: f=1 break elif d[s[x]][0]!=x and d[s[x-1]][1]==x-1: k1-=1 t=s[x] if f: print("YES") else: print("NO") ```
99,164
Provide tags and a correct Python 3 solution for this coding contest problem. <image> It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in the kingdom of Sweetland in case it turns out to reach the wrong hands. So it's a necessity to not let any uninvited guests in. There are 26 entrances in Jelly Castle, enumerated with uppercase English letters from A to Z. Because of security measures, each guest is known to be assigned an entrance he should enter the castle through. The door of each entrance is opened right before the first guest's arrival and closed right after the arrival of the last guest that should enter the castle through this entrance. No two guests can enter the castle simultaneously. For an entrance to be protected from possible intrusion, a candy guard should be assigned to it. There are k such guards in the castle, so if there are more than k opened doors, one of them is going to be left unguarded! Notice that a guard can't leave his post until the door he is assigned to is closed. Slastyona had a suspicion that there could be uninvited guests at the evening. She knows the order in which the invited guests entered the castle, and wants you to help her check whether there was a moment when more than k doors were opened. Input Two integers are given in the first string: the number of guests n and the number of guards k (1 ≀ n ≀ 106, 1 ≀ k ≀ 26). In the second string, n uppercase English letters s1s2... sn are given, where si is the entrance used by the i-th guest. Output Output Β«YESΒ» if at least one door was unguarded during some time, and Β«NOΒ» otherwise. You can output each letter in arbitrary case (upper or lower). Examples Input 5 1 AABBB Output NO Input 5 1 ABABB Output YES Note In the first sample case, the door A is opened right before the first guest's arrival and closed when the second guest enters the castle. The door B is opened right before the arrival of the third guest, and closed after the fifth one arrives. One guard can handle both doors, as the first one is closed before the second one is opened. In the second sample case, the door B is opened before the second guest's arrival, but the only guard can't leave the door A unattended, as there is still one more guest that should enter the castle through this door. Tags: data structures, implementation Correct Solution: ``` from time import time n, k = map(int, input().split()) g = input() e = [-1] * 26 for i in range(n): e[ord(g[i]) - 65] = i curS = 0 f = 1 met = [0] * 26 for i in range(n): if not met[ord(g[i]) - 65]: curS += 1 met[ord(g[i]) - 65] = 1 if curS > k: f = 0 break if i == e[ord(g[i]) - 65]: curS -= 1 if f: print("NO") else: print("YES") ```
99,165
Provide tags and a correct Python 3 solution for this coding contest problem. <image> It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in the kingdom of Sweetland in case it turns out to reach the wrong hands. So it's a necessity to not let any uninvited guests in. There are 26 entrances in Jelly Castle, enumerated with uppercase English letters from A to Z. Because of security measures, each guest is known to be assigned an entrance he should enter the castle through. The door of each entrance is opened right before the first guest's arrival and closed right after the arrival of the last guest that should enter the castle through this entrance. No two guests can enter the castle simultaneously. For an entrance to be protected from possible intrusion, a candy guard should be assigned to it. There are k such guards in the castle, so if there are more than k opened doors, one of them is going to be left unguarded! Notice that a guard can't leave his post until the door he is assigned to is closed. Slastyona had a suspicion that there could be uninvited guests at the evening. She knows the order in which the invited guests entered the castle, and wants you to help her check whether there was a moment when more than k doors were opened. Input Two integers are given in the first string: the number of guests n and the number of guards k (1 ≀ n ≀ 106, 1 ≀ k ≀ 26). In the second string, n uppercase English letters s1s2... sn are given, where si is the entrance used by the i-th guest. Output Output Β«YESΒ» if at least one door was unguarded during some time, and Β«NOΒ» otherwise. You can output each letter in arbitrary case (upper or lower). Examples Input 5 1 AABBB Output NO Input 5 1 ABABB Output YES Note In the first sample case, the door A is opened right before the first guest's arrival and closed when the second guest enters the castle. The door B is opened right before the arrival of the third guest, and closed after the fifth one arrives. One guard can handle both doors, as the first one is closed before the second one is opened. In the second sample case, the door B is opened before the second guest's arrival, but the only guard can't leave the door A unattended, as there is still one more guest that should enter the castle through this door. Tags: data structures, implementation Correct Solution: ``` """ Author : Arif Ahmad Date : Algo : Difficulty : """ from sys import stdin, stdout def main(): n, k = [int(_) for _ in stdin.readline().strip().split()] s = stdin.readline().strip() last = dict() for i in range(26): c = chr(ord('A') + i) for j in range(n-1, -1, -1): if s[j] == c: last[c] = j break guardAssigned = dict() for i in range(26): c = chr(ord('A') + i) guardAssigned[c] = False totalGuard = 0 maxGuard = 0 for i, c in enumerate(s): if not guardAssigned[c]: guardAssigned[c] = True totalGuard += 1 maxGuard = max(maxGuard, totalGuard) if i == last[c]: totalGuard -= 1 #print('maxgurad:', maxGuard) if maxGuard > k: stdout.write('YES\n') else: stdout.write('NO\n') if __name__ == '__main__': main() ```
99,166
Provide tags and a correct Python 3 solution for this coding contest problem. <image> It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in the kingdom of Sweetland in case it turns out to reach the wrong hands. So it's a necessity to not let any uninvited guests in. There are 26 entrances in Jelly Castle, enumerated with uppercase English letters from A to Z. Because of security measures, each guest is known to be assigned an entrance he should enter the castle through. The door of each entrance is opened right before the first guest's arrival and closed right after the arrival of the last guest that should enter the castle through this entrance. No two guests can enter the castle simultaneously. For an entrance to be protected from possible intrusion, a candy guard should be assigned to it. There are k such guards in the castle, so if there are more than k opened doors, one of them is going to be left unguarded! Notice that a guard can't leave his post until the door he is assigned to is closed. Slastyona had a suspicion that there could be uninvited guests at the evening. She knows the order in which the invited guests entered the castle, and wants you to help her check whether there was a moment when more than k doors were opened. Input Two integers are given in the first string: the number of guests n and the number of guards k (1 ≀ n ≀ 106, 1 ≀ k ≀ 26). In the second string, n uppercase English letters s1s2... sn are given, where si is the entrance used by the i-th guest. Output Output Β«YESΒ» if at least one door was unguarded during some time, and Β«NOΒ» otherwise. You can output each letter in arbitrary case (upper or lower). Examples Input 5 1 AABBB Output NO Input 5 1 ABABB Output YES Note In the first sample case, the door A is opened right before the first guest's arrival and closed when the second guest enters the castle. The door B is opened right before the arrival of the third guest, and closed after the fifth one arrives. One guard can handle both doors, as the first one is closed before the second one is opened. In the second sample case, the door B is opened before the second guest's arrival, but the only guard can't leave the door A unattended, as there is still one more guest that should enter the castle through this door. Tags: data structures, implementation Correct Solution: ``` n, k = map(int, input().split()) s = input() d1 = {} d2 = {} for i, v in enumerate(s): if v not in d1: d1[v] = i d2[v] = i order = [] for v in d1: order.append((d1[v], -1)) order.append((d2[v], 1)) order.sort() cur = k for _, v in order: cur += v if cur < 0: print("YES") break else: print("NO") ```
99,167
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in the kingdom of Sweetland in case it turns out to reach the wrong hands. So it's a necessity to not let any uninvited guests in. There are 26 entrances in Jelly Castle, enumerated with uppercase English letters from A to Z. Because of security measures, each guest is known to be assigned an entrance he should enter the castle through. The door of each entrance is opened right before the first guest's arrival and closed right after the arrival of the last guest that should enter the castle through this entrance. No two guests can enter the castle simultaneously. For an entrance to be protected from possible intrusion, a candy guard should be assigned to it. There are k such guards in the castle, so if there are more than k opened doors, one of them is going to be left unguarded! Notice that a guard can't leave his post until the door he is assigned to is closed. Slastyona had a suspicion that there could be uninvited guests at the evening. She knows the order in which the invited guests entered the castle, and wants you to help her check whether there was a moment when more than k doors were opened. Input Two integers are given in the first string: the number of guests n and the number of guards k (1 ≀ n ≀ 106, 1 ≀ k ≀ 26). In the second string, n uppercase English letters s1s2... sn are given, where si is the entrance used by the i-th guest. Output Output Β«YESΒ» if at least one door was unguarded during some time, and Β«NOΒ» otherwise. You can output each letter in arbitrary case (upper or lower). Examples Input 5 1 AABBB Output NO Input 5 1 ABABB Output YES Note In the first sample case, the door A is opened right before the first guest's arrival and closed when the second guest enters the castle. The door B is opened right before the arrival of the third guest, and closed after the fifth one arrives. One guard can handle both doors, as the first one is closed before the second one is opened. In the second sample case, the door B is opened before the second guest's arrival, but the only guard can't leave the door A unattended, as there is still one more guest that should enter the castle through this door. Submitted Solution: ``` n,k=map(int,input().split()) s=input() flag=False last_pos={} gate=set() for i in range(len(s)): last_pos[s[i]]=i #print(last_pos) for i in range(len(s)): gate.add(s[i]) if len(gate)>k: flag=True break if last_pos[s[i]]==i: gate.remove(s[i]) if flag: print('YES') else: print('NO') ``` Yes
99,168
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in the kingdom of Sweetland in case it turns out to reach the wrong hands. So it's a necessity to not let any uninvited guests in. There are 26 entrances in Jelly Castle, enumerated with uppercase English letters from A to Z. Because of security measures, each guest is known to be assigned an entrance he should enter the castle through. The door of each entrance is opened right before the first guest's arrival and closed right after the arrival of the last guest that should enter the castle through this entrance. No two guests can enter the castle simultaneously. For an entrance to be protected from possible intrusion, a candy guard should be assigned to it. There are k such guards in the castle, so if there are more than k opened doors, one of them is going to be left unguarded! Notice that a guard can't leave his post until the door he is assigned to is closed. Slastyona had a suspicion that there could be uninvited guests at the evening. She knows the order in which the invited guests entered the castle, and wants you to help her check whether there was a moment when more than k doors were opened. Input Two integers are given in the first string: the number of guests n and the number of guards k (1 ≀ n ≀ 106, 1 ≀ k ≀ 26). In the second string, n uppercase English letters s1s2... sn are given, where si is the entrance used by the i-th guest. Output Output Β«YESΒ» if at least one door was unguarded during some time, and Β«NOΒ» otherwise. You can output each letter in arbitrary case (upper or lower). Examples Input 5 1 AABBB Output NO Input 5 1 ABABB Output YES Note In the first sample case, the door A is opened right before the first guest's arrival and closed when the second guest enters the castle. The door B is opened right before the arrival of the third guest, and closed after the fifth one arrives. One guard can handle both doors, as the first one is closed before the second one is opened. In the second sample case, the door B is opened before the second guest's arrival, but the only guard can't leave the door A unattended, as there is still one more guest that should enter the castle through this door. Submitted Solution: ``` n, k = [int(x) for x in input().split()] a = [ord(x) for x in list(input())] b = [0] * 32 for i in a: b[i - 65] += 1 c = [0] * 32 i = 0 f = 0 for i in a: c[i - 65] += 1 if c[i - 65] == 1: k -= 1 if k < 0: f = 1 break if c[i - 65] == b[i - 65] : k += 1 if f == 1: print('YES') else: print('NO') ``` Yes
99,169
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in the kingdom of Sweetland in case it turns out to reach the wrong hands. So it's a necessity to not let any uninvited guests in. There are 26 entrances in Jelly Castle, enumerated with uppercase English letters from A to Z. Because of security measures, each guest is known to be assigned an entrance he should enter the castle through. The door of each entrance is opened right before the first guest's arrival and closed right after the arrival of the last guest that should enter the castle through this entrance. No two guests can enter the castle simultaneously. For an entrance to be protected from possible intrusion, a candy guard should be assigned to it. There are k such guards in the castle, so if there are more than k opened doors, one of them is going to be left unguarded! Notice that a guard can't leave his post until the door he is assigned to is closed. Slastyona had a suspicion that there could be uninvited guests at the evening. She knows the order in which the invited guests entered the castle, and wants you to help her check whether there was a moment when more than k doors were opened. Input Two integers are given in the first string: the number of guests n and the number of guards k (1 ≀ n ≀ 106, 1 ≀ k ≀ 26). In the second string, n uppercase English letters s1s2... sn are given, where si is the entrance used by the i-th guest. Output Output Β«YESΒ» if at least one door was unguarded during some time, and Β«NOΒ» otherwise. You can output each letter in arbitrary case (upper or lower). Examples Input 5 1 AABBB Output NO Input 5 1 ABABB Output YES Note In the first sample case, the door A is opened right before the first guest's arrival and closed when the second guest enters the castle. The door B is opened right before the arrival of the third guest, and closed after the fifth one arrives. One guard can handle both doors, as the first one is closed before the second one is opened. In the second sample case, the door B is opened before the second guest's arrival, but the only guard can't leave the door A unattended, as there is still one more guest that should enter the castle through this door. Submitted Solution: ``` from sys import stdin input=lambda : stdin.readline().strip() from math import ceil,sqrt,factorial INT_MIN=float("-infinity") INT_MAX=float("infinity") n,k=map(int,input().split()) flag='NO' d=set() z={} s=input() for i in range(n): z[s[i]]=i for i in range(n): d.add(s[i]) # print(d) if len(d)>k: flag='YES' break if z[s[i]]==i: d.remove(s[i]) print(flag) ``` Yes
99,170
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in the kingdom of Sweetland in case it turns out to reach the wrong hands. So it's a necessity to not let any uninvited guests in. There are 26 entrances in Jelly Castle, enumerated with uppercase English letters from A to Z. Because of security measures, each guest is known to be assigned an entrance he should enter the castle through. The door of each entrance is opened right before the first guest's arrival and closed right after the arrival of the last guest that should enter the castle through this entrance. No two guests can enter the castle simultaneously. For an entrance to be protected from possible intrusion, a candy guard should be assigned to it. There are k such guards in the castle, so if there are more than k opened doors, one of them is going to be left unguarded! Notice that a guard can't leave his post until the door he is assigned to is closed. Slastyona had a suspicion that there could be uninvited guests at the evening. She knows the order in which the invited guests entered the castle, and wants you to help her check whether there was a moment when more than k doors were opened. Input Two integers are given in the first string: the number of guests n and the number of guards k (1 ≀ n ≀ 106, 1 ≀ k ≀ 26). In the second string, n uppercase English letters s1s2... sn are given, where si is the entrance used by the i-th guest. Output Output Β«YESΒ» if at least one door was unguarded during some time, and Β«NOΒ» otherwise. You can output each letter in arbitrary case (upper or lower). Examples Input 5 1 AABBB Output NO Input 5 1 ABABB Output YES Note In the first sample case, the door A is opened right before the first guest's arrival and closed when the second guest enters the castle. The door B is opened right before the arrival of the third guest, and closed after the fifth one arrives. One guard can handle both doors, as the first one is closed before the second one is opened. In the second sample case, the door B is opened before the second guest's arrival, but the only guard can't leave the door A unattended, as there is still one more guest that should enter the castle through this door. Submitted Solution: ``` import os from io import BytesIO def main(): input = BytesIO(os.read(0, os.fstat(0).st_size)).readline n, k = map(int, input().split()) g = [x - 65 for x in input()] e = [-1] * 26 for i in range(n): e[g[i]] = i curS = 0 f = 1 met = [0] * 26 for i in range(n): if not met[g[i]]: curS += 1 met[g[i]] = 1 if curS > k: f = 0 break if i == e[g[i]]: curS -= 1 print('NO' if f else 'YES') main() ``` Yes
99,171
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in the kingdom of Sweetland in case it turns out to reach the wrong hands. So it's a necessity to not let any uninvited guests in. There are 26 entrances in Jelly Castle, enumerated with uppercase English letters from A to Z. Because of security measures, each guest is known to be assigned an entrance he should enter the castle through. The door of each entrance is opened right before the first guest's arrival and closed right after the arrival of the last guest that should enter the castle through this entrance. No two guests can enter the castle simultaneously. For an entrance to be protected from possible intrusion, a candy guard should be assigned to it. There are k such guards in the castle, so if there are more than k opened doors, one of them is going to be left unguarded! Notice that a guard can't leave his post until the door he is assigned to is closed. Slastyona had a suspicion that there could be uninvited guests at the evening. She knows the order in which the invited guests entered the castle, and wants you to help her check whether there was a moment when more than k doors were opened. Input Two integers are given in the first string: the number of guests n and the number of guards k (1 ≀ n ≀ 106, 1 ≀ k ≀ 26). In the second string, n uppercase English letters s1s2... sn are given, where si is the entrance used by the i-th guest. Output Output Β«YESΒ» if at least one door was unguarded during some time, and Β«NOΒ» otherwise. You can output each letter in arbitrary case (upper or lower). Examples Input 5 1 AABBB Output NO Input 5 1 ABABB Output YES Note In the first sample case, the door A is opened right before the first guest's arrival and closed when the second guest enters the castle. The door B is opened right before the arrival of the third guest, and closed after the fifth one arrives. One guard can handle both doors, as the first one is closed before the second one is opened. In the second sample case, the door B is opened before the second guest's arrival, but the only guard can't leave the door A unattended, as there is still one more guest that should enter the castle through this door. Submitted Solution: ``` n, k = [int(x) for x in input().split()] a = [ord(x) for x in list(input())] b = [0] * 26 for i in a: b[i - 65] += 1 c = [0] * 26 i = 0 f = 0 while i != len(a): c[a[i] - 65] += 1 if c[a[i] - 65] == 1: k -= 1 elif c[a[i] - 65] == b[a[i] - 65]: k += 1 i += 1 if k < 0: f = 1 if f == 1: print('YES') else: print('NO') ``` No
99,172
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in the kingdom of Sweetland in case it turns out to reach the wrong hands. So it's a necessity to not let any uninvited guests in. There are 26 entrances in Jelly Castle, enumerated with uppercase English letters from A to Z. Because of security measures, each guest is known to be assigned an entrance he should enter the castle through. The door of each entrance is opened right before the first guest's arrival and closed right after the arrival of the last guest that should enter the castle through this entrance. No two guests can enter the castle simultaneously. For an entrance to be protected from possible intrusion, a candy guard should be assigned to it. There are k such guards in the castle, so if there are more than k opened doors, one of them is going to be left unguarded! Notice that a guard can't leave his post until the door he is assigned to is closed. Slastyona had a suspicion that there could be uninvited guests at the evening. She knows the order in which the invited guests entered the castle, and wants you to help her check whether there was a moment when more than k doors were opened. Input Two integers are given in the first string: the number of guests n and the number of guards k (1 ≀ n ≀ 106, 1 ≀ k ≀ 26). In the second string, n uppercase English letters s1s2... sn are given, where si is the entrance used by the i-th guest. Output Output Β«YESΒ» if at least one door was unguarded during some time, and Β«NOΒ» otherwise. You can output each letter in arbitrary case (upper or lower). Examples Input 5 1 AABBB Output NO Input 5 1 ABABB Output YES Note In the first sample case, the door A is opened right before the first guest's arrival and closed when the second guest enters the castle. The door B is opened right before the arrival of the third guest, and closed after the fifth one arrives. One guard can handle both doors, as the first one is closed before the second one is opened. In the second sample case, the door B is opened before the second guest's arrival, but the only guard can't leave the door A unattended, as there is still one more guest that should enter the castle through this door. Submitted Solution: ``` #Proti letter shurur age ki obostha ache shei hisab korte hobe #Ki obostha ache sheita khujar jonno (Age joto jon shuru - age jotojon sesh) temp=input().split(" ") n=int(temp[0]) k=int(temp[1]) s=input() alphabet=set(s) starts=[] ends=[] for x in alphabet: starts.append(s.index(x)) ends.append(s.rindex(x)) res=0 for x in ends: count=0 for y in starts: if y<x: count+=1 for y in ends: if y<x: count-=1 if count>=k: res=1 if res: print("YES") else: print("NO") ``` No
99,173
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in the kingdom of Sweetland in case it turns out to reach the wrong hands. So it's a necessity to not let any uninvited guests in. There are 26 entrances in Jelly Castle, enumerated with uppercase English letters from A to Z. Because of security measures, each guest is known to be assigned an entrance he should enter the castle through. The door of each entrance is opened right before the first guest's arrival and closed right after the arrival of the last guest that should enter the castle through this entrance. No two guests can enter the castle simultaneously. For an entrance to be protected from possible intrusion, a candy guard should be assigned to it. There are k such guards in the castle, so if there are more than k opened doors, one of them is going to be left unguarded! Notice that a guard can't leave his post until the door he is assigned to is closed. Slastyona had a suspicion that there could be uninvited guests at the evening. She knows the order in which the invited guests entered the castle, and wants you to help her check whether there was a moment when more than k doors were opened. Input Two integers are given in the first string: the number of guests n and the number of guards k (1 ≀ n ≀ 106, 1 ≀ k ≀ 26). In the second string, n uppercase English letters s1s2... sn are given, where si is the entrance used by the i-th guest. Output Output Β«YESΒ» if at least one door was unguarded during some time, and Β«NOΒ» otherwise. You can output each letter in arbitrary case (upper or lower). Examples Input 5 1 AABBB Output NO Input 5 1 ABABB Output YES Note In the first sample case, the door A is opened right before the first guest's arrival and closed when the second guest enters the castle. The door B is opened right before the arrival of the third guest, and closed after the fifth one arrives. One guard can handle both doors, as the first one is closed before the second one is opened. In the second sample case, the door B is opened before the second guest's arrival, but the only guard can't leave the door A unattended, as there is still one more guest that should enter the castle through this door. Submitted Solution: ``` n,k=map(int,input().split()) exp=input() last='B' cnt=0 b=[-1]*27 e=[-1]*27 Cnt=[0]*27 for i in range(n): tmp=ord(exp[i])-ord('A') if b[tmp]==-1: b[tmp]=i e[tmp]=i for i in range(n): tmp=ord(exp[i])-ord('A') for j in range(tmp): if b[j]<i and e[j]>i: Cnt[tmp]=1 for i in range(26): cnt+=Cnt[i] if cnt>=k: print('YES') else: print('NO') ``` No
99,174
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in the kingdom of Sweetland in case it turns out to reach the wrong hands. So it's a necessity to not let any uninvited guests in. There are 26 entrances in Jelly Castle, enumerated with uppercase English letters from A to Z. Because of security measures, each guest is known to be assigned an entrance he should enter the castle through. The door of each entrance is opened right before the first guest's arrival and closed right after the arrival of the last guest that should enter the castle through this entrance. No two guests can enter the castle simultaneously. For an entrance to be protected from possible intrusion, a candy guard should be assigned to it. There are k such guards in the castle, so if there are more than k opened doors, one of them is going to be left unguarded! Notice that a guard can't leave his post until the door he is assigned to is closed. Slastyona had a suspicion that there could be uninvited guests at the evening. She knows the order in which the invited guests entered the castle, and wants you to help her check whether there was a moment when more than k doors were opened. Input Two integers are given in the first string: the number of guests n and the number of guards k (1 ≀ n ≀ 106, 1 ≀ k ≀ 26). In the second string, n uppercase English letters s1s2... sn are given, where si is the entrance used by the i-th guest. Output Output Β«YESΒ» if at least one door was unguarded during some time, and Β«NOΒ» otherwise. You can output each letter in arbitrary case (upper or lower). Examples Input 5 1 AABBB Output NO Input 5 1 ABABB Output YES Note In the first sample case, the door A is opened right before the first guest's arrival and closed when the second guest enters the castle. The door B is opened right before the arrival of the third guest, and closed after the fifth one arrives. One guard can handle both doors, as the first one is closed before the second one is opened. In the second sample case, the door B is opened before the second guest's arrival, but the only guard can't leave the door A unattended, as there is still one more guest that should enter the castle through this door. Submitted Solution: ``` from collections import Counter n,k=map(int,input().split()) s=input() a=list(s) count=0 b=Counter(a) c=[] for k1,v in b.items(): c.append(v) ans=n for i in range(len(c)): if(c[i]>1): count=count+1 ans=ans-1 if(ans!=0): count=count+1 if(count-1>k): print("YES") else: print("NO") ``` No
99,175
Provide tags and a correct Python 3 solution for this coding contest problem. Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well. In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned. Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023. Input The first line contains an integer n (1 ≀ n ≀ 5Β·105) β€” the number of lines. Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant xi 0 ≀ xi ≀ 1023. Output Output an integer k (0 ≀ k ≀ 5) β€” the length of your program. Next k lines must contain commands in the same format as in the input. Examples Input 3 | 3 ^ 2 | 1 Output 2 | 3 ^ 2 Input 3 &amp; 1 &amp; 3 &amp; 5 Output 1 &amp; 1 Input 3 ^ 1 ^ 2 ^ 3 Output 0 Note You can read about bitwise operations in <https://en.wikipedia.org/wiki/Bitwise_operation>. Second sample: Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs. Tags: bitmasks, constructive algorithms Correct Solution: ``` n=int(input()) bits0=[0]*10 bits1=[1]*10 b0=0 b1=1023 fname=['&','|','^'] f=[[[0,0],[0,1]],[[0,1],[1,1]],[[0,1],[1,0]]] for i in range(n): s=input() e=str(bin(int(s[2:]))) d=int(s[2:]) if s[0]=='^': b0=b0^d b1 = b1 ^ d elif s[0]=='|': b0=b0|d b1 = b1 | d elif s[0]=='&': b0=b0&d b1 = b1 & d for j in range(10): bits0[9-j]=b0%2 b0=b0//2 bits1[9 - j] = b1 % 2 b1 = b1 // 2 c=[[0]*10,[0]*10,[1]*10] for j in range(10): if bits0[j]==bits1[j]: if bits0[j]==0: c[2][j]=0 else: c[1][j]=1 else: if bits0[j]==1: c[0][j]=1 print(3) c0,c1,c2=[0,0,0] for i in range(10): c0+=c[0][i]*(2**(9-i)) c1 += c[1][i] * (2 ** (9 - i)) c2 += c[2][i] * (2 ** (9 - i)) print("^ "+str(c0)) print("| "+str(c1)) print("& "+str(c2)) ```
99,176
Provide tags and a correct Python 3 solution for this coding contest problem. Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well. In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned. Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023. Input The first line contains an integer n (1 ≀ n ≀ 5Β·105) β€” the number of lines. Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant xi 0 ≀ xi ≀ 1023. Output Output an integer k (0 ≀ k ≀ 5) β€” the length of your program. Next k lines must contain commands in the same format as in the input. Examples Input 3 | 3 ^ 2 | 1 Output 2 | 3 ^ 2 Input 3 &amp; 1 &amp; 3 &amp; 5 Output 1 &amp; 1 Input 3 ^ 1 ^ 2 ^ 3 Output 0 Note You can read about bitwise operations in <https://en.wikipedia.org/wiki/Bitwise_operation>. Second sample: Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs. Tags: bitmasks, constructive algorithms Correct Solution: ``` n = int(input()) a, b = 1023, 0 for _ in range(n): c, d = input().split() d = int(d) if c == '|': a, b = a | d, b | d elif c == '&': a, b = a & d, b & d elif c == '^': a, b = a ^ d, b ^ d print('2\n| {}\n^ {}'.format(a ^ b ^ 1023, a ^ 1023)) # Made By Mostafa_Khaled ```
99,177
Provide tags and a correct Python 3 solution for this coding contest problem. Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well. In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned. Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023. Input The first line contains an integer n (1 ≀ n ≀ 5Β·105) β€” the number of lines. Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant xi 0 ≀ xi ≀ 1023. Output Output an integer k (0 ≀ k ≀ 5) β€” the length of your program. Next k lines must contain commands in the same format as in the input. Examples Input 3 | 3 ^ 2 | 1 Output 2 | 3 ^ 2 Input 3 &amp; 1 &amp; 3 &amp; 5 Output 1 &amp; 1 Input 3 ^ 1 ^ 2 ^ 3 Output 0 Note You can read about bitwise operations in <https://en.wikipedia.org/wiki/Bitwise_operation>. Second sample: Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs. Tags: bitmasks, constructive algorithms Correct Solution: ``` n = int(input()) A = 1023 B = 0 a = 1023 b = 0 print(4) for i in range(n): s = str(input()) if s[0] == '&': a = a & int(s[2:]) b = b & int(s[2:]) elif s[0] == '|': a = a | int(s[2:]) b = b | int(s[2:]) elif s[0] == '^': a = a ^ int(s[2:]) b = b ^ int(s[2:]) Al = [1,1,1,1,1,1,1,1,1,1] Bl = [0,0,0,0,0,0,0,0,0,0] al = [0 for kk in range(10)] bl = [0 for kk in range(10)] #print(a,b) for i in range(9,-1,-1): if a >= 2 ** i: al[i] = 1 a -= 2**i for i in range(9,-1,-1): if b >= 2 ** i: bl[i] = 1 b -= 2**i #print(al,bl) And = [] Or = [] Xor = [] for i in range(10): if al[i] == 0 and bl[i] == 0: And.append(i) if al[i] == 0 and bl[i] == 1: Xor.append(i) if al[i] == 1 and bl[i] == 1: Or.append(i) #print(And, Or, Xor) ### r = 0 for i in range(10): if i not in And: r += 2**i print("&", r) ### r = 0 if Xor == []: print("^ 0") print("^ 0") elif Xor == [0]: print("^ 0") print("& 1") #elif len(Xor) == 1: #r = 2**(max(Xor)+1) - 1 #print("^", r) #print("| 1") else: r = 2**(max(Xor)+1) - 1 print("^", r) r = 0 for i in range(max(Xor) + 1): if i not in Xor: r += 2**i print("^", r) ### r = 0 for i in range(10): if i in Or: r += 2**i print("|", r) #print((1023 | 999)^689) #print((0 | 999)^689) #print((300 | 999)^689) #print((((300 & 350)^31)^15)|326) ```
99,178
Provide tags and a correct Python 3 solution for this coding contest problem. Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well. In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned. Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023. Input The first line contains an integer n (1 ≀ n ≀ 5Β·105) β€” the number of lines. Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant xi 0 ≀ xi ≀ 1023. Output Output an integer k (0 ≀ k ≀ 5) β€” the length of your program. Next k lines must contain commands in the same format as in the input. Examples Input 3 | 3 ^ 2 | 1 Output 2 | 3 ^ 2 Input 3 &amp; 1 &amp; 3 &amp; 5 Output 1 &amp; 1 Input 3 ^ 1 ^ 2 ^ 3 Output 0 Note You can read about bitwise operations in <https://en.wikipedia.org/wiki/Bitwise_operation>. Second sample: Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs. Tags: bitmasks, constructive algorithms Correct Solution: ``` import sys input=sys.stdin.readline n=int(input()) start1=0 start2=1023 for _ in range(n): a,b=map(str,input().split()) b=int(b) if a=='|': start1=b|start1 start2=b|start2 elif a=='^': start1=b^start1 start2=b^start2 else: start1=b&start1 start2=b&start2 ans=[] ands=1023 xors=0 ors=0 for i in range(10): k=1<<i if start1&k and start2&k: ors+=k elif start1&k and not start2&k: xors+=k elif (not start1&k) and (not start2&k): ands-=k print(3) print('&',ands) print('^',xors) print('|',ors) ```
99,179
Provide tags and a correct Python 3 solution for this coding contest problem. Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well. In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned. Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023. Input The first line contains an integer n (1 ≀ n ≀ 5Β·105) β€” the number of lines. Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant xi 0 ≀ xi ≀ 1023. Output Output an integer k (0 ≀ k ≀ 5) β€” the length of your program. Next k lines must contain commands in the same format as in the input. Examples Input 3 | 3 ^ 2 | 1 Output 2 | 3 ^ 2 Input 3 &amp; 1 &amp; 3 &amp; 5 Output 1 &amp; 1 Input 3 ^ 1 ^ 2 ^ 3 Output 0 Note You can read about bitwise operations in <https://en.wikipedia.org/wiki/Bitwise_operation>. Second sample: Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs. Tags: bitmasks, constructive algorithms Correct Solution: ``` from math import* n = int(input()) x = 0 y = 1023 for i in range(n): gg = input().split() if gg[0] == '&': x &= int(gg[1]) y &= int(gg[1]) if gg[0] == '|': x |= int(gg[1]) y |= int(gg[1]) if gg[0] == '^': x ^= int(gg[1]) y ^= int(gg[1]) print(3) print('|', x & y) print('&', x | y) print('^', x & (y ^ 1023)) ```
99,180
Provide tags and a correct Python 3 solution for this coding contest problem. Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well. In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned. Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023. Input The first line contains an integer n (1 ≀ n ≀ 5Β·105) β€” the number of lines. Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant xi 0 ≀ xi ≀ 1023. Output Output an integer k (0 ≀ k ≀ 5) β€” the length of your program. Next k lines must contain commands in the same format as in the input. Examples Input 3 | 3 ^ 2 | 1 Output 2 | 3 ^ 2 Input 3 &amp; 1 &amp; 3 &amp; 5 Output 1 &amp; 1 Input 3 ^ 1 ^ 2 ^ 3 Output 0 Note You can read about bitwise operations in <https://en.wikipedia.org/wiki/Bitwise_operation>. Second sample: Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs. Tags: bitmasks, constructive algorithms Correct Solution: ``` import queue def readTuple(): return input().split() def readInts(): return tuple(map(int, readTuple())) def to_int(x): x=x[::-1] res = 0 for i in x: res <<= 1 res |= i return res def solve(): res = ['X']*10 n, = readInts() a,b = 0, 1023 for _ in range(n): char, num = readTuple() num = int(num) if char == '|': a |= num b |= num if char == '&': a &= num b &= num if char == '^': a ^= num b ^= num XOR, OR = [],[] for i in range(10): b1 = a&(1<<i) b2 = b&(1<<i) if b1 and b2: OR.append(1) XOR.append(0) if not b1 and not b2: OR.append(1) XOR.append(1) if b1 and not b2: OR.append(0) XOR.append(1) if not b1 and b2: OR.append(0) XOR.append(0) print(2) print(f"| {to_int(OR)}") print(f"^ {to_int(XOR)}") if __name__ == '__main__': solve() ```
99,181
Provide tags and a correct Python 3 solution for this coding contest problem. Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well. In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned. Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023. Input The first line contains an integer n (1 ≀ n ≀ 5Β·105) β€” the number of lines. Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant xi 0 ≀ xi ≀ 1023. Output Output an integer k (0 ≀ k ≀ 5) β€” the length of your program. Next k lines must contain commands in the same format as in the input. Examples Input 3 | 3 ^ 2 | 1 Output 2 | 3 ^ 2 Input 3 &amp; 1 &amp; 3 &amp; 5 Output 1 &amp; 1 Input 3 ^ 1 ^ 2 ^ 3 Output 0 Note You can read about bitwise operations in <https://en.wikipedia.org/wiki/Bitwise_operation>. Second sample: Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs. Tags: bitmasks, constructive algorithms Correct Solution: ``` def fun (n1,o,n2): if o=="|": return n1|n2 elif o=="&": return n1&n2 else: return n1^n2 def fun2(n): l=[0 for i in range(10)] for i in range(9,-1,-1): if 1<<i <=n: l[i]=1 n-=1<<i return l n=int(input()) a=0 b=1023 for i in range(n): o,n2=input().split() n2=int(n2) a=fun(a,o,n2) b=fun(b,o,n2) l1=fun2(a) l2=fun2(b) a=0 b=0 for i in range(10): if l1[i]==1 and l2[i]==1: a+=1<<i elif l1[i]==0 and l2[i]==0: a+=1<<i b+=1<<i elif l1[i]==1 and l2[i]==0: b+=1<<i print(2) print("|",a) print("^",b) ```
99,182
Provide tags and a correct Python 3 solution for this coding contest problem. Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well. In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned. Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023. Input The first line contains an integer n (1 ≀ n ≀ 5Β·105) β€” the number of lines. Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant xi 0 ≀ xi ≀ 1023. Output Output an integer k (0 ≀ k ≀ 5) β€” the length of your program. Next k lines must contain commands in the same format as in the input. Examples Input 3 | 3 ^ 2 | 1 Output 2 | 3 ^ 2 Input 3 &amp; 1 &amp; 3 &amp; 5 Output 1 &amp; 1 Input 3 ^ 1 ^ 2 ^ 3 Output 0 Note You can read about bitwise operations in <https://en.wikipedia.org/wiki/Bitwise_operation>. Second sample: Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs. Tags: bitmasks, constructive algorithms Correct Solution: ``` n = int(input()) mask_ans1 = 1023 mask_ans2 = 0 for i in range(n): com, x = input().split() x = int(x) if com == '&': mask_ans1 &= x mask_ans2 &= x elif com == '|': mask_ans1 |= x mask_ans2 |= x elif com == '^': mask_ans1 ^= x mask_ans2 ^= x ans11 = 1023 & ~mask_ans2 ans12 = mask_ans1 ans13 = 1023&(1023^mask_ans1) ans1 = 1023^(1023 & ~mask_ans1) & ans11 ans2 = mask_ans2 & ans12 ans3 = 1023&(mask_ans2^0) & ans13 lst = [] cnt = 3 if ans1 == 1023: cnt -= 1 if ans2 == 0: cnt -= 1 if ans3 == 0: cnt -= 1 print(cnt) if ans1 != 1023: print('&', ans1) if ans2 != 0: print('|', ans2) if ans3 != 0: print('^', ans3) ```
99,183
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well. In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned. Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023. Input The first line contains an integer n (1 ≀ n ≀ 5Β·105) β€” the number of lines. Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant xi 0 ≀ xi ≀ 1023. Output Output an integer k (0 ≀ k ≀ 5) β€” the length of your program. Next k lines must contain commands in the same format as in the input. Examples Input 3 | 3 ^ 2 | 1 Output 2 | 3 ^ 2 Input 3 &amp; 1 &amp; 3 &amp; 5 Output 1 &amp; 1 Input 3 ^ 1 ^ 2 ^ 3 Output 0 Note You can read about bitwise operations in <https://en.wikipedia.org/wiki/Bitwise_operation>. Second sample: Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs. Submitted Solution: ``` import sys, math def main(): ops = getops(sys.stdin) n1 = 0 n2 = 1023 for op in ops: n1 = calc(op, n1) n2 = calc(op, n2) if n2 == 1023 and n1 == 0: print(0) else: and_ = 1023 or_ = 0 xor_ = 0 for i in range(10): b1 = n1 % 2 b2 = n2 % 2 n1 = n1 // 2 n2 = n2 // 2 if b1 == 1 and b2 == 1: or_ = or_ | 2**i elif b1 == 1 and b2 == 0: xor_ = xor_ | 2**i elif b1 == 0 and b2 == 0: and_ = and_ - 2**i print(3) print('&', and_) print('|', or_) print('^', xor_) def getops(fh): n = int(fh.readline()) ops = [] for i in range(n): opi, numi = fh.readline().split() numi = int(numi) ops.append((opi, numi)) return ops def calc(op, res): opi, numi = op if opi == '|': res = res | numi elif opi == '&': res = res & numi else: res = res ^ numi return res if __name__ == "__main__": main() ``` Yes
99,184
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well. In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned. Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023. Input The first line contains an integer n (1 ≀ n ≀ 5Β·105) β€” the number of lines. Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant xi 0 ≀ xi ≀ 1023. Output Output an integer k (0 ≀ k ≀ 5) β€” the length of your program. Next k lines must contain commands in the same format as in the input. Examples Input 3 | 3 ^ 2 | 1 Output 2 | 3 ^ 2 Input 3 &amp; 1 &amp; 3 &amp; 5 Output 1 &amp; 1 Input 3 ^ 1 ^ 2 ^ 3 Output 0 Note You can read about bitwise operations in <https://en.wikipedia.org/wiki/Bitwise_operation>. Second sample: Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs. Submitted Solution: ``` n = int(input()) a, b = 1023, 0 for _ in range(n): c, d = input().split() d = int(d) if c == '|': a, b = a | d, b | d elif c == '&': a, b = a & d, b & d elif c == '^': a, b = a ^ d, b ^ d print('2\n| {}\n^ {}'.format(a ^ b ^ 1023, a ^ 1023)) ``` Yes
99,185
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well. In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned. Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023. Input The first line contains an integer n (1 ≀ n ≀ 5Β·105) β€” the number of lines. Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant xi 0 ≀ xi ≀ 1023. Output Output an integer k (0 ≀ k ≀ 5) β€” the length of your program. Next k lines must contain commands in the same format as in the input. Examples Input 3 | 3 ^ 2 | 1 Output 2 | 3 ^ 2 Input 3 &amp; 1 &amp; 3 &amp; 5 Output 1 &amp; 1 Input 3 ^ 1 ^ 2 ^ 3 Output 0 Note You can read about bitwise operations in <https://en.wikipedia.org/wiki/Bitwise_operation>. Second sample: Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs. Submitted Solution: ``` import sys import math import collections import heapq n=int(input()) a,b=1023,0 for i in range(n): x,y=(i for i in input().split()) y=int(y) if(x=='&'): a&=y b&=y elif(x=='|'): a|=y b|=y else: a^=y b^=y print(2) print("|",a^b^1023) print("^",a^1023) ``` Yes
99,186
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well. In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned. Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023. Input The first line contains an integer n (1 ≀ n ≀ 5Β·105) β€” the number of lines. Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant xi 0 ≀ xi ≀ 1023. Output Output an integer k (0 ≀ k ≀ 5) β€” the length of your program. Next k lines must contain commands in the same format as in the input. Examples Input 3 | 3 ^ 2 | 1 Output 2 | 3 ^ 2 Input 3 &amp; 1 &amp; 3 &amp; 5 Output 1 &amp; 1 Input 3 ^ 1 ^ 2 ^ 3 Output 0 Note You can read about bitwise operations in <https://en.wikipedia.org/wiki/Bitwise_operation>. Second sample: Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs. Submitted Solution: ``` '''input 3 & 1 & 3 & 5 ''' ''' Author : dhanyaabhirami Great things never come from comfort zones ''' from collections import defaultdict as dd from collections import Counter as ccd from itertools import permutations as pp from itertools import combinations as cc from random import randint as rd from bisect import bisect_left as bl from bisect import bisect_right as br import heapq as hq import math mod=pow(10,9) +7 def inp(flag=0): if flag==0: return list(map(int,input().strip().split(' '))) else: return int(input()) # Code credits # assert(debug()==true) # for _ in range(int(input())): # n=inp(1) n=int(input()) a=0 b=1023 for i in range(n): c,k= input().strip().split(' ') k=int(k) if (c=='|'): a|=k b|=k elif (c=='^'): a^=k b^=k elif (c=='&'): a&=k b&=k OR = 0 XOR = 0 for i in range(10): x=1<<i if a&x and b&x: # set 1 OR|=x if a&x and ~b&x: # swap XOR|=x if ~a&x and ~b&x: # set 0 OR|=x XOR|=x print('2') print('|',OR) print('^',XOR) ``` Yes
99,187
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well. In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned. Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023. Input The first line contains an integer n (1 ≀ n ≀ 5Β·105) β€” the number of lines. Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant xi 0 ≀ xi ≀ 1023. Output Output an integer k (0 ≀ k ≀ 5) β€” the length of your program. Next k lines must contain commands in the same format as in the input. Examples Input 3 | 3 ^ 2 | 1 Output 2 | 3 ^ 2 Input 3 &amp; 1 &amp; 3 &amp; 5 Output 1 &amp; 1 Input 3 ^ 1 ^ 2 ^ 3 Output 0 Note You can read about bitwise operations in <https://en.wikipedia.org/wiki/Bitwise_operation>. Second sample: Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs. Submitted Solution: ``` a, b = 0, 1023 n=int(input()) for i in range(n): cmd = input() c, x = cmd.split() x = int(x) if c == "|": a, b = a | x, b | x elif c == "&": a, b = a & x, b & x else: a, b = a ^ x, b ^ x x = 0 y = 1023 z = 0 for i in range(10): a_i = (a << i) & 1 b_i = (b << i) & 1 if a_i and b_i: x |= 1 << i if (not a_i) and (not b_i): y ^= 1 << i if a_i and (not b_i): z ^= 1 << i print("3\n| {}\n& {}\n^ {}".format(x, y, z)) ``` No
99,188
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well. In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned. Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023. Input The first line contains an integer n (1 ≀ n ≀ 5Β·105) β€” the number of lines. Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant xi 0 ≀ xi ≀ 1023. Output Output an integer k (0 ≀ k ≀ 5) β€” the length of your program. Next k lines must contain commands in the same format as in the input. Examples Input 3 | 3 ^ 2 | 1 Output 2 | 3 ^ 2 Input 3 &amp; 1 &amp; 3 &amp; 5 Output 1 &amp; 1 Input 3 ^ 1 ^ 2 ^ 3 Output 0 Note You can read about bitwise operations in <https://en.wikipedia.org/wiki/Bitwise_operation>. Second sample: Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs. Submitted Solution: ``` n = int(input()) stack = [] p = 1023 d = {'&':1023, '|':0, '^':0} for i in range(n): com = list(map(str, input().split())) c, x = com[0], int(com[1]) if c == '&': for k in d.keys(): d[k] &= x elif c == '|': d[c] |= x else: d[c] ^= x ans = [] ans.append(('&', d['&'])) ans.append(('|', d['|'])) ans.append(('^', d['^'])) print(len(ans)) for i in range(len(ans)): print(*ans[i]) ``` No
99,189
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well. In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned. Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023. Input The first line contains an integer n (1 ≀ n ≀ 5Β·105) β€” the number of lines. Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant xi 0 ≀ xi ≀ 1023. Output Output an integer k (0 ≀ k ≀ 5) β€” the length of your program. Next k lines must contain commands in the same format as in the input. Examples Input 3 | 3 ^ 2 | 1 Output 2 | 3 ^ 2 Input 3 &amp; 1 &amp; 3 &amp; 5 Output 1 &amp; 1 Input 3 ^ 1 ^ 2 ^ 3 Output 0 Note You can read about bitwise operations in <https://en.wikipedia.org/wiki/Bitwise_operation>. Second sample: Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs. Submitted Solution: ``` '''input 3 & 1 & 3 & 5 ''' ''' Author : dhanyaabhirami Great things never come from comfort zones ''' from collections import defaultdict as dd from collections import Counter as ccd from itertools import permutations as pp from itertools import combinations as cc from random import randint as rd from bisect import bisect_left as bl from bisect import bisect_right as br import heapq as hq import math mod=pow(10,9) +7 def inp(flag=0): if flag==0: return list(map(int,input().strip().split(' '))) else: return int(input()) # Code credits # assert(debug()==true) # for _ in range(int(input())): # n=inp(1) n=int(input()) a=0 b=1023 for i in range(n): c,k= input().strip().split(' ') k=int(k) if (c=='|'): a|=k b|=k elif (c=='^'): a^=k b^=k elif (c=='&'): a&=k b&=k OR = 0 XOR = 0 for i in range(10): x=1<<i if a&x and b&x: XOR|=x OR|=x if ~a&x and b&x: XOR|=x if ~a&x and ~b&x: OR|=x print('2') print('|',OR) print('^',XOR) ``` No
99,190
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well. In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned. Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023. Input The first line contains an integer n (1 ≀ n ≀ 5Β·105) β€” the number of lines. Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant xi 0 ≀ xi ≀ 1023. Output Output an integer k (0 ≀ k ≀ 5) β€” the length of your program. Next k lines must contain commands in the same format as in the input. Examples Input 3 | 3 ^ 2 | 1 Output 2 | 3 ^ 2 Input 3 &amp; 1 &amp; 3 &amp; 5 Output 1 &amp; 1 Input 3 ^ 1 ^ 2 ^ 3 Output 0 Note You can read about bitwise operations in <https://en.wikipedia.org/wiki/Bitwise_operation>. Second sample: Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs. Submitted Solution: ``` ## necessary imports import sys input = sys.stdin.readline from bisect import bisect_left; from bisect import bisect_right; from math import ceil, factorial; def ceil(x): if x != int(x): x = int(x) + 1; return x; # swap_array function def swaparr(arr, a,b): temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; ## gcd function def gcd(a,b): if b == 0: return a; return gcd(b, a % b); ## nCr function efficient using Binomial Cofficient def nCr(n, k): if(k > n - k): k = n - k; res = 1; for i in range(k): res = res * (n - i); res = res / (i + 1); return int(res); ## prime factorization def primefs(n): ## if n == 1 ## calculating primes primes = {} while(n%2 == 0 and n > 0): primes[2] = primes.get(2, 0) + 1 n = n//2 for i in range(3, int(n**0.5)+2, 2): while(n%i == 0 and n > 0): primes[i] = primes.get(i, 0) + 1 n = n//i if n > 2: primes[n] = primes.get(n, 0) + 1 ## prime factoriazation of n is stored in dictionary ## primes and can be accesed. O(sqrt n) return primes ## MODULAR EXPONENTIATION FUNCTION def power(x, y, p): res = 1 x = x % p if (x == 0) : return 0 while (y > 0) : if ((y & 1) == 1) : res = (res * x) % p y = y >> 1 x = (x * x) % p return res ## DISJOINT SET UNINON FUNCTIONS def swap(a,b): temp = a a = b b = temp return a,b; # find function with path compression included (recursive) # def find(x, link): # if link[x] == x: # return x # link[x] = find(link[x], link); # return link[x]; # find function with path compression (ITERATIVE) def find(x, link): p = x; while( p != link[p]): p = link[p]; while( x != p): nex = link[x]; link[x] = p; x = nex; return p; # the union function which makes union(x,y) # of two nodes x and y def union(x, y, link, size): x = find(x, link) y = find(y, link) if size[x] < size[y]: x,y = swap(x,y) if x != y: size[x] += size[y] link[y] = x ## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES def sieve(n): prime = [True for i in range(n+1)] p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * p, n+1, p): prime[i] = False p += 1 return prime #### PRIME FACTORIZATION IN O(log n) using Sieve #### MAXN = int(1e5 + 5) def spf_sieve(): spf[1] = 1; for i in range(2, MAXN): spf[i] = i; for i in range(4, MAXN, 2): spf[i] = 2; for i in range(3, ceil(MAXN ** 0.5), 2): if spf[i] == i: for j in range(i*i, MAXN, i): if spf[j] == j: spf[j] = i; ## function for storing smallest prime factors (spf) in the array ################## un-comment below 2 lines when using factorization ################# # spf = [0 for i in range(MAXN)] # spf_sieve(); def factoriazation(x): ret = {}; while x != 1: ret[spf[x]] = ret.get(spf[x], 0) + 1; x = x//spf[x] return ret; ## this function is useful for multiple queries only, o/w use ## primefs function above. complexity O(log n) ## taking integer array input def int_array(): return list(map(int, input().strip().split())); def float_array(): return list(map(float, input().strip().split())); ## taking string array input def str_array(): return input().strip().split(); #defining a couple constants MOD = int(1e9)+7; CMOD = 998244353; INF = float('inf'); NINF = -float('inf'); ################### ---------------- TEMPLATE ENDS HERE ---------------- ################### n = int(input()); ops = []; for _ in range(n): s = input().strip().split(); ops.append((s[0], int(s[1]))); if n <= 5: print(n); for i in range(n): print(ops[i][0] + ' ' + str(ops[i][1])); exit(); x = ops[1][1]; for i in range(2, n): c = ops[i][0]; if c == '|': x = x | ops[i][1]; elif c == '&': x = x & ops[i][1]; else: x = x ^ ops[i][1]; print(2); print(ops[0][0] + ' ' + str(ops[0][1])); print(ops[1][0] + ' ' + str(x)); ``` No
99,191
Provide tags and a correct Python 3 solution for this coding contest problem. In the year of 30XX participants of some world programming championship live in a single large hotel. The hotel has n floors. Each floor has m sections with a single corridor connecting all of them. The sections are enumerated from 1 to m along the corridor, and all sections with equal numbers on different floors are located exactly one above the other. Thus, the hotel can be represented as a rectangle of height n and width m. We can denote sections with pairs of integers (i, j), where i is the floor, and j is the section number on the floor. The guests can walk along the corridor on each floor, use stairs and elevators. Each stairs or elevator occupies all sections (1, x), (2, x), …, (n, x) for some x between 1 and m. All sections not occupied with stairs or elevators contain guest rooms. It takes one time unit to move between neighboring sections on the same floor or to move one floor up or down using stairs. It takes one time unit to move up to v floors in any direction using an elevator. You can assume you don't have to wait for an elevator, and the time needed to enter or exit an elevator is negligible. You are to process q queries. Each query is a question "what is the minimum time needed to go from a room in section (x_1, y_1) to a room in section (x_2, y_2)?" Input The first line contains five integers n, m, c_l, c_e, v (2 ≀ n, m ≀ 10^8, 0 ≀ c_l, c_e ≀ 10^5, 1 ≀ c_l + c_e ≀ m - 1, 1 ≀ v ≀ n - 1) β€” the number of floors and section on each floor, the number of stairs, the number of elevators and the maximum speed of an elevator, respectively. The second line contains c_l integers l_1, …, l_{c_l} in increasing order (1 ≀ l_i ≀ m), denoting the positions of the stairs. If c_l = 0, the second line is empty. The third line contains c_e integers e_1, …, e_{c_e} in increasing order, denoting the elevators positions in the same format. It is guaranteed that all integers l_i and e_i are distinct. The fourth line contains a single integer q (1 ≀ q ≀ 10^5) β€” the number of queries. The next q lines describe queries. Each of these lines contains four integers x_1, y_1, x_2, y_2 (1 ≀ x_1, x_2 ≀ n, 1 ≀ y_1, y_2 ≀ m) β€” the coordinates of starting and finishing sections for the query. It is guaranteed that the starting and finishing sections are distinct. It is also guaranteed that these sections contain guest rooms, i. e. y_1 and y_2 are not among l_i and e_i. Output Print q integers, one per line β€” the answers for the queries. Example Input 5 6 1 1 3 2 5 3 1 1 5 6 1 3 5 4 3 3 5 3 Output 7 5 4 Note In the first query the optimal way is to go to the elevator in the 5-th section in four time units, use it to go to the fifth floor in two time units and go to the destination in one more time unit. In the second query it is still optimal to use the elevator, but in the third query it is better to use the stairs in the section 2. Tags: binary search Correct Solution: ``` from bisect import bisect_left input = __import__('sys').stdin.readline MIS = lambda: map(int,input().split()) def walk(x1, y1, x2, y2, L, v): if y1 == y2: return abs(x2-x1) dy = abs(y1-y2) vertical = dy // v if dy%v: vertical+= 1 i = bisect_left(L, x1) xs1 = L[i-1] if 0<=i-1<len(L) else float('inf') xs2 = L[i] if 0<=i<len(L) else float('inf') xs3 = L[i+1] if 0<=i+1<len(L) else float('inf') d = min(abs(x1-xs1)+abs(xs1-x2), abs(x1-xs2)+abs(xs2-x2), abs(x1-xs3)+abs(xs3-x2)) return d + vertical n, m, cs, ce, v = MIS() sta = list(MIS()) ele = list(MIS()) for TEST in range(int(input())): y1, x1, y2, x2 = MIS() if x1 > x2: x1, x2 = x2, x1 y1, y2 = y2, y1 print(min(walk(x1, y1, x2, y2, sta, 1), walk(x1, y1, x2, y2, ele, v))) ```
99,192
Provide tags and a correct Python 3 solution for this coding contest problem. In the year of 30XX participants of some world programming championship live in a single large hotel. The hotel has n floors. Each floor has m sections with a single corridor connecting all of them. The sections are enumerated from 1 to m along the corridor, and all sections with equal numbers on different floors are located exactly one above the other. Thus, the hotel can be represented as a rectangle of height n and width m. We can denote sections with pairs of integers (i, j), where i is the floor, and j is the section number on the floor. The guests can walk along the corridor on each floor, use stairs and elevators. Each stairs or elevator occupies all sections (1, x), (2, x), …, (n, x) for some x between 1 and m. All sections not occupied with stairs or elevators contain guest rooms. It takes one time unit to move between neighboring sections on the same floor or to move one floor up or down using stairs. It takes one time unit to move up to v floors in any direction using an elevator. You can assume you don't have to wait for an elevator, and the time needed to enter or exit an elevator is negligible. You are to process q queries. Each query is a question "what is the minimum time needed to go from a room in section (x_1, y_1) to a room in section (x_2, y_2)?" Input The first line contains five integers n, m, c_l, c_e, v (2 ≀ n, m ≀ 10^8, 0 ≀ c_l, c_e ≀ 10^5, 1 ≀ c_l + c_e ≀ m - 1, 1 ≀ v ≀ n - 1) β€” the number of floors and section on each floor, the number of stairs, the number of elevators and the maximum speed of an elevator, respectively. The second line contains c_l integers l_1, …, l_{c_l} in increasing order (1 ≀ l_i ≀ m), denoting the positions of the stairs. If c_l = 0, the second line is empty. The third line contains c_e integers e_1, …, e_{c_e} in increasing order, denoting the elevators positions in the same format. It is guaranteed that all integers l_i and e_i are distinct. The fourth line contains a single integer q (1 ≀ q ≀ 10^5) β€” the number of queries. The next q lines describe queries. Each of these lines contains four integers x_1, y_1, x_2, y_2 (1 ≀ x_1, x_2 ≀ n, 1 ≀ y_1, y_2 ≀ m) β€” the coordinates of starting and finishing sections for the query. It is guaranteed that the starting and finishing sections are distinct. It is also guaranteed that these sections contain guest rooms, i. e. y_1 and y_2 are not among l_i and e_i. Output Print q integers, one per line β€” the answers for the queries. Example Input 5 6 1 1 3 2 5 3 1 1 5 6 1 3 5 4 3 3 5 3 Output 7 5 4 Note In the first query the optimal way is to go to the elevator in the 5-th section in four time units, use it to go to the fifth floor in two time units and go to the destination in one more time unit. In the second query it is still optimal to use the elevator, but in the third query it is better to use the stairs in the section 2. Tags: binary search Correct Solution: ``` # python3 import sys from bisect import bisect def readline(): return tuple(map(int, input().split())) def readlines(): return (tuple(map(int, line.split())) for line in sys.stdin.readlines()) def bisect_bounds(arr, val): idx = bisect(arr, val) if idx: yield idx - 1 if idx < len(arr): yield idx class Minimizator: def __init__(self, value=float('inf')): self.value = value def eat(self, value): self.value = min(self.value, value) def main(): n, m, cl, ce, v = readline() l = readline() e = readline() assert len(l) == cl assert len(e) == ce q, = readline() answers = list() for (x1, y1, x2, y2) in readlines(): if x1 == x2: answers.append(abs(y1 - y2)) else: ans = Minimizator(n + 2*m) for idx in bisect_bounds(l, y1): ladder = l[idx] ans.eat(abs(x1 - x2) + abs(ladder - y1) + abs(ladder - y2)) for idx in bisect_bounds(e, y1): elevator = e[idx] ans.eat((abs(x1 - x2) - 1) // v + 1 + abs(elevator - y1) + abs(elevator - y2)) answers.append(ans.value) print("\n".join(map(str, answers))) main() ```
99,193
Provide tags and a correct Python 3 solution for this coding contest problem. In the year of 30XX participants of some world programming championship live in a single large hotel. The hotel has n floors. Each floor has m sections with a single corridor connecting all of them. The sections are enumerated from 1 to m along the corridor, and all sections with equal numbers on different floors are located exactly one above the other. Thus, the hotel can be represented as a rectangle of height n and width m. We can denote sections with pairs of integers (i, j), where i is the floor, and j is the section number on the floor. The guests can walk along the corridor on each floor, use stairs and elevators. Each stairs or elevator occupies all sections (1, x), (2, x), …, (n, x) for some x between 1 and m. All sections not occupied with stairs or elevators contain guest rooms. It takes one time unit to move between neighboring sections on the same floor or to move one floor up or down using stairs. It takes one time unit to move up to v floors in any direction using an elevator. You can assume you don't have to wait for an elevator, and the time needed to enter or exit an elevator is negligible. You are to process q queries. Each query is a question "what is the minimum time needed to go from a room in section (x_1, y_1) to a room in section (x_2, y_2)?" Input The first line contains five integers n, m, c_l, c_e, v (2 ≀ n, m ≀ 10^8, 0 ≀ c_l, c_e ≀ 10^5, 1 ≀ c_l + c_e ≀ m - 1, 1 ≀ v ≀ n - 1) β€” the number of floors and section on each floor, the number of stairs, the number of elevators and the maximum speed of an elevator, respectively. The second line contains c_l integers l_1, …, l_{c_l} in increasing order (1 ≀ l_i ≀ m), denoting the positions of the stairs. If c_l = 0, the second line is empty. The third line contains c_e integers e_1, …, e_{c_e} in increasing order, denoting the elevators positions in the same format. It is guaranteed that all integers l_i and e_i are distinct. The fourth line contains a single integer q (1 ≀ q ≀ 10^5) β€” the number of queries. The next q lines describe queries. Each of these lines contains four integers x_1, y_1, x_2, y_2 (1 ≀ x_1, x_2 ≀ n, 1 ≀ y_1, y_2 ≀ m) β€” the coordinates of starting and finishing sections for the query. It is guaranteed that the starting and finishing sections are distinct. It is also guaranteed that these sections contain guest rooms, i. e. y_1 and y_2 are not among l_i and e_i. Output Print q integers, one per line β€” the answers for the queries. Example Input 5 6 1 1 3 2 5 3 1 1 5 6 1 3 5 4 3 3 5 3 Output 7 5 4 Note In the first query the optimal way is to go to the elevator in the 5-th section in four time units, use it to go to the fifth floor in two time units and go to the destination in one more time unit. In the second query it is still optimal to use the elevator, but in the third query it is better to use the stairs in the section 2. Tags: binary search Correct Solution: ``` def takeClosest(myList, myNumber): """ Assumes myList is sorted. Returns closest value to myNumber. If two numbers are equally close, return the smallest number. """ if len(myList) == 0: return 9e10 pos = bisect_left(myList, myNumber) if pos == 0: return myList[0] if pos == len(myList): return myList[-1] before = myList[pos - 1] after = myList[pos] if after - myNumber < myNumber - before: return after else: return before from bisect import bisect_left from math import ceil n, m, n_stairs, n_elevators, v = map(int, input().split(" ")) if n_stairs > 0: stairs = list(map(int, input().split(" "))) else: stairs = [] input() if n_elevators > 0: elevators = list(map(int, input().split(" "))) else: elevators = [] input() queries = int(input()) res = [] for i in range(queries): x1, y1, x2, y2 = map(int, input().split(" ")) next_elevator = takeClosest(elevators, (y1 + y2) / 2) next_stairs = takeClosest(stairs, (y1 + y2) / 2) time_elevator = abs(x1 - x2) / v time_stairs = abs(x1 - x2) mi = min(y1, y2) ma = max(y1, y2) if next_elevator < mi: time_elevator += (mi - next_elevator) * 2 elif next_elevator > ma: time_elevator += (next_elevator - ma) * 2 if next_stairs < mi: time_stairs += (mi - next_stairs) * 2 elif next_stairs > ma: time_stairs += (next_stairs - ma) * 2 dis = abs(y1 - y2) if time_elevator < time_stairs: dis += time_elevator else: dis += time_stairs if x1 == x2: res.append(abs(y1 - y2)) else: res.append(ceil(dis)) print(*res, sep="\n") # Made By Mostafa_Khaled ```
99,194
Provide tags and a correct Python 3 solution for this coding contest problem. In the year of 30XX participants of some world programming championship live in a single large hotel. The hotel has n floors. Each floor has m sections with a single corridor connecting all of them. The sections are enumerated from 1 to m along the corridor, and all sections with equal numbers on different floors are located exactly one above the other. Thus, the hotel can be represented as a rectangle of height n and width m. We can denote sections with pairs of integers (i, j), where i is the floor, and j is the section number on the floor. The guests can walk along the corridor on each floor, use stairs and elevators. Each stairs or elevator occupies all sections (1, x), (2, x), …, (n, x) for some x between 1 and m. All sections not occupied with stairs or elevators contain guest rooms. It takes one time unit to move between neighboring sections on the same floor or to move one floor up or down using stairs. It takes one time unit to move up to v floors in any direction using an elevator. You can assume you don't have to wait for an elevator, and the time needed to enter or exit an elevator is negligible. You are to process q queries. Each query is a question "what is the minimum time needed to go from a room in section (x_1, y_1) to a room in section (x_2, y_2)?" Input The first line contains five integers n, m, c_l, c_e, v (2 ≀ n, m ≀ 10^8, 0 ≀ c_l, c_e ≀ 10^5, 1 ≀ c_l + c_e ≀ m - 1, 1 ≀ v ≀ n - 1) β€” the number of floors and section on each floor, the number of stairs, the number of elevators and the maximum speed of an elevator, respectively. The second line contains c_l integers l_1, …, l_{c_l} in increasing order (1 ≀ l_i ≀ m), denoting the positions of the stairs. If c_l = 0, the second line is empty. The third line contains c_e integers e_1, …, e_{c_e} in increasing order, denoting the elevators positions in the same format. It is guaranteed that all integers l_i and e_i are distinct. The fourth line contains a single integer q (1 ≀ q ≀ 10^5) β€” the number of queries. The next q lines describe queries. Each of these lines contains four integers x_1, y_1, x_2, y_2 (1 ≀ x_1, x_2 ≀ n, 1 ≀ y_1, y_2 ≀ m) β€” the coordinates of starting and finishing sections for the query. It is guaranteed that the starting and finishing sections are distinct. It is also guaranteed that these sections contain guest rooms, i. e. y_1 and y_2 are not among l_i and e_i. Output Print q integers, one per line β€” the answers for the queries. Example Input 5 6 1 1 3 2 5 3 1 1 5 6 1 3 5 4 3 3 5 3 Output 7 5 4 Note In the first query the optimal way is to go to the elevator in the 5-th section in four time units, use it to go to the fifth floor in two time units and go to the destination in one more time unit. In the second query it is still optimal to use the elevator, but in the third query it is better to use the stairs in the section 2. Tags: binary search Correct Solution: ``` from __future__ import division, print_function import bisect import math import itertools import sys from atexit import register if sys.version_info[0] < 3: from io import BytesIO as stream else: from io import StringIO as stream if sys.version_info[0] < 3: class dict(dict): """dict() -> new empty dictionary""" def items(self): """D.items() -> a set-like object providing a view on D's items""" return dict.iteritems(self) def keys(self): """D.keys() -> a set-like object providing a view on D's keys""" return dict.iterkeys(self) def values(self): """D.values() -> an object providing a view on D's values""" return dict.itervalues(self) input = raw_input range = xrange filter = itertools.ifilter map = itertools.imap zip = itertools.izip def sync_with_stdio(sync=True): """Set whether the standard Python streams are allowed to buffer their I/O. Args: sync (bool, optional): The new synchronization setting. """ global input, flush if sync: flush = sys.stdout.flush else: sys.stdin = stream(sys.stdin.read()) input = lambda: sys.stdin.readline().rstrip('\r\n') sys.stdout = stream() register(lambda: sys.__stdout__.write(sys.stdout.getvalue())) def main(): n,m,c1,ce,v=map(int,input().split()) posstairs=list(map(int,input().split())) posele=list(map(int,input().split())) q=int(input()) for i in range(0,q): y1,x1,y2,x2=map(int,input().split()) if x2<x1: x1,x2=x2,x1 if ce!=0: ind1=bisect.bisect_left(posele,x1) if ind1==ce: ind1-=1 t1=abs(x1-posele[ind1])+abs(posele[ind1]-x2)+math.ceil(abs(y2-y1)/v) ind1-=1 if ind1>=0: t1=min(t1,abs(x1-posele[ind1])+abs(posele[ind1]-x2)+math.ceil(abs(y2-y1)/v)) if c1!=0: ind3=bisect.bisect_left(posstairs,x1) if ind3==c1: ind3-=1 t2=abs(x1-posstairs[ind3])+abs(posstairs[ind3]-x2)+abs(y2-y1) ind3-=1 if ind3>=0: t2=min(t2,abs(x1-posstairs[ind3])+abs(posstairs[ind3]-x2)+abs(y2-y1)) if y1==y2: print(abs(x2-x1)) elif ce!=0 and c1!=0: print(min(t1,t2)) elif ce!=0: print(t1) else : print(t2) if __name__ == '__main__': sync_with_stdio(False) main() ```
99,195
Provide tags and a correct Python 3 solution for this coding contest problem. In the year of 30XX participants of some world programming championship live in a single large hotel. The hotel has n floors. Each floor has m sections with a single corridor connecting all of them. The sections are enumerated from 1 to m along the corridor, and all sections with equal numbers on different floors are located exactly one above the other. Thus, the hotel can be represented as a rectangle of height n and width m. We can denote sections with pairs of integers (i, j), where i is the floor, and j is the section number on the floor. The guests can walk along the corridor on each floor, use stairs and elevators. Each stairs or elevator occupies all sections (1, x), (2, x), …, (n, x) for some x between 1 and m. All sections not occupied with stairs or elevators contain guest rooms. It takes one time unit to move between neighboring sections on the same floor or to move one floor up or down using stairs. It takes one time unit to move up to v floors in any direction using an elevator. You can assume you don't have to wait for an elevator, and the time needed to enter or exit an elevator is negligible. You are to process q queries. Each query is a question "what is the minimum time needed to go from a room in section (x_1, y_1) to a room in section (x_2, y_2)?" Input The first line contains five integers n, m, c_l, c_e, v (2 ≀ n, m ≀ 10^8, 0 ≀ c_l, c_e ≀ 10^5, 1 ≀ c_l + c_e ≀ m - 1, 1 ≀ v ≀ n - 1) β€” the number of floors and section on each floor, the number of stairs, the number of elevators and the maximum speed of an elevator, respectively. The second line contains c_l integers l_1, …, l_{c_l} in increasing order (1 ≀ l_i ≀ m), denoting the positions of the stairs. If c_l = 0, the second line is empty. The third line contains c_e integers e_1, …, e_{c_e} in increasing order, denoting the elevators positions in the same format. It is guaranteed that all integers l_i and e_i are distinct. The fourth line contains a single integer q (1 ≀ q ≀ 10^5) β€” the number of queries. The next q lines describe queries. Each of these lines contains four integers x_1, y_1, x_2, y_2 (1 ≀ x_1, x_2 ≀ n, 1 ≀ y_1, y_2 ≀ m) β€” the coordinates of starting and finishing sections for the query. It is guaranteed that the starting and finishing sections are distinct. It is also guaranteed that these sections contain guest rooms, i. e. y_1 and y_2 are not among l_i and e_i. Output Print q integers, one per line β€” the answers for the queries. Example Input 5 6 1 1 3 2 5 3 1 1 5 6 1 3 5 4 3 3 5 3 Output 7 5 4 Note In the first query the optimal way is to go to the elevator in the 5-th section in four time units, use it to go to the fifth floor in two time units and go to the destination in one more time unit. In the second query it is still optimal to use the elevator, but in the third query it is better to use the stairs in the section 2. Tags: binary search Correct Solution: ``` import sys from bisect import bisect_left from math import ceil input=sys.stdin.readline n,m,cl,ce,v=map(int,input().split()) l=list(map(int,input().split())) e=list(map(int,input().split())) q=int(input()) for _ in range(q): x1,y1,x2,y2=map(int,input().split()) if x1==x2: print(abs(y1-y2)) continue ans=[] idx=bisect_left(l,y1) for i in range(idx-1,idx+2): if 0<=i<cl: t=abs(y1-l[i])+abs(x1-x2)+abs(l[i]-y2) ans.append(t) idx=bisect_left(e,y1) for i in range(idx-1,idx+2): if 0<=i<ce: t=abs(y1-e[i])+ceil(abs(x1-x2)/v)+abs(y2-e[i]) ans.append(t) print(min(ans)) ```
99,196
Provide tags and a correct Python 3 solution for this coding contest problem. In the year of 30XX participants of some world programming championship live in a single large hotel. The hotel has n floors. Each floor has m sections with a single corridor connecting all of them. The sections are enumerated from 1 to m along the corridor, and all sections with equal numbers on different floors are located exactly one above the other. Thus, the hotel can be represented as a rectangle of height n and width m. We can denote sections with pairs of integers (i, j), where i is the floor, and j is the section number on the floor. The guests can walk along the corridor on each floor, use stairs and elevators. Each stairs or elevator occupies all sections (1, x), (2, x), …, (n, x) for some x between 1 and m. All sections not occupied with stairs or elevators contain guest rooms. It takes one time unit to move between neighboring sections on the same floor or to move one floor up or down using stairs. It takes one time unit to move up to v floors in any direction using an elevator. You can assume you don't have to wait for an elevator, and the time needed to enter or exit an elevator is negligible. You are to process q queries. Each query is a question "what is the minimum time needed to go from a room in section (x_1, y_1) to a room in section (x_2, y_2)?" Input The first line contains five integers n, m, c_l, c_e, v (2 ≀ n, m ≀ 10^8, 0 ≀ c_l, c_e ≀ 10^5, 1 ≀ c_l + c_e ≀ m - 1, 1 ≀ v ≀ n - 1) β€” the number of floors and section on each floor, the number of stairs, the number of elevators and the maximum speed of an elevator, respectively. The second line contains c_l integers l_1, …, l_{c_l} in increasing order (1 ≀ l_i ≀ m), denoting the positions of the stairs. If c_l = 0, the second line is empty. The third line contains c_e integers e_1, …, e_{c_e} in increasing order, denoting the elevators positions in the same format. It is guaranteed that all integers l_i and e_i are distinct. The fourth line contains a single integer q (1 ≀ q ≀ 10^5) β€” the number of queries. The next q lines describe queries. Each of these lines contains four integers x_1, y_1, x_2, y_2 (1 ≀ x_1, x_2 ≀ n, 1 ≀ y_1, y_2 ≀ m) β€” the coordinates of starting and finishing sections for the query. It is guaranteed that the starting and finishing sections are distinct. It is also guaranteed that these sections contain guest rooms, i. e. y_1 and y_2 are not among l_i and e_i. Output Print q integers, one per line β€” the answers for the queries. Example Input 5 6 1 1 3 2 5 3 1 1 5 6 1 3 5 4 3 3 5 3 Output 7 5 4 Note In the first query the optimal way is to go to the elevator in the 5-th section in four time units, use it to go to the fifth floor in two time units and go to the destination in one more time unit. In the second query it is still optimal to use the elevator, but in the third query it is better to use the stairs in the section 2. Tags: binary search Correct Solution: ``` def takeClosest(myList, myNumber): """ Assumes myList is sorted. Returns closest value to myNumber. If two numbers are equally close, return the smallest number. """ if len(myList) == 0: return 9e10 pos = bisect_left(myList, myNumber) if pos == 0: return myList[0] if pos == len(myList): return myList[-1] before = myList[pos - 1] after = myList[pos] if after - myNumber < myNumber - before: return after else: return before from bisect import bisect_left from math import ceil n, m, n_stairs, n_elevators, v = map(int, input().split(" ")) if n_stairs > 0: stairs = list(map(int, input().split(" "))) else: stairs = [] input() if n_elevators > 0: elevators = list(map(int, input().split(" "))) else: elevators = [] input() queries = int(input()) res = [] for i in range(queries): x1, y1, x2, y2 = map(int, input().split(" ")) next_elevator = takeClosest(elevators, (y1 + y2) / 2) next_stairs = takeClosest(stairs, (y1 + y2) / 2) time_elevator = abs(x1 - x2) / v time_stairs = abs(x1 - x2) mi = min(y1, y2) ma = max(y1, y2) if next_elevator < mi: time_elevator += (mi - next_elevator) * 2 elif next_elevator > ma: time_elevator += (next_elevator - ma) * 2 if next_stairs < mi: time_stairs += (mi - next_stairs) * 2 elif next_stairs > ma: time_stairs += (next_stairs - ma) * 2 dis = abs(y1 - y2) if time_elevator < time_stairs: dis += time_elevator else: dis += time_stairs if x1 == x2: res.append(abs(y1 - y2)) else: res.append(ceil(dis)) print(*res, sep="\n") ```
99,197
Provide tags and a correct Python 3 solution for this coding contest problem. In the year of 30XX participants of some world programming championship live in a single large hotel. The hotel has n floors. Each floor has m sections with a single corridor connecting all of them. The sections are enumerated from 1 to m along the corridor, and all sections with equal numbers on different floors are located exactly one above the other. Thus, the hotel can be represented as a rectangle of height n and width m. We can denote sections with pairs of integers (i, j), where i is the floor, and j is the section number on the floor. The guests can walk along the corridor on each floor, use stairs and elevators. Each stairs or elevator occupies all sections (1, x), (2, x), …, (n, x) for some x between 1 and m. All sections not occupied with stairs or elevators contain guest rooms. It takes one time unit to move between neighboring sections on the same floor or to move one floor up or down using stairs. It takes one time unit to move up to v floors in any direction using an elevator. You can assume you don't have to wait for an elevator, and the time needed to enter or exit an elevator is negligible. You are to process q queries. Each query is a question "what is the minimum time needed to go from a room in section (x_1, y_1) to a room in section (x_2, y_2)?" Input The first line contains five integers n, m, c_l, c_e, v (2 ≀ n, m ≀ 10^8, 0 ≀ c_l, c_e ≀ 10^5, 1 ≀ c_l + c_e ≀ m - 1, 1 ≀ v ≀ n - 1) β€” the number of floors and section on each floor, the number of stairs, the number of elevators and the maximum speed of an elevator, respectively. The second line contains c_l integers l_1, …, l_{c_l} in increasing order (1 ≀ l_i ≀ m), denoting the positions of the stairs. If c_l = 0, the second line is empty. The third line contains c_e integers e_1, …, e_{c_e} in increasing order, denoting the elevators positions in the same format. It is guaranteed that all integers l_i and e_i are distinct. The fourth line contains a single integer q (1 ≀ q ≀ 10^5) β€” the number of queries. The next q lines describe queries. Each of these lines contains four integers x_1, y_1, x_2, y_2 (1 ≀ x_1, x_2 ≀ n, 1 ≀ y_1, y_2 ≀ m) β€” the coordinates of starting and finishing sections for the query. It is guaranteed that the starting and finishing sections are distinct. It is also guaranteed that these sections contain guest rooms, i. e. y_1 and y_2 are not among l_i and e_i. Output Print q integers, one per line β€” the answers for the queries. Example Input 5 6 1 1 3 2 5 3 1 1 5 6 1 3 5 4 3 3 5 3 Output 7 5 4 Note In the first query the optimal way is to go to the elevator in the 5-th section in four time units, use it to go to the fifth floor in two time units and go to the destination in one more time unit. In the second query it is still optimal to use the elevator, but in the third query it is better to use the stairs in the section 2. Tags: binary search Correct Solution: ``` import bisect as bs import sys inp = sys.stdin.readlines() n, m, ladders, elevators, v = [int(x) for x in inp[0].strip().split()] ladders = [int(x) for x in inp[1].strip().split()] elevators = [int(x) for x in inp[2].strip().split()] q = int(inp[3].strip()) qs = [] for i in range(q): qs.append([int(x) for x in inp[4+i].strip().split()]) output = [] for query in qs: x1, y1, x2, y2 = query if x1 == x2: output.append(abs(y1-y2)) continue cur_ld = [] if ladders and (y1 > ladders[0]): cur_ld.append(ladders[bs.bisect_left(ladders, y1)-1]) if ladders and (y1 < ladders[-1]): cur_ld.append(ladders[bs.bisect_right(ladders, y1)]) cur_elev = [] if elevators and (y1 > elevators[0]): cur_elev.append(elevators[bs.bisect_left(elevators, y1)-1]) if elevators and (y1 < elevators[-1]): cur_elev.append(elevators[bs.bisect_right(elevators, y1)]) ans = [] for lad in cur_ld: ans.append(abs(y1 - lad) + abs(y2 - lad) + abs(x1 - x2)) for elev in cur_elev: height = abs(x1-x2) elspeed = height // v if height % v != 0: elspeed+=1 ans.append(abs(y1 - elev) + abs(y2 - elev) + elspeed) ans = min(ans) output.append(ans) output = '\n'.join(map(str, output)) print(output) ```
99,198
Provide tags and a correct Python 3 solution for this coding contest problem. In the year of 30XX participants of some world programming championship live in a single large hotel. The hotel has n floors. Each floor has m sections with a single corridor connecting all of them. The sections are enumerated from 1 to m along the corridor, and all sections with equal numbers on different floors are located exactly one above the other. Thus, the hotel can be represented as a rectangle of height n and width m. We can denote sections with pairs of integers (i, j), where i is the floor, and j is the section number on the floor. The guests can walk along the corridor on each floor, use stairs and elevators. Each stairs or elevator occupies all sections (1, x), (2, x), …, (n, x) for some x between 1 and m. All sections not occupied with stairs or elevators contain guest rooms. It takes one time unit to move between neighboring sections on the same floor or to move one floor up or down using stairs. It takes one time unit to move up to v floors in any direction using an elevator. You can assume you don't have to wait for an elevator, and the time needed to enter or exit an elevator is negligible. You are to process q queries. Each query is a question "what is the minimum time needed to go from a room in section (x_1, y_1) to a room in section (x_2, y_2)?" Input The first line contains five integers n, m, c_l, c_e, v (2 ≀ n, m ≀ 10^8, 0 ≀ c_l, c_e ≀ 10^5, 1 ≀ c_l + c_e ≀ m - 1, 1 ≀ v ≀ n - 1) β€” the number of floors and section on each floor, the number of stairs, the number of elevators and the maximum speed of an elevator, respectively. The second line contains c_l integers l_1, …, l_{c_l} in increasing order (1 ≀ l_i ≀ m), denoting the positions of the stairs. If c_l = 0, the second line is empty. The third line contains c_e integers e_1, …, e_{c_e} in increasing order, denoting the elevators positions in the same format. It is guaranteed that all integers l_i and e_i are distinct. The fourth line contains a single integer q (1 ≀ q ≀ 10^5) β€” the number of queries. The next q lines describe queries. Each of these lines contains four integers x_1, y_1, x_2, y_2 (1 ≀ x_1, x_2 ≀ n, 1 ≀ y_1, y_2 ≀ m) β€” the coordinates of starting and finishing sections for the query. It is guaranteed that the starting and finishing sections are distinct. It is also guaranteed that these sections contain guest rooms, i. e. y_1 and y_2 are not among l_i and e_i. Output Print q integers, one per line β€” the answers for the queries. Example Input 5 6 1 1 3 2 5 3 1 1 5 6 1 3 5 4 3 3 5 3 Output 7 5 4 Note In the first query the optimal way is to go to the elevator in the 5-th section in four time units, use it to go to the fifth floor in two time units and go to the destination in one more time unit. In the second query it is still optimal to use the elevator, but in the third query it is better to use the stairs in the section 2. Tags: binary search Correct Solution: ``` import sys def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return map(int,minp().split()) n,m,cl,ce,v = mints() l = list(mints()) e = list(mints()) def dist(x1, y1, x2, y2, t, yv): if t == 0: return abs(y1-yv)+abs(yv-y2)+abs(x1-x2) if t == 1: return abs(y1-yv)+abs(yv-y2)+(abs(x2-x1)+v-1)//v q = mint() bigg = 10**100 for i in range(q): x1,y1,x2,y2 = mints() best = bigg if len(l) != 0: L = 0 R = len(l)-1 while R-L > 1: C = (L+R)//2 if l[C] <= y1: L = C else: R = C best = min(best, dist(x1,y1,x2,y2,0,l[L])) best = min(best, dist(x1,y1,x2,y2,0,l[R])) L = 0 R = len(l)-1 while R-L > 1: C = (L+R)//2 if l[C] <= y2: L = C else: R = C best = min(best, dist(x1,y1,x2,y2,0,l[L])) best = min(best, dist(x1,y1,x2,y2,0,l[R])) if len(e) != 0: L = 0 R = len(e)-1 while R-L > 1: C = (L+R)//2 if e[C] <= y1: L = C else: R = C best = min(best, dist(x1,y1,x2,y2,1,e[L])) best = min(best, dist(x1,y1,x2,y2,1,e[R])) L = 0 R = len(e)-1 while R-L > 1: C = (L+R)//2 if e[C] <= y2: L = C else: R = C best = min(best, dist(x1,y1,x2,y2,1,e[L])) best = min(best, dist(x1,y1,x2,y2,1,e[R])) if x1 == x2: best = min(best, abs(y1-y2)) print(best) ```
99,199