text
stringlengths
198
433k
conversation_id
int64
0
109k
Provide tags and a correct Python 3 solution for this coding contest problem. Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a mask of a positive integer n the number that is obtained after successive writing of all lucky digits of number n from the left to the right. For example, the mask of number 72174994 is number 7744, the mask of 7 is 7, the mask of 9999047 is 47. Obviously, mask of any number is always a lucky number. Petya has two numbers — an arbitrary integer a and a lucky number b. Help him find the minimum number c (c > a) such that the mask of number c equals b. Input The only line contains two integers a and b (1 ≤ a, b ≤ 105). It is guaranteed that number b is lucky. Output In the only line print a single number — the number c that is sought by Petya. Examples Input 1 7 Output 7 Input 100 47 Output 147 Tags: brute force, implementation Correct Solution: ``` a, b = list(map(int, input().split())) while True: a += 1 sta = str(a) m = "" n = 0 for i in range(len(sta)): if sta[i] == '4' or sta[i] == '7': m += sta[i] if len(m) > 0: n = int(m) if n == b: print(a) break ```
94,600
Provide tags and a correct Python 3 solution for this coding contest problem. Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a mask of a positive integer n the number that is obtained after successive writing of all lucky digits of number n from the left to the right. For example, the mask of number 72174994 is number 7744, the mask of 7 is 7, the mask of 9999047 is 47. Obviously, mask of any number is always a lucky number. Petya has two numbers — an arbitrary integer a and a lucky number b. Help him find the minimum number c (c > a) such that the mask of number c equals b. Input The only line contains two integers a and b (1 ≤ a, b ≤ 105). It is guaranteed that number b is lucky. Output In the only line print a single number — the number c that is sought by Petya. Examples Input 1 7 Output 7 Input 100 47 Output 147 Tags: brute force, implementation Correct Solution: ``` a,b=map(str,input().split()) def mask(x): st='' for i in str(x): if i=='7' or i=='4': st+=i return(st) for i in range(int(a)+1,177778): if mask(i)!=b: pass else: print(i) quit() ```
94,601
Provide tags and a correct Python 3 solution for this coding contest problem. Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a mask of a positive integer n the number that is obtained after successive writing of all lucky digits of number n from the left to the right. For example, the mask of number 72174994 is number 7744, the mask of 7 is 7, the mask of 9999047 is 47. Obviously, mask of any number is always a lucky number. Petya has two numbers — an arbitrary integer a and a lucky number b. Help him find the minimum number c (c > a) such that the mask of number c equals b. Input The only line contains two integers a and b (1 ≤ a, b ≤ 105). It is guaranteed that number b is lucky. Output In the only line print a single number — the number c that is sought by Petya. Examples Input 1 7 Output 7 Input 100 47 Output 147 Tags: brute force, implementation Correct Solution: ``` a,b=map(str,input().split()) def check(x): st='' for i in str(x): if i=='7' or i=='4': st+=i return(st) for i in range(int(a)+1,177778): if check(i)!=b: pass else: print(i) quit() ```
94,602
Provide tags and a correct Python 3 solution for this coding contest problem. Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a mask of a positive integer n the number that is obtained after successive writing of all lucky digits of number n from the left to the right. For example, the mask of number 72174994 is number 7744, the mask of 7 is 7, the mask of 9999047 is 47. Obviously, mask of any number is always a lucky number. Petya has two numbers — an arbitrary integer a and a lucky number b. Help him find the minimum number c (c > a) such that the mask of number c equals b. Input The only line contains two integers a and b (1 ≤ a, b ≤ 105). It is guaranteed that number b is lucky. Output In the only line print a single number — the number c that is sought by Petya. Examples Input 1 7 Output 7 Input 100 47 Output 147 Tags: brute force, implementation Correct Solution: ``` a=input() list1 = a.split(' ') num1=list1[0] num2=list1[1] def mask(num): num=str(num) str1="" for i in range(0,len(num)): if (ord(num[i])-48)==7 or (ord(num[i])-48)==4: str1=str1+num[i] return str1 for i in range(int(num1)+1,1000000): if mask(i)==num2: print(i) quit() ```
94,603
Provide tags and a correct Python 3 solution for this coding contest problem. Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a mask of a positive integer n the number that is obtained after successive writing of all lucky digits of number n from the left to the right. For example, the mask of number 72174994 is number 7744, the mask of 7 is 7, the mask of 9999047 is 47. Obviously, mask of any number is always a lucky number. Petya has two numbers — an arbitrary integer a and a lucky number b. Help him find the minimum number c (c > a) such that the mask of number c equals b. Input The only line contains two integers a and b (1 ≤ a, b ≤ 105). It is guaranteed that number b is lucky. Output In the only line print a single number — the number c that is sought by Petya. Examples Input 1 7 Output 7 Input 100 47 Output 147 Tags: brute force, implementation Correct Solution: ``` target,lucky=map(int,input().split()) if lucky>target: print(lucky) else: checkarr=list(map(int,str(lucky))) while True: target+=1 i=0 check=False tmp=list(map(int,str(target))) for val in tmp: if val==checkarr[i]: i+=1 if i==len(checkarr): check=True break if check: tmpstr=[] for val in tmp: if val==7: tmpstr.append(7) elif val==4: tmpstr.append(4) if tmpstr==checkarr: print(target) break ```
94,604
Provide tags and a correct Python 3 solution for this coding contest problem. Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a mask of a positive integer n the number that is obtained after successive writing of all lucky digits of number n from the left to the right. For example, the mask of number 72174994 is number 7744, the mask of 7 is 7, the mask of 9999047 is 47. Obviously, mask of any number is always a lucky number. Petya has two numbers — an arbitrary integer a and a lucky number b. Help him find the minimum number c (c > a) such that the mask of number c equals b. Input The only line contains two integers a and b (1 ≤ a, b ≤ 105). It is guaranteed that number b is lucky. Output In the only line print a single number — the number c that is sought by Petya. Examples Input 1 7 Output 7 Input 100 47 Output 147 Tags: brute force, implementation Correct Solution: ``` import math def mask(x): tmp,res=0,0 while(x): if(x%10==4 or x%10==7): tmp=tmp*10+(x%10) x//=10 while(tmp): res=res*10+(tmp%10) tmp//=10 return res try: t=1 while(t): t-=1 a,b=map(int,input().split()) a+=1 while(mask(a)!=b): a+=1 print(a) except: pass ```
94,605
Provide tags and a correct Python 3 solution for this coding contest problem. Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a mask of a positive integer n the number that is obtained after successive writing of all lucky digits of number n from the left to the right. For example, the mask of number 72174994 is number 7744, the mask of 7 is 7, the mask of 9999047 is 47. Obviously, mask of any number is always a lucky number. Petya has two numbers — an arbitrary integer a and a lucky number b. Help him find the minimum number c (c > a) such that the mask of number c equals b. Input The only line contains two integers a and b (1 ≤ a, b ≤ 105). It is guaranteed that number b is lucky. Output In the only line print a single number — the number c that is sought by Petya. Examples Input 1 7 Output 7 Input 100 47 Output 147 Tags: brute force, implementation Correct Solution: ``` s = input() a = int(s.split()[0]) b = int(s.split()[1]) def getMask(num): s = str(num) l = [c for c in s if c=='4' or c=='7'] if len(l) == 0: return 0 return int(''.join(l)) ans = a + 1 while not getMask(ans) == b: ans = ans + 1 print(ans) ```
94,606
Provide tags and a correct Python 3 solution for this coding contest problem. Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a mask of a positive integer n the number that is obtained after successive writing of all lucky digits of number n from the left to the right. For example, the mask of number 72174994 is number 7744, the mask of 7 is 7, the mask of 9999047 is 47. Obviously, mask of any number is always a lucky number. Petya has two numbers — an arbitrary integer a and a lucky number b. Help him find the minimum number c (c > a) such that the mask of number c equals b. Input The only line contains two integers a and b (1 ≤ a, b ≤ 105). It is guaranteed that number b is lucky. Output In the only line print a single number — the number c that is sought by Petya. Examples Input 1 7 Output 7 Input 100 47 Output 147 Tags: brute force, implementation Correct Solution: ``` def mask(x,k): t="" for i in x: if i in "47":t+=i return t!=k a,b=map(int,input().split()) z=a while mask(str(a),str(b)) or a<=z:a+=1 print(a) ```
94,607
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a mask of a positive integer n the number that is obtained after successive writing of all lucky digits of number n from the left to the right. For example, the mask of number 72174994 is number 7744, the mask of 7 is 7, the mask of 9999047 is 47. Obviously, mask of any number is always a lucky number. Petya has two numbers — an arbitrary integer a and a lucky number b. Help him find the minimum number c (c > a) such that the mask of number c equals b. Input The only line contains two integers a and b (1 ≤ a, b ≤ 105). It is guaranteed that number b is lucky. Output In the only line print a single number — the number c that is sought by Petya. Examples Input 1 7 Output 7 Input 100 47 Output 147 Submitted Solution: ``` def f(x): s="0" for c in str(x): if c=='7' or c=='4': s+=c return int(s) a,b=map(int,input().split()) x=a+1 while f(x)!=b: x+=1 print(x) ``` Yes
94,608
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a mask of a positive integer n the number that is obtained after successive writing of all lucky digits of number n from the left to the right. For example, the mask of number 72174994 is number 7744, the mask of 7 is 7, the mask of 9999047 is 47. Obviously, mask of any number is always a lucky number. Petya has two numbers — an arbitrary integer a and a lucky number b. Help him find the minimum number c (c > a) such that the mask of number c equals b. Input The only line contains two integers a and b (1 ≤ a, b ≤ 105). It is guaranteed that number b is lucky. Output In the only line print a single number — the number c that is sought by Petya. Examples Input 1 7 Output 7 Input 100 47 Output 147 Submitted Solution: ``` a, b = input().split() for i in range(max(int(a) + 1, int(b)), 999999): if ''.join(c for c in str(i) if c in ('4,7')) == b: print(i);exit() ``` Yes
94,609
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a mask of a positive integer n the number that is obtained after successive writing of all lucky digits of number n from the left to the right. For example, the mask of number 72174994 is number 7744, the mask of 7 is 7, the mask of 9999047 is 47. Obviously, mask of any number is always a lucky number. Petya has two numbers — an arbitrary integer a and a lucky number b. Help him find the minimum number c (c > a) such that the mask of number c equals b. Input The only line contains two integers a and b (1 ≤ a, b ≤ 105). It is guaranteed that number b is lucky. Output In the only line print a single number — the number c that is sought by Petya. Examples Input 1 7 Output 7 Input 100 47 Output 147 Submitted Solution: ``` def mask(x): s = 0 n = str(x) for i in range(len(n)): if n[i] == '7' or n[i] == '4': s = s * 10 + int(n[i]) return s a , b = (input().split()) a= int(a) a= a + 1 b= int(b) while mask(a) != b: a = a + 1 print(a) ``` Yes
94,610
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a mask of a positive integer n the number that is obtained after successive writing of all lucky digits of number n from the left to the right. For example, the mask of number 72174994 is number 7744, the mask of 7 is 7, the mask of 9999047 is 47. Obviously, mask of any number is always a lucky number. Petya has two numbers — an arbitrary integer a and a lucky number b. Help him find the minimum number c (c > a) such that the mask of number c equals b. Input The only line contains two integers a and b (1 ≤ a, b ≤ 105). It is guaranteed that number b is lucky. Output In the only line print a single number — the number c that is sought by Petya. Examples Input 1 7 Output 7 Input 100 47 Output 147 Submitted Solution: ``` a = [int(x) for x in input().split()] b=str(a[0]+1) c=str(a[1]) def getmask(q): s="" for i in q: if i in ["4","7"]: s+=i return s while getmask(b)!=c : b=str(int(b)+1) print(b) ``` Yes
94,611
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a mask of a positive integer n the number that is obtained after successive writing of all lucky digits of number n from the left to the right. For example, the mask of number 72174994 is number 7744, the mask of 7 is 7, the mask of 9999047 is 47. Obviously, mask of any number is always a lucky number. Petya has two numbers — an arbitrary integer a and a lucky number b. Help him find the minimum number c (c > a) such that the mask of number c equals b. Input The only line contains two integers a and b (1 ≤ a, b ≤ 105). It is guaranteed that number b is lucky. Output In the only line print a single number — the number c that is sought by Petya. Examples Input 1 7 Output 7 Input 100 47 Output 147 Submitted Solution: ``` a = [int(x) for x in input().split()] b=str(a[0]) c=str(a[1]) while c not in b: b=str(int(b)+1) print(b) ``` No
94,612
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a mask of a positive integer n the number that is obtained after successive writing of all lucky digits of number n from the left to the right. For example, the mask of number 72174994 is number 7744, the mask of 7 is 7, the mask of 9999047 is 47. Obviously, mask of any number is always a lucky number. Petya has two numbers — an arbitrary integer a and a lucky number b. Help him find the minimum number c (c > a) such that the mask of number c equals b. Input The only line contains two integers a and b (1 ≤ a, b ≤ 105). It is guaranteed that number b is lucky. Output In the only line print a single number — the number c that is sought by Petya. Examples Input 1 7 Output 7 Input 100 47 Output 147 Submitted Solution: ``` def f(a, b): j = 0 for i in b: j = a.find(i, j) if j < 0: return False return True a, b = input().split() if len(a) < len(b): ans = b else: u, v = len(a) - 1, len(b) - 1 for i in range(len(b)): x, y = u - i, v - i if a[x:] > b[y:]: t = str(int(a[:x]) + 1) if f(t, b[:y]): ans = t + b[y:] break elif f(a[:x], b[:y]): ans = a[:x] + b[y:] break print(ans) ``` No
94,613
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a mask of a positive integer n the number that is obtained after successive writing of all lucky digits of number n from the left to the right. For example, the mask of number 72174994 is number 7744, the mask of 7 is 7, the mask of 9999047 is 47. Obviously, mask of any number is always a lucky number. Petya has two numbers — an arbitrary integer a and a lucky number b. Help him find the minimum number c (c > a) such that the mask of number c equals b. Input The only line contains two integers a and b (1 ≤ a, b ≤ 105). It is guaranteed that number b is lucky. Output In the only line print a single number — the number c that is sought by Petya. Examples Input 1 7 Output 7 Input 100 47 Output 147 Submitted Solution: ``` #from dust i have come dust i will be import sys a,b=map(int,input().split()) sa=str(a) sb=str(b) if len(sa)==len(sb): if b>a: print(b) else: sys.stdout.write("1"+sb) else: if b>a: print(b) else: #extract the same len of b from a sc="" l=len(sa)-len(sb) for i in range(l,len(sa)): sc+=sa[i] c=int(sc) #if c<b then write first l chars if c<b: for i in range(l): sys.stdout.write(sa[i]) sys.stdout.write(sb) # otherwise from l-1 to 0 try increasing 1 else: sc="" for i in range(l): sc+=sa[i] c=int(sc) c+=1 sys.stdout.write(str(c)+sb) ``` No
94,614
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a mask of a positive integer n the number that is obtained after successive writing of all lucky digits of number n from the left to the right. For example, the mask of number 72174994 is number 7744, the mask of 7 is 7, the mask of 9999047 is 47. Obviously, mask of any number is always a lucky number. Petya has two numbers — an arbitrary integer a and a lucky number b. Help him find the minimum number c (c > a) such that the mask of number c equals b. Input The only line contains two integers a and b (1 ≤ a, b ≤ 105). It is guaranteed that number b is lucky. Output In the only line print a single number — the number c that is sought by Petya. Examples Input 1 7 Output 7 Input 100 47 Output 147 Submitted Solution: ``` ''' Created on Feb 11, 2015 @author: mohamed265 ''' def fun (a, b): #print(a ,b) lenA = len(a) o = 0 for i in range(lenA): if b[o] == a[i]: o += 1 if o == len(b): return False return True # for i in range(o , l temp = input().split() a = int(temp[0]) +1 b = temp[1] while fun(str(a), b): a +=1 print(a) ``` No
94,615
Provide tags and a correct Python 3 solution for this coding contest problem. We define a spanning tree of a graph to be a BFS tree rooted at vertex s if and only if for every node t the shortest distance between s and t in the graph is equal to the shortest distance between s and t in the spanning tree. Given a graph, we define f(x,y) to be the number of spanning trees of that graph that are BFS trees rooted at vertices x and y at the same time. You are given an undirected connected graph with n vertices and m edges. Calculate f(i,j) for all i, j by modulo 998 244 353. Input The first line contains two integers n, m (1 ≤ n ≤ 400, 0 ≤ m ≤ 600) — the number of vertices and the number of edges in the graph. The i-th of the next m lines contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i < b_i), representing an edge connecting a_i and b_i. It is guaranteed that all edges are distinct and the graph is connected. Output Print n lines, each consisting of n integers. The integer printed in the row i and the column j should be f(i,j) mod 998 244 353. Examples Input 4 4 1 2 2 3 3 4 1 4 Output 2 1 0 1 1 2 1 0 0 1 2 1 1 0 1 2 Input 8 9 1 2 1 3 1 4 2 7 3 5 3 6 4 8 2 3 3 4 Output 1 0 0 0 0 0 0 0 0 2 0 0 0 0 2 0 0 0 1 0 1 1 0 0 0 0 0 2 0 0 0 2 0 0 1 0 1 1 0 0 0 0 1 0 1 1 0 0 0 2 0 0 0 0 2 0 0 0 0 2 0 0 0 2 Note The following picture describes the first example. <image> The tree with red edges is a BFS tree rooted at both 1 and 2. <image> Similarly, the BFS tree for other adjacent pairs of vertices can be generated in this way. Tags: combinatorics, dfs and similar, graphs, math, shortest paths, trees Correct Solution: ``` import sys, os from collections import defaultdict, deque if os.environ['USERNAME']=='kissz': inp=open('in2.txt','r').readline def debug(*args): print(*args,file=sys.stderr) else: inp=sys.stdin.readline def debug(*args): pass # SCRIPT STARTS HERE def solve(): n,m=map(int,inp().split()) G=defaultdict(list) for i in range(m): u,v=map(int,inp().split()) G[u-1]+=[v-1] G[v-1]+=[u-1] combs=[[-1]*n for _ in range(n)] def bfs(i): Q=deque([i]) D=[-1]*n D[i]=0 while Q: node=Q.pop() for neighbor in G[node]: if D[neighbor]==-1: Q.appendleft(neighbor) D[neighbor]=D[node]+1 return D dists=[bfs(i) for i in range(n)] for i in range(n): for j in range(i+1): node=j failed=False while node!=i: c=0 next_node=-1 for neighbor in G[node]: if dists[i][neighbor]<dists[i][node]: c+=1 next_node=neighbor if c==1: node=next_node else: failed=True break call=1 if failed: combs[i][j]=combs[j][i]=0 else: for k in range(n): if dists[i][k]+dists[j][k]>dists[i][j]: c=0 for l in G[k]: if dists[i][l]+1==dists[i][k] and dists[j][l]+1==dists[j][k]: c+=1 call=(call*c)% 998244353 combs[i][j]=combs[j][i]=call for i in range(n): print(*combs[i]) solve() ```
94,616
Provide tags and a correct Python 3 solution for this coding contest problem. We define a spanning tree of a graph to be a BFS tree rooted at vertex s if and only if for every node t the shortest distance between s and t in the graph is equal to the shortest distance between s and t in the spanning tree. Given a graph, we define f(x,y) to be the number of spanning trees of that graph that are BFS trees rooted at vertices x and y at the same time. You are given an undirected connected graph with n vertices and m edges. Calculate f(i,j) for all i, j by modulo 998 244 353. Input The first line contains two integers n, m (1 ≤ n ≤ 400, 0 ≤ m ≤ 600) — the number of vertices and the number of edges in the graph. The i-th of the next m lines contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i < b_i), representing an edge connecting a_i and b_i. It is guaranteed that all edges are distinct and the graph is connected. Output Print n lines, each consisting of n integers. The integer printed in the row i and the column j should be f(i,j) mod 998 244 353. Examples Input 4 4 1 2 2 3 3 4 1 4 Output 2 1 0 1 1 2 1 0 0 1 2 1 1 0 1 2 Input 8 9 1 2 1 3 1 4 2 7 3 5 3 6 4 8 2 3 3 4 Output 1 0 0 0 0 0 0 0 0 2 0 0 0 0 2 0 0 0 1 0 1 1 0 0 0 0 0 2 0 0 0 2 0 0 1 0 1 1 0 0 0 0 1 0 1 1 0 0 0 2 0 0 0 0 2 0 0 0 0 2 0 0 0 2 Note The following picture describes the first example. <image> The tree with red edges is a BFS tree rooted at both 1 and 2. <image> Similarly, the BFS tree for other adjacent pairs of vertices can be generated in this way. Tags: combinatorics, dfs and similar, graphs, math, shortest paths, trees Correct Solution: ``` #!/usr/bin/env python import os import sys from io import BytesIO, IOBase def main(): n,m = map(int,input().split()) MOD = 998244353 adjList = [] dist = [] ans = [] for _ in range(n): adjList.append([]) for _ in range(m): a,b = map(int,input().split()) adjList[a - 1].append(b - 1) adjList[b - 1].append(a - 1) for i in range(n): curDist = [-1] * n curDist[i] = 0 bfsQueue = [i] bfsIndex = 0 while len(bfsQueue) > bfsIndex: c = bfsQueue[bfsIndex] bfsIndex += 1 for elem in adjList[c]: if curDist[elem] == -1: curDist[elem] = curDist[c] + 1 bfsQueue.append(elem) dist.append(curDist) for _ in range(n): ans.append([0] * n) for i in range(n): for j in range(i, n): # Find shortest path between i and j isCovered = [False] * n isCovered[i] = True isCovered[j] = True jCpy = j flag = True while jCpy != i: cnt = 0 cntIndex = -1 for elem in adjList[jCpy]: if dist[i][elem] == dist[i][jCpy] - 1: cnt += 1 cntIndex = elem if cnt >= 2: flag = False break else: isCovered[cntIndex] = True jCpy = cntIndex if not flag: ans[i][j] = 0 ans[j][i] = 0 else: curAns = 1 for k in range(n): if isCovered[k]: continue cnt = 0 for elem in adjList[k]: if dist[i][elem] == dist[i][k] - 1 and dist[j][elem] == dist[j][k] - 1: cnt += 1 curAns *= cnt curAns %= MOD ans[i][j] = curAns ans[j][i] = curAns for elem in ans: print(" ".join(map(str,elem))) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main() ```
94,617
Provide tags and a correct Python 3 solution for this coding contest problem. We define a spanning tree of a graph to be a BFS tree rooted at vertex s if and only if for every node t the shortest distance between s and t in the graph is equal to the shortest distance between s and t in the spanning tree. Given a graph, we define f(x,y) to be the number of spanning trees of that graph that are BFS trees rooted at vertices x and y at the same time. You are given an undirected connected graph with n vertices and m edges. Calculate f(i,j) for all i, j by modulo 998 244 353. Input The first line contains two integers n, m (1 ≤ n ≤ 400, 0 ≤ m ≤ 600) — the number of vertices and the number of edges in the graph. The i-th of the next m lines contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i < b_i), representing an edge connecting a_i and b_i. It is guaranteed that all edges are distinct and the graph is connected. Output Print n lines, each consisting of n integers. The integer printed in the row i and the column j should be f(i,j) mod 998 244 353. Examples Input 4 4 1 2 2 3 3 4 1 4 Output 2 1 0 1 1 2 1 0 0 1 2 1 1 0 1 2 Input 8 9 1 2 1 3 1 4 2 7 3 5 3 6 4 8 2 3 3 4 Output 1 0 0 0 0 0 0 0 0 2 0 0 0 0 2 0 0 0 1 0 1 1 0 0 0 0 0 2 0 0 0 2 0 0 1 0 1 1 0 0 0 0 1 0 1 1 0 0 0 2 0 0 0 0 2 0 0 0 0 2 0 0 0 2 Note The following picture describes the first example. <image> The tree with red edges is a BFS tree rooted at both 1 and 2. <image> Similarly, the BFS tree for other adjacent pairs of vertices can be generated in this way. Tags: combinatorics, dfs and similar, graphs, math, shortest paths, trees Correct Solution: ``` import io import os from collections import deque def solve(N, M, edges): graph = [[] for i in range(N)] for u, v in edges: graph[u].append(v) graph[v].append(u) def bfs(source): q = deque([source]) dist = [-1] * N dist[source] = 0 while q: node = q.popleft() d = dist[node] for nbr in graph[node]: if dist[nbr] == -1: q.append(nbr) dist[nbr] = d + 1 return dist dists = [bfs(u) for u in range(N)] MOD = 998244353 ans = [[0 for i in range(N)] for j in range(N)] for x in range(N): for y in range(x, N): onPath = 0 for i in range(N): if dists[x][i] + dists[y][i] == dists[x][y]: onPath += 1 numVertices = dists[x][y] + 1 # including x and y ways = 1 if onPath > numVertices: ways = 0 else: for i in range(N): if dists[x][i] + dists[y][i] != dists[x][y]: count = 0 for j in graph[i]: if ( dists[x][i] == dists[x][j] + 1 and dists[y][i] == dists[y][j] + 1 ): count += 1 ways = (ways * count) % MOD if not ways: break ans[x][y] = ways ans[y][x] = ways return "\n".join(" ".join(map(str, row)) for row in ans) if __name__ == "__main__": input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline TC = 1 for tc in range(1, TC + 1): N, M = [int(x) for x in input().split()] edges = [[int(x) - 1 for x in input().split()] for i in range(M)] # 0 indexed ans = solve(N, M, edges) print(ans) ```
94,618
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We define a spanning tree of a graph to be a BFS tree rooted at vertex s if and only if for every node t the shortest distance between s and t in the graph is equal to the shortest distance between s and t in the spanning tree. Given a graph, we define f(x,y) to be the number of spanning trees of that graph that are BFS trees rooted at vertices x and y at the same time. You are given an undirected connected graph with n vertices and m edges. Calculate f(i,j) for all i, j by modulo 998 244 353. Input The first line contains two integers n, m (1 ≤ n ≤ 400, 0 ≤ m ≤ 600) — the number of vertices and the number of edges in the graph. The i-th of the next m lines contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i < b_i), representing an edge connecting a_i and b_i. It is guaranteed that all edges are distinct and the graph is connected. Output Print n lines, each consisting of n integers. The integer printed in the row i and the column j should be f(i,j) mod 998 244 353. Examples Input 4 4 1 2 2 3 3 4 1 4 Output 2 1 0 1 1 2 1 0 0 1 2 1 1 0 1 2 Input 8 9 1 2 1 3 1 4 2 7 3 5 3 6 4 8 2 3 3 4 Output 1 0 0 0 0 0 0 0 0 2 0 0 0 0 2 0 0 0 1 0 1 1 0 0 0 0 0 2 0 0 0 2 0 0 1 0 1 1 0 0 0 0 1 0 1 1 0 0 0 2 0 0 0 0 2 0 0 0 0 2 0 0 0 2 Note The following picture describes the first example. <image> The tree with red edges is a BFS tree rooted at both 1 and 2. <image> Similarly, the BFS tree for other adjacent pairs of vertices can be generated in this way. Submitted Solution: ``` def divisors(M): d=[] i=1 while M>=i**2: if M%i==0: d.append(i) if i**2!=M: d.append(M//i) i=i+1 return d def popcount(x): x = x - ((x >> 1) & 0x55555555) x = (x & 0x33333333) + ((x >> 2) & 0x33333333) x = (x + (x >> 4)) & 0x0f0f0f0f x = x + (x >> 8) x = x + (x >> 16) return x & 0x0000007f def eratosthenes(n): res=[0 for i in range(n+1)] prime=set([]) for i in range(2,n+1): if not res[i]: prime.add(i) for j in range(1,n//i+1): res[i*j]=1 return prime def factorization(n): res=[] for p in prime: if n%p==0: while n%p==0: n//=p res.append(p) if n!=1: res.append(n) return res def euler_phi(n): res = n for x in range(2,n+1): if x ** 2 > n: break if n%x==0: res = res//x * (x-1) while n%x==0: n //= x if n!=1: res = res//n * (n-1) return res def ind(b,n): res=0 while n%b==0: res+=1 n//=b return res def isPrimeMR(n): d = n - 1 d = d // (d & -d) L = [2, 3, 5, 7, 11, 13, 17] for a in L: t = d y = pow(a, t, n) if y == 1: continue while y != n - 1: y = (y * y) % n if y == 1 or t == n - 1: return 0 t <<= 1 return 1 def findFactorRho(n): from math import gcd m = 1 << n.bit_length() // 8 for c in range(1, 99): f = lambda x: (x * x + c) % n y, r, q, g = 2, 1, 1, 1 while g == 1: x = y for i in range(r): y = f(y) k = 0 while k < r and g == 1: ys = y for i in range(min(m, r - k)): y = f(y) q = q * abs(x - y) % n g = gcd(q, n) k += m r <<= 1 if g == n: g = 1 while g == 1: ys = f(ys) g = gcd(abs(x - ys), n) if g < n: if isPrimeMR(g): return g elif isPrimeMR(n // g): return n // g return findFactorRho(g) def primeFactor(n): i = 2 ret = {} rhoFlg = 0 while i*i <= n: k = 0 while n % i == 0: n //= i k += 1 if k: ret[i] = k i += 1 + i % 2 if i == 101 and n >= 2 ** 20: while n > 1: if isPrimeMR(n): ret[n], n = 1, 1 else: rhoFlg = 1 j = findFactorRho(n) k = 0 while n % j == 0: n //= j k += 1 ret[j] = k if n > 1: ret[n] = 1 if rhoFlg: ret = {x: ret[x] for x in sorted(ret)} return ret def divisors(n): res = [1] prime = primeFactor(n) for p in prime: newres = [] for d in res: for j in range(prime[p]+1): newres.append(d*p**j) res = newres res.sort() return res def xorfactorial(num):#排他的論理和の階乗 if num==0: return 0 elif num==1: return 1 elif num==2: return 3 elif num==3: return 0 else: x=baseorder(num) return (2**x)*((num-2**x+1)%2)+function(num-2**x) def xorconv(n,X,Y): if n==0: res=[(X[0]*Y[0])%mod] return res x=[X[i]+X[i+2**(n-1)] for i in range(2**(n-1))] y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))] z=[X[i]-X[i+2**(n-1)] for i in range(2**(n-1))] w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))] res1=xorconv(n-1,x,y) res2=xorconv(n-1,z,w) former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))] latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))] former=list(map(lambda x:x%mod,former)) latter=list(map(lambda x:x%mod,latter)) return former+latter def merge_sort(A,B): pos_A,pos_B = 0,0 n,m = len(A),len(B) res = [] while pos_A < n and pos_B < m: a,b = A[pos_A],B[pos_B] if a < b: res.append(a) pos_A += 1 else: res.append(b) pos_B += 1 res += A[pos_A:] res += B[pos_B:] return res class UnionFindVerSize(): def __init__(self, N): self._parent = [n for n in range(0, N)] self._size = [1] * N self.group = N def find_root(self, x): if self._parent[x] == x: return x self._parent[x] = self.find_root(self._parent[x]) stack = [x] while self._parent[stack[-1]]!=stack[-1]: stack.append(self._parent[stack[-1]]) for v in stack: self._parent[v] = stack[-1] return self._parent[x] def unite(self, x, y): gx = self.find_root(x) gy = self.find_root(y) if gx == gy: return self.group -= 1 if self._size[gx] < self._size[gy]: self._parent[gx] = gy self._size[gy] += self._size[gx] else: self._parent[gy] = gx self._size[gx] += self._size[gy] def get_size(self, x): return self._size[self.find_root(x)] def is_same_group(self, x, y): return self.find_root(x) == self.find_root(y) class WeightedUnionFind(): def __init__(self,N): self.parent = [i for i in range(N)] self.size = [1 for i in range(N)] self.val = [0 for i in range(N)] self.flag = True self.edge = [[] for i in range(N)] def dfs(self,v,pv): stack = [(v,pv)] new_parent = self.parent[pv] while stack: v,pv = stack.pop() self.parent[v] = new_parent for nv,w in self.edge[v]: if nv!=pv: self.val[nv] = self.val[v] + w stack.append((nv,v)) def unite(self,x,y,w): if not self.flag: return if self.parent[x]==self.parent[y]: self.flag = (self.val[x] - self.val[y] == w) return if self.size[self.parent[x]]>self.size[self.parent[y]]: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[x] += self.size[y] self.val[y] = self.val[x] - w self.dfs(y,x) else: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[y] += self.size[x] self.val[x] = self.val[y] + w self.dfs(x,y) class Dijkstra(): class Edge(): def __init__(self, _to, _cost): self.to = _to self.cost = _cost def __init__(self, V): self.G = [[] for i in range(V)] self._E = 0 self._V = V @property def E(self): return self._E @property def V(self): return self._V def add_edge(self, _from, _to, _cost): self.G[_from].append(self.Edge(_to, _cost)) self._E += 1 def shortest_path(self, s): import heapq que = [] d = [10**15] * self.V d[s] = 0 heapq.heappush(que, (0, s)) while len(que) != 0: cost, v = heapq.heappop(que) if d[v] < cost: continue for i in range(len(self.G[v])): e = self.G[v][i] if d[e.to] > d[v] + e.cost: d[e.to] = d[v] + e.cost heapq.heappush(que, (d[e.to], e.to)) return d #Z[i]:length of the longest list starting from S[i] which is also a prefix of S #O(|S|) def Z_algorithm(s): N = len(s) Z_alg = [0]*N Z_alg[0] = N i = 1 j = 0 while i < N: while i+j < N and s[j] == s[i+j]: j += 1 Z_alg[i] = j if j == 0: i += 1 continue k = 1 while i+k < N and k + Z_alg[k]<j: Z_alg[i+k] = Z_alg[k] k += 1 i += k j -= k return Z_alg class BIT(): def __init__(self,n): self.BIT=[0]*(n+1) self.num=n def query(self,idx): res_sum = 0 while idx > 0: res_sum += self.BIT[idx] idx -= idx&(-idx) return res_sum #Ai += x O(logN) def update(self,idx,x): while idx <= self.num: self.BIT[idx] += x idx += idx&(-idx) return class dancinglink(): def __init__(self,n,debug=False): self.n = n self.debug = debug self._left = [i-1 for i in range(n)] self._right = [i+1 for i in range(n)] self.exist = [True for i in range(n)] def pop(self,k): if self.debug: assert self.exist[k] L = self._left[k] R = self._right[k] if L!=-1: if R!=self.n: self._right[L],self._left[R] = R,L else: self._right[L] = self.n elif R!=self.n: self._left[R] = -1 self.exist[k] = False def left(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._left[res] if res==-1: break k -= 1 return res def right(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._right[res] if res==self.n: break k -= 1 return res class SparseTable(): def __init__(self,A,merge_func,ide_ele): N=len(A) n=N.bit_length() self.table=[[ide_ele for i in range(n)] for i in range(N)] self.merge_func=merge_func for i in range(N): self.table[i][0]=A[i] for j in range(1,n): for i in range(0,N-2**j+1): f=self.table[i][j-1] s=self.table[i+2**(j-1)][j-1] self.table[i][j]=self.merge_func(f,s) def query(self,s,t): b=t-s+1 m=b.bit_length()-1 return self.merge_func(self.table[s][m],self.table[t-2**m+1][m]) class BinaryTrie: class node: def __init__(self,val): self.left = None self.right = None self.max = val def __init__(self): self.root = self.node(-10**15) def append(self,key,val): pos = self.root for i in range(29,-1,-1): pos.max = max(pos.max,val) if key>>i & 1: if pos.right is None: pos.right = self.node(val) pos = pos.right else: pos = pos.right else: if pos.left is None: pos.left = self.node(val) pos = pos.left else: pos = pos.left pos.max = max(pos.max,val) def search(self,M,xor): res = -10**15 pos = self.root for i in range(29,-1,-1): if pos is None: break if M>>i & 1: if xor>>i & 1: if pos.right: res = max(res,pos.right.max) pos = pos.left else: if pos.left: res = max(res,pos.left.max) pos = pos.right else: if xor>>i & 1: pos = pos.right else: pos = pos.left if pos: res = max(res,pos.max) return res def solveequation(edge,ans,n,m): #edge=[[to,dire,id]...] x=[0]*m used=[False]*n for v in range(n): if used[v]: continue y = dfs(v) if y!=0: return False return x def dfs(v): used[v]=True r=ans[v] for to,dire,id in edge[v]: if used[to]: continue y=dfs(to) if dire==-1: x[id]=y else: x[id]=-y r+=y return r class Matrix(): mod=10**9+7 def set_mod(m): Matrix.mod=m def __init__(self,L): self.row=len(L) self.column=len(L[0]) self._matrix=L for i in range(self.row): for j in range(self.column): self._matrix[i][j]%=Matrix.mod def __getitem__(self,item): if type(item)==int: raise IndexError("you must specific row and column") elif len(item)!=2: raise IndexError("you must specific row and column") i,j=item return self._matrix[i][j] def __setitem__(self,item,val): if type(item)==int: raise IndexError("you must specific row and column") elif len(item)!=2: raise IndexError("you must specific row and column") i,j=item self._matrix[i][j]=val def __add__(self,other): if (self.row,self.column)!=(other.row,other.column): raise SizeError("sizes of matrixes are different") res=[[0 for j in range(self.column)] for i in range(self.row)] for i in range(self.row): for j in range(self.column): res[i][j]=self._matrix[i][j]+other._matrix[i][j] res[i][j]%=Matrix.mod return Matrix(res) def __sub__(self,other): if (self.row,self.column)!=(other.row,other.column): raise SizeError("sizes of matrixes are different") res=[[0 for j in range(self.column)] for i in range(self.row)] for i in range(self.row): for j in range(self.column): res[i][j]=self._matrix[i][j]-other._matrix[i][j] res[i][j]%=Matrix.mod return Matrix(res) def __mul__(self,other): if type(other)!=int: if self.column!=other.row: raise SizeError("sizes of matrixes are different") res=[[0 for j in range(other.column)] for i in range(self.row)] for i in range(self.row): for j in range(other.column): temp=0 for k in range(self.column): temp+=self._matrix[i][k]*other._matrix[k][j] res[i][j]=temp%Matrix.mod return Matrix(res) else: n=other res=[[(n*self._matrix[i][j])%Matrix.mod for j in range(self.column)] for i in range(self.row)] return Matrix(res) def __pow__(self,m): if self.column!=self.row: raise MatrixPowError("the size of row must be the same as that of column") n=self.row res=Matrix([[int(i==j) for i in range(n)] for j in range(n)]) while m: if m%2==1: res=res*self self=self*self m//=2 return res def __str__(self): res=[] for i in range(self.row): for j in range(self.column): res.append(str(self._matrix[i][j])) res.append(" ") res.append("\n") res=res[:len(res)-1] return "".join(res) class SegmentTree: def __init__(self, init_val, segfunc, ide_ele): n = len(init_val) self.segfunc = segfunc self.ide_ele = ide_ele self.num = 1 << (n - 1).bit_length() self.tree = [ide_ele] * 2 * self.num for i in range(n): self.tree[self.num + i] = init_val[i] for i in range(self.num - 1, 0, -1): self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1]) def update(self, k, x): k += self.num self.tree[k] = x while k > 1: self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1]) k >>= 1 def query(self, l, r): res = self.ide_ele l += self.num r += self.num while l < r: if l & 1: res = self.segfunc(res, self.tree[l]) l += 1 if r & 1: res = self.segfunc(res, self.tree[r - 1]) l >>= 1 r >>= 1 return res def bisect_l(self,l,r,x): l += self.num r += self.num Lmin = -1 Rmin = -1 while l<r: if l & 1: if self.tree[l] <= x and Lmin==-1: Lmin = l l += 1 if r & 1: if self.tree[r-1] <=x: Rmin = r-1 l >>= 1 r >>= 1 if Lmin != -1: pos = Lmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num elif Rmin != -1: pos = Rmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num else: return -1 import sys,random,bisect from collections import deque,defaultdict from heapq import heapify,heappop,heappush from itertools import permutations from math import log,gcd input = lambda :sys.stdin.readline().rstrip() mi = lambda :map(int,input().split()) li = lambda :list(mi()) mod = 998244353 N = 2*10**3 g1 = [1]*(N+1) g2 = [1]*(N+1) inverse = [1]*(N+1) for i in range( 2, N + 1 ): g1[i]=( ( g1[i-1] * i ) % mod ) inverse[i]=( ( -inverse[mod % i] * (mod//i) ) % mod ) g2[i]=( (g2[i-1] * inverse[i]) % mod ) inverse[0]=0 mod = 998244353 n,m = mi() edge = [[] for i in range(n)] Edge = [] for _ in range(m): a,b = mi() edge[a-1].append(b-1) edge[b-1].append(a-1) Edge.append((a-1,b-1)) dist = [[10**17 for j in range(n)] for i in range(n)] for s in range(n): deq = deque([s]) dist[s][s] = 0 while deq: v = deq.popleft() for nv in edge[v]: if dist[s][nv]==10**17: dist[s][nv] = dist[s][v] + 1 deq.append(nv) ans = [[0 for j in range(n)] for i in range(n)] for i in range(n): for j in range(n): tmp = [0 for i in range(n)] tmp_edge = [[] for i in range(n)] deg = [0 for i in range(n)] for k in range(m): a,b = Edge[k] if dist[i][a]==dist[i][b]+1 and dist[j][a]==dist[j][b]+1: tmp[a] += 1 elif dist[i][a]+1==dist[i][b] and dist[j][a]+1==dist[j][b]: tmp[b] += 1 elif dist[i][a]==dist[i][b]+1 and dist[j][a]+1==dist[j][b]: tmp_edge[b].append(a) deg[a] += 1 elif dist[i][a]+1==dist[i][b] and dist[j][a]==dist[j][b]+1: tmp_edge[a].append(b) deg[b] += 1 deq = deque([i]) res = [] while deq: v = deq.popleft() res.append(v) for nv in tmp_edge[v]: deg[nv] -= 1 if not deg[nv]: deq.append(nv) check = [v for v in res if tmp[v]==0] ttt = len(check) dp = [0 for i in range(n)] dp[i] = 1 for k in range(1,ttt): if dist[i][check[k]]==dist[i][check[k-1]]: dp[i] = 0 pos = 0 L = 0 for v in res: if check[pos] == v: for k in range(L,v): dp[k] = 0 L = v pos += 1 else: dp[v] *= inverse[tmp[v]] dp[v] %= mod for nv in tmp_edge[v]: dp[nv] += dp[v] dp[nv] %= mod res = dp[j] for k in range(n): if tmp[k]!=0: res *= tmp[k] res %= mod ans[i][j] = res for i in range(n): print(*ans[i]) ``` No
94,619
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We define a spanning tree of a graph to be a BFS tree rooted at vertex s if and only if for every node t the shortest distance between s and t in the graph is equal to the shortest distance between s and t in the spanning tree. Given a graph, we define f(x,y) to be the number of spanning trees of that graph that are BFS trees rooted at vertices x and y at the same time. You are given an undirected connected graph with n vertices and m edges. Calculate f(i,j) for all i, j by modulo 998 244 353. Input The first line contains two integers n, m (1 ≤ n ≤ 400, 0 ≤ m ≤ 600) — the number of vertices and the number of edges in the graph. The i-th of the next m lines contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i < b_i), representing an edge connecting a_i and b_i. It is guaranteed that all edges are distinct and the graph is connected. Output Print n lines, each consisting of n integers. The integer printed in the row i and the column j should be f(i,j) mod 998 244 353. Examples Input 4 4 1 2 2 3 3 4 1 4 Output 2 1 0 1 1 2 1 0 0 1 2 1 1 0 1 2 Input 8 9 1 2 1 3 1 4 2 7 3 5 3 6 4 8 2 3 3 4 Output 1 0 0 0 0 0 0 0 0 2 0 0 0 0 2 0 0 0 1 0 1 1 0 0 0 0 0 2 0 0 0 2 0 0 1 0 1 1 0 0 0 0 1 0 1 1 0 0 0 2 0 0 0 0 2 0 0 0 0 2 0 0 0 2 Note The following picture describes the first example. <image> The tree with red edges is a BFS tree rooted at both 1 and 2. <image> Similarly, the BFS tree for other adjacent pairs of vertices can be generated in this way. Submitted Solution: ``` def divisors(M): d=[] i=1 while M>=i**2: if M%i==0: d.append(i) if i**2!=M: d.append(M//i) i=i+1 return d def popcount(x): x = x - ((x >> 1) & 0x55555555) x = (x & 0x33333333) + ((x >> 2) & 0x33333333) x = (x + (x >> 4)) & 0x0f0f0f0f x = x + (x >> 8) x = x + (x >> 16) return x & 0x0000007f def eratosthenes(n): res=[0 for i in range(n+1)] prime=set([]) for i in range(2,n+1): if not res[i]: prime.add(i) for j in range(1,n//i+1): res[i*j]=1 return prime def factorization(n): res=[] for p in prime: if n%p==0: while n%p==0: n//=p res.append(p) if n!=1: res.append(n) return res def euler_phi(n): res = n for x in range(2,n+1): if x ** 2 > n: break if n%x==0: res = res//x * (x-1) while n%x==0: n //= x if n!=1: res = res//n * (n-1) return res def ind(b,n): res=0 while n%b==0: res+=1 n//=b return res def isPrimeMR(n): d = n - 1 d = d // (d & -d) L = [2, 3, 5, 7, 11, 13, 17] for a in L: t = d y = pow(a, t, n) if y == 1: continue while y != n - 1: y = (y * y) % n if y == 1 or t == n - 1: return 0 t <<= 1 return 1 def findFactorRho(n): from math import gcd m = 1 << n.bit_length() // 8 for c in range(1, 99): f = lambda x: (x * x + c) % n y, r, q, g = 2, 1, 1, 1 while g == 1: x = y for i in range(r): y = f(y) k = 0 while k < r and g == 1: ys = y for i in range(min(m, r - k)): y = f(y) q = q * abs(x - y) % n g = gcd(q, n) k += m r <<= 1 if g == n: g = 1 while g == 1: ys = f(ys) g = gcd(abs(x - ys), n) if g < n: if isPrimeMR(g): return g elif isPrimeMR(n // g): return n // g return findFactorRho(g) def primeFactor(n): i = 2 ret = {} rhoFlg = 0 while i*i <= n: k = 0 while n % i == 0: n //= i k += 1 if k: ret[i] = k i += 1 + i % 2 if i == 101 and n >= 2 ** 20: while n > 1: if isPrimeMR(n): ret[n], n = 1, 1 else: rhoFlg = 1 j = findFactorRho(n) k = 0 while n % j == 0: n //= j k += 1 ret[j] = k if n > 1: ret[n] = 1 if rhoFlg: ret = {x: ret[x] for x in sorted(ret)} return ret def divisors(n): res = [1] prime = primeFactor(n) for p in prime: newres = [] for d in res: for j in range(prime[p]+1): newres.append(d*p**j) res = newres res.sort() return res def xorfactorial(num):#排他的論理和の階乗 if num==0: return 0 elif num==1: return 1 elif num==2: return 3 elif num==3: return 0 else: x=baseorder(num) return (2**x)*((num-2**x+1)%2)+function(num-2**x) def xorconv(n,X,Y): if n==0: res=[(X[0]*Y[0])%mod] return res x=[X[i]+X[i+2**(n-1)] for i in range(2**(n-1))] y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))] z=[X[i]-X[i+2**(n-1)] for i in range(2**(n-1))] w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))] res1=xorconv(n-1,x,y) res2=xorconv(n-1,z,w) former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))] latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))] former=list(map(lambda x:x%mod,former)) latter=list(map(lambda x:x%mod,latter)) return former+latter def merge_sort(A,B): pos_A,pos_B = 0,0 n,m = len(A),len(B) res = [] while pos_A < n and pos_B < m: a,b = A[pos_A],B[pos_B] if a < b: res.append(a) pos_A += 1 else: res.append(b) pos_B += 1 res += A[pos_A:] res += B[pos_B:] return res class UnionFindVerSize(): def __init__(self, N): self._parent = [n for n in range(0, N)] self._size = [1] * N self.group = N def find_root(self, x): if self._parent[x] == x: return x self._parent[x] = self.find_root(self._parent[x]) stack = [x] while self._parent[stack[-1]]!=stack[-1]: stack.append(self._parent[stack[-1]]) for v in stack: self._parent[v] = stack[-1] return self._parent[x] def unite(self, x, y): gx = self.find_root(x) gy = self.find_root(y) if gx == gy: return self.group -= 1 if self._size[gx] < self._size[gy]: self._parent[gx] = gy self._size[gy] += self._size[gx] else: self._parent[gy] = gx self._size[gx] += self._size[gy] def get_size(self, x): return self._size[self.find_root(x)] def is_same_group(self, x, y): return self.find_root(x) == self.find_root(y) class WeightedUnionFind(): def __init__(self,N): self.parent = [i for i in range(N)] self.size = [1 for i in range(N)] self.val = [0 for i in range(N)] self.flag = True self.edge = [[] for i in range(N)] def dfs(self,v,pv): stack = [(v,pv)] new_parent = self.parent[pv] while stack: v,pv = stack.pop() self.parent[v] = new_parent for nv,w in self.edge[v]: if nv!=pv: self.val[nv] = self.val[v] + w stack.append((nv,v)) def unite(self,x,y,w): if not self.flag: return if self.parent[x]==self.parent[y]: self.flag = (self.val[x] - self.val[y] == w) return if self.size[self.parent[x]]>self.size[self.parent[y]]: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[x] += self.size[y] self.val[y] = self.val[x] - w self.dfs(y,x) else: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[y] += self.size[x] self.val[x] = self.val[y] + w self.dfs(x,y) class Dijkstra(): class Edge(): def __init__(self, _to, _cost): self.to = _to self.cost = _cost def __init__(self, V): self.G = [[] for i in range(V)] self._E = 0 self._V = V @property def E(self): return self._E @property def V(self): return self._V def add_edge(self, _from, _to, _cost): self.G[_from].append(self.Edge(_to, _cost)) self._E += 1 def shortest_path(self, s): import heapq que = [] d = [10**15] * self.V d[s] = 0 heapq.heappush(que, (0, s)) while len(que) != 0: cost, v = heapq.heappop(que) if d[v] < cost: continue for i in range(len(self.G[v])): e = self.G[v][i] if d[e.to] > d[v] + e.cost: d[e.to] = d[v] + e.cost heapq.heappush(que, (d[e.to], e.to)) return d #Z[i]:length of the longest list starting from S[i] which is also a prefix of S #O(|S|) def Z_algorithm(s): N = len(s) Z_alg = [0]*N Z_alg[0] = N i = 1 j = 0 while i < N: while i+j < N and s[j] == s[i+j]: j += 1 Z_alg[i] = j if j == 0: i += 1 continue k = 1 while i+k < N and k + Z_alg[k]<j: Z_alg[i+k] = Z_alg[k] k += 1 i += k j -= k return Z_alg class BIT(): def __init__(self,n): self.BIT=[0]*(n+1) self.num=n def query(self,idx): res_sum = 0 while idx > 0: res_sum += self.BIT[idx] idx -= idx&(-idx) return res_sum #Ai += x O(logN) def update(self,idx,x): while idx <= self.num: self.BIT[idx] += x idx += idx&(-idx) return class dancinglink(): def __init__(self,n,debug=False): self.n = n self.debug = debug self._left = [i-1 for i in range(n)] self._right = [i+1 for i in range(n)] self.exist = [True for i in range(n)] def pop(self,k): if self.debug: assert self.exist[k] L = self._left[k] R = self._right[k] if L!=-1: if R!=self.n: self._right[L],self._left[R] = R,L else: self._right[L] = self.n elif R!=self.n: self._left[R] = -1 self.exist[k] = False def left(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._left[res] if res==-1: break k -= 1 return res def right(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._right[res] if res==self.n: break k -= 1 return res class SparseTable(): def __init__(self,A,merge_func,ide_ele): N=len(A) n=N.bit_length() self.table=[[ide_ele for i in range(n)] for i in range(N)] self.merge_func=merge_func for i in range(N): self.table[i][0]=A[i] for j in range(1,n): for i in range(0,N-2**j+1): f=self.table[i][j-1] s=self.table[i+2**(j-1)][j-1] self.table[i][j]=self.merge_func(f,s) def query(self,s,t): b=t-s+1 m=b.bit_length()-1 return self.merge_func(self.table[s][m],self.table[t-2**m+1][m]) class BinaryTrie: class node: def __init__(self,val): self.left = None self.right = None self.max = val def __init__(self): self.root = self.node(-10**15) def append(self,key,val): pos = self.root for i in range(29,-1,-1): pos.max = max(pos.max,val) if key>>i & 1: if pos.right is None: pos.right = self.node(val) pos = pos.right else: pos = pos.right else: if pos.left is None: pos.left = self.node(val) pos = pos.left else: pos = pos.left pos.max = max(pos.max,val) def search(self,M,xor): res = -10**15 pos = self.root for i in range(29,-1,-1): if pos is None: break if M>>i & 1: if xor>>i & 1: if pos.right: res = max(res,pos.right.max) pos = pos.left else: if pos.left: res = max(res,pos.left.max) pos = pos.right else: if xor>>i & 1: pos = pos.right else: pos = pos.left if pos: res = max(res,pos.max) return res def solveequation(edge,ans,n,m): #edge=[[to,dire,id]...] x=[0]*m used=[False]*n for v in range(n): if used[v]: continue y = dfs(v) if y!=0: return False return x def dfs(v): used[v]=True r=ans[v] for to,dire,id in edge[v]: if used[to]: continue y=dfs(to) if dire==-1: x[id]=y else: x[id]=-y r+=y return r class Matrix(): mod=10**9+7 def set_mod(m): Matrix.mod=m def __init__(self,L): self.row=len(L) self.column=len(L[0]) self._matrix=L for i in range(self.row): for j in range(self.column): self._matrix[i][j]%=Matrix.mod def __getitem__(self,item): if type(item)==int: raise IndexError("you must specific row and column") elif len(item)!=2: raise IndexError("you must specific row and column") i,j=item return self._matrix[i][j] def __setitem__(self,item,val): if type(item)==int: raise IndexError("you must specific row and column") elif len(item)!=2: raise IndexError("you must specific row and column") i,j=item self._matrix[i][j]=val def __add__(self,other): if (self.row,self.column)!=(other.row,other.column): raise SizeError("sizes of matrixes are different") res=[[0 for j in range(self.column)] for i in range(self.row)] for i in range(self.row): for j in range(self.column): res[i][j]=self._matrix[i][j]+other._matrix[i][j] res[i][j]%=Matrix.mod return Matrix(res) def __sub__(self,other): if (self.row,self.column)!=(other.row,other.column): raise SizeError("sizes of matrixes are different") res=[[0 for j in range(self.column)] for i in range(self.row)] for i in range(self.row): for j in range(self.column): res[i][j]=self._matrix[i][j]-other._matrix[i][j] res[i][j]%=Matrix.mod return Matrix(res) def __mul__(self,other): if type(other)!=int: if self.column!=other.row: raise SizeError("sizes of matrixes are different") res=[[0 for j in range(other.column)] for i in range(self.row)] for i in range(self.row): for j in range(other.column): temp=0 for k in range(self.column): temp+=self._matrix[i][k]*other._matrix[k][j] res[i][j]=temp%Matrix.mod return Matrix(res) else: n=other res=[[(n*self._matrix[i][j])%Matrix.mod for j in range(self.column)] for i in range(self.row)] return Matrix(res) def __pow__(self,m): if self.column!=self.row: raise MatrixPowError("the size of row must be the same as that of column") n=self.row res=Matrix([[int(i==j) for i in range(n)] for j in range(n)]) while m: if m%2==1: res=res*self self=self*self m//=2 return res def __str__(self): res=[] for i in range(self.row): for j in range(self.column): res.append(str(self._matrix[i][j])) res.append(" ") res.append("\n") res=res[:len(res)-1] return "".join(res) class SegmentTree: def __init__(self, init_val, segfunc, ide_ele): n = len(init_val) self.segfunc = segfunc self.ide_ele = ide_ele self.num = 1 << (n - 1).bit_length() self.tree = [ide_ele] * 2 * self.num for i in range(n): self.tree[self.num + i] = init_val[i] for i in range(self.num - 1, 0, -1): self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1]) def update(self, k, x): k += self.num self.tree[k] = x while k > 1: self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1]) k >>= 1 def query(self, l, r): res = self.ide_ele l += self.num r += self.num while l < r: if l & 1: res = self.segfunc(res, self.tree[l]) l += 1 if r & 1: res = self.segfunc(res, self.tree[r - 1]) l >>= 1 r >>= 1 return res def bisect_l(self,l,r,x): l += self.num r += self.num Lmin = -1 Rmin = -1 while l<r: if l & 1: if self.tree[l] <= x and Lmin==-1: Lmin = l l += 1 if r & 1: if self.tree[r-1] <=x: Rmin = r-1 l >>= 1 r >>= 1 if Lmin != -1: pos = Lmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num elif Rmin != -1: pos = Rmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num else: return -1 import sys,random,bisect from collections import deque,defaultdict from heapq import heapify,heappop,heappush from itertools import permutations from math import log,gcd input = lambda :sys.stdin.buffer.readline() mi = lambda :map(int,input().split()) li = lambda :list(mi()) mod = 998244353 N = 2*10**3 g1 = [1]*(N+1) g2 = [1]*(N+1) inverse = [1]*(N+1) for i in range( 2, N + 1 ): g1[i]=( ( g1[i-1] * i ) % mod ) inverse[i]=( ( -inverse[mod % i] * (mod//i) ) % mod ) g2[i]=( (g2[i-1] * inverse[i]) % mod ) inverse[0]=0 mod = 998244353 n,m = mi() edge = [[] for i in range(n)] Edge = [] for _ in range(m): a,b = mi() edge[a-1].append(b-1) edge[b-1].append(a-1) Edge.append((a-1,b-1)) dist = [[10**17 for j in range(n)] for i in range(n)] for s in range(n): deq = deque([s]) dist[s][s] = 0 while deq: v = deq.popleft() for nv in edge[v]: if dist[s][nv]==10**17: dist[s][nv] = dist[s][v] + 1 deq.append(nv) node_dist = [[j for j in range(n)] for i in range(n)] for i in range(n): node_dist[i].sort(key=lambda v:dist[i][v]) ans = [[0 for j in range(n)] for i in range(n)] for i in range(n): di = dist[i] for j in range(i,n): dj = dist[j] tmp = [0 for i in range(n)] tmp_edge = [[] for i in range(n)] deg = [0 for i in range(n)] for k in range(m): a,b = Edge[k] if di[a]==di[b]+1: if dj[a]==dj[b]+1: tmp[a] += 1 elif dj[a]+1==dj[b]: tmp_edge[b].append(a) deg[a] += 1 elif di[a]+1==di[b]: if dj[a]+1==dj[b]: tmp[b] += 1 elif dj[a]==dj[b]+1: tmp_edge[a].append(b) deg[b] += 1 deq = deque([i]) res = [] while deq: v = deq.popleft() res.append(v) for nv in tmp_edge[v]: deg[nv] -= 1 if not deg[nv]: deq.append(nv) res = [v for v in node_dist[i] if not tmp[v]] ttt = len(res) dp = [0 for i in range(n)] dp[i] = 1 for k in range(1,ttt): if di[res[k]]==di[res[k-1]]: dp[i] = 0 for v in res: if tmp[v]!=0: dp[v] *= inverse[tmp[v]] dp[v] %= mod for nv in tmp_edge[v]: dp[nv] += dp[v] dp[nv] %= mod res = dp[j] for k in range(n): if tmp[k]!=0: res *= tmp[k] res %= mod ans[i][j] = ans[j][i] = res % mod for i in range(n): print(*ans[i]) ``` No
94,620
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We define a spanning tree of a graph to be a BFS tree rooted at vertex s if and only if for every node t the shortest distance between s and t in the graph is equal to the shortest distance between s and t in the spanning tree. Given a graph, we define f(x,y) to be the number of spanning trees of that graph that are BFS trees rooted at vertices x and y at the same time. You are given an undirected connected graph with n vertices and m edges. Calculate f(i,j) for all i, j by modulo 998 244 353. Input The first line contains two integers n, m (1 ≤ n ≤ 400, 0 ≤ m ≤ 600) — the number of vertices and the number of edges in the graph. The i-th of the next m lines contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i < b_i), representing an edge connecting a_i and b_i. It is guaranteed that all edges are distinct and the graph is connected. Output Print n lines, each consisting of n integers. The integer printed in the row i and the column j should be f(i,j) mod 998 244 353. Examples Input 4 4 1 2 2 3 3 4 1 4 Output 2 1 0 1 1 2 1 0 0 1 2 1 1 0 1 2 Input 8 9 1 2 1 3 1 4 2 7 3 5 3 6 4 8 2 3 3 4 Output 1 0 0 0 0 0 0 0 0 2 0 0 0 0 2 0 0 0 1 0 1 1 0 0 0 0 0 2 0 0 0 2 0 0 1 0 1 1 0 0 0 0 1 0 1 1 0 0 0 2 0 0 0 0 2 0 0 0 0 2 0 0 0 2 Note The following picture describes the first example. <image> The tree with red edges is a BFS tree rooted at both 1 and 2. <image> Similarly, the BFS tree for other adjacent pairs of vertices can be generated in this way. Submitted Solution: ``` import sys from sys import stdin from collections import deque tt = 1 for loop in range(tt): n,m = map(int,stdin.readline().split()) lis = [ [] for i in range(n) ] for i in range(m): a,b = map(int,stdin.readline().split()) a -= 1 b -= 1 lis[a].append(b) lis[b].append(a) able = [True] * n ans = [[0] * n for i in range(n)] mod = 998244353 for st in range(n): if able[st] and len(lis[st]) == 1: nums = [0] * n d = [float("inf")] * n d[st] = 0 q = deque([st]) while q: v = q.popleft() for nex in lis[v]: if d[nex] >= d[v] + 1: nums[nex] += 1 if d[nex] > d[v] + 1: d[nex] = d[v] + 1 q.append(nex) ed = 1 for i in range(n): if nums[i] > 1: ed *= nums[i] ed %= mod #print (nums,ed) for i in range(n): for j in range(n): if nums[i] <= 1 and nums[j] <= 1: ans[i][j] = ed ans[j][i] = ed for i in range(n): if nums[i] <= 1: able[i] = False for ii in ans: print (*ii) ``` No
94,621
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We define a spanning tree of a graph to be a BFS tree rooted at vertex s if and only if for every node t the shortest distance between s and t in the graph is equal to the shortest distance between s and t in the spanning tree. Given a graph, we define f(x,y) to be the number of spanning trees of that graph that are BFS trees rooted at vertices x and y at the same time. You are given an undirected connected graph with n vertices and m edges. Calculate f(i,j) for all i, j by modulo 998 244 353. Input The first line contains two integers n, m (1 ≤ n ≤ 400, 0 ≤ m ≤ 600) — the number of vertices and the number of edges in the graph. The i-th of the next m lines contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i < b_i), representing an edge connecting a_i and b_i. It is guaranteed that all edges are distinct and the graph is connected. Output Print n lines, each consisting of n integers. The integer printed in the row i and the column j should be f(i,j) mod 998 244 353. Examples Input 4 4 1 2 2 3 3 4 1 4 Output 2 1 0 1 1 2 1 0 0 1 2 1 1 0 1 2 Input 8 9 1 2 1 3 1 4 2 7 3 5 3 6 4 8 2 3 3 4 Output 1 0 0 0 0 0 0 0 0 2 0 0 0 0 2 0 0 0 1 0 1 1 0 0 0 0 0 2 0 0 0 2 0 0 1 0 1 1 0 0 0 0 1 0 1 1 0 0 0 2 0 0 0 0 2 0 0 0 0 2 0 0 0 2 Note The following picture describes the first example. <image> The tree with red edges is a BFS tree rooted at both 1 and 2. <image> Similarly, the BFS tree for other adjacent pairs of vertices can be generated in this way. Submitted Solution: ``` #!/usr/bin/env python import os import sys from io import BytesIO, IOBase def main(): n,m = map(int,input().split()) MOD = 998244353 adjList = [] dist = [] ans = [] for _ in range(n): adjList.append([]) for _ in range(m): a,b = map(int,input().split()) adjList[a - 1].append(b - 1) adjList[b - 1].append(a - 1) for i in range(n): curDist = [-1] * n curDist[i] = 0 bfsQueue = [i] bfsIndex = 0 while len(bfsQueue) > bfsIndex: c = bfsQueue[bfsIndex] bfsIndex += 1 for elem in adjList[c]: if curDist[elem] == -1: curDist[elem] = curDist[c] + 1 bfsQueue.append(elem) dist.append(curDist) for i in range(n): ans.append([]) for j in range(n): # Find shortest path between i and j isCovered = [False] * n isCovered[i] = True isCovered[j] = True jCpy = j flag = True while jCpy != i: cnt = 0 cntIndex = -1 for elem in adjList[jCpy]: if dist[i][elem] == dist[i][jCpy] - 1: cnt += 1 cntIndex = elem if cnt >= 2: flag = False break else: isCovered[cntIndex] = True jCpy = cntIndex if not flag: ans[i].append(0) else: curAns = 1 for k in range(n): if isCovered[k]: continue cnt = 0 for elem in adjList[k]: if dist[i][elem] == dist[i][k] - 1 and dist[j][elem] == dist[j][k] - 1: cnt += 1 curAns = (curAns * cnt) % MOD if not curAns: break ans[i].append(curAns) for elem in ans: print(" ".join(map(str,elem))) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main() ``` No
94,622
Provide tags and a correct Python 3 solution for this coding contest problem. You have r red and b blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet: * has at least one red bean (or the number of red beans r_i ≥ 1); * has at least one blue bean (or the number of blue beans b_i ≥ 1); * the number of red and blue beans should differ in no more than d (or |r_i - b_i| ≤ d) Can you distribute all beans? Input The first line contains the single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers r, b, and d (1 ≤ r, b ≤ 10^9; 0 ≤ d ≤ 10^9) — the number of red and blue beans and the maximum absolute difference in each packet. Output For each test case, if you can distribute all beans, print YES. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer). Example Input 4 1 1 0 2 7 3 6 1 4 5 4 0 Output YES YES NO NO Note In the first test case, you can form one packet with 1 red and 1 blue bean. The absolute difference |1 - 1| = 0 ≤ d. In the second test case, you can form two packets: 1 red and 4 blue beans in the first packet and 1 red and 3 blue beans in the second one. In the third test case, since b = 1, you can form only one packet with 6 red and 1 blue beans. The absolute difference |6 - 1| = 5 > d. In the fourth test case, since d = 0 so each packet should contain the same number of red and blue beans, but r ≠ b. Tags: math Correct Solution: ``` # cook your dish here #jai_shree_raam #jai_bajrang_bali #this function is taken from GeekForGeeks import math from collections import defaultdict as dfc from collections import Counter from math import gcd def SOE(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 l=[] for p in range(2, n+1): if prime[p]: l+=[p] return l def i1(): return int(input())#single integer def i2(): return map(int,input().split())#two integers def i3(): return list(map(int,input().split()))#list of integers def i4(): return input()#string input def i5(): return list(str(i1()))#list of characters of a string def kbit(a, k): if ((a>>(k-1)) and 1): return True else: return False for i in range(i1()): r,b,d=i2() k1=abs(r-b) if(k1==0): print("YES") else: k2=min(r,b) c=k1//k2 if(k1%k2!=0): c=c+1 if(c>d): print("NO") else: print("YES") ```
94,623
Provide tags and a correct Python 3 solution for this coding contest problem. You have r red and b blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet: * has at least one red bean (or the number of red beans r_i ≥ 1); * has at least one blue bean (or the number of blue beans b_i ≥ 1); * the number of red and blue beans should differ in no more than d (or |r_i - b_i| ≤ d) Can you distribute all beans? Input The first line contains the single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers r, b, and d (1 ≤ r, b ≤ 10^9; 0 ≤ d ≤ 10^9) — the number of red and blue beans and the maximum absolute difference in each packet. Output For each test case, if you can distribute all beans, print YES. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer). Example Input 4 1 1 0 2 7 3 6 1 4 5 4 0 Output YES YES NO NO Note In the first test case, you can form one packet with 1 red and 1 blue bean. The absolute difference |1 - 1| = 0 ≤ d. In the second test case, you can form two packets: 1 red and 4 blue beans in the first packet and 1 red and 3 blue beans in the second one. In the third test case, since b = 1, you can form only one packet with 6 red and 1 blue beans. The absolute difference |6 - 1| = 5 > d. In the fourth test case, since d = 0 so each packet should contain the same number of red and blue beans, but r ≠ b. Tags: math Correct Solution: ``` for _ in range(int(input())): a, b, d = map(int, input().split()) x, diff = min(a, b), abs(a - b) if diff / x > d: print("NO") else: print("YES") ```
94,624
Provide tags and a correct Python 3 solution for this coding contest problem. You have r red and b blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet: * has at least one red bean (or the number of red beans r_i ≥ 1); * has at least one blue bean (or the number of blue beans b_i ≥ 1); * the number of red and blue beans should differ in no more than d (or |r_i - b_i| ≤ d) Can you distribute all beans? Input The first line contains the single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers r, b, and d (1 ≤ r, b ≤ 10^9; 0 ≤ d ≤ 10^9) — the number of red and blue beans and the maximum absolute difference in each packet. Output For each test case, if you can distribute all beans, print YES. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer). Example Input 4 1 1 0 2 7 3 6 1 4 5 4 0 Output YES YES NO NO Note In the first test case, you can form one packet with 1 red and 1 blue bean. The absolute difference |1 - 1| = 0 ≤ d. In the second test case, you can form two packets: 1 red and 4 blue beans in the first packet and 1 red and 3 blue beans in the second one. In the third test case, since b = 1, you can form only one packet with 6 red and 1 blue beans. The absolute difference |6 - 1| = 5 > d. In the fourth test case, since d = 0 so each packet should contain the same number of red and blue beans, but r ≠ b. Tags: math Correct Solution: ``` from sys import stdin, stdout for testcase in range(int(stdin.readline())): r, b, d = list(map(int, stdin.readline().split())) if d==0: print(["NO", "YES"][r==b]) else: print(["NO", "YES"][ abs(r-b)/d <= min(r, b) ]) ```
94,625
Provide tags and a correct Python 3 solution for this coding contest problem. You have r red and b blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet: * has at least one red bean (or the number of red beans r_i ≥ 1); * has at least one blue bean (or the number of blue beans b_i ≥ 1); * the number of red and blue beans should differ in no more than d (or |r_i - b_i| ≤ d) Can you distribute all beans? Input The first line contains the single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers r, b, and d (1 ≤ r, b ≤ 10^9; 0 ≤ d ≤ 10^9) — the number of red and blue beans and the maximum absolute difference in each packet. Output For each test case, if you can distribute all beans, print YES. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer). Example Input 4 1 1 0 2 7 3 6 1 4 5 4 0 Output YES YES NO NO Note In the first test case, you can form one packet with 1 red and 1 blue bean. The absolute difference |1 - 1| = 0 ≤ d. In the second test case, you can form two packets: 1 red and 4 blue beans in the first packet and 1 red and 3 blue beans in the second one. In the third test case, since b = 1, you can form only one packet with 6 red and 1 blue beans. The absolute difference |6 - 1| = 5 > d. In the fourth test case, since d = 0 so each packet should contain the same number of red and blue beans, but r ≠ b. Tags: math Correct Solution: ``` for _ in range(int(input())): a,b,c=map(int, input().split()) if b>a: a,b=b,a if b*(c+1)>=a: print("YES") else: print("NO") ```
94,626
Provide tags and a correct Python 3 solution for this coding contest problem. You have r red and b blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet: * has at least one red bean (or the number of red beans r_i ≥ 1); * has at least one blue bean (or the number of blue beans b_i ≥ 1); * the number of red and blue beans should differ in no more than d (or |r_i - b_i| ≤ d) Can you distribute all beans? Input The first line contains the single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers r, b, and d (1 ≤ r, b ≤ 10^9; 0 ≤ d ≤ 10^9) — the number of red and blue beans and the maximum absolute difference in each packet. Output For each test case, if you can distribute all beans, print YES. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer). Example Input 4 1 1 0 2 7 3 6 1 4 5 4 0 Output YES YES NO NO Note In the first test case, you can form one packet with 1 red and 1 blue bean. The absolute difference |1 - 1| = 0 ≤ d. In the second test case, you can form two packets: 1 red and 4 blue beans in the first packet and 1 red and 3 blue beans in the second one. In the third test case, since b = 1, you can form only one packet with 6 red and 1 blue beans. The absolute difference |6 - 1| = 5 > d. In the fourth test case, since d = 0 so each packet should contain the same number of red and blue beans, but r ≠ b. Tags: math Correct Solution: ``` t=int(input()) for _ in range(t): r,b,d=map(int,input().split()) if r==b: print("YES") elif r<b: if b<=(1+d)*r: print("YES") else: print("NO") elif r>b: if r<=(1+d)*b: print("YES") else: print("NO") else: print("NO") ```
94,627
Provide tags and a correct Python 3 solution for this coding contest problem. You have r red and b blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet: * has at least one red bean (or the number of red beans r_i ≥ 1); * has at least one blue bean (or the number of blue beans b_i ≥ 1); * the number of red and blue beans should differ in no more than d (or |r_i - b_i| ≤ d) Can you distribute all beans? Input The first line contains the single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers r, b, and d (1 ≤ r, b ≤ 10^9; 0 ≤ d ≤ 10^9) — the number of red and blue beans and the maximum absolute difference in each packet. Output For each test case, if you can distribute all beans, print YES. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer). Example Input 4 1 1 0 2 7 3 6 1 4 5 4 0 Output YES YES NO NO Note In the first test case, you can form one packet with 1 red and 1 blue bean. The absolute difference |1 - 1| = 0 ≤ d. In the second test case, you can form two packets: 1 red and 4 blue beans in the first packet and 1 red and 3 blue beans in the second one. In the third test case, since b = 1, you can form only one packet with 6 red and 1 blue beans. The absolute difference |6 - 1| = 5 > d. In the fourth test case, since d = 0 so each packet should contain the same number of red and blue beans, but r ≠ b. Tags: math Correct Solution: ``` for _ in range(int(input())): r, b, d = map(int, input().split()) if r > b: r, b = b, r if b <= r * (d+1) and b and r: print('YES') else: print('NO') ```
94,628
Provide tags and a correct Python 3 solution for this coding contest problem. You have r red and b blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet: * has at least one red bean (or the number of red beans r_i ≥ 1); * has at least one blue bean (or the number of blue beans b_i ≥ 1); * the number of red and blue beans should differ in no more than d (or |r_i - b_i| ≤ d) Can you distribute all beans? Input The first line contains the single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers r, b, and d (1 ≤ r, b ≤ 10^9; 0 ≤ d ≤ 10^9) — the number of red and blue beans and the maximum absolute difference in each packet. Output For each test case, if you can distribute all beans, print YES. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer). Example Input 4 1 1 0 2 7 3 6 1 4 5 4 0 Output YES YES NO NO Note In the first test case, you can form one packet with 1 red and 1 blue bean. The absolute difference |1 - 1| = 0 ≤ d. In the second test case, you can form two packets: 1 red and 4 blue beans in the first packet and 1 red and 3 blue beans in the second one. In the third test case, since b = 1, you can form only one packet with 6 red and 1 blue beans. The absolute difference |6 - 1| = 5 > d. In the fourth test case, since d = 0 so each packet should contain the same number of red and blue beans, but r ≠ b. Tags: math Correct Solution: ``` t = int(input()) for _ in range(t): r,b,d = [int(i) for i in input().strip().split()] check = True if d==0: if r!=b: print("NO") check = False else: max_packets = min(r,b) if (r+b-max_packets)>(d+1)*max_packets: print("NO") check = False if check: print("YES") ```
94,629
Provide tags and a correct Python 3 solution for this coding contest problem. You have r red and b blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet: * has at least one red bean (or the number of red beans r_i ≥ 1); * has at least one blue bean (or the number of blue beans b_i ≥ 1); * the number of red and blue beans should differ in no more than d (or |r_i - b_i| ≤ d) Can you distribute all beans? Input The first line contains the single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers r, b, and d (1 ≤ r, b ≤ 10^9; 0 ≤ d ≤ 10^9) — the number of red and blue beans and the maximum absolute difference in each packet. Output For each test case, if you can distribute all beans, print YES. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer). Example Input 4 1 1 0 2 7 3 6 1 4 5 4 0 Output YES YES NO NO Note In the first test case, you can form one packet with 1 red and 1 blue bean. The absolute difference |1 - 1| = 0 ≤ d. In the second test case, you can form two packets: 1 red and 4 blue beans in the first packet and 1 red and 3 blue beans in the second one. In the third test case, since b = 1, you can form only one packet with 6 red and 1 blue beans. The absolute difference |6 - 1| = 5 > d. In the fourth test case, since d = 0 so each packet should contain the same number of red and blue beans, but r ≠ b. Tags: math Correct Solution: ``` t = int(input()) for _ in range(t): r, b, d = map(int, input().split()) x = min(r, b) * d print('YES' if abs(r - b) <= x else 'NO') ```
94,630
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have r red and b blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet: * has at least one red bean (or the number of red beans r_i ≥ 1); * has at least one blue bean (or the number of blue beans b_i ≥ 1); * the number of red and blue beans should differ in no more than d (or |r_i - b_i| ≤ d) Can you distribute all beans? Input The first line contains the single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers r, b, and d (1 ≤ r, b ≤ 10^9; 0 ≤ d ≤ 10^9) — the number of red and blue beans and the maximum absolute difference in each packet. Output For each test case, if you can distribute all beans, print YES. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer). Example Input 4 1 1 0 2 7 3 6 1 4 5 4 0 Output YES YES NO NO Note In the first test case, you can form one packet with 1 red and 1 blue bean. The absolute difference |1 - 1| = 0 ≤ d. In the second test case, you can form two packets: 1 red and 4 blue beans in the first packet and 1 red and 3 blue beans in the second one. In the third test case, since b = 1, you can form only one packet with 6 red and 1 blue beans. The absolute difference |6 - 1| = 5 > d. In the fourth test case, since d = 0 so each packet should contain the same number of red and blue beans, but r ≠ b. Submitted Solution: ``` import math from sys import stdin,stdout from operator import itemgetter t=int(input()) for i in range(t): n,m,d=map(int,stdin.readline().split()) flag=0 if(d==0): if(n!=m): flag=1 else: mi=min(n,m) k=mi*(d+1) if(max(m,n)>k): flag=1 if(flag==1): print("NO") else: print("YES") ``` Yes
94,631
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have r red and b blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet: * has at least one red bean (or the number of red beans r_i ≥ 1); * has at least one blue bean (or the number of blue beans b_i ≥ 1); * the number of red and blue beans should differ in no more than d (or |r_i - b_i| ≤ d) Can you distribute all beans? Input The first line contains the single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers r, b, and d (1 ≤ r, b ≤ 10^9; 0 ≤ d ≤ 10^9) — the number of red and blue beans and the maximum absolute difference in each packet. Output For each test case, if you can distribute all beans, print YES. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer). Example Input 4 1 1 0 2 7 3 6 1 4 5 4 0 Output YES YES NO NO Note In the first test case, you can form one packet with 1 red and 1 blue bean. The absolute difference |1 - 1| = 0 ≤ d. In the second test case, you can form two packets: 1 red and 4 blue beans in the first packet and 1 red and 3 blue beans in the second one. In the third test case, since b = 1, you can form only one packet with 6 red and 1 blue beans. The absolute difference |6 - 1| = 5 > d. In the fourth test case, since d = 0 so each packet should contain the same number of red and blue beans, but r ≠ b. Submitted Solution: ``` import sys,os,io from sys import stdin,stdout from math import log, gcd, ceil from collections import defaultdict, deque, Counter from heapq import heappush, heappop from bisect import bisect_left , bisect_right import math # input = stdin.readline alphabets = list('abcdefghijklmnopqrstuvwxyz') def isPrime(x): for i in range(2,x): if i*i>x: break if (x%i==0): return False return True def ncr(n, r, p): num = den = 1 for i in range(r): num = (num * (n - i)) % p den = (den * (i + 1)) % p return (num * pow(den, p - 2, p)) % p def primeFactors(n): l = [] while n % 2 == 0: l.append(2) n = n / 2 for i in range(3,int(math.sqrt(n))+1,2): while n % i== 0: l.append(int(i)) n = n / i if n > 2: l.append(n) return list(set(l)) 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 # y = y/2 x = (x * x) % p return res def SieveOfEratosthenes(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 def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def si(): return input() def prefix_sum(arr): r = [0] * (len(arr)+1) for i, el in enumerate(arr): r[i+1] = r[i] + el return r def divideCeil(n,x): if (n%x==0): return n//x return n//x+1 def ii(): return int(input()) def li(): return list(map(int,input().split())) def ws(s): sys.stdout.write(s + '\n') def wi(n): sys.stdout.write(str(n) + '\n') def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n') def power_set(L): cardinality=len(L) n=2 ** cardinality powerset = [] for i in range(n): a=bin(i)[2:] subset=[] for j in range(len(a)): if a[-j-1]=='1': subset.append(L[j]) powerset.append(subset) powerset_orderred=[] for k in range(cardinality+1): for w in powerset: if len(w)==k: powerset_orderred.append(w) return powerset_orderred def fastPlrintNextLines(a): # 12 # 3 # 1 #like this #a is list of strings print('\n'.join(map(str,a))) def sortByFirstAndSecond(A): A = sorted(A,key = lambda x:x[0]) A = sorted(A,key = lambda x:x[1]) return list(A) #__________________________TEMPLATE__________________OVER_______________________________________________________ if(os.path.exists('input.txt')): sys.stdin = open("input.txt","r") ; sys.stdout = open("output.txt","w") # else: # input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline for _ in range(int(input())): a,b,c = map(int,input().split()) if(a<b): if(b> a*(c+1)): print("NO") else: print("YES") else: if(a> b*(c+1)): print("NO") else: print("YES") # li = list(map(int,input().split())) ``` Yes
94,632
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have r red and b blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet: * has at least one red bean (or the number of red beans r_i ≥ 1); * has at least one blue bean (or the number of blue beans b_i ≥ 1); * the number of red and blue beans should differ in no more than d (or |r_i - b_i| ≤ d) Can you distribute all beans? Input The first line contains the single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers r, b, and d (1 ≤ r, b ≤ 10^9; 0 ≤ d ≤ 10^9) — the number of red and blue beans and the maximum absolute difference in each packet. Output For each test case, if you can distribute all beans, print YES. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer). Example Input 4 1 1 0 2 7 3 6 1 4 5 4 0 Output YES YES NO NO Note In the first test case, you can form one packet with 1 red and 1 blue bean. The absolute difference |1 - 1| = 0 ≤ d. In the second test case, you can form two packets: 1 red and 4 blue beans in the first packet and 1 red and 3 blue beans in the second one. In the third test case, since b = 1, you can form only one packet with 6 red and 1 blue beans. The absolute difference |6 - 1| = 5 > d. In the fourth test case, since d = 0 so each packet should contain the same number of red and blue beans, but r ≠ b. Submitted Solution: ``` for _ in range(int(input())): r,b,d=map(int,input().split()) z,y=min(r,b),max(r,b) diff=y-z zz=diff//z+(diff%z!=0) if d<zz: print("NO") else: print("YES") ``` Yes
94,633
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have r red and b blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet: * has at least one red bean (or the number of red beans r_i ≥ 1); * has at least one blue bean (or the number of blue beans b_i ≥ 1); * the number of red and blue beans should differ in no more than d (or |r_i - b_i| ≤ d) Can you distribute all beans? Input The first line contains the single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers r, b, and d (1 ≤ r, b ≤ 10^9; 0 ≤ d ≤ 10^9) — the number of red and blue beans and the maximum absolute difference in each packet. Output For each test case, if you can distribute all beans, print YES. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer). Example Input 4 1 1 0 2 7 3 6 1 4 5 4 0 Output YES YES NO NO Note In the first test case, you can form one packet with 1 red and 1 blue bean. The absolute difference |1 - 1| = 0 ≤ d. In the second test case, you can form two packets: 1 red and 4 blue beans in the first packet and 1 red and 3 blue beans in the second one. In the third test case, since b = 1, you can form only one packet with 6 red and 1 blue beans. The absolute difference |6 - 1| = 5 > d. In the fourth test case, since d = 0 so each packet should contain the same number of red and blue beans, but r ≠ b. Submitted Solution: ``` import math def getint(): return [int(i) for i in input().split()] def getstr(): return [str(i) for i in input().split()] #-------------------------------------------------------------------------- def solve(): a,b,k=getint() a_=min(a,b)*(1+k) b_=max(a,b) if a_>=b_: print("YES") else: print("NO") #-------------------------------------------------------------------------- for _ in range(int(input())): solve() ``` Yes
94,634
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have r red and b blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet: * has at least one red bean (or the number of red beans r_i ≥ 1); * has at least one blue bean (or the number of blue beans b_i ≥ 1); * the number of red and blue beans should differ in no more than d (or |r_i - b_i| ≤ d) Can you distribute all beans? Input The first line contains the single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers r, b, and d (1 ≤ r, b ≤ 10^9; 0 ≤ d ≤ 10^9) — the number of red and blue beans and the maximum absolute difference in each packet. Output For each test case, if you can distribute all beans, print YES. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer). Example Input 4 1 1 0 2 7 3 6 1 4 5 4 0 Output YES YES NO NO Note In the first test case, you can form one packet with 1 red and 1 blue bean. The absolute difference |1 - 1| = 0 ≤ d. In the second test case, you can form two packets: 1 red and 4 blue beans in the first packet and 1 red and 3 blue beans in the second one. In the third test case, since b = 1, you can form only one packet with 6 red and 1 blue beans. The absolute difference |6 - 1| = 5 > d. In the fourth test case, since d = 0 so each packet should contain the same number of red and blue beans, but r ≠ b. Submitted Solution: ``` from math import ceil for tc in range(int(input())): r,b,d = map(int,input().split()) mini = min(r,b) maxi = max(r,b) ans = ceil(maxi/mini) if abs(ans-mini) <= d: print('YES') else: print('NO') ``` No
94,635
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have r red and b blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet: * has at least one red bean (or the number of red beans r_i ≥ 1); * has at least one blue bean (or the number of blue beans b_i ≥ 1); * the number of red and blue beans should differ in no more than d (or |r_i - b_i| ≤ d) Can you distribute all beans? Input The first line contains the single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers r, b, and d (1 ≤ r, b ≤ 10^9; 0 ≤ d ≤ 10^9) — the number of red and blue beans and the maximum absolute difference in each packet. Output For each test case, if you can distribute all beans, print YES. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer). Example Input 4 1 1 0 2 7 3 6 1 4 5 4 0 Output YES YES NO NO Note In the first test case, you can form one packet with 1 red and 1 blue bean. The absolute difference |1 - 1| = 0 ≤ d. In the second test case, you can form two packets: 1 red and 4 blue beans in the first packet and 1 red and 3 blue beans in the second one. In the third test case, since b = 1, you can form only one packet with 6 red and 1 blue beans. The absolute difference |6 - 1| = 5 > d. In the fourth test case, since d = 0 so each packet should contain the same number of red and blue beans, but r ≠ b. Submitted Solution: ``` for _ in range(int(input())): r,b,d=map(int,input().split()) if d==0: if r!=b: print('No') else: print('Yes') elif min(r,b)==1: if abs(r-b)<=d: print('Yes') else: print("No") else: print("Yes") ``` No
94,636
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have r red and b blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet: * has at least one red bean (or the number of red beans r_i ≥ 1); * has at least one blue bean (or the number of blue beans b_i ≥ 1); * the number of red and blue beans should differ in no more than d (or |r_i - b_i| ≤ d) Can you distribute all beans? Input The first line contains the single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers r, b, and d (1 ≤ r, b ≤ 10^9; 0 ≤ d ≤ 10^9) — the number of red and blue beans and the maximum absolute difference in each packet. Output For each test case, if you can distribute all beans, print YES. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer). Example Input 4 1 1 0 2 7 3 6 1 4 5 4 0 Output YES YES NO NO Note In the first test case, you can form one packet with 1 red and 1 blue bean. The absolute difference |1 - 1| = 0 ≤ d. In the second test case, you can form two packets: 1 red and 4 blue beans in the first packet and 1 red and 3 blue beans in the second one. In the third test case, since b = 1, you can form only one packet with 6 red and 1 blue beans. The absolute difference |6 - 1| = 5 > d. In the fourth test case, since d = 0 so each packet should contain the same number of red and blue beans, but r ≠ b. Submitted Solution: ``` try: n=int(input()) for i in range(n): r,b,d=map(int,input().split()) if(r==b and d==0): print("YES") else: print("NO") if(r>=1): if(b>=1): if((r-b)<=d): print("YES") else: print("NO") else: print("NO") else: print("NO") except: pass ``` No
94,637
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have r red and b blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet: * has at least one red bean (or the number of red beans r_i ≥ 1); * has at least one blue bean (or the number of blue beans b_i ≥ 1); * the number of red and blue beans should differ in no more than d (or |r_i - b_i| ≤ d) Can you distribute all beans? Input The first line contains the single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first and only line of each test case contains three integers r, b, and d (1 ≤ r, b ≤ 10^9; 0 ≤ d ≤ 10^9) — the number of red and blue beans and the maximum absolute difference in each packet. Output For each test case, if you can distribute all beans, print YES. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer). Example Input 4 1 1 0 2 7 3 6 1 4 5 4 0 Output YES YES NO NO Note In the first test case, you can form one packet with 1 red and 1 blue bean. The absolute difference |1 - 1| = 0 ≤ d. In the second test case, you can form two packets: 1 red and 4 blue beans in the first packet and 1 red and 3 blue beans in the second one. In the third test case, since b = 1, you can form only one packet with 6 red and 1 blue beans. The absolute difference |6 - 1| = 5 > d. In the fourth test case, since d = 0 so each packet should contain the same number of red and blue beans, but r ≠ b. Submitted Solution: ``` t=int(input()) while(t>0): r,b,d=[int(x) for x in input().split()] if d==0: if r==b: print("YES") else: print("NO") elif r<=(b+d): print("YES") else: print("NO") t=t-1 ``` No
94,638
Provide tags and a correct Python 3 solution for this coding contest problem. AquaMoon and Cirno are playing an interesting game with arrays. Cirno has prepared two arrays a and b, both consist of n non-negative integers. AquaMoon can perform the following operation an arbitrary number of times (possibly zero): * She chooses two indices i and j (1 ≤ i, j ≤ n), then decreases the i-th element of array a by 1, and increases the j-th element of array a by 1. The resulting values at i-th and j-th index of array a are a_i - 1 and a_j + 1, respectively. Each element of array a must be non-negative after each operation. If i = j this operation doesn't change the array a. AquaMoon wants to make some operations to make arrays a and b equal. Two arrays a and b are considered equal if and only if a_i = b_i for all 1 ≤ i ≤ n. Help AquaMoon to find a sequence of operations that will solve her problem or find, that it is impossible to make arrays a and b equal. Please note, that you don't have to minimize the number of operations. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains a single integer n (1 ≤ n ≤ 100). The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 100). The sum of all a_i does not exceed 100. The third line of each test case contains n integers b_1, b_2, ..., b_n (0 ≤ b_i ≤ 100). The sum of all b_i does not exceed 100. Output For each test case print "-1" on the only line if it is impossible to make two arrays equal with some sequence of operations. Otherwise, print an integer m (0 ≤ m ≤ 100) in the first line — the number of operations. Then print m lines, each line consists of two integers i and j — the indices you choose for the operation. It can be proven that if it is possible to make two arrays equal with some sequence of operations, there exists a sequence with m ≤ 100. If there are multiple possible solutions, you can print any. Example Input 4 4 1 2 3 4 3 1 2 4 2 1 3 2 1 1 0 0 5 4 3 2 1 0 0 1 2 3 4 Output 2 2 1 3 1 -1 0 6 1 4 1 4 1 5 1 5 2 5 2 5 Note In the first example, we do the following operations: * i = 2, j = 1: [1, 2, 3, 4] → [2, 1, 3, 4]; * i = 3, j = 1: [2, 1, 3, 4] → [3, 1, 2, 4]; In the second example, it's impossible to make two arrays equal. Tags: brute force, greedy Correct Solution: ``` t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) if sum(a) != sum(b): print(-1) else: s = 0 for i in range(n): s += abs(a[i] - b[i]) print(s // 2) for i in range(n): if a[i] < b[i]: while a[i] != b[i]: for j in range(i + 1, n): if a[i] == b[i]: break if a[j] >= 0 and a[j] > b[j]: print(j+1, i+1) a[j] -= 1 a[i] += 1 else: while a[i] != b[i]: for j in range(i + 1, n): if a[i] == b[i]: break if a[j] < b[j]: print(i+1, j+1) a[j] += 1 a[i] -= 1 ```
94,639
Provide tags and a correct Python 3 solution for this coding contest problem. AquaMoon and Cirno are playing an interesting game with arrays. Cirno has prepared two arrays a and b, both consist of n non-negative integers. AquaMoon can perform the following operation an arbitrary number of times (possibly zero): * She chooses two indices i and j (1 ≤ i, j ≤ n), then decreases the i-th element of array a by 1, and increases the j-th element of array a by 1. The resulting values at i-th and j-th index of array a are a_i - 1 and a_j + 1, respectively. Each element of array a must be non-negative after each operation. If i = j this operation doesn't change the array a. AquaMoon wants to make some operations to make arrays a and b equal. Two arrays a and b are considered equal if and only if a_i = b_i for all 1 ≤ i ≤ n. Help AquaMoon to find a sequence of operations that will solve her problem or find, that it is impossible to make arrays a and b equal. Please note, that you don't have to minimize the number of operations. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains a single integer n (1 ≤ n ≤ 100). The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 100). The sum of all a_i does not exceed 100. The third line of each test case contains n integers b_1, b_2, ..., b_n (0 ≤ b_i ≤ 100). The sum of all b_i does not exceed 100. Output For each test case print "-1" on the only line if it is impossible to make two arrays equal with some sequence of operations. Otherwise, print an integer m (0 ≤ m ≤ 100) in the first line — the number of operations. Then print m lines, each line consists of two integers i and j — the indices you choose for the operation. It can be proven that if it is possible to make two arrays equal with some sequence of operations, there exists a sequence with m ≤ 100. If there are multiple possible solutions, you can print any. Example Input 4 4 1 2 3 4 3 1 2 4 2 1 3 2 1 1 0 0 5 4 3 2 1 0 0 1 2 3 4 Output 2 2 1 3 1 -1 0 6 1 4 1 4 1 5 1 5 2 5 2 5 Note In the first example, we do the following operations: * i = 2, j = 1: [1, 2, 3, 4] → [2, 1, 3, 4]; * i = 3, j = 1: [2, 1, 3, 4] → [3, 1, 2, 4]; In the second example, it's impossible to make two arrays equal. Tags: brute force, greedy Correct Solution: ``` for _ in range(int(input())): n=int(input()) arr1=list(map(int,input().split())) arr2=list(map(int,input().split())) pos=[] # f,g=0,0 # for i in range(n): # if arr1[i]<arr2[i]: # pos.append((i,arr2[i]-arr1[i])) # elif arr1[i]>arr2[i]: # neg.append((i,arr1[i]-arr2[i])) neg=[] if sum(arr1)!=sum(arr2): print(-1) else: for i in range(n): if arr2[i]-arr1[i]>0: for j in range(arr2[i]-arr1[i]): pos.append(i+1) elif arr2[i]-arr1[i]<0: for j in range(arr1[i]-arr2[i]): neg.append(i+1) print(len(pos)) for i in range(len(pos)): print(neg[i],pos[i]) ```
94,640
Provide tags and a correct Python 3 solution for this coding contest problem. AquaMoon and Cirno are playing an interesting game with arrays. Cirno has prepared two arrays a and b, both consist of n non-negative integers. AquaMoon can perform the following operation an arbitrary number of times (possibly zero): * She chooses two indices i and j (1 ≤ i, j ≤ n), then decreases the i-th element of array a by 1, and increases the j-th element of array a by 1. The resulting values at i-th and j-th index of array a are a_i - 1 and a_j + 1, respectively. Each element of array a must be non-negative after each operation. If i = j this operation doesn't change the array a. AquaMoon wants to make some operations to make arrays a and b equal. Two arrays a and b are considered equal if and only if a_i = b_i for all 1 ≤ i ≤ n. Help AquaMoon to find a sequence of operations that will solve her problem or find, that it is impossible to make arrays a and b equal. Please note, that you don't have to minimize the number of operations. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains a single integer n (1 ≤ n ≤ 100). The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 100). The sum of all a_i does not exceed 100. The third line of each test case contains n integers b_1, b_2, ..., b_n (0 ≤ b_i ≤ 100). The sum of all b_i does not exceed 100. Output For each test case print "-1" on the only line if it is impossible to make two arrays equal with some sequence of operations. Otherwise, print an integer m (0 ≤ m ≤ 100) in the first line — the number of operations. Then print m lines, each line consists of two integers i and j — the indices you choose for the operation. It can be proven that if it is possible to make two arrays equal with some sequence of operations, there exists a sequence with m ≤ 100. If there are multiple possible solutions, you can print any. Example Input 4 4 1 2 3 4 3 1 2 4 2 1 3 2 1 1 0 0 5 4 3 2 1 0 0 1 2 3 4 Output 2 2 1 3 1 -1 0 6 1 4 1 4 1 5 1 5 2 5 2 5 Note In the first example, we do the following operations: * i = 2, j = 1: [1, 2, 3, 4] → [2, 1, 3, 4]; * i = 3, j = 1: [2, 1, 3, 4] → [3, 1, 2, 4]; In the second example, it's impossible to make two arrays equal. Tags: brute force, greedy Correct Solution: ``` def sex(a, b): if sum(a) != sum(b): print(-1) return if len(a) != len(b): print(-1) return result = '' plus = [] minus = [] for i in range(len(a)): if a[i] < b[i]: for _ in range(b[i] - a[i]): plus.append(i) else: for _ in range(a[i] - b[i]): minus.append(i) m = len(plus) print(m) for i in range(m): print(minus[i] + 1, plus[i] + 1) t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) sex(a, b) ```
94,641
Provide tags and a correct Python 3 solution for this coding contest problem. AquaMoon and Cirno are playing an interesting game with arrays. Cirno has prepared two arrays a and b, both consist of n non-negative integers. AquaMoon can perform the following operation an arbitrary number of times (possibly zero): * She chooses two indices i and j (1 ≤ i, j ≤ n), then decreases the i-th element of array a by 1, and increases the j-th element of array a by 1. The resulting values at i-th and j-th index of array a are a_i - 1 and a_j + 1, respectively. Each element of array a must be non-negative after each operation. If i = j this operation doesn't change the array a. AquaMoon wants to make some operations to make arrays a and b equal. Two arrays a and b are considered equal if and only if a_i = b_i for all 1 ≤ i ≤ n. Help AquaMoon to find a sequence of operations that will solve her problem or find, that it is impossible to make arrays a and b equal. Please note, that you don't have to minimize the number of operations. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains a single integer n (1 ≤ n ≤ 100). The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 100). The sum of all a_i does not exceed 100. The third line of each test case contains n integers b_1, b_2, ..., b_n (0 ≤ b_i ≤ 100). The sum of all b_i does not exceed 100. Output For each test case print "-1" on the only line if it is impossible to make two arrays equal with some sequence of operations. Otherwise, print an integer m (0 ≤ m ≤ 100) in the first line — the number of operations. Then print m lines, each line consists of two integers i and j — the indices you choose for the operation. It can be proven that if it is possible to make two arrays equal with some sequence of operations, there exists a sequence with m ≤ 100. If there are multiple possible solutions, you can print any. Example Input 4 4 1 2 3 4 3 1 2 4 2 1 3 2 1 1 0 0 5 4 3 2 1 0 0 1 2 3 4 Output 2 2 1 3 1 -1 0 6 1 4 1 4 1 5 1 5 2 5 2 5 Note In the first example, we do the following operations: * i = 2, j = 1: [1, 2, 3, 4] → [2, 1, 3, 4]; * i = 3, j = 1: [2, 1, 3, 4] → [3, 1, 2, 4]; In the second example, it's impossible to make two arrays equal. Tags: brute force, greedy Correct Solution: ``` for idfghjk in range(int(input())): n=(int(input())) a=list(map(int,input().split())) b=list(map(int,input().split())) ai=[] aj=[] for i in range(n): if a[i]>b[i]: for j in range(a[i]-b[i]): ai.append(i) if a[i]<b[i]: for j in range(b[i]-a[i]): aj.append(i) if len(ai)==len(aj): print(len(ai)) for i in range(len(ai)): print(ai[i]+1,aj[i]+1) else: print(-1) ```
94,642
Provide tags and a correct Python 3 solution for this coding contest problem. AquaMoon and Cirno are playing an interesting game with arrays. Cirno has prepared two arrays a and b, both consist of n non-negative integers. AquaMoon can perform the following operation an arbitrary number of times (possibly zero): * She chooses two indices i and j (1 ≤ i, j ≤ n), then decreases the i-th element of array a by 1, and increases the j-th element of array a by 1. The resulting values at i-th and j-th index of array a are a_i - 1 and a_j + 1, respectively. Each element of array a must be non-negative after each operation. If i = j this operation doesn't change the array a. AquaMoon wants to make some operations to make arrays a and b equal. Two arrays a and b are considered equal if and only if a_i = b_i for all 1 ≤ i ≤ n. Help AquaMoon to find a sequence of operations that will solve her problem or find, that it is impossible to make arrays a and b equal. Please note, that you don't have to minimize the number of operations. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains a single integer n (1 ≤ n ≤ 100). The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 100). The sum of all a_i does not exceed 100. The third line of each test case contains n integers b_1, b_2, ..., b_n (0 ≤ b_i ≤ 100). The sum of all b_i does not exceed 100. Output For each test case print "-1" on the only line if it is impossible to make two arrays equal with some sequence of operations. Otherwise, print an integer m (0 ≤ m ≤ 100) in the first line — the number of operations. Then print m lines, each line consists of two integers i and j — the indices you choose for the operation. It can be proven that if it is possible to make two arrays equal with some sequence of operations, there exists a sequence with m ≤ 100. If there are multiple possible solutions, you can print any. Example Input 4 4 1 2 3 4 3 1 2 4 2 1 3 2 1 1 0 0 5 4 3 2 1 0 0 1 2 3 4 Output 2 2 1 3 1 -1 0 6 1 4 1 4 1 5 1 5 2 5 2 5 Note In the first example, we do the following operations: * i = 2, j = 1: [1, 2, 3, 4] → [2, 1, 3, 4]; * i = 3, j = 1: [2, 1, 3, 4] → [3, 1, 2, 4]; In the second example, it's impossible to make two arrays equal. Tags: brute force, greedy Correct Solution: ``` import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") ####################################### a=int(input()) for i in range(a): s=int(input()) z=list(map(int,input().split())) q=list(map(int,input().split())) large=[] small=[] for i in range(len(z)): if(z[i]>q[i]): large.append(i) elif(z[i]<q[i]): small.append(i) i=0 j=0 ans=[] flag=0 for i in range(len(small)): t=small[i] while(j<len(large) and z[t]!=q[t]): m=large[j] if(z[m]==q[m]): j+=1 continue; ans.append([m+1,t+1]) z[t]+=1 z[m]-=1 if(z[t]!=q[t]): flag=1 break; for i in range(len(z)): if(z[i]!=q[i]): flag=1 break; if(flag==1): print(-1) continue; print(len(ans)) for i in range(len(ans)): print(ans[i][0],ans[i][1]) ```
94,643
Provide tags and a correct Python 3 solution for this coding contest problem. AquaMoon and Cirno are playing an interesting game with arrays. Cirno has prepared two arrays a and b, both consist of n non-negative integers. AquaMoon can perform the following operation an arbitrary number of times (possibly zero): * She chooses two indices i and j (1 ≤ i, j ≤ n), then decreases the i-th element of array a by 1, and increases the j-th element of array a by 1. The resulting values at i-th and j-th index of array a are a_i - 1 and a_j + 1, respectively. Each element of array a must be non-negative after each operation. If i = j this operation doesn't change the array a. AquaMoon wants to make some operations to make arrays a and b equal. Two arrays a and b are considered equal if and only if a_i = b_i for all 1 ≤ i ≤ n. Help AquaMoon to find a sequence of operations that will solve her problem or find, that it is impossible to make arrays a and b equal. Please note, that you don't have to minimize the number of operations. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains a single integer n (1 ≤ n ≤ 100). The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 100). The sum of all a_i does not exceed 100. The third line of each test case contains n integers b_1, b_2, ..., b_n (0 ≤ b_i ≤ 100). The sum of all b_i does not exceed 100. Output For each test case print "-1" on the only line if it is impossible to make two arrays equal with some sequence of operations. Otherwise, print an integer m (0 ≤ m ≤ 100) in the first line — the number of operations. Then print m lines, each line consists of two integers i and j — the indices you choose for the operation. It can be proven that if it is possible to make two arrays equal with some sequence of operations, there exists a sequence with m ≤ 100. If there are multiple possible solutions, you can print any. Example Input 4 4 1 2 3 4 3 1 2 4 2 1 3 2 1 1 0 0 5 4 3 2 1 0 0 1 2 3 4 Output 2 2 1 3 1 -1 0 6 1 4 1 4 1 5 1 5 2 5 2 5 Note In the first example, we do the following operations: * i = 2, j = 1: [1, 2, 3, 4] → [2, 1, 3, 4]; * i = 3, j = 1: [2, 1, 3, 4] → [3, 1, 2, 4]; In the second example, it's impossible to make two arrays equal. Tags: brute force, greedy Correct Solution: ``` t = int(input()) for i in range(t): l = int(input()) a = list( map(int,input().split()) ) b = list( map(int,input().split()) ) if a==b: print(0) continue r=[] rc = 0 for j in range(l): if a[j]>b[j]: for k in range(j+1,l): if a[k]<b[k]: tmp = min([abs(a[j]-b[j]),abs(a[k]-b[k])]) r.append([str(j+1)+" "+str(k+1),tmp]) a[j]-=tmp a[k]+=tmp rc+=tmp if a[j]==0: break elif a[j]<b[j]: for k in range(j+1,l): if a[k]>b[k]: tmp = min([abs(a[j]-b[j]),abs(a[k]-b[k])]) r.append([str(k+1)+" "+str(j+1),tmp]) a[j]+=tmp a[k]-=tmp rc+=tmp if a[j]==0: break if a!=b: print(-1) else: print(rc) for j in r: for k in range(j[1]): print(j[0]) ```
94,644
Provide tags and a correct Python 3 solution for this coding contest problem. AquaMoon and Cirno are playing an interesting game with arrays. Cirno has prepared two arrays a and b, both consist of n non-negative integers. AquaMoon can perform the following operation an arbitrary number of times (possibly zero): * She chooses two indices i and j (1 ≤ i, j ≤ n), then decreases the i-th element of array a by 1, and increases the j-th element of array a by 1. The resulting values at i-th and j-th index of array a are a_i - 1 and a_j + 1, respectively. Each element of array a must be non-negative after each operation. If i = j this operation doesn't change the array a. AquaMoon wants to make some operations to make arrays a and b equal. Two arrays a and b are considered equal if and only if a_i = b_i for all 1 ≤ i ≤ n. Help AquaMoon to find a sequence of operations that will solve her problem or find, that it is impossible to make arrays a and b equal. Please note, that you don't have to minimize the number of operations. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains a single integer n (1 ≤ n ≤ 100). The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 100). The sum of all a_i does not exceed 100. The third line of each test case contains n integers b_1, b_2, ..., b_n (0 ≤ b_i ≤ 100). The sum of all b_i does not exceed 100. Output For each test case print "-1" on the only line if it is impossible to make two arrays equal with some sequence of operations. Otherwise, print an integer m (0 ≤ m ≤ 100) in the first line — the number of operations. Then print m lines, each line consists of two integers i and j — the indices you choose for the operation. It can be proven that if it is possible to make two arrays equal with some sequence of operations, there exists a sequence with m ≤ 100. If there are multiple possible solutions, you can print any. Example Input 4 4 1 2 3 4 3 1 2 4 2 1 3 2 1 1 0 0 5 4 3 2 1 0 0 1 2 3 4 Output 2 2 1 3 1 -1 0 6 1 4 1 4 1 5 1 5 2 5 2 5 Note In the first example, we do the following operations: * i = 2, j = 1: [1, 2, 3, 4] → [2, 1, 3, 4]; * i = 3, j = 1: [2, 1, 3, 4] → [3, 1, 2, 4]; In the second example, it's impossible to make two arrays equal. Tags: brute force, greedy Correct Solution: ``` import sys LI=lambda:list(map(int,sys.stdin.readline().split())) MI=lambda:map(int,sys.stdin.readline().split()) SI=lambda:sys.stdin.readline().strip('\n') II=lambda:int(sys.stdin.readline()) for _ in range(II()): n, a, b=II(), LI(), LI() v=[b[i]-a[i] for i in range(n)] if sum(v): print(-1) else: p, n=[], [] for i,x in enumerate(v): if x>0: for j in range(x):p.append(i+1) else: for j in range(-x):n.append(i+1) print(len(n)) while p or n: print(n.pop(), p.pop()) ```
94,645
Provide tags and a correct Python 3 solution for this coding contest problem. AquaMoon and Cirno are playing an interesting game with arrays. Cirno has prepared two arrays a and b, both consist of n non-negative integers. AquaMoon can perform the following operation an arbitrary number of times (possibly zero): * She chooses two indices i and j (1 ≤ i, j ≤ n), then decreases the i-th element of array a by 1, and increases the j-th element of array a by 1. The resulting values at i-th and j-th index of array a are a_i - 1 and a_j + 1, respectively. Each element of array a must be non-negative after each operation. If i = j this operation doesn't change the array a. AquaMoon wants to make some operations to make arrays a and b equal. Two arrays a and b are considered equal if and only if a_i = b_i for all 1 ≤ i ≤ n. Help AquaMoon to find a sequence of operations that will solve her problem or find, that it is impossible to make arrays a and b equal. Please note, that you don't have to minimize the number of operations. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains a single integer n (1 ≤ n ≤ 100). The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 100). The sum of all a_i does not exceed 100. The third line of each test case contains n integers b_1, b_2, ..., b_n (0 ≤ b_i ≤ 100). The sum of all b_i does not exceed 100. Output For each test case print "-1" on the only line if it is impossible to make two arrays equal with some sequence of operations. Otherwise, print an integer m (0 ≤ m ≤ 100) in the first line — the number of operations. Then print m lines, each line consists of two integers i and j — the indices you choose for the operation. It can be proven that if it is possible to make two arrays equal with some sequence of operations, there exists a sequence with m ≤ 100. If there are multiple possible solutions, you can print any. Example Input 4 4 1 2 3 4 3 1 2 4 2 1 3 2 1 1 0 0 5 4 3 2 1 0 0 1 2 3 4 Output 2 2 1 3 1 -1 0 6 1 4 1 4 1 5 1 5 2 5 2 5 Note In the first example, we do the following operations: * i = 2, j = 1: [1, 2, 3, 4] → [2, 1, 3, 4]; * i = 3, j = 1: [2, 1, 3, 4] → [3, 1, 2, 4]; In the second example, it's impossible to make two arrays equal. Tags: brute force, greedy Correct Solution: ``` for _ in range(int(input())): n=int(input()) a = list(map(int,input().strip().split())) b = list(map(int,input().strip().split())) c=0 if len(a)==1: if a[0]==b[0]:print(0) else:print(-1) else: x=[] y=[] for i in range(n): if a[i]>b[i]: x+=[i+1]*(a[i]-b[i]) c+=(a[i]-b[i]) elif b[i]>a[i]: y+=[i+1]*(b[i]-a[i]) c+=(a[i]-b[i]) if c==0: print(len(x)) for j in range(len(x)): print(x[j],y[j]) else:print(-1) ```
94,646
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. AquaMoon and Cirno are playing an interesting game with arrays. Cirno has prepared two arrays a and b, both consist of n non-negative integers. AquaMoon can perform the following operation an arbitrary number of times (possibly zero): * She chooses two indices i and j (1 ≤ i, j ≤ n), then decreases the i-th element of array a by 1, and increases the j-th element of array a by 1. The resulting values at i-th and j-th index of array a are a_i - 1 and a_j + 1, respectively. Each element of array a must be non-negative after each operation. If i = j this operation doesn't change the array a. AquaMoon wants to make some operations to make arrays a and b equal. Two arrays a and b are considered equal if and only if a_i = b_i for all 1 ≤ i ≤ n. Help AquaMoon to find a sequence of operations that will solve her problem or find, that it is impossible to make arrays a and b equal. Please note, that you don't have to minimize the number of operations. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains a single integer n (1 ≤ n ≤ 100). The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 100). The sum of all a_i does not exceed 100. The third line of each test case contains n integers b_1, b_2, ..., b_n (0 ≤ b_i ≤ 100). The sum of all b_i does not exceed 100. Output For each test case print "-1" on the only line if it is impossible to make two arrays equal with some sequence of operations. Otherwise, print an integer m (0 ≤ m ≤ 100) in the first line — the number of operations. Then print m lines, each line consists of two integers i and j — the indices you choose for the operation. It can be proven that if it is possible to make two arrays equal with some sequence of operations, there exists a sequence with m ≤ 100. If there are multiple possible solutions, you can print any. Example Input 4 4 1 2 3 4 3 1 2 4 2 1 3 2 1 1 0 0 5 4 3 2 1 0 0 1 2 3 4 Output 2 2 1 3 1 -1 0 6 1 4 1 4 1 5 1 5 2 5 2 5 Note In the first example, we do the following operations: * i = 2, j = 1: [1, 2, 3, 4] → [2, 1, 3, 4]; * i = 3, j = 1: [2, 1, 3, 4] → [3, 1, 2, 4]; In the second example, it's impossible to make two arrays equal. Submitted Solution: ``` R=lambda:map(int,input().split()) t,=R() while t: t-=1;R();a=[[],[]];s=i=0 for x,y in zip(R(),R()):i+=1;d=y-x;s+=d;a[d>0]+=[i]*abs(d) print(*s and[-1]or[len(a[0])]+[f'{i} {j}'for i,j in zip(*a)]) ``` Yes
94,647
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. AquaMoon and Cirno are playing an interesting game with arrays. Cirno has prepared two arrays a and b, both consist of n non-negative integers. AquaMoon can perform the following operation an arbitrary number of times (possibly zero): * She chooses two indices i and j (1 ≤ i, j ≤ n), then decreases the i-th element of array a by 1, and increases the j-th element of array a by 1. The resulting values at i-th and j-th index of array a are a_i - 1 and a_j + 1, respectively. Each element of array a must be non-negative after each operation. If i = j this operation doesn't change the array a. AquaMoon wants to make some operations to make arrays a and b equal. Two arrays a and b are considered equal if and only if a_i = b_i for all 1 ≤ i ≤ n. Help AquaMoon to find a sequence of operations that will solve her problem or find, that it is impossible to make arrays a and b equal. Please note, that you don't have to minimize the number of operations. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains a single integer n (1 ≤ n ≤ 100). The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 100). The sum of all a_i does not exceed 100. The third line of each test case contains n integers b_1, b_2, ..., b_n (0 ≤ b_i ≤ 100). The sum of all b_i does not exceed 100. Output For each test case print "-1" on the only line if it is impossible to make two arrays equal with some sequence of operations. Otherwise, print an integer m (0 ≤ m ≤ 100) in the first line — the number of operations. Then print m lines, each line consists of two integers i and j — the indices you choose for the operation. It can be proven that if it is possible to make two arrays equal with some sequence of operations, there exists a sequence with m ≤ 100. If there are multiple possible solutions, you can print any. Example Input 4 4 1 2 3 4 3 1 2 4 2 1 3 2 1 1 0 0 5 4 3 2 1 0 0 1 2 3 4 Output 2 2 1 3 1 -1 0 6 1 4 1 4 1 5 1 5 2 5 2 5 Note In the first example, we do the following operations: * i = 2, j = 1: [1, 2, 3, 4] → [2, 1, 3, 4]; * i = 3, j = 1: [2, 1, 3, 4] → [3, 1, 2, 4]; In the second example, it's impossible to make two arrays equal. Submitted Solution: ``` def ans(a,b,n): if(sum(a)!=sum(b)): print(-1) return d = {} count = 0 for i in range(len(a)): #we count adds if(a[i]<b[i]): count+=(b[i]-a[i]) if(a[i]!=b[i]): d[i+1] = b[i]-a[i] print(count) d1 = {} d2 = {} for i in d: if d[i]<0: d2[i] = d[i] else: d1[i] = d[i] l1 = list(d1.keys())#add l2 = list(d2.keys())#subtract i = 0 j = 0 while(i<len(l1) and j<len(l2)): x = d1[l1[i]] y = d2[l2[j]] print(str(l2[j])+' '+str(l1[i])) d1[l1[i]]-=1 d2[l2[j]]+=1 if d1[l1[i]]==0: i+=1 if d2[l2[j]]==0: j+=1 return m = int(input()) for i in range(m): n = int(input()) arr = input().split() a = [] for i in arr: a.append(int(i)) arr = input().split() b = [] for i in arr: b.append(int(i)) ans(a,b,n) ``` Yes
94,648
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. AquaMoon and Cirno are playing an interesting game with arrays. Cirno has prepared two arrays a and b, both consist of n non-negative integers. AquaMoon can perform the following operation an arbitrary number of times (possibly zero): * She chooses two indices i and j (1 ≤ i, j ≤ n), then decreases the i-th element of array a by 1, and increases the j-th element of array a by 1. The resulting values at i-th and j-th index of array a are a_i - 1 and a_j + 1, respectively. Each element of array a must be non-negative after each operation. If i = j this operation doesn't change the array a. AquaMoon wants to make some operations to make arrays a and b equal. Two arrays a and b are considered equal if and only if a_i = b_i for all 1 ≤ i ≤ n. Help AquaMoon to find a sequence of operations that will solve her problem or find, that it is impossible to make arrays a and b equal. Please note, that you don't have to minimize the number of operations. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains a single integer n (1 ≤ n ≤ 100). The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 100). The sum of all a_i does not exceed 100. The third line of each test case contains n integers b_1, b_2, ..., b_n (0 ≤ b_i ≤ 100). The sum of all b_i does not exceed 100. Output For each test case print "-1" on the only line if it is impossible to make two arrays equal with some sequence of operations. Otherwise, print an integer m (0 ≤ m ≤ 100) in the first line — the number of operations. Then print m lines, each line consists of two integers i and j — the indices you choose for the operation. It can be proven that if it is possible to make two arrays equal with some sequence of operations, there exists a sequence with m ≤ 100. If there are multiple possible solutions, you can print any. Example Input 4 4 1 2 3 4 3 1 2 4 2 1 3 2 1 1 0 0 5 4 3 2 1 0 0 1 2 3 4 Output 2 2 1 3 1 -1 0 6 1 4 1 4 1 5 1 5 2 5 2 5 Note In the first example, we do the following operations: * i = 2, j = 1: [1, 2, 3, 4] → [2, 1, 3, 4]; * i = 3, j = 1: [2, 1, 3, 4] → [3, 1, 2, 4]; In the second example, it's impossible to make two arrays equal. Submitted Solution: ``` import sys input=sys.stdin.readline t=int(input()) for _ in range(t): n=int(input()) a=list(map(int,input().split())) b=list(map(int,input().split())) c=[] d=[] if sum(a)!=sum(b): print(-1) continue for i in range(n): if a[i]>b[i]: for j in range(a[i]-b[i]): c.append(i+1) if a[i]<b[i]: for j in range(b[i]-a[i]): d.append(i+1) l=len(c) print(l) for i in range(l): print(c[i],d[i]) ``` Yes
94,649
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. AquaMoon and Cirno are playing an interesting game with arrays. Cirno has prepared two arrays a and b, both consist of n non-negative integers. AquaMoon can perform the following operation an arbitrary number of times (possibly zero): * She chooses two indices i and j (1 ≤ i, j ≤ n), then decreases the i-th element of array a by 1, and increases the j-th element of array a by 1. The resulting values at i-th and j-th index of array a are a_i - 1 and a_j + 1, respectively. Each element of array a must be non-negative after each operation. If i = j this operation doesn't change the array a. AquaMoon wants to make some operations to make arrays a and b equal. Two arrays a and b are considered equal if and only if a_i = b_i for all 1 ≤ i ≤ n. Help AquaMoon to find a sequence of operations that will solve her problem or find, that it is impossible to make arrays a and b equal. Please note, that you don't have to minimize the number of operations. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains a single integer n (1 ≤ n ≤ 100). The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 100). The sum of all a_i does not exceed 100. The third line of each test case contains n integers b_1, b_2, ..., b_n (0 ≤ b_i ≤ 100). The sum of all b_i does not exceed 100. Output For each test case print "-1" on the only line if it is impossible to make two arrays equal with some sequence of operations. Otherwise, print an integer m (0 ≤ m ≤ 100) in the first line — the number of operations. Then print m lines, each line consists of two integers i and j — the indices you choose for the operation. It can be proven that if it is possible to make two arrays equal with some sequence of operations, there exists a sequence with m ≤ 100. If there are multiple possible solutions, you can print any. Example Input 4 4 1 2 3 4 3 1 2 4 2 1 3 2 1 1 0 0 5 4 3 2 1 0 0 1 2 3 4 Output 2 2 1 3 1 -1 0 6 1 4 1 4 1 5 1 5 2 5 2 5 Note In the first example, we do the following operations: * i = 2, j = 1: [1, 2, 3, 4] → [2, 1, 3, 4]; * i = 3, j = 1: [2, 1, 3, 4] → [3, 1, 2, 4]; In the second example, it's impossible to make two arrays equal. Submitted Solution: ``` from sys import stdin for _ in range(int(stdin.readline())): n=int(stdin.readline()) a=list(map(int,stdin.readline().split())) b=list(map(int,stdin.readline().split())) ans=0 if sum(a)!=sum(b): print(-1) else: ans=0 arr=[] for i in range(n): j=i+1 while j<n and a[i]!=b[i]: if (a[i]>b[i] and a[j]>=b[j]) or (a[i]<b[i] and a[j]<=b[j]): j+=1 continue while a[j]!=b[j] and a[i]!=b[i]: if a[i]>b[i]: a[i]-=1 a[j]+=1 arr.append([i+1,j+1]) else: a[i]+=1 a[j]-=1 arr.append([j+1,i+1]) #print(i,j) #print(a) ans+=1 j+=1 print(ans) #print(a) for a in arr: print(*a) ``` Yes
94,650
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. AquaMoon and Cirno are playing an interesting game with arrays. Cirno has prepared two arrays a and b, both consist of n non-negative integers. AquaMoon can perform the following operation an arbitrary number of times (possibly zero): * She chooses two indices i and j (1 ≤ i, j ≤ n), then decreases the i-th element of array a by 1, and increases the j-th element of array a by 1. The resulting values at i-th and j-th index of array a are a_i - 1 and a_j + 1, respectively. Each element of array a must be non-negative after each operation. If i = j this operation doesn't change the array a. AquaMoon wants to make some operations to make arrays a and b equal. Two arrays a and b are considered equal if and only if a_i = b_i for all 1 ≤ i ≤ n. Help AquaMoon to find a sequence of operations that will solve her problem or find, that it is impossible to make arrays a and b equal. Please note, that you don't have to minimize the number of operations. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains a single integer n (1 ≤ n ≤ 100). The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 100). The sum of all a_i does not exceed 100. The third line of each test case contains n integers b_1, b_2, ..., b_n (0 ≤ b_i ≤ 100). The sum of all b_i does not exceed 100. Output For each test case print "-1" on the only line if it is impossible to make two arrays equal with some sequence of operations. Otherwise, print an integer m (0 ≤ m ≤ 100) in the first line — the number of operations. Then print m lines, each line consists of two integers i and j — the indices you choose for the operation. It can be proven that if it is possible to make two arrays equal with some sequence of operations, there exists a sequence with m ≤ 100. If there are multiple possible solutions, you can print any. Example Input 4 4 1 2 3 4 3 1 2 4 2 1 3 2 1 1 0 0 5 4 3 2 1 0 0 1 2 3 4 Output 2 2 1 3 1 -1 0 6 1 4 1 4 1 5 1 5 2 5 2 5 Note In the first example, we do the following operations: * i = 2, j = 1: [1, 2, 3, 4] → [2, 1, 3, 4]; * i = 3, j = 1: [2, 1, 3, 4] → [3, 1, 2, 4]; In the second example, it's impossible to make two arrays equal. Submitted Solution: ``` n=int(input()) for _ in range(n): p=int(input()) d=[] a=list(map(int,input().split())) b=list(map(int,input().split())) if a==b: print(0) continue for i in range(len(a)): if a[i]==b[i]: d.append(i) j=0 w=0 i = len(a) - 1 po=[] while w==0: while i in d: i -= 1 while j in d: j += 1 a[i],a[j]=a[j],a[i] po.append([i+1,j+1]) if a[i]==b[i]: d.append(i) if a[j]==b[j]: d.append(j) if a==b: for k in po: print(k[0],k[-1]) break if i==j: print(-1) w=90 break ``` No
94,651
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. AquaMoon and Cirno are playing an interesting game with arrays. Cirno has prepared two arrays a and b, both consist of n non-negative integers. AquaMoon can perform the following operation an arbitrary number of times (possibly zero): * She chooses two indices i and j (1 ≤ i, j ≤ n), then decreases the i-th element of array a by 1, and increases the j-th element of array a by 1. The resulting values at i-th and j-th index of array a are a_i - 1 and a_j + 1, respectively. Each element of array a must be non-negative after each operation. If i = j this operation doesn't change the array a. AquaMoon wants to make some operations to make arrays a and b equal. Two arrays a and b are considered equal if and only if a_i = b_i for all 1 ≤ i ≤ n. Help AquaMoon to find a sequence of operations that will solve her problem or find, that it is impossible to make arrays a and b equal. Please note, that you don't have to minimize the number of operations. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains a single integer n (1 ≤ n ≤ 100). The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 100). The sum of all a_i does not exceed 100. The third line of each test case contains n integers b_1, b_2, ..., b_n (0 ≤ b_i ≤ 100). The sum of all b_i does not exceed 100. Output For each test case print "-1" on the only line if it is impossible to make two arrays equal with some sequence of operations. Otherwise, print an integer m (0 ≤ m ≤ 100) in the first line — the number of operations. Then print m lines, each line consists of two integers i and j — the indices you choose for the operation. It can be proven that if it is possible to make two arrays equal with some sequence of operations, there exists a sequence with m ≤ 100. If there are multiple possible solutions, you can print any. Example Input 4 4 1 2 3 4 3 1 2 4 2 1 3 2 1 1 0 0 5 4 3 2 1 0 0 1 2 3 4 Output 2 2 1 3 1 -1 0 6 1 4 1 4 1 5 1 5 2 5 2 5 Note In the first example, we do the following operations: * i = 2, j = 1: [1, 2, 3, 4] → [2, 1, 3, 4]; * i = 3, j = 1: [2, 1, 3, 4] → [3, 1, 2, 4]; In the second example, it's impossible to make two arrays equal. Submitted Solution: ``` for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) if sum(a) != sum(b): print(-1) continue ac = a.copy() bc = b.copy() swaps = [] for i in range(n-1, -1, -1): #print(a, i) for j in range(i-1, -1, -1): if a[i] < b[i]: if a[j] >= 1: add = b[i]-a[i] if a[j] >= add: a[i] += add a[j] -= add for k in range(add): swaps.append([i+1,j+1]) else: tmp = a[j] a[i] += a[j] a[j] = 0 for k in range(tmp): swaps.append([i+1,j+1]) if a==b: print(len(swaps)) for swap in swaps: print(*sorted(swap)) continue swaps = [] for i in range(n-1, -1, -1): #print(bc, i) for j in range(i-1, -1, -1): if ac[i] > bc[i]: if bc[j] >= 1: add = ac[i]-bc[i] if bc[j] >= add: bc[i] += add bc[j] -= add for k in range(add): swaps.append([i+1,j+1]) else: tmp = bc[j] bc[i] += bc[j] bc[j] = 0 for k in range(tmp): swaps.append([i+1,j+1]) if ac==bc: print(len(swaps)) for swap in swaps: print(*sorted(swap)) continue else: print(-1) ``` No
94,652
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. AquaMoon and Cirno are playing an interesting game with arrays. Cirno has prepared two arrays a and b, both consist of n non-negative integers. AquaMoon can perform the following operation an arbitrary number of times (possibly zero): * She chooses two indices i and j (1 ≤ i, j ≤ n), then decreases the i-th element of array a by 1, and increases the j-th element of array a by 1. The resulting values at i-th and j-th index of array a are a_i - 1 and a_j + 1, respectively. Each element of array a must be non-negative after each operation. If i = j this operation doesn't change the array a. AquaMoon wants to make some operations to make arrays a and b equal. Two arrays a and b are considered equal if and only if a_i = b_i for all 1 ≤ i ≤ n. Help AquaMoon to find a sequence of operations that will solve her problem or find, that it is impossible to make arrays a and b equal. Please note, that you don't have to minimize the number of operations. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains a single integer n (1 ≤ n ≤ 100). The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 100). The sum of all a_i does not exceed 100. The third line of each test case contains n integers b_1, b_2, ..., b_n (0 ≤ b_i ≤ 100). The sum of all b_i does not exceed 100. Output For each test case print "-1" on the only line if it is impossible to make two arrays equal with some sequence of operations. Otherwise, print an integer m (0 ≤ m ≤ 100) in the first line — the number of operations. Then print m lines, each line consists of two integers i and j — the indices you choose for the operation. It can be proven that if it is possible to make two arrays equal with some sequence of operations, there exists a sequence with m ≤ 100. If there are multiple possible solutions, you can print any. Example Input 4 4 1 2 3 4 3 1 2 4 2 1 3 2 1 1 0 0 5 4 3 2 1 0 0 1 2 3 4 Output 2 2 1 3 1 -1 0 6 1 4 1 4 1 5 1 5 2 5 2 5 Note In the first example, we do the following operations: * i = 2, j = 1: [1, 2, 3, 4] → [2, 1, 3, 4]; * i = 3, j = 1: [2, 1, 3, 4] → [3, 1, 2, 4]; In the second example, it's impossible to make two arrays equal. Submitted Solution: ``` t=int(input()) for i in range(t): n=int(input()) a=list(map(int,input().split())) b=list(map(int,input().split())) li=[] if sum(a)==sum(b): li1=[] for i in range(n): li.append(a[i]-b[i]) for i in range(n): for j in range(i+1,n): if li[i]>0 and li[j]<0: y=min(li[i],abs(li[j])) li[i]-=y li[j]+=y for k in range(y): li1.append([i+1,j+1]) for j in range(i+1,n): if li[i]<0 and li[j]>0: y=min(abs(li[i]),li[j]) li[i]+=y li[j]-=y for k in range(y): li1.append([i+1,j+1]) print(len(li1)) for i in range(len(li1)): li1[i].sort() print(*li1[i]) else: print(-1) ``` No
94,653
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. AquaMoon and Cirno are playing an interesting game with arrays. Cirno has prepared two arrays a and b, both consist of n non-negative integers. AquaMoon can perform the following operation an arbitrary number of times (possibly zero): * She chooses two indices i and j (1 ≤ i, j ≤ n), then decreases the i-th element of array a by 1, and increases the j-th element of array a by 1. The resulting values at i-th and j-th index of array a are a_i - 1 and a_j + 1, respectively. Each element of array a must be non-negative after each operation. If i = j this operation doesn't change the array a. AquaMoon wants to make some operations to make arrays a and b equal. Two arrays a and b are considered equal if and only if a_i = b_i for all 1 ≤ i ≤ n. Help AquaMoon to find a sequence of operations that will solve her problem or find, that it is impossible to make arrays a and b equal. Please note, that you don't have to minimize the number of operations. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains a single integer n (1 ≤ n ≤ 100). The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 100). The sum of all a_i does not exceed 100. The third line of each test case contains n integers b_1, b_2, ..., b_n (0 ≤ b_i ≤ 100). The sum of all b_i does not exceed 100. Output For each test case print "-1" on the only line if it is impossible to make two arrays equal with some sequence of operations. Otherwise, print an integer m (0 ≤ m ≤ 100) in the first line — the number of operations. Then print m lines, each line consists of two integers i and j — the indices you choose for the operation. It can be proven that if it is possible to make two arrays equal with some sequence of operations, there exists a sequence with m ≤ 100. If there are multiple possible solutions, you can print any. Example Input 4 4 1 2 3 4 3 1 2 4 2 1 3 2 1 1 0 0 5 4 3 2 1 0 0 1 2 3 4 Output 2 2 1 3 1 -1 0 6 1 4 1 4 1 5 1 5 2 5 2 5 Note In the first example, we do the following operations: * i = 2, j = 1: [1, 2, 3, 4] → [2, 1, 3, 4]; * i = 3, j = 1: [2, 1, 3, 4] → [3, 1, 2, 4]; In the second example, it's impossible to make two arrays equal. Submitted Solution: ``` t = int(input()) for _ in range(t): n = int(input()) a = [int(c) for c in input().split()] b = [int(d) for d in input().split()] x1 = sum(a) x2 = sum(b) if x1!=x2: print(-1) elif a==b: print(0) else: for i in range(n): for j in range(n): if a[i] > b[i] and a[j] < b[j]: while a[i]!=b[i] and a[j]!=b[j]: a[i]-=1 a[j]+=1 print(i+1, j+1) elif a[i] < b[i] and a[j] > b[j]: while a[j]>0 and a[i]!=b[i] and a[j]!=b[j]: a[i]+=1 a[j]-=1 print(j+1, i+1) ``` No
94,654
Provide tags and a correct Python 3 solution for this coding contest problem. "The Chamber of Secrets has been opened again" — this news has spread all around Hogwarts and some of the students have been petrified due to seeing the basilisk. Dumbledore got fired and now Harry is trying to enter the Chamber of Secrets. These aren't good news for Lord Voldemort. The problem is, he doesn't want anybody to be able to enter the chamber. The Dark Lord is going to be busy sucking life out of Ginny. The Chamber of Secrets is an n × m rectangular grid in which some of the cells are columns. A light ray (and a basilisk's gaze) passes through the columns without changing its direction. But with some spell we can make a column magic to reflect the light ray (or the gaze) in all four directions when it receives the ray. This is shown in the figure below. <image> The left light ray passes through a regular column, and the right ray — through the magic column. The basilisk is located at the right side of the lower right cell of the grid and is looking to the left (in the direction of the lower left cell). According to the legend, anyone who meets a basilisk's gaze directly dies immediately. But if someone meets a basilisk's gaze through a column, this person will get petrified. We know that the door to the Chamber is located on the left side of the upper left corner of the grid and anyone who wants to enter will look in the direction of its movement (in the direction of the upper right cell) from that position. <image> This figure illustrates the first sample test. Given the dimensions of the chamber and the location of regular columns, Lord Voldemort has asked you to find the minimum number of columns that we need to make magic so that anyone who wants to enter the chamber would be petrified or just declare that it's impossible to secure the chamber. Input The first line of the input contains two integer numbers n and m (2 ≤ n, m ≤ 1000). Each of the next n lines contains m characters. Each character is either "." or "#" and represents one cell of the Chamber grid. It's "." if the corresponding cell is empty and "#" if it's a regular column. Output Print the minimum number of columns to make magic or -1 if it's impossible to do. Examples Input 3 3 .#. ... .#. Output 2 Input 4 3 ##. ... .#. .#. Output 2 Note The figure above shows the first sample test. In the first sample we should make both columns magic. The dragon figure represents the basilisk and the binoculars represent the person who will enter the Chamber of secrets. The black star shows the place where the person will be petrified. Yellow lines represent basilisk gaze moving through columns. Tags: dfs and similar, shortest paths Correct Solution: ``` import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") ########################################################## import math import bisect mod = 998244353 # for _ in range(int(input())): from collections import Counter # sys.setrecursionlimit(10**6) # dp=[[-1 for i in range(n+5)]for j in range(cap+5)] # arr= list(map(int, input().split())) # n,l= map(int, input().split()) # arr= list(map(int, input().split())) # for _ in range(int(input())): # n=int(input()) # for _ in range(int(input())): import bisect from heapq import * from collections import defaultdict,deque n,m=map(int, input().split()) g=[[] for i in range(n+m)] for i in range(n): s=input() for j,x in enumerate(s): if x=="#": g[i].append(n+j) g[n+j].append(i) q=deque([0]) dis=[10**9]*(n+m) dis[0]=0 while q: node=q.popleft() for i in g[node]: if dis[i]>dis[node]+1: dis[i]=dis[node]+1 q.append(i) print(-1 if dis[n-1]==10**9 else dis[n-1]) # ls=list(map(int, input().split())) # d=defaultdict(list) #for _ in range(int(input())): #import math #print(math.factorial(20)//200) # n=int(input()) # n,k= map(int, input().split()) # arr=list(map(int, input().split())) ```
94,655
Provide tags and a correct Python 3 solution for this coding contest problem. "The Chamber of Secrets has been opened again" — this news has spread all around Hogwarts and some of the students have been petrified due to seeing the basilisk. Dumbledore got fired and now Harry is trying to enter the Chamber of Secrets. These aren't good news for Lord Voldemort. The problem is, he doesn't want anybody to be able to enter the chamber. The Dark Lord is going to be busy sucking life out of Ginny. The Chamber of Secrets is an n × m rectangular grid in which some of the cells are columns. A light ray (and a basilisk's gaze) passes through the columns without changing its direction. But with some spell we can make a column magic to reflect the light ray (or the gaze) in all four directions when it receives the ray. This is shown in the figure below. <image> The left light ray passes through a regular column, and the right ray — through the magic column. The basilisk is located at the right side of the lower right cell of the grid and is looking to the left (in the direction of the lower left cell). According to the legend, anyone who meets a basilisk's gaze directly dies immediately. But if someone meets a basilisk's gaze through a column, this person will get petrified. We know that the door to the Chamber is located on the left side of the upper left corner of the grid and anyone who wants to enter will look in the direction of its movement (in the direction of the upper right cell) from that position. <image> This figure illustrates the first sample test. Given the dimensions of the chamber and the location of regular columns, Lord Voldemort has asked you to find the minimum number of columns that we need to make magic so that anyone who wants to enter the chamber would be petrified or just declare that it's impossible to secure the chamber. Input The first line of the input contains two integer numbers n and m (2 ≤ n, m ≤ 1000). Each of the next n lines contains m characters. Each character is either "." or "#" and represents one cell of the Chamber grid. It's "." if the corresponding cell is empty and "#" if it's a regular column. Output Print the minimum number of columns to make magic or -1 if it's impossible to do. Examples Input 3 3 .#. ... .#. Output 2 Input 4 3 ##. ... .#. .#. Output 2 Note The figure above shows the first sample test. In the first sample we should make both columns magic. The dragon figure represents the basilisk and the binoculars represent the person who will enter the Chamber of secrets. The black star shows the place where the person will be petrified. Yellow lines represent basilisk gaze moving through columns. Tags: dfs and similar, shortest paths Correct Solution: ``` from collections import deque from collections import defaultdict n, m = map(int, input().split()) INF = 10 ** 9 visited=defaultdict(int) g = [[] for _ in range(n + m)] # 0..(n-1) -- rows, n..n+m-1 -- columns for i in range(n): s=input() for j,c in enumerate(s): j_v=n+j if(c=="#"): g[i].append(j_v) g[j_v].append(i) q = deque([0]) total_col=0 visited[0]=0 while q: u=q.popleft() visited[u] = visited[u] + 1 for v in g[u]: if(v==n-1): visited[n-1]=visited[u] q.clear() break if(visited[v]==0): visited[v]=visited[u] q.append(v) print(-1 if (visited[n-1]==0) else visited[n-1]) ```
94,656
Provide tags and a correct Python 3 solution for this coding contest problem. "The Chamber of Secrets has been opened again" — this news has spread all around Hogwarts and some of the students have been petrified due to seeing the basilisk. Dumbledore got fired and now Harry is trying to enter the Chamber of Secrets. These aren't good news for Lord Voldemort. The problem is, he doesn't want anybody to be able to enter the chamber. The Dark Lord is going to be busy sucking life out of Ginny. The Chamber of Secrets is an n × m rectangular grid in which some of the cells are columns. A light ray (and a basilisk's gaze) passes through the columns without changing its direction. But with some spell we can make a column magic to reflect the light ray (or the gaze) in all four directions when it receives the ray. This is shown in the figure below. <image> The left light ray passes through a regular column, and the right ray — through the magic column. The basilisk is located at the right side of the lower right cell of the grid and is looking to the left (in the direction of the lower left cell). According to the legend, anyone who meets a basilisk's gaze directly dies immediately. But if someone meets a basilisk's gaze through a column, this person will get petrified. We know that the door to the Chamber is located on the left side of the upper left corner of the grid and anyone who wants to enter will look in the direction of its movement (in the direction of the upper right cell) from that position. <image> This figure illustrates the first sample test. Given the dimensions of the chamber and the location of regular columns, Lord Voldemort has asked you to find the minimum number of columns that we need to make magic so that anyone who wants to enter the chamber would be petrified or just declare that it's impossible to secure the chamber. Input The first line of the input contains two integer numbers n and m (2 ≤ n, m ≤ 1000). Each of the next n lines contains m characters. Each character is either "." or "#" and represents one cell of the Chamber grid. It's "." if the corresponding cell is empty and "#" if it's a regular column. Output Print the minimum number of columns to make magic or -1 if it's impossible to do. Examples Input 3 3 .#. ... .#. Output 2 Input 4 3 ##. ... .#. .#. Output 2 Note The figure above shows the first sample test. In the first sample we should make both columns magic. The dragon figure represents the basilisk and the binoculars represent the person who will enter the Chamber of secrets. The black star shows the place where the person will be petrified. Yellow lines represent basilisk gaze moving through columns. Tags: dfs and similar, shortest paths Correct Solution: ``` n, m = map(int, input().split()) t = [input() for i in range(n)] p = list(zip(*t)) u, v = [True] * n, [True] * m x, u[n - 1], d = [n - 1], False, 0 while x: y = [] for i in x: for j, k in enumerate(t[i]): if k == '#' and v[j]: v[j] = False y.append(j) x = [] for i in y: for j, k in enumerate(p[i]): if k == '#' and u[j]: u[j] = False x.append(j) d += 1 if 0 in x: print(2 * d) break else: print(-1) ```
94,657
Provide tags and a correct Python 3 solution for this coding contest problem. "The Chamber of Secrets has been opened again" — this news has spread all around Hogwarts and some of the students have been petrified due to seeing the basilisk. Dumbledore got fired and now Harry is trying to enter the Chamber of Secrets. These aren't good news for Lord Voldemort. The problem is, he doesn't want anybody to be able to enter the chamber. The Dark Lord is going to be busy sucking life out of Ginny. The Chamber of Secrets is an n × m rectangular grid in which some of the cells are columns. A light ray (and a basilisk's gaze) passes through the columns without changing its direction. But with some spell we can make a column magic to reflect the light ray (or the gaze) in all four directions when it receives the ray. This is shown in the figure below. <image> The left light ray passes through a regular column, and the right ray — through the magic column. The basilisk is located at the right side of the lower right cell of the grid and is looking to the left (in the direction of the lower left cell). According to the legend, anyone who meets a basilisk's gaze directly dies immediately. But if someone meets a basilisk's gaze through a column, this person will get petrified. We know that the door to the Chamber is located on the left side of the upper left corner of the grid and anyone who wants to enter will look in the direction of its movement (in the direction of the upper right cell) from that position. <image> This figure illustrates the first sample test. Given the dimensions of the chamber and the location of regular columns, Lord Voldemort has asked you to find the minimum number of columns that we need to make magic so that anyone who wants to enter the chamber would be petrified or just declare that it's impossible to secure the chamber. Input The first line of the input contains two integer numbers n and m (2 ≤ n, m ≤ 1000). Each of the next n lines contains m characters. Each character is either "." or "#" and represents one cell of the Chamber grid. It's "." if the corresponding cell is empty and "#" if it's a regular column. Output Print the minimum number of columns to make magic or -1 if it's impossible to do. Examples Input 3 3 .#. ... .#. Output 2 Input 4 3 ##. ... .#. .#. Output 2 Note The figure above shows the first sample test. In the first sample we should make both columns magic. The dragon figure represents the basilisk and the binoculars represent the person who will enter the Chamber of secrets. The black star shows the place where the person will be petrified. Yellow lines represent basilisk gaze moving through columns. Tags: dfs and similar, shortest paths Correct Solution: ``` from collections import deque n, m = map(int, input().split()) INF = 10 ** 9 g = [[] for _ in range(n + m)] # 0..(n-1) -- rows, n..n+m-1 -- columns for i in range(n): s = input() for j, c in enumerate(s): j_v = n + j if c == '#': g[i].append(j_v) g[j_v].append(i) q = deque([0]) dist = [INF for _ in range(n + m)] dist[0] = 0 while q: u = q.popleft() for v in g[u]: n_dist_v = dist[u] + 1 if n_dist_v < dist[v]: dist[v] = n_dist_v q.append(v) print(-1 if dist[n - 1] == INF else dist[n - 1]) ```
94,658
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. "The Chamber of Secrets has been opened again" — this news has spread all around Hogwarts and some of the students have been petrified due to seeing the basilisk. Dumbledore got fired and now Harry is trying to enter the Chamber of Secrets. These aren't good news for Lord Voldemort. The problem is, he doesn't want anybody to be able to enter the chamber. The Dark Lord is going to be busy sucking life out of Ginny. The Chamber of Secrets is an n × m rectangular grid in which some of the cells are columns. A light ray (and a basilisk's gaze) passes through the columns without changing its direction. But with some spell we can make a column magic to reflect the light ray (or the gaze) in all four directions when it receives the ray. This is shown in the figure below. <image> The left light ray passes through a regular column, and the right ray — through the magic column. The basilisk is located at the right side of the lower right cell of the grid and is looking to the left (in the direction of the lower left cell). According to the legend, anyone who meets a basilisk's gaze directly dies immediately. But if someone meets a basilisk's gaze through a column, this person will get petrified. We know that the door to the Chamber is located on the left side of the upper left corner of the grid and anyone who wants to enter will look in the direction of its movement (in the direction of the upper right cell) from that position. <image> This figure illustrates the first sample test. Given the dimensions of the chamber and the location of regular columns, Lord Voldemort has asked you to find the minimum number of columns that we need to make magic so that anyone who wants to enter the chamber would be petrified or just declare that it's impossible to secure the chamber. Input The first line of the input contains two integer numbers n and m (2 ≤ n, m ≤ 1000). Each of the next n lines contains m characters. Each character is either "." or "#" and represents one cell of the Chamber grid. It's "." if the corresponding cell is empty and "#" if it's a regular column. Output Print the minimum number of columns to make magic or -1 if it's impossible to do. Examples Input 3 3 .#. ... .#. Output 2 Input 4 3 ##. ... .#. .#. Output 2 Note The figure above shows the first sample test. In the first sample we should make both columns magic. The dragon figure represents the basilisk and the binoculars represent the person who will enter the Chamber of secrets. The black star shows the place where the person will be petrified. Yellow lines represent basilisk gaze moving through columns. Submitted Solution: ``` from collections import deque inf = 1000000000000 tmp = list(map(int, input().split(' ')[:2])) n = tmp[0] m = tmp[1] graph = [[]for _ in range(n)] for i in range(n): tmp = input() graph[i] = tmp used = [False]*(n + m) finalGraph = [[] for _ in range(n + m)] for i in range(n): for j in range(m): #print(graph[i][j]) if graph[i][j] == '#': #print(i, " ", j + n) finalGraph[i].append(j + n) finalGraph[n + j].append(i) #print(finalGraph, " final graph") d = deque() d.append(n - 1) weight = [] for _ in range(n + m): weight.append(inf) weight[n - 1] = 0 while d: cur = d.pop() for check in finalGraph[cur]: if not used[check]: used[check] = True weight[check] = weight[cur] + 1 d.append(check) if weight[0] == inf: print(-1) else : print(weight[0]) ``` No
94,659
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. "The Chamber of Secrets has been opened again" — this news has spread all around Hogwarts and some of the students have been petrified due to seeing the basilisk. Dumbledore got fired and now Harry is trying to enter the Chamber of Secrets. These aren't good news for Lord Voldemort. The problem is, he doesn't want anybody to be able to enter the chamber. The Dark Lord is going to be busy sucking life out of Ginny. The Chamber of Secrets is an n × m rectangular grid in which some of the cells are columns. A light ray (and a basilisk's gaze) passes through the columns without changing its direction. But with some spell we can make a column magic to reflect the light ray (or the gaze) in all four directions when it receives the ray. This is shown in the figure below. <image> The left light ray passes through a regular column, and the right ray — through the magic column. The basilisk is located at the right side of the lower right cell of the grid and is looking to the left (in the direction of the lower left cell). According to the legend, anyone who meets a basilisk's gaze directly dies immediately. But if someone meets a basilisk's gaze through a column, this person will get petrified. We know that the door to the Chamber is located on the left side of the upper left corner of the grid and anyone who wants to enter will look in the direction of its movement (in the direction of the upper right cell) from that position. <image> This figure illustrates the first sample test. Given the dimensions of the chamber and the location of regular columns, Lord Voldemort has asked you to find the minimum number of columns that we need to make magic so that anyone who wants to enter the chamber would be petrified or just declare that it's impossible to secure the chamber. Input The first line of the input contains two integer numbers n and m (2 ≤ n, m ≤ 1000). Each of the next n lines contains m characters. Each character is either "." or "#" and represents one cell of the Chamber grid. It's "." if the corresponding cell is empty and "#" if it's a regular column. Output Print the minimum number of columns to make magic or -1 if it's impossible to do. Examples Input 3 3 .#. ... .#. Output 2 Input 4 3 ##. ... .#. .#. Output 2 Note The figure above shows the first sample test. In the first sample we should make both columns magic. The dragon figure represents the basilisk and the binoculars represent the person who will enter the Chamber of secrets. The black star shows the place where the person will be petrified. Yellow lines represent basilisk gaze moving through columns. Submitted Solution: ``` n, m = map(int, input().split()) first = set() firstStatus = 0 lastStatus = 0 curr_intersection = set() last = set() row = [] intersections=[] i = 0 intersectPoint = 0 for elem in (input()): if (elem == "#"): first.add(i) firstStatus = 1 i += 1 intersections.append(set()) row.append(first.copy()) for a in range(n - 1): i = 0 lastStatus = 0 last.clear() for elem in (input()): if (elem == "#"): last.add(i) i=i+1 j=0 if(last!=set()): lastStatus=0 row.append(last.copy()) for i in range(len(row) - 1): curr_intersection = row[len(row) - i - 2].intersection(row[len(row) - 1]) if (curr_intersection == set()): j = j + 1 lastStatus = 0 row.pop() else: lastStatus = 1 break intersections.append(curr_intersection.copy()) if(intersections[len(intersections) - j - 2] == set() and len(intersections)!=2): lastStatus=0 if(lastStatus==1): if (intersections[len(intersections)-j-2].intersection(intersections[len(intersections)-1]) == set() ): intersectPoint = intersectPoint + 2-j if (firstStatus == 0 or lastStatus == 0): print(-1) else: print(intersectPoint) ``` No
94,660
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. "The Chamber of Secrets has been opened again" — this news has spread all around Hogwarts and some of the students have been petrified due to seeing the basilisk. Dumbledore got fired and now Harry is trying to enter the Chamber of Secrets. These aren't good news for Lord Voldemort. The problem is, he doesn't want anybody to be able to enter the chamber. The Dark Lord is going to be busy sucking life out of Ginny. The Chamber of Secrets is an n × m rectangular grid in which some of the cells are columns. A light ray (and a basilisk's gaze) passes through the columns without changing its direction. But with some spell we can make a column magic to reflect the light ray (or the gaze) in all four directions when it receives the ray. This is shown in the figure below. <image> The left light ray passes through a regular column, and the right ray — through the magic column. The basilisk is located at the right side of the lower right cell of the grid and is looking to the left (in the direction of the lower left cell). According to the legend, anyone who meets a basilisk's gaze directly dies immediately. But if someone meets a basilisk's gaze through a column, this person will get petrified. We know that the door to the Chamber is located on the left side of the upper left corner of the grid and anyone who wants to enter will look in the direction of its movement (in the direction of the upper right cell) from that position. <image> This figure illustrates the first sample test. Given the dimensions of the chamber and the location of regular columns, Lord Voldemort has asked you to find the minimum number of columns that we need to make magic so that anyone who wants to enter the chamber would be petrified or just declare that it's impossible to secure the chamber. Input The first line of the input contains two integer numbers n and m (2 ≤ n, m ≤ 1000). Each of the next n lines contains m characters. Each character is either "." or "#" and represents one cell of the Chamber grid. It's "." if the corresponding cell is empty and "#" if it's a regular column. Output Print the minimum number of columns to make magic or -1 if it's impossible to do. Examples Input 3 3 .#. ... .#. Output 2 Input 4 3 ##. ... .#. .#. Output 2 Note The figure above shows the first sample test. In the first sample we should make both columns magic. The dragon figure represents the basilisk and the binoculars represent the person who will enter the Chamber of secrets. The black star shows the place where the person will be petrified. Yellow lines represent basilisk gaze moving through columns. Submitted Solution: ``` n, m = map(int, input().split()) first = set() firstStatus = 0 lastStatus = 0 curr_intersection = set() last = set() row = [] intersections=[] i = 0 intersectPoint = 0 for elem in (input()): if (elem == "#"): first.add(i) firstStatus = 1 i += 1 intersections.append(set()) row.append(first.copy()) for a in range(n - 1): i = 0 lastStatus = 0 last.clear() for elem in (input()): if (elem == "#"): last.add(i) i=i+1 j=0 if(last!=set()): lastStatus=0 row.append(last.copy()) for i in range(len(row) - 1): curr_intersection = row[len(row) - i - 2].intersection(row[len(row) - 1]) if (curr_intersection == set()): j = j + 1 lastStatus = 0 else: lastStatus = 1 break intersections.append(curr_intersection.copy()) if(lastStatus==1): if (intersections[len(intersections)-j-2].intersection(intersections[len(intersections)-1]) == set()): intersectPoint = intersectPoint + 2-j if (firstStatus == 0 or lastStatus == 0): print(-1) else: print(intersectPoint) ``` No
94,661
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. "The Chamber of Secrets has been opened again" — this news has spread all around Hogwarts and some of the students have been petrified due to seeing the basilisk. Dumbledore got fired and now Harry is trying to enter the Chamber of Secrets. These aren't good news for Lord Voldemort. The problem is, he doesn't want anybody to be able to enter the chamber. The Dark Lord is going to be busy sucking life out of Ginny. The Chamber of Secrets is an n × m rectangular grid in which some of the cells are columns. A light ray (and a basilisk's gaze) passes through the columns without changing its direction. But with some spell we can make a column magic to reflect the light ray (or the gaze) in all four directions when it receives the ray. This is shown in the figure below. <image> The left light ray passes through a regular column, and the right ray — through the magic column. The basilisk is located at the right side of the lower right cell of the grid and is looking to the left (in the direction of the lower left cell). According to the legend, anyone who meets a basilisk's gaze directly dies immediately. But if someone meets a basilisk's gaze through a column, this person will get petrified. We know that the door to the Chamber is located on the left side of the upper left corner of the grid and anyone who wants to enter will look in the direction of its movement (in the direction of the upper right cell) from that position. <image> This figure illustrates the first sample test. Given the dimensions of the chamber and the location of regular columns, Lord Voldemort has asked you to find the minimum number of columns that we need to make magic so that anyone who wants to enter the chamber would be petrified or just declare that it's impossible to secure the chamber. Input The first line of the input contains two integer numbers n and m (2 ≤ n, m ≤ 1000). Each of the next n lines contains m characters. Each character is either "." or "#" and represents one cell of the Chamber grid. It's "." if the corresponding cell is empty and "#" if it's a regular column. Output Print the minimum number of columns to make magic or -1 if it's impossible to do. Examples Input 3 3 .#. ... .#. Output 2 Input 4 3 ##. ... .#. .#. Output 2 Note The figure above shows the first sample test. In the first sample we should make both columns magic. The dragon figure represents the basilisk and the binoculars represent the person who will enter the Chamber of secrets. The black star shows the place where the person will be petrified. Yellow lines represent basilisk gaze moving through columns. Submitted Solution: ``` from collections import deque inf = 1000000000000 tmp = list(map(int, input().split(' ')[:2])) n = tmp[0] m = tmp[1] graph = [[]for _ in range(n)] for i in range(n): tmp = input() graph[i] = tmp used = [False]*(n + m) finalGraph = [[] for _ in range(n + m)] for i in range(n): for j in range(m): #print(graph[i][j]) if graph[i][j] == '#': #print(i, " ", j + n) finalGraph[i].append(j + n) finalGraph[n + j].append(i) #print(finalGraph, " final graph") d = deque() d.append(n - 1) weight = [] for _ in range(n + m): weight.append(inf) #print(weight) weight[n - 1] = 0 end = False while d and not end: cur = d.pop() if not used[cur]: used[cur] = True #print(cur, " cur ") for check in finalGraph[cur]: if not used[check]: #print(check, " check") #used[check] = True if check == 0: end = True weight[check] = weight[cur] + 1 d.append(check) if weight[0] == inf: print(-1) else : print(weight[0]) ``` No
94,662
Provide tags and a correct Python 3 solution for this coding contest problem. Hamming distance between strings a and b of equal length (denoted by h(a, b)) is equal to the number of distinct integers i (1 ≤ i ≤ |a|), such that ai ≠ bi, where ai is the i-th symbol of string a, bi is the i-th symbol of string b. For example, the Hamming distance between strings "aba" and "bba" equals 1, they have different first symbols. For strings "bbba" and "aaab" the Hamming distance equals 4. John Doe had a paper on which four strings of equal length s1, s2, s3 and s4 were written. Each string si consisted only of lowercase letters "a" and "b". John found the Hamming distances between all pairs of strings he had. Then he lost the paper with the strings but he didn't lose the Hamming distances between all pairs. Help John restore the strings; find some four strings s'1, s'2, s'3, s'4 of equal length that consist only of lowercase letters "a" and "b", such that the pairwise Hamming distances between them are the same as between John's strings. More formally, set s'i must satisfy the condition <image>. To make the strings easier to put down on a piece of paper, you should choose among all suitable sets of strings the one that has strings of minimum length. Input The first line contains space-separated integers h(s1, s2), h(s1, s3), h(s1, s4). The second line contains space-separated integers h(s2, s3) and h(s2, s4). The third line contains the single integer h(s3, s4). All given integers h(si, sj) are non-negative and do not exceed 105. It is guaranteed that at least one number h(si, sj) is positive. Output Print -1 if there's no suitable set of strings. Otherwise print on the first line number len — the length of each string. On the i-th of the next four lines print string s'i. If there are multiple sets with the minimum length of the strings, print any of them. Examples Input 4 4 4 4 4 4 Output 6 aaaabb aabbaa bbaaaa bbbbbb Tags: constructive algorithms, greedy, math, matrices Correct Solution: ``` h = [[0 in range(10)] for j in range(10)] for i in range(1, 4): h[i] = [0 for j in range(i + 1)] + list(map(int, input().split())) #for i in range(1, 4): # print(" ".join(map(str, h[i][1:5]))) if (h[1][2] + h[1][3] < h[2][3] or (h[1][2] + h[1][3] - h[2][3]) % 2 == 1): print("-1") exit(0) BB = (h[1][2] + h[1][3] - h[2][3]) // 2 BA = h[1][2] - BB AB = h[1][3] - BB NowB = h[1][4] NowLen = BB + AB + BA Now24 = BA + NowB + BB Now34 = AB + NowB + BB BAB = 0 ABB = 0 BBB = 0 Dif = (BA - AB) - (h[2][4] - h[3][4]) if (abs(Dif) % 2 == 1): print("-1") exit(0) if Dif < 0: ABB += abs(Dif) // 2 Now34 -= ABB * 2 #Now24 += ABB if (AB < ABB or NowB < ABB): print("-1") exit(0) NowB -= ABB else: BAB += Dif // 2 Now24 -= BAB * 2 #Now34 += BAB if (BA < BAB or NowB < BAB): print("-1") exit(0) NowB -= BAB if (Now24 < h[2][4] or (Now24 - h[2][4]) % 2 == 1): print("-1") exit(0) #print(Now34 - h[3][4]) for i in range(BB + 1): if (i > NowB): break Now = i * 2 if (Now > Now24 - h[2][4]): break if min([(NowB - i) // 2, BA - BAB, AB - ABB]) * 2 >= Now24 - h[2][4] - Now: #print(i, Now24, h[2][4], NowB) BBB += i BAB += (Now24 - h[2][4] - Now) // 2 ABB += (Now24 - h[2][4] - Now) // 2 NowB -= i + (Now24 - h[2][4] - Now) print(NowLen + NowB) print("".join(["a" for j in range(NowLen)] + ["a" for j in range(NowB)])) print("".join(["a" for j in range(AB)] + ["b" for j in range(BB + BA)] + ["a" for j in range(NowB)])) print("".join(["b" for j in range(AB + BB)] + ["a" for j in range(BA)] + ["a" for j in range(NowB)])) print("".join(["b" for j in range(ABB)] + ["a" for j in range(AB - ABB)] + ["b" for j in range(BBB)] + ["a" for j in range(BB - BBB)] + ["b" for j in range(BAB)] + ["a" for j in range(BA - BAB)] + ["b" for j in range(NowB)])) exit(0) print("-1") ```
94,663
Provide tags and a correct Python 3 solution for this coding contest problem. Hamming distance between strings a and b of equal length (denoted by h(a, b)) is equal to the number of distinct integers i (1 ≤ i ≤ |a|), such that ai ≠ bi, where ai is the i-th symbol of string a, bi is the i-th symbol of string b. For example, the Hamming distance between strings "aba" and "bba" equals 1, they have different first symbols. For strings "bbba" and "aaab" the Hamming distance equals 4. John Doe had a paper on which four strings of equal length s1, s2, s3 and s4 were written. Each string si consisted only of lowercase letters "a" and "b". John found the Hamming distances between all pairs of strings he had. Then he lost the paper with the strings but he didn't lose the Hamming distances between all pairs. Help John restore the strings; find some four strings s'1, s'2, s'3, s'4 of equal length that consist only of lowercase letters "a" and "b", such that the pairwise Hamming distances between them are the same as between John's strings. More formally, set s'i must satisfy the condition <image>. To make the strings easier to put down on a piece of paper, you should choose among all suitable sets of strings the one that has strings of minimum length. Input The first line contains space-separated integers h(s1, s2), h(s1, s3), h(s1, s4). The second line contains space-separated integers h(s2, s3) and h(s2, s4). The third line contains the single integer h(s3, s4). All given integers h(si, sj) are non-negative and do not exceed 105. It is guaranteed that at least one number h(si, sj) is positive. Output Print -1 if there's no suitable set of strings. Otherwise print on the first line number len — the length of each string. On the i-th of the next four lines print string s'i. If there are multiple sets with the minimum length of the strings, print any of them. Examples Input 4 4 4 4 4 4 Output 6 aaaabb aabbaa bbaaaa bbbbbb Tags: constructive algorithms, greedy, math, matrices Correct Solution: ``` def get_input(): a, b, d = map(int, input().split()) c, e = map(int, input().split()) f = int(input()) return [a, b, c, d, e, f] def check_condition(a, b, c, d, e, f): condition1 = (a + b + c) % 2 == 0 condition2 = (d + e + a) % 2 == 0 condition3 = (e + f + c) % 2 == 0 condition4 = (d + f + b) % 2 == 0 condition = condition1 and condition2 and condition3 and condition4 return condition def find_t(a, b, c, d, e, f): t_min1 = round((d + f - a - c) / 2) t_min2 = round((e + f - a - b) / 2) t_min3 = round((d + e - b - c) / 2) t_min4 = 0 t_min = max(t_min1, t_min2, t_min3, t_min4) t_max1 = round((d + e - a) / 2) t_max2 = round((e + f - c) / 2) t_max3 = round((d + f - b) / 2) t_max = min(t_max1, t_max2, t_max3) if t_min <= t_max: return t_min else: return -1 def find_all(a, b, c, d, e, f, t): x1 = round((a + c - d - f) / 2 + t) x2 = round((d + f - b) / 2 - t) y1 = round((a + b - e - f) / 2 + t) y2 = round((e + f - c) / 2 - t) z1 = round((b + c - d - e) / 2 + t) z2 = round((d + e - a) / 2 - t) return [x1, x2, y1, y2, z1, z2] def generate_string(x1, x2, y1, y2, z1, z2, t): n = x1 + x2 + y1 + y2 + z1 + z2 + t s1 = ''.join(['a'] * n) s2 = ''.join(['a'] * (z1 + z2 + t)) + ''.join(['b'] * (x1 + x2 + y1 + y2)) s3 = ''.join(['a'] * t) + ''.join(['b'] * (y1 + y2 + z1 + z2)) + ''.join(['a'] * (x1 + x2)) s4 = ''.join(['b'] * (t + z2)) + ''.join(['a'] * (z1 + y2)) + ''.join(['b'] * (y1 + x2)) + ''.join(['a'] * x1) return [s1, s2, s3, s4] def __main__(): fail_output = "-1" a, b, c, d, e, f = map(int, get_input()) if not(check_condition(a, b, c, d, e, f)): print(fail_output) return False t = find_t(a, b, c, d, e, f) if t < 0: print(fail_output) return False x1, x2, y1, y2, z1, z2 = map(int, find_all(a, b, c, d, e, f, t)) s1, s2, s3, s4 = map(str, generate_string(x1, x2, y1, y2, z1, z2, t)) print(str(x1 + x2 + y1 + y2 + z1 + z2 + t) + '\n') print(s1 + '\n') print(s2 + '\n') print(s3 + '\n') print(s4 + '\n') __main__() # Made By Mostafa_Khaled ```
94,664
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Hamming distance between strings a and b of equal length (denoted by h(a, b)) is equal to the number of distinct integers i (1 ≤ i ≤ |a|), such that ai ≠ bi, where ai is the i-th symbol of string a, bi is the i-th symbol of string b. For example, the Hamming distance between strings "aba" and "bba" equals 1, they have different first symbols. For strings "bbba" and "aaab" the Hamming distance equals 4. John Doe had a paper on which four strings of equal length s1, s2, s3 and s4 were written. Each string si consisted only of lowercase letters "a" and "b". John found the Hamming distances between all pairs of strings he had. Then he lost the paper with the strings but he didn't lose the Hamming distances between all pairs. Help John restore the strings; find some four strings s'1, s'2, s'3, s'4 of equal length that consist only of lowercase letters "a" and "b", such that the pairwise Hamming distances between them are the same as between John's strings. More formally, set s'i must satisfy the condition <image>. To make the strings easier to put down on a piece of paper, you should choose among all suitable sets of strings the one that has strings of minimum length. Input The first line contains space-separated integers h(s1, s2), h(s1, s3), h(s1, s4). The second line contains space-separated integers h(s2, s3) and h(s2, s4). The third line contains the single integer h(s3, s4). All given integers h(si, sj) are non-negative and do not exceed 105. It is guaranteed that at least one number h(si, sj) is positive. Output Print -1 if there's no suitable set of strings. Otherwise print on the first line number len — the length of each string. On the i-th of the next four lines print string s'i. If there are multiple sets with the minimum length of the strings, print any of them. Examples Input 4 4 4 4 4 4 Output 6 aaaabb aabbaa bbaaaa bbbbbb Submitted Solution: ``` h = [[0 in range(10)] for j in range(10)] for i in range(1, 4): h[i] = [0 for j in range(i + 1)] + list(map(int, input().split())) #for i in range(1, 4): # print(" ".join(map(str, h[i][1:5]))) if (h[1][2] + h[1][3] < h[2][3] or (h[1][2] + h[1][3] - h[2][3]) % 2 == 1): print("-1") exit(0) BB = (h[1][2] + h[1][3] - h[2][3]) // 2 AB = h[1][2] - BB BA = h[1][3] - BB NowB = h[1][4] NowLen = BB + AB + BA Now24 = BA + NowB + BB; Now34 = AB + NowB + BB; BAB = 0 ABB = 0 BBB = 0 Dif = (BA - AB) - (h[2][4] - h[3][4]) if (abs(Dif) % 2 == 1): print("-1") exit(0) if Dif < 0: ABB += abs(Dif) // 2 Now34 -= ABB * 2 #Now24 += ABB if (AB < ABB or NowB < ABB): print("-1") exit(0) NowB -= ABB else: BAB += Dif // 2 Now24 -= BAB * 2 #Now34 += BAB if (BA < BAB or NowB < BAB): print("-1") exit(0) NowB -= BAB if (Now24 < h[2][4] or (Now24 - h[2][4]) % 2 == 1): print("-1") exit(0) #print(Now34 - h[3][4]) for i in range(BB + 1): if (i > NowB): break Now = i * 2 if (Now > Now24 - h[2][4]): break if min([(NowB - i) // 2, BA - BAB, AB - ABB]) * 2 >= Now24 - h[2][4] - Now: #print(i, Now24, h[2][4], NowB) BBB += Now BAB += (Now24 - h[2][4] - Now) // 2 ABB += (Now24 - h[2][4] - Now) // 2 NowB -= i + (Now24 - h[2][4] - Now) print(NowLen + NowB) print("".join(["a" for j in range(NowLen)] + ["a" for j in range(NowB)])) print("".join(["a" for j in range(AB)] + ["b" for j in range(BB + BA)] + ["a" for j in range(NowB)])) print("".join(["b" for j in range(AB + BB)] + ["a" for j in range(BA)] + ["a" for j in range(NowB)])) print("".join(["b" for j in range(ABB)] + ["a" for j in range(AB)[ABB:]] + ["b" for j in range(BBB)] + ["a" for j in range(BB)[BBB:]] + ["b" for j in range(BAB)] + ["a" for j in range(BA)[BAB:]] + ["b" for j in range(NowB)])) exit(0) print("-1") ``` No
94,665
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Hamming distance between strings a and b of equal length (denoted by h(a, b)) is equal to the number of distinct integers i (1 ≤ i ≤ |a|), such that ai ≠ bi, where ai is the i-th symbol of string a, bi is the i-th symbol of string b. For example, the Hamming distance between strings "aba" and "bba" equals 1, they have different first symbols. For strings "bbba" and "aaab" the Hamming distance equals 4. John Doe had a paper on which four strings of equal length s1, s2, s3 and s4 were written. Each string si consisted only of lowercase letters "a" and "b". John found the Hamming distances between all pairs of strings he had. Then he lost the paper with the strings but he didn't lose the Hamming distances between all pairs. Help John restore the strings; find some four strings s'1, s'2, s'3, s'4 of equal length that consist only of lowercase letters "a" and "b", such that the pairwise Hamming distances between them are the same as between John's strings. More formally, set s'i must satisfy the condition <image>. To make the strings easier to put down on a piece of paper, you should choose among all suitable sets of strings the one that has strings of minimum length. Input The first line contains space-separated integers h(s1, s2), h(s1, s3), h(s1, s4). The second line contains space-separated integers h(s2, s3) and h(s2, s4). The third line contains the single integer h(s3, s4). All given integers h(si, sj) are non-negative and do not exceed 105. It is guaranteed that at least one number h(si, sj) is positive. Output Print -1 if there's no suitable set of strings. Otherwise print on the first line number len — the length of each string. On the i-th of the next four lines print string s'i. If there are multiple sets with the minimum length of the strings, print any of them. Examples Input 4 4 4 4 4 4 Output 6 aaaabb aabbaa bbaaaa bbbbbb Submitted Solution: ``` h = [[0 in range(10)] for j in range(10)] for i in range(1, 4): h[i] = [0 for j in range(i + 1)] + list(map(int, input().split())) #for i in range(1, 4): # print(" ".join(map(str, h[i][1:5]))) if (h[1][2] + h[1][3] < h[2][3] or (h[1][2] + h[1][3] - h[2][3]) % 2 == 1): print("-1") exit(0) BB = (h[1][2] + h[1][3] - h[2][3]) // 2 AB = h[1][2] - BB BA = h[1][3] - BB NowB = h[1][4] NowLen = BB + AB + BA Now24 = BA + NowB + BB Now34 = AB + NowB + BB BAB = 0 ABB = 0 BBB = 0 Dif = (BA - AB) - (h[2][4] - h[3][4]) if (abs(Dif) % 2 == 1): print("-1") exit(0) if Dif < 0: ABB += abs(Dif) // 2 Now34 -= ABB * 2 #Now24 += ABB if (AB < ABB or NowB < ABB): print("-1") exit(0) NowB -= ABB else: BAB += Dif // 2 Now24 -= BAB * 2 #Now34 += BAB if (BA < BAB or NowB < BAB): print("-1") exit(0) NowB -= BAB if (Now24 < h[2][4] or (Now24 - h[2][4]) % 2 == 1): print("-1") exit(0) #print(Now34 - h[3][4]) for i in range(BB + 1): if (i > NowB): break Now = i * 2 if (Now > Now24 - h[2][4]): break if min([(NowB - i) // 2, BA - BAB, AB - ABB]) * 2 >= Now24 - h[2][4] - Now: #print(i, Now24, h[2][4], NowB) BBB += i BAB += (Now24 - h[2][4] - Now) // 2 ABB += (Now24 - h[2][4] - Now) // 2 NowB -= i + (Now24 - h[2][4] - Now) print(NowLen + NowB) print("".join(["a" for j in range(NowLen)] + ["a" for j in range(NowB)])) print("".join(["a" for j in range(AB)] + ["b" for j in range(BB + BA)] + ["a" for j in range(NowB)])) print("".join(["b" for j in range(AB + BB)] + ["a" for j in range(BA)] + ["a" for j in range(NowB)])) print("".join(["b" for j in range(ABB)] + ["a" for j in range(AB - ABB)] + ["b" for j in range(BBB)] + ["a" for j in range(BB - BBB)] + ["b" for j in range(BAB)] + ["a" for j in range(BA - BAB)] + ["b" for j in range(NowB)])) exit(0) print("-1") ``` No
94,666
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Hamming distance between strings a and b of equal length (denoted by h(a, b)) is equal to the number of distinct integers i (1 ≤ i ≤ |a|), such that ai ≠ bi, where ai is the i-th symbol of string a, bi is the i-th symbol of string b. For example, the Hamming distance between strings "aba" and "bba" equals 1, they have different first symbols. For strings "bbba" and "aaab" the Hamming distance equals 4. John Doe had a paper on which four strings of equal length s1, s2, s3 and s4 were written. Each string si consisted only of lowercase letters "a" and "b". John found the Hamming distances between all pairs of strings he had. Then he lost the paper with the strings but he didn't lose the Hamming distances between all pairs. Help John restore the strings; find some four strings s'1, s'2, s'3, s'4 of equal length that consist only of lowercase letters "a" and "b", such that the pairwise Hamming distances between them are the same as between John's strings. More formally, set s'i must satisfy the condition <image>. To make the strings easier to put down on a piece of paper, you should choose among all suitable sets of strings the one that has strings of minimum length. Input The first line contains space-separated integers h(s1, s2), h(s1, s3), h(s1, s4). The second line contains space-separated integers h(s2, s3) and h(s2, s4). The third line contains the single integer h(s3, s4). All given integers h(si, sj) are non-negative and do not exceed 105. It is guaranteed that at least one number h(si, sj) is positive. Output Print -1 if there's no suitable set of strings. Otherwise print on the first line number len — the length of each string. On the i-th of the next four lines print string s'i. If there are multiple sets with the minimum length of the strings, print any of them. Examples Input 4 4 4 4 4 4 Output 6 aaaabb aabbaa bbaaaa bbbbbb Submitted Solution: ``` h = [[0 in range(10)] for j in range(10)] for i in range(1, 4): h[i] = [0 for j in range(i + 1)] + list(map(int, input().split())) #for i in range(1, 4): # print(" ".join(map(str, h[i][1:5]))) if (h[1][2] + h[1][3] < h[2][3] or (h[1][2] + h[1][3] - h[2][3]) % 2 == 1): print("-1") exit(0) BB = (h[1][2] + h[1][3] - h[2][3]) // 2 AB = h[1][2] - BB BA = h[1][3] - BB NowB = h[1][4] NowLen = BB + AB + BA Now24 = BA + NowB + BB; Now34 = AB + NowB + BB; BAB = 0 ABB = 0 BBB = 0 Dif = (BA - AB) - (h[2][4] - h[3][4]) if (abs(Dif) % 2 == 1): print("-1") exit(0) if Dif < 0: ABB += abs(Dif) // 2 Now34 -= ABB * 2 #Now24 += ABB if (AB < ABB or NowB < ABB): print("-1") exit(0) NowB -= ABB else: BAB += Dif // 2 Now24 -= BAB * 2 #Now34 += BAB if (BA < BAB or NowB < BAB): print("-1") exit(0) NowB -= BAB if (Now24 < h[2][4] or (Now24 - h[2][4]) % 2 == 1): print("-1") exit(0) #print(Now34 - h[3][4]) for i in range(BB + 1): if (i > NowB): break Now = i * 2 if (Now > Now24 - h[2][4]): break if min([(NowB - i) // 2, BA - BAB, AB - ABB]) * 2 >= Now24 - h[2][4] - Now: #print(i, Now24, h[2][4], NowB) BBB += i BAB += (Now24 - h[2][4] - Now) // 2 ABB += (Now24 - h[2][4] - Now) // 2 NowB -= i + (Now24 - h[2][4] - Now) print(NowLen + NowB) print("".join(["a" for j in range(NowLen)] + ["a" for j in range(NowB)])) print("".join(["a" for j in range(AB)] + ["b" for j in range(BB + BA)] + ["a" for j in range(NowB)])) print("".join(["b" for j in range(AB + BB)] + ["a" for j in range(BA)] + ["a" for j in range(NowB)])) print("".join(["b" for j in range(ABB)] + ["a" for j in range(AB)[ABB:]] + ["b" for j in range(BBB)] + ["a" for j in range(BB)[BBB:]] + ["b" for j in range(BAB)] + ["a" for j in range(BA)[BAB:]] + ["b" for j in range(NowB)])) exit(0) print("-1") ``` No
94,667
Provide tags and a correct Python 3 solution for this coding contest problem. There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integer n (1 ≤ n ≤ 50) — the number of stones on the table. The next line contains string s, which represents the colors of the stones. We'll consider the stones in the row numbered from 1 to n from left to right. Then the i-th character s equals "R", if the i-th stone is red, "G", if it's green and "B", if it's blue. Output Print a single integer — the answer to the problem. Examples Input 3 RRG Output 1 Input 5 RRRRR Output 4 Input 4 BRBG Output 0 Tags: implementation Correct Solution: ``` input() s=list(input()) c = 0 for i in range(len(s)-1): if s[i] == s[i+1]: c=c+1 print(c) ```
94,668
Provide tags and a correct Python 3 solution for this coding contest problem. There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integer n (1 ≤ n ≤ 50) — the number of stones on the table. The next line contains string s, which represents the colors of the stones. We'll consider the stones in the row numbered from 1 to n from left to right. Then the i-th character s equals "R", if the i-th stone is red, "G", if it's green and "B", if it's blue. Output Print a single integer — the answer to the problem. Examples Input 3 RRG Output 1 Input 5 RRRRR Output 4 Input 4 BRBG Output 0 Tags: implementation Correct Solution: ``` n = input() s = input() a = 0 p = 'C' for letter in s: if letter == p: a +=1 else: p = letter print(a) ```
94,669
Provide tags and a correct Python 3 solution for this coding contest problem. There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integer n (1 ≤ n ≤ 50) — the number of stones on the table. The next line contains string s, which represents the colors of the stones. We'll consider the stones in the row numbered from 1 to n from left to right. Then the i-th character s equals "R", if the i-th stone is red, "G", if it's green and "B", if it's blue. Output Print a single integer — the answer to the problem. Examples Input 3 RRG Output 1 Input 5 RRRRR Output 4 Input 4 BRBG Output 0 Tags: implementation Correct Solution: ``` n = int(input()) s = input() ptr1 = 0 ptr2 = 1 cnt = 0 while ptr1 < n and ptr2 < n: while ptr2 < n and s[ptr1] == s[ptr2]: ptr2 += 1 cnt += 1 ptr1 = ptr2 ptr2 += 1 print(cnt) ```
94,670
Provide tags and a correct Python 3 solution for this coding contest problem. There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integer n (1 ≤ n ≤ 50) — the number of stones on the table. The next line contains string s, which represents the colors of the stones. We'll consider the stones in the row numbered from 1 to n from left to right. Then the i-th character s equals "R", if the i-th stone is red, "G", if it's green and "B", if it's blue. Output Print a single integer — the answer to the problem. Examples Input 3 RRG Output 1 Input 5 RRRRR Output 4 Input 4 BRBG Output 0 Tags: implementation Correct Solution: ``` n=int(input()) k=input() count=0 for i in range(len(k)-1): if k[i]==k[i+1]: count=count+1 print(count) ```
94,671
Provide tags and a correct Python 3 solution for this coding contest problem. There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integer n (1 ≤ n ≤ 50) — the number of stones on the table. The next line contains string s, which represents the colors of the stones. We'll consider the stones in the row numbered from 1 to n from left to right. Then the i-th character s equals "R", if the i-th stone is red, "G", if it's green and "B", if it's blue. Output Print a single integer — the answer to the problem. Examples Input 3 RRG Output 1 Input 5 RRRRR Output 4 Input 4 BRBG Output 0 Tags: implementation Correct Solution: ``` l = int(input()) inp = list(input()) p = inp[0] c = '' n = 0 for i in range(l): if(i==0): continue c=inp[i] if(c==p): n+=1 else: p=c print(n) ```
94,672
Provide tags and a correct Python 3 solution for this coding contest problem. There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integer n (1 ≤ n ≤ 50) — the number of stones on the table. The next line contains string s, which represents the colors of the stones. We'll consider the stones in the row numbered from 1 to n from left to right. Then the i-th character s equals "R", if the i-th stone is red, "G", if it's green and "B", if it's blue. Output Print a single integer — the answer to the problem. Examples Input 3 RRG Output 1 Input 5 RRRRR Output 4 Input 4 BRBG Output 0 Tags: implementation Correct Solution: ``` n=int(input()) f=str(input()) count=0 for i in range(len(f)-1): if(f[i]==f[i+1]): count+=1 print(count) ```
94,673
Provide tags and a correct Python 3 solution for this coding contest problem. There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integer n (1 ≤ n ≤ 50) — the number of stones on the table. The next line contains string s, which represents the colors of the stones. We'll consider the stones in the row numbered from 1 to n from left to right. Then the i-th character s equals "R", if the i-th stone is red, "G", if it's green and "B", if it's blue. Output Print a single integer — the answer to the problem. Examples Input 3 RRG Output 1 Input 5 RRRRR Output 4 Input 4 BRBG Output 0 Tags: implementation Correct Solution: ``` n = int(input()) s = str(input()) current = "P" result = 0 for i in s: if i != current: current = i else: result+=1 print(result) ```
94,674
Provide tags and a correct Python 3 solution for this coding contest problem. There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integer n (1 ≤ n ≤ 50) — the number of stones on the table. The next line contains string s, which represents the colors of the stones. We'll consider the stones in the row numbered from 1 to n from left to right. Then the i-th character s equals "R", if the i-th stone is red, "G", if it's green and "B", if it's blue. Output Print a single integer — the answer to the problem. Examples Input 3 RRG Output 1 Input 5 RRRRR Output 4 Input 4 BRBG Output 0 Tags: implementation Correct Solution: ``` n = int(input()) s = [i for i in input()] count = 0 for i in range(0,n-1): if s[i] == s[i+1]: count += 1 print(count) ```
94,675
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integer n (1 ≤ n ≤ 50) — the number of stones on the table. The next line contains string s, which represents the colors of the stones. We'll consider the stones in the row numbered from 1 to n from left to right. Then the i-th character s equals "R", if the i-th stone is red, "G", if it's green and "B", if it's blue. Output Print a single integer — the answer to the problem. Examples Input 3 RRG Output 1 Input 5 RRRRR Output 4 Input 4 BRBG Output 0 Submitted Solution: ``` u=int(input()) k=input() c=0 for i in range(len(k)-1): if(k[i]==k[i+1]): c+=1 print(c) ``` Yes
94,676
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integer n (1 ≤ n ≤ 50) — the number of stones on the table. The next line contains string s, which represents the colors of the stones. We'll consider the stones in the row numbered from 1 to n from left to right. Then the i-th character s equals "R", if the i-th stone is red, "G", if it's green and "B", if it's blue. Output Print a single integer — the answer to the problem. Examples Input 3 RRG Output 1 Input 5 RRRRR Output 4 Input 4 BRBG Output 0 Submitted Solution: ``` n=int(input()) s=input() cnt=0 for i in range(n-1): if s[i]==s[i+1]: cnt+=1 print(cnt) ``` Yes
94,677
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integer n (1 ≤ n ≤ 50) — the number of stones on the table. The next line contains string s, which represents the colors of the stones. We'll consider the stones in the row numbered from 1 to n from left to right. Then the i-th character s equals "R", if the i-th stone is red, "G", if it's green and "B", if it's blue. Output Print a single integer — the answer to the problem. Examples Input 3 RRG Output 1 Input 5 RRRRR Output 4 Input 4 BRBG Output 0 Submitted Solution: ``` n = int(input()) m = input() s = 0 for i in range(n-1): if m[i] == m[i+1]: s += 1 print(s) ``` Yes
94,678
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integer n (1 ≤ n ≤ 50) — the number of stones on the table. The next line contains string s, which represents the colors of the stones. We'll consider the stones in the row numbered from 1 to n from left to right. Then the i-th character s equals "R", if the i-th stone is red, "G", if it's green and "B", if it's blue. Output Print a single integer — the answer to the problem. Examples Input 3 RRG Output 1 Input 5 RRRRR Output 4 Input 4 BRBG Output 0 Submitted Solution: ``` n = input() ent = input() lista = [] for e in ent: lista.append(e) cont = 0 for i in range(len(lista)-1, 0, -1): if lista[i] == lista[i-1]: cont+= 1 print(cont) ``` Yes
94,679
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integer n (1 ≤ n ≤ 50) — the number of stones on the table. The next line contains string s, which represents the colors of the stones. We'll consider the stones in the row numbered from 1 to n from left to right. Then the i-th character s equals "R", if the i-th stone is red, "G", if it's green and "B", if it's blue. Output Print a single integer — the answer to the problem. Examples Input 3 RRG Output 1 Input 5 RRRRR Output 4 Input 4 BRBG Output 0 Submitted Solution: ``` n=int(input()) m=input() a=[] r,b,g=0,0,0 for i in m: if(i=="R"): r=r+1 b=0 g=0 if(r>1): a.append(r) elif(i=="B"): b=b+1 r=0 g=0 if(b>1): a.append(b) else: g=g+1 r=0 g=0 if(g>1): a.append(g) if(len(a)>0): print(max(a)-1) else: print("0") ``` No
94,680
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integer n (1 ≤ n ≤ 50) — the number of stones on the table. The next line contains string s, which represents the colors of the stones. We'll consider the stones in the row numbered from 1 to n from left to right. Then the i-th character s equals "R", if the i-th stone is red, "G", if it's green and "B", if it's blue. Output Print a single integer — the answer to the problem. Examples Input 3 RRG Output 1 Input 5 RRRRR Output 4 Input 4 BRBG Output 0 Submitted Solution: ``` n = int(input()) st = input() count = 0 for i in range (1,n): if st[i-1] == st[i]: count +=i print (count ) ``` No
94,681
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integer n (1 ≤ n ≤ 50) — the number of stones on the table. The next line contains string s, which represents the colors of the stones. We'll consider the stones in the row numbered from 1 to n from left to right. Then the i-th character s equals "R", if the i-th stone is red, "G", if it's green and "B", if it's blue. Output Print a single integer — the answer to the problem. Examples Input 3 RRG Output 1 Input 5 RRRRR Output 4 Input 4 BRBG Output 0 Submitted Solution: ``` num = int(input()) string = input() i = 1 while i < len(string): print(string) if string[i] == string[i - 1]: if i != len(string) - 1: string = string[:i] + string[i + 1:] else: string = string[:i] else: i += 1 print(num - len(string)) ``` No
94,682
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integer n (1 ≤ n ≤ 50) — the number of stones on the table. The next line contains string s, which represents the colors of the stones. We'll consider the stones in the row numbered from 1 to n from left to right. Then the i-th character s equals "R", if the i-th stone is red, "G", if it's green and "B", if it's blue. Output Print a single integer — the answer to the problem. Examples Input 3 RRG Output 1 Input 5 RRRRR Output 4 Input 4 BRBG Output 0 Submitted Solution: ``` _=input('') word=input('') ct = 0 ct += word.count('RR') ct += word.count('BB') ct += word.count('GG') print(ct) ``` No
94,683
Provide tags and a correct Python 3 solution for this coding contest problem. Robot Bender decided to make Fray a birthday present. He drove n nails and numbered them from 1 to n in some order. Bender decided to make a picture using metal rods. The picture is a closed polyline, which vertices should be nails (in the given order). The segments of the polyline should be parallel to the coordinate axes. Polyline is allowed to have self-intersections. Bender can take a rod and fold it exactly once in any place to form an angle of 90 degrees. Then he can attach the place of the fold to some unoccupied nail and attach two ends of this rod to adjacent nails. A nail is considered unoccupied if there is no rod attached to it (neither by it's end nor the by the fold place). No rod could be used twice. It is not required to use all the rods. Help Bender to solve this difficult task. Input The first line contains two positive integers n and m (4 ≤ n ≤ 500, 2 ≤ m ≤ 500, n is even) — the amount of nails and the amount of rods. i-th of the following n lines contains a pair of integers, denoting the coordinates of the i-th nail. Nails should be connected in the same order as they are given in the input. The last line contains m integers — the lenghts of the rods. All coordinates do not exceed 104 by absolute value. Lengths of the rods are between 1 and 200 000. No rod can be used twice. It is guaranteed that all segments of the given polyline are parallel to coordinate axes. No three consecutive nails lie on the same line. Output If it is impossible to solve Bender's problem, output NO. Otherwise, output YES in the first line, and in the second line output n numbers — i-th of them should be the number of rod, which fold place is attached to the i-th nail, or -1, if there is no such rod. If there are multiple solutions, print any of them. Examples Input 4 2 0 0 0 2 2 2 2 0 4 4 Output YES 1 -1 2 -1 Input 6 3 0 0 1 0 1 1 2 1 2 2 0 2 3 2 3 Output YES 1 -1 2 -1 3 -1 Input 6 3 0 0 1 0 1 1 2 1 2 2 0 2 2 2 3 Output NO Tags: implementation Correct Solution: ``` from collections import defaultdict n, m = map(int, input().split()) a, b = map(int, input().split()) x, y = a, b s = [0] * n for i in range(n - 1): u, v = map(int, input().split()) if u == a: s[i], b = abs(v - b), v else: s[i], a = abs(u - a), u s[n - 1] = abs(a - x) + abs(b - y) a, b = defaultdict(list), defaultdict(list) for i, j in enumerate(map(int, input().split()), 1): a[j].append(i) for j in a: b[j] = a[j][: ] q = [] for i in range(0, n, 2): j = s[i] + s[i + 1] if not a[j]: break q.append(str(a[j].pop())) if 2 * len(q) == n: print('YES\n-1 ' + ' -1 '.join(q)) else: q = [] for i in range(0, n, 2): j = s[i] + s[i - 1] if not b[j]: break q.append(str(b[j].pop())) if 2 * len(q) == n: print('YES\n' + ' -1 '.join(q) + ' -1') else: print('NO') ```
94,684
Provide tags and a correct Python 3 solution for this coding contest problem. Robot Bender decided to make Fray a birthday present. He drove n nails and numbered them from 1 to n in some order. Bender decided to make a picture using metal rods. The picture is a closed polyline, which vertices should be nails (in the given order). The segments of the polyline should be parallel to the coordinate axes. Polyline is allowed to have self-intersections. Bender can take a rod and fold it exactly once in any place to form an angle of 90 degrees. Then he can attach the place of the fold to some unoccupied nail and attach two ends of this rod to adjacent nails. A nail is considered unoccupied if there is no rod attached to it (neither by it's end nor the by the fold place). No rod could be used twice. It is not required to use all the rods. Help Bender to solve this difficult task. Input The first line contains two positive integers n and m (4 ≤ n ≤ 500, 2 ≤ m ≤ 500, n is even) — the amount of nails and the amount of rods. i-th of the following n lines contains a pair of integers, denoting the coordinates of the i-th nail. Nails should be connected in the same order as they are given in the input. The last line contains m integers — the lenghts of the rods. All coordinates do not exceed 104 by absolute value. Lengths of the rods are between 1 and 200 000. No rod can be used twice. It is guaranteed that all segments of the given polyline are parallel to coordinate axes. No three consecutive nails lie on the same line. Output If it is impossible to solve Bender's problem, output NO. Otherwise, output YES in the first line, and in the second line output n numbers — i-th of them should be the number of rod, which fold place is attached to the i-th nail, or -1, if there is no such rod. If there are multiple solutions, print any of them. Examples Input 4 2 0 0 0 2 2 2 2 0 4 4 Output YES 1 -1 2 -1 Input 6 3 0 0 1 0 1 1 2 1 2 2 0 2 3 2 3 Output YES 1 -1 2 -1 3 -1 Input 6 3 0 0 1 0 1 1 2 1 2 2 0 2 2 2 3 Output NO Tags: implementation Correct Solution: ``` from collections import defaultdict n, m = map(int, input().split()) tmp = list(tuple(map(int, input().split())) for _ in range(n)) nails = [abs(a - c) + abs(b - d) for (a, b), (c, d) in zip(tmp, tmp[2:] + tmp[:2])] segments = defaultdict(list) for i, s in enumerate(map(int, input().split()), 1): segments[s].append(i) for shift in -1, 0: res = [-1] * n for nailidx in range(shift, n + shift, 2): nail = nails[nailidx] if nail in segments and segments[nail]: res[(nailidx + 1) % n] = segments[nail].pop() else: break else: print("YES") print(" ".join(map(str, res))) exit(0) print("NO") ```
94,685
Provide tags and a correct Python 3 solution for this coding contest problem. Robot Bender decided to make Fray a birthday present. He drove n nails and numbered them from 1 to n in some order. Bender decided to make a picture using metal rods. The picture is a closed polyline, which vertices should be nails (in the given order). The segments of the polyline should be parallel to the coordinate axes. Polyline is allowed to have self-intersections. Bender can take a rod and fold it exactly once in any place to form an angle of 90 degrees. Then he can attach the place of the fold to some unoccupied nail and attach two ends of this rod to adjacent nails. A nail is considered unoccupied if there is no rod attached to it (neither by it's end nor the by the fold place). No rod could be used twice. It is not required to use all the rods. Help Bender to solve this difficult task. Input The first line contains two positive integers n and m (4 ≤ n ≤ 500, 2 ≤ m ≤ 500, n is even) — the amount of nails and the amount of rods. i-th of the following n lines contains a pair of integers, denoting the coordinates of the i-th nail. Nails should be connected in the same order as they are given in the input. The last line contains m integers — the lenghts of the rods. All coordinates do not exceed 104 by absolute value. Lengths of the rods are between 1 and 200 000. No rod can be used twice. It is guaranteed that all segments of the given polyline are parallel to coordinate axes. No three consecutive nails lie on the same line. Output If it is impossible to solve Bender's problem, output NO. Otherwise, output YES in the first line, and in the second line output n numbers — i-th of them should be the number of rod, which fold place is attached to the i-th nail, or -1, if there is no such rod. If there are multiple solutions, print any of them. Examples Input 4 2 0 0 0 2 2 2 2 0 4 4 Output YES 1 -1 2 -1 Input 6 3 0 0 1 0 1 1 2 1 2 2 0 2 3 2 3 Output YES 1 -1 2 -1 3 -1 Input 6 3 0 0 1 0 1 1 2 1 2 2 0 2 2 2 3 Output NO Tags: implementation Correct Solution: ``` #Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction import collections from itertools import permutations from collections import defaultdict from collections import deque import threading BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #-------------------game starts now----------------------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD #------------------------------------------------------------------------- def dist(a, b): return abs(a[0] - b[0]) + abs(a[1] - b[1]) def get_sorted_required_pruts(dists): res = [dists[i * 2] + dists[i * 2 + 1] for i in range(len(dists) // 2)] res = [(i, x) for i, x in enumerate(res)] return sorted(res, key=lambda x: x[1]) def get_answer(pruts, required_pruts): i = 0 j = 0 answer = "YES" seq = [] while i < len(required_pruts): if j == len(pruts): answer = "NO" return answer, None if pruts[j][1] > required_pruts[i][1]: answer = "NO" return answer, None if pruts[j][1] < required_pruts[i][1]: j += 1 else: seq.append((required_pruts[i][0], pruts[j][0] + 1)) i += 1 j += 1 return answer, [x[1] for x in sorted(seq)] n, m = map(int,input().split()) gvozdi = [None] * n for i in range(n): gvozdi[i] = list(map(int,input().split())) pruts = list(map(int,input().split())) pruts = [(i, p) for i, p in enumerate(pruts)] pruts = sorted(pruts, key=lambda x: x[1]) dists = [dist(gvozdi[i], gvozdi[i + 1]) for i in range(len(gvozdi) - 1)] dists.append(dist(gvozdi[0], gvozdi[-1])) even_required_pruts = get_sorted_required_pruts(dists) # print(dists[-1:] + dists[:-1]) odd_required_pruts = get_sorted_required_pruts(dists[-1:] + dists[:-1]) even_answer, even_seq = get_answer(pruts, even_required_pruts) odd_answer, odd_seq = get_answer(pruts, odd_required_pruts) if even_answer == "NO" and odd_answer == "NO": print("NO") elif even_answer == "YES": print("YES") even_seq = [even_seq[i // 2] if i % 2 == 1 else -1 for i in range(n)] print(" ".join(map(str, even_seq))) else: print("YES") # print(odd_seq) odd_seq = [odd_seq[i // 2] if i % 2 == 0 else -1 for i in range(n)] print(" ".join(map(str, odd_seq))) ```
94,686
Provide tags and a correct Python 3 solution for this coding contest problem. Robot Bender decided to make Fray a birthday present. He drove n nails and numbered them from 1 to n in some order. Bender decided to make a picture using metal rods. The picture is a closed polyline, which vertices should be nails (in the given order). The segments of the polyline should be parallel to the coordinate axes. Polyline is allowed to have self-intersections. Bender can take a rod and fold it exactly once in any place to form an angle of 90 degrees. Then he can attach the place of the fold to some unoccupied nail and attach two ends of this rod to adjacent nails. A nail is considered unoccupied if there is no rod attached to it (neither by it's end nor the by the fold place). No rod could be used twice. It is not required to use all the rods. Help Bender to solve this difficult task. Input The first line contains two positive integers n and m (4 ≤ n ≤ 500, 2 ≤ m ≤ 500, n is even) — the amount of nails and the amount of rods. i-th of the following n lines contains a pair of integers, denoting the coordinates of the i-th nail. Nails should be connected in the same order as they are given in the input. The last line contains m integers — the lenghts of the rods. All coordinates do not exceed 104 by absolute value. Lengths of the rods are between 1 and 200 000. No rod can be used twice. It is guaranteed that all segments of the given polyline are parallel to coordinate axes. No three consecutive nails lie on the same line. Output If it is impossible to solve Bender's problem, output NO. Otherwise, output YES in the first line, and in the second line output n numbers — i-th of them should be the number of rod, which fold place is attached to the i-th nail, or -1, if there is no such rod. If there are multiple solutions, print any of them. Examples Input 4 2 0 0 0 2 2 2 2 0 4 4 Output YES 1 -1 2 -1 Input 6 3 0 0 1 0 1 1 2 1 2 2 0 2 3 2 3 Output YES 1 -1 2 -1 3 -1 Input 6 3 0 0 1 0 1 1 2 1 2 2 0 2 2 2 3 Output NO Tags: implementation Correct Solution: ``` def dist(a, b): return abs(a[0] - b[0]) + abs(a[1] - b[1]) def get_sorted_required_pruts(dists): res = [dists[i * 2] + dists[i * 2 + 1] for i in range(len(dists) // 2)] res = [(i, x) for i, x in enumerate(res)] return sorted(res, key=lambda x: x[1]) def get_answer(pruts, required_pruts): i = 0 j = 0 answer = "YES" seq = [] while i < len(required_pruts): if j == len(pruts): answer = "NO" return answer, None if pruts[j][1] > required_pruts[i][1]: answer = "NO" return answer, None if pruts[j][1] < required_pruts[i][1]: j += 1 else: seq.append((required_pruts[i][0], pruts[j][0] + 1)) i += 1 j += 1 return answer, [x[1] for x in sorted(seq)] n, m = map(int,input().split()) gvozdi = [None] * n for i in range(n): gvozdi[i] = list(map(int,input().split())) pruts = list(map(int,input().split())) pruts = [(i, p) for i, p in enumerate(pruts)] pruts = sorted(pruts, key=lambda x: x[1]) dists = [dist(gvozdi[i], gvozdi[i + 1]) for i in range(len(gvozdi) - 1)] dists.append(dist(gvozdi[0], gvozdi[-1])) even_required_pruts = get_sorted_required_pruts(dists) # print(dists[-1:] + dists[:-1]) odd_required_pruts = get_sorted_required_pruts(dists[-1:] + dists[:-1]) even_answer, even_seq = get_answer(pruts, even_required_pruts) odd_answer, odd_seq = get_answer(pruts, odd_required_pruts) if even_answer == "NO" and odd_answer == "NO": print("NO") elif even_answer == "YES": print("YES") even_seq = [even_seq[i // 2] if i % 2 == 1 else -1 for i in range(n)] print(" ".join(map(str, even_seq))) else: print("YES") # print(odd_seq) odd_seq = [odd_seq[i // 2] if i % 2 == 0 else -1 for i in range(n)] print(" ".join(map(str, odd_seq))) ```
94,687
Provide tags and a correct Python 3 solution for this coding contest problem. Robot Bender decided to make Fray a birthday present. He drove n nails and numbered them from 1 to n in some order. Bender decided to make a picture using metal rods. The picture is a closed polyline, which vertices should be nails (in the given order). The segments of the polyline should be parallel to the coordinate axes. Polyline is allowed to have self-intersections. Bender can take a rod and fold it exactly once in any place to form an angle of 90 degrees. Then he can attach the place of the fold to some unoccupied nail and attach two ends of this rod to adjacent nails. A nail is considered unoccupied if there is no rod attached to it (neither by it's end nor the by the fold place). No rod could be used twice. It is not required to use all the rods. Help Bender to solve this difficult task. Input The first line contains two positive integers n and m (4 ≤ n ≤ 500, 2 ≤ m ≤ 500, n is even) — the amount of nails and the amount of rods. i-th of the following n lines contains a pair of integers, denoting the coordinates of the i-th nail. Nails should be connected in the same order as they are given in the input. The last line contains m integers — the lenghts of the rods. All coordinates do not exceed 104 by absolute value. Lengths of the rods are between 1 and 200 000. No rod can be used twice. It is guaranteed that all segments of the given polyline are parallel to coordinate axes. No three consecutive nails lie on the same line. Output If it is impossible to solve Bender's problem, output NO. Otherwise, output YES in the first line, and in the second line output n numbers — i-th of them should be the number of rod, which fold place is attached to the i-th nail, or -1, if there is no such rod. If there are multiple solutions, print any of them. Examples Input 4 2 0 0 0 2 2 2 2 0 4 4 Output YES 1 -1 2 -1 Input 6 3 0 0 1 0 1 1 2 1 2 2 0 2 3 2 3 Output YES 1 -1 2 -1 3 -1 Input 6 3 0 0 1 0 1 1 2 1 2 2 0 2 2 2 3 Output NO Tags: implementation Correct Solution: ``` n,m = map(int,input().split()) s = [] for i in range(n): a = map(int,input().split()) a = list(a) s.append(a) s_chet = [] for i in range(1,n-1,2): #Проход по четным гвоздям q = abs((s[i][0]-s[i-1][0])+(s[i][1]-s[i-1][1])) + abs((s[i][0]-s[i+1][0])+(s[i][1]-s[i+1][1])) s_chet.append((i + 1, q)) q = abs((s[-1][0]-s[-2][0])+(s[-1][1]-s[-2][1])) + abs((s[-1][0]-s[0][0])+(s[-1][1]-s[0][1])) s_chet.append((n, q)) s_nechet = [] for i in range(2,n-1,2): #Проход по нечетным гвоздям q = abs((s[i][0]-s[i-1][0])+(s[i][1]-s[i-1][1])) + abs((s[i][0]-s[i+1][0])+(s[i][1]-s[i+1][1])) s_nechet.append((i + 1, q)) q = abs((s[-1][0]-s[0][0])+(s[-1][1]-s[0][1])) + abs((s[1][0]-s[0][0])+(s[1][1]-s[0][1])) s_nechet.append((1, q)) ss = map(int, input().split()) ss = [[i + 1, ss_i] for i, ss_i in enumerate(ss)] s_chet.sort(key=lambda x: x[1]) s_nechet.sort(key=lambda x: x[1]) ss.sort(key=lambda x: x[1]) prut_chet = [-1] * n chet = True j = 0 for i in range(len(s_chet)): while j < len(ss) and ss[j][1] < s_chet[i][1]: j += 1 if j == len(ss) or ss[j][1] > s_chet[i][1]: chet = False break if s_chet[i][1] == ss[j][1]: prut_chet[s_chet[i][0] - 1] = ss[j][0] j += 1 continue if chet: print('YES') print(" ".join(map(str,prut_chet))) else: prut_nechet = [-1] * n nechet = True j = 0 for i in range(len(s_nechet)): while j < len(ss) and ss[j][1] < s_nechet[i][1]: j += 1 if j == len(ss) or ss[j][1] > s_nechet[i][1]: nechet = False break if s_nechet[i][1] == ss[j][1]: prut_nechet[s_nechet[i][0] - 1] = ss[j][0] j += 1 continue if nechet: print('YES') print(" ".join(map(str, prut_nechet))) else: print('NO') ```
94,688
Provide tags and a correct Python 3 solution for this coding contest problem. Robot Bender decided to make Fray a birthday present. He drove n nails and numbered them from 1 to n in some order. Bender decided to make a picture using metal rods. The picture is a closed polyline, which vertices should be nails (in the given order). The segments of the polyline should be parallel to the coordinate axes. Polyline is allowed to have self-intersections. Bender can take a rod and fold it exactly once in any place to form an angle of 90 degrees. Then he can attach the place of the fold to some unoccupied nail and attach two ends of this rod to adjacent nails. A nail is considered unoccupied if there is no rod attached to it (neither by it's end nor the by the fold place). No rod could be used twice. It is not required to use all the rods. Help Bender to solve this difficult task. Input The first line contains two positive integers n and m (4 ≤ n ≤ 500, 2 ≤ m ≤ 500, n is even) — the amount of nails and the amount of rods. i-th of the following n lines contains a pair of integers, denoting the coordinates of the i-th nail. Nails should be connected in the same order as they are given in the input. The last line contains m integers — the lenghts of the rods. All coordinates do not exceed 104 by absolute value. Lengths of the rods are between 1 and 200 000. No rod can be used twice. It is guaranteed that all segments of the given polyline are parallel to coordinate axes. No three consecutive nails lie on the same line. Output If it is impossible to solve Bender's problem, output NO. Otherwise, output YES in the first line, and in the second line output n numbers — i-th of them should be the number of rod, which fold place is attached to the i-th nail, or -1, if there is no such rod. If there are multiple solutions, print any of them. Examples Input 4 2 0 0 0 2 2 2 2 0 4 4 Output YES 1 -1 2 -1 Input 6 3 0 0 1 0 1 1 2 1 2 2 0 2 3 2 3 Output YES 1 -1 2 -1 3 -1 Input 6 3 0 0 1 0 1 1 2 1 2 2 0 2 2 2 3 Output NO Tags: implementation Correct Solution: ``` import sys n, m = map(int, input().split()) points = [tuple(map(int, input().split())) for i in range(n)] points.append(points.pop(0)) segments = [] x, y = points[-1] for a, b in points: if x == a: segments.append(abs(y - b)) else: segments.append(abs(x - a)) x, y = a, b rods = list(map(int, input().split())) rod_indices = {} for index, rod in enumerate(rods): rod_indices.setdefault(rod, []).append(index+1) for offset in range(2): target_indices = rod_indices.copy() assignment = [-1 for i in range(n)] for i in range(offset, n, 2): target = segments[(i-1)%n] + segments[i] if target not in target_indices or target_indices[target] == []: assignment = None break assignment[i] = target_indices[target].pop() if assignment != None: print('YES') print(' '.join(map(str, assignment))) sys.exit() print('NO') ```
94,689
Provide tags and a correct Python 3 solution for this coding contest problem. Robot Bender decided to make Fray a birthday present. He drove n nails and numbered them from 1 to n in some order. Bender decided to make a picture using metal rods. The picture is a closed polyline, which vertices should be nails (in the given order). The segments of the polyline should be parallel to the coordinate axes. Polyline is allowed to have self-intersections. Bender can take a rod and fold it exactly once in any place to form an angle of 90 degrees. Then he can attach the place of the fold to some unoccupied nail and attach two ends of this rod to adjacent nails. A nail is considered unoccupied if there is no rod attached to it (neither by it's end nor the by the fold place). No rod could be used twice. It is not required to use all the rods. Help Bender to solve this difficult task. Input The first line contains two positive integers n and m (4 ≤ n ≤ 500, 2 ≤ m ≤ 500, n is even) — the amount of nails and the amount of rods. i-th of the following n lines contains a pair of integers, denoting the coordinates of the i-th nail. Nails should be connected in the same order as they are given in the input. The last line contains m integers — the lenghts of the rods. All coordinates do not exceed 104 by absolute value. Lengths of the rods are between 1 and 200 000. No rod can be used twice. It is guaranteed that all segments of the given polyline are parallel to coordinate axes. No three consecutive nails lie on the same line. Output If it is impossible to solve Bender's problem, output NO. Otherwise, output YES in the first line, and in the second line output n numbers — i-th of them should be the number of rod, which fold place is attached to the i-th nail, or -1, if there is no such rod. If there are multiple solutions, print any of them. Examples Input 4 2 0 0 0 2 2 2 2 0 4 4 Output YES 1 -1 2 -1 Input 6 3 0 0 1 0 1 1 2 1 2 2 0 2 3 2 3 Output YES 1 -1 2 -1 3 -1 Input 6 3 0 0 1 0 1 1 2 1 2 2 0 2 2 2 3 Output NO Tags: implementation Correct Solution: ``` from collections import defaultdict def main(): n, m = map(int, input().split()) tmp = list(tuple(map(int, input().split())) for _ in range(n)) nails = [abs(a - c) + abs(b - d) for (a, b), (c, d) in zip(tmp, tmp[2:] + tmp[:2])] segments = defaultdict(list) for i, s in enumerate(map(int, input().split()), 1): segments[s].append(i) for shift in -1, 0: res = [-1] * n for nailidx in range(shift, n + shift, 2): nail = nails[nailidx] if nail in segments and segments[nail]: res[(nailidx + 1) % n] = segments[nail].pop() else: break else: print("YES") print(" ".join(map(str, res))) return print("NO") if __name__ == '__main__': main() ```
94,690
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Robot Bender decided to make Fray a birthday present. He drove n nails and numbered them from 1 to n in some order. Bender decided to make a picture using metal rods. The picture is a closed polyline, which vertices should be nails (in the given order). The segments of the polyline should be parallel to the coordinate axes. Polyline is allowed to have self-intersections. Bender can take a rod and fold it exactly once in any place to form an angle of 90 degrees. Then he can attach the place of the fold to some unoccupied nail and attach two ends of this rod to adjacent nails. A nail is considered unoccupied if there is no rod attached to it (neither by it's end nor the by the fold place). No rod could be used twice. It is not required to use all the rods. Help Bender to solve this difficult task. Input The first line contains two positive integers n and m (4 ≤ n ≤ 500, 2 ≤ m ≤ 500, n is even) — the amount of nails and the amount of rods. i-th of the following n lines contains a pair of integers, denoting the coordinates of the i-th nail. Nails should be connected in the same order as they are given in the input. The last line contains m integers — the lenghts of the rods. All coordinates do not exceed 104 by absolute value. Lengths of the rods are between 1 and 200 000. No rod can be used twice. It is guaranteed that all segments of the given polyline are parallel to coordinate axes. No three consecutive nails lie on the same line. Output If it is impossible to solve Bender's problem, output NO. Otherwise, output YES in the first line, and in the second line output n numbers — i-th of them should be the number of rod, which fold place is attached to the i-th nail, or -1, if there is no such rod. If there are multiple solutions, print any of them. Examples Input 4 2 0 0 0 2 2 2 2 0 4 4 Output YES 1 -1 2 -1 Input 6 3 0 0 1 0 1 1 2 1 2 2 0 2 3 2 3 Output YES 1 -1 2 -1 3 -1 Input 6 3 0 0 1 0 1 1 2 1 2 2 0 2 2 2 3 Output NO Submitted Solution: ``` n,m = map(int,input().split()) s = [] for i in range(n): a = map(int,input().split()) a = list(a) s.append(a) s_chet = [] for i in range(1,n-1,2): #Проход по четным гвоздям q = abs((s[i][0]-s[i-1][0])+(s[i][1]-s[i-1][1])) + abs((s[i][0]-s[i+1][0])+(s[i][1]-s[i+1][1])) s_chet.append(q) q1 = abs((s[-1][0]-s[-2][0])+(s[-1][1]-s[-2][1])) + abs((s[-1][0]-s[0][0])+(s[-1][1]-s[0][1])) s_chet.append(q1) s_ch = s_chet.copy() s_nechet = [] for i in range(2,n-1,2): #Проход по нечетным гвоздям qq = abs((s[i][0]-s[i-1][0])+(s[i][1]-s[i-1][1])) + abs((s[i][0]-s[i+1][0])+(s[i][1]-s[i+1][1])) s_nechet.append(qq) qq1 = abs((s[-1][0]-s[0][0])+(s[-1][1]-s[0][1])) + abs((s[1][0]-s[0][0])+(s[1][1]-s[0][1])) s_nechet.append(qq1) s_n = s_nechet.copy() ss = map(int,input().split()) ss = list(ss) ss1 = ss.copy() ss2 = ss.copy() for i in s_chet: if i in ss1: s_ch.remove(i) ss1.remove(i) if len(s_ch) == 0: print('YES') sss = [] for i in range(m): sss.append(-1) sss.append(i+1) print(" ".join(map(str,sss))) else: for i in s_nechet: if i in ss2: s_n.remove(i) ss2.remove(i) if len(s_n) == 0: print('YES') sss = [] for i in range(m): sss.append(i+1) sss.append(-1) print(" ".join(map(str,sss))) else: print('NO') ``` No
94,691
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Robot Bender decided to make Fray a birthday present. He drove n nails and numbered them from 1 to n in some order. Bender decided to make a picture using metal rods. The picture is a closed polyline, which vertices should be nails (in the given order). The segments of the polyline should be parallel to the coordinate axes. Polyline is allowed to have self-intersections. Bender can take a rod and fold it exactly once in any place to form an angle of 90 degrees. Then he can attach the place of the fold to some unoccupied nail and attach two ends of this rod to adjacent nails. A nail is considered unoccupied if there is no rod attached to it (neither by it's end nor the by the fold place). No rod could be used twice. It is not required to use all the rods. Help Bender to solve this difficult task. Input The first line contains two positive integers n and m (4 ≤ n ≤ 500, 2 ≤ m ≤ 500, n is even) — the amount of nails and the amount of rods. i-th of the following n lines contains a pair of integers, denoting the coordinates of the i-th nail. Nails should be connected in the same order as they are given in the input. The last line contains m integers — the lenghts of the rods. All coordinates do not exceed 104 by absolute value. Lengths of the rods are between 1 and 200 000. No rod can be used twice. It is guaranteed that all segments of the given polyline are parallel to coordinate axes. No three consecutive nails lie on the same line. Output If it is impossible to solve Bender's problem, output NO. Otherwise, output YES in the first line, and in the second line output n numbers — i-th of them should be the number of rod, which fold place is attached to the i-th nail, or -1, if there is no such rod. If there are multiple solutions, print any of them. Examples Input 4 2 0 0 0 2 2 2 2 0 4 4 Output YES 1 -1 2 -1 Input 6 3 0 0 1 0 1 1 2 1 2 2 0 2 3 2 3 Output YES 1 -1 2 -1 3 -1 Input 6 3 0 0 1 0 1 1 2 1 2 2 0 2 2 2 3 Output NO Submitted Solution: ``` n,m = map(int,input().split()) x = 0 y = 0 sx = [] sy = [] for i in range(n): A = map(int,input().split()) A = list(A) if A[0] in sx: sx = sx else: sx.append(A[0]) if A[1] in sy: sy = sy else: sy.append(A[1]) q = 2 * sx[-1] + 2 * sy[-1] ss = map(int,input().split()) ss = list(ss) if sum(ss) >= q: print('YES') ss = [] for i in range(1,m+1): ss.append(i) ss.append(-1) print(" ".join(map(str,ss))) else: print('NO') ``` No
94,692
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Robot Bender decided to make Fray a birthday present. He drove n nails and numbered them from 1 to n in some order. Bender decided to make a picture using metal rods. The picture is a closed polyline, which vertices should be nails (in the given order). The segments of the polyline should be parallel to the coordinate axes. Polyline is allowed to have self-intersections. Bender can take a rod and fold it exactly once in any place to form an angle of 90 degrees. Then he can attach the place of the fold to some unoccupied nail and attach two ends of this rod to adjacent nails. A nail is considered unoccupied if there is no rod attached to it (neither by it's end nor the by the fold place). No rod could be used twice. It is not required to use all the rods. Help Bender to solve this difficult task. Input The first line contains two positive integers n and m (4 ≤ n ≤ 500, 2 ≤ m ≤ 500, n is even) — the amount of nails and the amount of rods. i-th of the following n lines contains a pair of integers, denoting the coordinates of the i-th nail. Nails should be connected in the same order as they are given in the input. The last line contains m integers — the lenghts of the rods. All coordinates do not exceed 104 by absolute value. Lengths of the rods are between 1 and 200 000. No rod can be used twice. It is guaranteed that all segments of the given polyline are parallel to coordinate axes. No three consecutive nails lie on the same line. Output If it is impossible to solve Bender's problem, output NO. Otherwise, output YES in the first line, and in the second line output n numbers — i-th of them should be the number of rod, which fold place is attached to the i-th nail, or -1, if there is no such rod. If there are multiple solutions, print any of them. Examples Input 4 2 0 0 0 2 2 2 2 0 4 4 Output YES 1 -1 2 -1 Input 6 3 0 0 1 0 1 1 2 1 2 2 0 2 3 2 3 Output YES 1 -1 2 -1 3 -1 Input 6 3 0 0 1 0 1 1 2 1 2 2 0 2 2 2 3 Output NO Submitted Solution: ``` import sys n, m = map(int, input().split()) points = [tuple(map(int, input().split())) for i in range(n)] segments = [] x, y = points[-1] for a, b in points: if x == a: segments.append(abs(y - b)) else: segments.append(abs(x - a)) x, y = a, b rods = list(map(int, input().split())) rod_indices = {} for index, rod in enumerate(rods): rod_indices.setdefault(rod, []).append(index+1) for offset in range(2): target_indices = rod_indices.copy() assignment = [-1 for i in range(n)] for i in range(offset, n, 2): target = segments[(i-1)%n] + segments[i] if target not in target_indices or target_indices[target] == []: assignment = None break assignment[i] = target_indices[target].pop() if assignment != None: print('YES') print(' '.join(map(str, assignment))) sys.exit() print('NO') ``` No
94,693
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Robot Bender decided to make Fray a birthday present. He drove n nails and numbered them from 1 to n in some order. Bender decided to make a picture using metal rods. The picture is a closed polyline, which vertices should be nails (in the given order). The segments of the polyline should be parallel to the coordinate axes. Polyline is allowed to have self-intersections. Bender can take a rod and fold it exactly once in any place to form an angle of 90 degrees. Then he can attach the place of the fold to some unoccupied nail and attach two ends of this rod to adjacent nails. A nail is considered unoccupied if there is no rod attached to it (neither by it's end nor the by the fold place). No rod could be used twice. It is not required to use all the rods. Help Bender to solve this difficult task. Input The first line contains two positive integers n and m (4 ≤ n ≤ 500, 2 ≤ m ≤ 500, n is even) — the amount of nails and the amount of rods. i-th of the following n lines contains a pair of integers, denoting the coordinates of the i-th nail. Nails should be connected in the same order as they are given in the input. The last line contains m integers — the lenghts of the rods. All coordinates do not exceed 104 by absolute value. Lengths of the rods are between 1 and 200 000. No rod can be used twice. It is guaranteed that all segments of the given polyline are parallel to coordinate axes. No three consecutive nails lie on the same line. Output If it is impossible to solve Bender's problem, output NO. Otherwise, output YES in the first line, and in the second line output n numbers — i-th of them should be the number of rod, which fold place is attached to the i-th nail, or -1, if there is no such rod. If there are multiple solutions, print any of them. Examples Input 4 2 0 0 0 2 2 2 2 0 4 4 Output YES 1 -1 2 -1 Input 6 3 0 0 1 0 1 1 2 1 2 2 0 2 3 2 3 Output YES 1 -1 2 -1 3 -1 Input 6 3 0 0 1 0 1 1 2 1 2 2 0 2 2 2 3 Output NO Submitted Solution: ``` n,m = map(int,input().split()) s = [] for i in range(n): a = map(int,input().split()) a = list(a) s.append(a) s_chet = [] for i in range(1,n-1,2): #Проход по четным гвоздям q = abs(sum(s[i])-sum(s[i-1])) + abs(sum(s[i])-sum(s[i+1])) s_chet.append(q) q1 = abs(sum(s[-1])-sum(s[-2])) + abs(sum(s[-1])-sum(s[0])) s_chet.append(q1) s_ch = s_chet.copy() s_nechet = [] for i in range(2,n-1,2): #Проход по нечетным гвоздям qq = abs(sum(s[i])-sum(s[i-1])) + abs(sum(s[i])-sum(s[i+1])) s_nechet.append(qq) qq1 = abs(sum(s[-1])-sum(s[0])) + abs(sum(s[1])-sum(s[0])) s_nechet.append(qq1) s_n = s_nechet.copy() ss = map(int,input().split()) ss = list(ss) ss1 = ss.copy() ss2 = ss.copy() for i in s_chet: if i in ss1: s_ch.remove(i) ss1.remove(i) if len(s_ch) == 0: print('YES') sss = [] for i in range(m): sss.append(-1) sss.append(i+1) print(" ".join(map(str,sss))) else: for i in s_nechet: if i in ss2: s_n.remove(i) ss2.remove(i) if len(s_n) == 0: print('YES') sss = [] for i in range(m): sss.append(i+1) sss.append(-1) print(" ".join(map(str,sss))) else: print('NO') ``` No
94,694
Provide tags and a correct Python 3 solution for this coding contest problem. Sereja and his friends went to a picnic. The guys had n soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles. Sereja knows that the i-th bottle is from brand ai, besides, you can use it to open other bottles of brand bi. You can use one bottle to open multiple other bottles. Sereja can open bottle with opened bottle or closed bottle. Knowing this, Sereja wants to find out the number of bottles they've got that they won't be able to open in any way. Help him and find this number. Input The first line contains integer n (1 ≤ n ≤ 100) — the number of bottles. The next n lines contain the bottles' description. The i-th line contains two integers ai, bi (1 ≤ ai, bi ≤ 1000) — the description of the i-th bottle. Output In a single line print a single integer — the answer to the problem. Examples Input 4 1 1 2 2 3 3 4 4 Output 4 Input 4 1 2 2 3 3 4 4 1 Output 0 Tags: brute force Correct Solution: ``` n = int(input()) a = [] b=[] freq={} for i in range(n): ai,bi = [int(x) for x in input().split()] a.append(ai) b.append(bi) if bi not in freq: freq[bi] = 0 freq[bi] +=1 #No of bottles than can be used to open bi ans= n for i in range(n): #a[i]#can be used to open bottle bi #to open ith bottle, we need to find which i has the a[i] in its b array if a[i] not in freq or freq[a[i]] == 0: continue if freq[a[i]] == 1 and b[i] == a[i]: continue ans -=1 print(ans) ```
94,695
Provide tags and a correct Python 3 solution for this coding contest problem. Sereja and his friends went to a picnic. The guys had n soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles. Sereja knows that the i-th bottle is from brand ai, besides, you can use it to open other bottles of brand bi. You can use one bottle to open multiple other bottles. Sereja can open bottle with opened bottle or closed bottle. Knowing this, Sereja wants to find out the number of bottles they've got that they won't be able to open in any way. Help him and find this number. Input The first line contains integer n (1 ≤ n ≤ 100) — the number of bottles. The next n lines contain the bottles' description. The i-th line contains two integers ai, bi (1 ≤ ai, bi ≤ 1000) — the description of the i-th bottle. Output In a single line print a single integer — the answer to the problem. Examples Input 4 1 1 2 2 3 3 4 4 Output 4 Input 4 1 2 2 3 3 4 4 1 Output 0 Tags: brute force Correct Solution: ``` n=int(input()) arr=[] rra=[] for i in range (n): z=list(map(int,input().split())) rra.append(z[0]) arr.append(z[1]) count=0 for i in range(n) : temp=arr[i] indexx=i arr.remove(temp) if rra[i] in arr : arr.insert(indexx,temp) else : count+=1 arr.insert(indexx,temp) print(count) ```
94,696
Provide tags and a correct Python 3 solution for this coding contest problem. Sereja and his friends went to a picnic. The guys had n soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles. Sereja knows that the i-th bottle is from brand ai, besides, you can use it to open other bottles of brand bi. You can use one bottle to open multiple other bottles. Sereja can open bottle with opened bottle or closed bottle. Knowing this, Sereja wants to find out the number of bottles they've got that they won't be able to open in any way. Help him and find this number. Input The first line contains integer n (1 ≤ n ≤ 100) — the number of bottles. The next n lines contain the bottles' description. The i-th line contains two integers ai, bi (1 ≤ ai, bi ≤ 1000) — the description of the i-th bottle. Output In a single line print a single integer — the answer to the problem. Examples Input 4 1 1 2 2 3 3 4 4 Output 4 Input 4 1 2 2 3 3 4 4 1 Output 0 Tags: brute force Correct Solution: ``` import sys,math from collections import deque,defaultdict import operator as op from functools import reduce from itertools import permutations #sys.setrecursionlimit(10**6) I=sys.stdin.readline #alpha="abcdefghijklmnopqrstuvwxyz" """ x_move=[-1,0,1,0,-1,1,1,-1] y_move=[0,1,0,-1,1,1,-1,-1] """ def ii(): return int(I().strip()) def li(): return list(map(int,I().strip().split())) def mi(): return map(int,I().strip().split()) """def ncr(n, r): r = min(r, n-r) numer = (reduce(op.mul, range(n, n-r, -1), 1))%(10**9+7) denom = (reduce(op.mul, range(1, r+1), 1))%(10**9+7) return (numer // denom)%(10**9+7)""" def ncr(n, r, p): # initialize numerator # and denominator num = den = 1 for i in range(r): num = (num * (n - i)) % p den = (den * (i + 1)) % p return (num * pow(den, p - 2, p)) % p def gcd(x, y): while y: x, y = y, x % y return x def valid(row,col,rows,cols,rcross,lcross): return rows[row]==0 and cols[col]==0 and rcross[col+row]==0 and lcross[col-row]==0 def div(n): if n==1: return 1 cnt=2 for i in range(2,int(n**.5)+1): if n%i==0: if i!=n//i: cnt+=2 else: cnt+=1 return cnt def isPrime(n): if n<=1: return False elif n<=2: return True else: flag=True for i in range(2,int(n**.5)+1): if n%i==0: flag=False break return flag def s(b): ans=[] while b>0: tmp=b%10 ans.append(tmp) b=b//10 return ans def main(): n=ii() d=defaultdict(int) brnd=[] for i in range(n): x,y=mi() brnd.append((x,y)) cnt=n for i in range(n): for j in range(n): if i!=j: if brnd[j][1]==brnd[i][0]: cnt-=1 break print(cnt) if __name__ == '__main__': main() ```
94,697
Provide tags and a correct Python 3 solution for this coding contest problem. Sereja and his friends went to a picnic. The guys had n soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles. Sereja knows that the i-th bottle is from brand ai, besides, you can use it to open other bottles of brand bi. You can use one bottle to open multiple other bottles. Sereja can open bottle with opened bottle or closed bottle. Knowing this, Sereja wants to find out the number of bottles they've got that they won't be able to open in any way. Help him and find this number. Input The first line contains integer n (1 ≤ n ≤ 100) — the number of bottles. The next n lines contain the bottles' description. The i-th line contains two integers ai, bi (1 ≤ ai, bi ≤ 1000) — the description of the i-th bottle. Output In a single line print a single integer — the answer to the problem. Examples Input 4 1 1 2 2 3 3 4 4 Output 4 Input 4 1 2 2 3 3 4 4 1 Output 0 Tags: brute force Correct Solution: ``` n = int(input()) a, b = [], [] for i in range(n): l, m = input().split() a.append(int(l)) b.append(int(m)) count = 0 for i in range(n): for j in range(n): if b[j] == a[i] and i != j: count += 1 break print(n - count) ```
94,698
Provide tags and a correct Python 3 solution for this coding contest problem. Sereja and his friends went to a picnic. The guys had n soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles. Sereja knows that the i-th bottle is from brand ai, besides, you can use it to open other bottles of brand bi. You can use one bottle to open multiple other bottles. Sereja can open bottle with opened bottle or closed bottle. Knowing this, Sereja wants to find out the number of bottles they've got that they won't be able to open in any way. Help him and find this number. Input The first line contains integer n (1 ≤ n ≤ 100) — the number of bottles. The next n lines contain the bottles' description. The i-th line contains two integers ai, bi (1 ≤ ai, bi ≤ 1000) — the description of the i-th bottle. Output In a single line print a single integer — the answer to the problem. Examples Input 4 1 1 2 2 3 3 4 4 Output 4 Input 4 1 2 2 3 3 4 4 1 Output 0 Tags: brute force Correct Solution: ``` #A. Sereja and Bottles n = int(input()) a = [] b = [] for _ in range(n): x,y = map(int,input().split()) a.append(x) b.append(y) total = n for i in range(n): for j in range(n): if i!=j and a[i]==b[j]: total -= 1 break print(total) ```
94,699