message
stringlengths
2
22.8k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
16
109k
cluster
float64
1
1
__index_level_0__
int64
32
217k
Provide tags and a correct Python 3 solution for this coding contest problem. Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well. There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route. Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is ai coins. You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). Formally, for every <image> you have to calculate <image>, where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large. Input The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105). Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input. The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city. Output Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). Examples Input 4 2 1 2 4 2 3 7 6 20 1 25 Output 6 14 1 25 Input 3 3 1 2 1 2 3 1 1 3 1 30 10 20 Output 12 10 12
instruction
0
29,713
1
59,426
Tags: data structures, graphs, shortest paths Correct Solution: ``` from __future__ import division, print_function py2 = round(0.5) # Should take 900 ms something if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange import os, sys from io import BytesIO, IOBase # FastIO for PyPy2 and PyPy3 by Pajenegod, class FastI(object): def __init__(self, fd=0, buffersize=2**14): self.stream = stream = BytesIO(); self.bufendl = 0 def read2buffer(): curpos = stream.tell(); s = os.read(fd, buffersize + os.fstat(fd).st_size) stream.seek(0,2); stream.write(s); stream.seek(curpos); return s self.read2buffer = read2buffer def read(self): while self.read2buffer(): pass return self.stream.read() if self.stream.tell() else self.stream.getvalue() def readline(self): while self.bufendl == 0: s = self.read2buffer(); self.bufendl += s.count(b'\n') + (not s) self.bufendl -= 1; return self.stream.readline() def input(self): return self.readline().rstrip(b'\r\n') # Reads n integers (n=-1 is until end of input), use zero to change type def readnumbers(self, n=-1, zero=0): conv = ord if py2 else lambda x:x # Figure out curpos and buffer size curpos = self.stream.tell() self.stream.seek(0,2) buffsize = self.stream.tell() self.stream.seek(curpos) A = []; numb = zero; sign = 1 while n==-1 or len(A)<n: # If at end of current buffer if curpos >= buffsize: s = self.read2buffer() buffsize += len(s) self.bufendl += s.count(b'\n') + (not s) if curpos==buffsize: break for i,c in enumerate(self.stream.read(min(128,buffsize-curpos))): if c >= b'0'[0]: numb = 10 * numb + (conv(c) - 48) elif c == b'-'[0]: sign = -1 elif c != b'\r'[0]: # whitespace if c == b'\n'[0]: self.bufendl -= 1 A.append(sign*numb) if n!=-1 and len(A)==n: break numb = zero; sign = 1 curpos += i + 1 # If no trailing whitespace if curpos == buffsize and not self.stream.seek(-1,2) and self.stream.read(1)[0] >= b'0'[0]: self.bufendl -= 1 A.append(sign*numb) assert(n==-1 or len(A)==n) self.stream.seek(curpos) return A class FastO(IOBase): def __init__(self, fd=1): stream = BytesIO() self.flush = lambda: os.write(1, stream.getvalue()) and not stream.truncate(0) and stream.seek(0) self.write = stream.write if py2 else lambda s: stream.write(s.encode()) sys.stdin, sys.stdout = FastI(), FastO() input = sys.stdin.readline big = 3E12 class segheap: def __init__(self,data): n = len(data) m = 1 while m<n:m*=2 self.n = n self.m = m self.data = [big]*(2*m) for i in range(n): self.data[i+m] = data[i] for i in reversed(range(m)): self.data[i] = min(self.data[2*i],self.data[2*i+1]) def mini(self): i = 1 while i<self.m: if self.data[i]==self.data[2*i]: i = 2*i else: i = 2*i+1 i -= self.m self.setter(i,big) return i def setter(self,ind,val): ind += self.m if val<self.data[ind]: while ind>0 and self.data[ind]>val: self.data[ind] = val ind //= 2 elif val>self.data[ind]: old_val = self.data[ind] self.data[ind] = val ind //= 2 while ind>0 and self.data[ind]==old_val: self.data[ind] = min(self.data[2*ind],self.data[2*ind+1]) ind //= 2 n, m = [int(x) for x in sys.stdin.readline().split()] inp = sys.stdin.readnumbers(-1, 0.0) coupl = [[] for _ in range(n)] cost = [[] for _ in range(n)] for _ in range(m): v = int(inp[_*3+0])-1 u = int(inp[_*3+1])-1 w = inp[_*3+2] coupl[v].append(u) coupl[u].append(v) cost[u].append(w) cost[v].append(w) best = [inp[3*m + i] for i in range(n)] Q = segheap(best) while Q.data[1]!=big: c = Q.data[1] node = Q.mini() if best[node]!=c: continue for j in range(len(coupl[node])): nei = coupl[node][j] C = c+2*cost[node][j] if C<best[nei]: best[nei] = C Q.setter(nei,C) for x in best: sys.stdout.write(str(int(x))) sys.stdout.write(' ') ```
output
1
29,713
1
59,427
Provide tags and a correct Python 3 solution for this coding contest problem. Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well. There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route. Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is ai coins. You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). Formally, for every <image> you have to calculate <image>, where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large. Input The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105). Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input. The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city. Output Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). Examples Input 4 2 1 2 4 2 3 7 6 20 1 25 Output 6 14 1 25 Input 3 3 1 2 1 2 3 1 1 3 1 30 10 20 Output 12 10 12
instruction
0
29,714
1
59,428
Tags: data structures, graphs, shortest paths Correct Solution: ``` from __future__ import division, print_function py2 = round(0.5) # OLD VERSION if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange import os, sys from io import BytesIO, IOBase # FastIO for PyPy2 and PyPy3 by Pajenegod, class FastI(object): def __init__(self, fd=0, buffersize=2**14): self.stream = stream = BytesIO(); self.bufendl = 0 def read2buffer(): curpos = stream.tell(); s = os.read(fd, buffersize + os.fstat(fd).st_size) stream.seek(0,2); stream.write(s); stream.seek(curpos); return s self.read2buffer = read2buffer def read(self): while self.read2buffer(): pass return self.stream.read() if self.stream.tell() else self.stream.getvalue() def readline(self): while self.bufendl == 0: s = self.read2buffer(); self.bufendl += s.count(b'\n') + (not s) self.bufendl -= 1; return self.stream.readline() def input(self): return self.readline().rstrip(b'\r\n') def readnumbers(self, n,zero=0): conv = ord if py2 else lambda x:x A = []; numb = zero; sign = 1 curpos = self.stream.tell() self.stream.seek(0,2) buffsize = self.stream.tell() self.stream.seek(curpos) while len(A)<n: if curpos>=buffsize: self.read2buffer() self.stream.seek(0,2) buffsize = self.stream.tell() self.stream.seek(curpos) if curpos==buffsize: break s = self.stream.read(min(64,buffsize-curpos)) i = 0 while i<len(s) and len(A)!=n: if s[i] >= b'0'[0]: numb = 10 * numb + (conv(s[i]) - 48) elif s[i] != b'\r'[0]: if s[i] == b'-'[0]: sign = -1 else: A.append(sign*numb); numb = zero; sign = 1 i += 1 curpos += i if curpos == buffsize and len(A)<n: A.append(sign*numb) assert(len(A)==n) self.stream.seek(curpos) return A class FastO(IOBase): def __init__(self, fd=1): stream = BytesIO() self.flush = lambda: os.write(1, stream.getvalue()) and not stream.truncate(0) and stream.seek(0) self.write = stream.write if py2 else lambda s: stream.write(s.encode()) sys.stdin, sys.stdout = FastI(), FastO() input = sys.stdin.readline big = 3E12 class segheap: def __init__(self,data): n = len(data) m = 1 while m<n:m*=2 self.n = n self.m = m self.data = [big]*(2*m) for i in range(n): self.data[i+m] = data[i] for i in reversed(range(m)): self.data[i] = min(self.data[2*i],self.data[2*i+1]) def mini(self): i = 1 while i<self.m: if self.data[i]==self.data[2*i]: i = 2*i else: i = 2*i+1 i -= self.m self.setter(i,big) return i def setter(self,ind,val): ind += self.m if val<self.data[ind]: while ind>0 and self.data[ind]>val: self.data[ind] = val ind //= 2 elif val>self.data[ind]: old_val = self.data[ind] self.data[ind] = val ind //= 2 while ind>0 and self.data[ind]==old_val: self.data[ind] = min(self.data[2*ind],self.data[2*ind+1]) ind //= 2 n, m = [int(x) for x in sys.stdin.readline().split()] inp = sys.stdin.readnumbers(3*m, 0.0) coupl = [[] for _ in range(n)] cost = [[] for _ in range(n)] for _ in range(m): v = int(inp[_*3+0]-1) u = int(inp[_*3+1]-1) w = inp[_*3+2] coupl[v].append(u) coupl[u].append(v) cost[u].append(w) cost[v].append(w) inp = sys.stdin.readnumbers(n, 0.0) best = [inp[i] for i in range(n)] Q = segheap(best) while Q.data[1]!=big: c = Q.data[1] node = Q.mini() if best[node]!=c: continue for j in range(len(coupl[node])): nei = coupl[node][j] C = c+2*cost[node][j] if C<best[nei]: best[nei] = C Q.setter(nei,C) for x in best: sys.stdout.write(str(int(x))) sys.stdout.write(' ') ```
output
1
29,714
1
59,429
Provide tags and a correct Python 3 solution for this coding contest problem. Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well. There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route. Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is ai coins. You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). Formally, for every <image> you have to calculate <image>, where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large. Input The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105). Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input. The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city. Output Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). Examples Input 4 2 1 2 4 2 3 7 6 20 1 25 Output 6 14 1 25 Input 3 3 1 2 1 2 3 1 1 3 1 30 10 20 Output 12 10 12
instruction
0
29,715
1
59,430
Tags: data structures, graphs, shortest paths Correct Solution: ``` #!/usr/bin/env python3 import os import sys from io import BytesIO class FastI: def __init__(self): self.stream = BytesIO() self.newlines = 0 def read(self, b=b'\n'): while b: b, ptr = os.read(0, (1 << 13) + os.fstat(0).st_size), self.stream.tell() self.stream.seek(0, 2), self.stream.write(b), self.stream.seek(ptr) return self.stream.read() if self.stream.tell() else self.stream.getvalue() def readline(self, b=b'\n'): while b and self.newlines == 0: b, ptr = os.read(0, (1 << 13) + os.fstat(0).st_size), self.stream.tell() self.stream.seek(0, 2), self.stream.write(b), self.stream.seek(ptr) self.newlines += b.count(b'\n') self.newlines -= bool(b) return self.stream.readline() def readnumber(self, var=int): """ Read numbers till EOF. Use var to change type. """ b = self.read() num, sign = var(0), 1 for char in b: if char >= b'0' [0]: num = 10 * num + char - 48 elif char == b'-' [0]: sign = -1 elif char != b'\r' [0]: yield sign * num num, sign = var(0), 1 if b and b[-1] >= b'0' [0]: yield sign * num class FastO: def __init__(self): stream = BytesIO() self.flush = lambda: os.write(1, stream.getvalue()) and not stream.truncate(0) and stream.seek(0) self.write = lambda s: stream.write(s.encode()) sys.stdin, sys.stdout = FastI(), FastO() input, flush = sys.stdin.readline, sys.stdout.flush big = 3E12 class segheap: def __init__(self, data): n = len(data) m = 1 while m < n: m *= 2 self.n = n self.m = m self.data = [big] * (2 * m) for i in range(n): self.data[i + m] = data[i] for i in reversed(range(m)): self.data[i] = min(self.data[2 * i], self.data[2 * i + 1]) def mini(self): i = 1 while i < self.m: if self.data[i] == self.data[2 * i]: i = 2 * i else: i = 2 * i + 1 i -= self.m self.setter(i, big) return i def setter(self, ind, val): ind += self.m if val < self.data[ind]: while ind > 0 and self.data[ind] > val: self.data[ind] = val ind //= 2 elif val > self.data[ind]: old_val = self.data[ind] self.data[ind] = val ind //= 2 while ind > 0 and self.data[ind] == old_val: self.data[ind] = min(self.data[2 * ind], self.data[2 * ind + 1]) ind //= 2 inp = sys.stdin.readnumber(float) n, m = int(next(inp)), int(next(inp)) coupl = [[] for _ in range(n)] cost = [[] for _ in range(n)] for _ in range(m): v = int(next(inp) - 1) u = int(next(inp) - 1) w = next(inp) coupl[v].append(u) coupl[u].append(v) cost[u].append(w) cost[v].append(w) best = [next(inp) for i in range(n)] Q = segheap(best) while Q.data[1] != big: c = Q.data[1] node = Q.mini() if best[node] != c: continue for j in range(len(coupl[node])): nei = coupl[node][j] C = c + 2 * cost[node][j] if C < best[nei]: best[nei] = C Q.setter(nei, C) for x in best: sys.stdout.write(str(int(x))) sys.stdout.write(' ') ```
output
1
29,715
1
59,431
Provide tags and a correct Python 3 solution for this coding contest problem. Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well. There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route. Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is ai coins. You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). Formally, for every <image> you have to calculate <image>, where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large. Input The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105). Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input. The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city. Output Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). Examples Input 4 2 1 2 4 2 3 7 6 20 1 25 Output 6 14 1 25 Input 3 3 1 2 1 2 3 1 1 3 1 30 10 20 Output 12 10 12
instruction
0
29,716
1
59,432
Tags: data structures, graphs, shortest paths Correct Solution: ``` from __future__ import division, print_function import os import sys from io import BytesIO, IOBase py2 = round(0.5) if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange class FastI(): stream = BytesIO() newlines = 0 read = lambda self: self.stream.read() if self._read() or self.stream.tell() else self.stream.getvalue() def _read(self, getline=False, s=b'\n'): while s and not (getline and self.newlines): s, ptr = os.read(0, (1 << 13) + os.fstat(0).st_size), self.stream.tell() self.newlines += s.count(b'\n') self.stream.seek(0, 2) self.stream.write(s) self.stream.seek(ptr) def readline(self): self._read(True) self.newlines -= 1 return self.stream.readline() def readnumbers(self, n, var=int): A, numb, sign = [], var(0), 1 ptr = self.stream.tell() self.stream.seek(0, 2) buffsize = self.stream.tell() self.stream.seek(ptr) while len(A) < n: if ptr >= buffsize: s, _ptr = os.read(0, (1 << 13) + os.fstat(0).st_size), self.stream.tell() self.stream.seek(0, 2) self.stream.write(s) self.stream.seek(_ptr) buffsize += len(s) if ptr == buffsize: break i, s = 0, self.stream.read(min(32, buffsize - ptr)) while i < len(s) and len(A) < n: if s[i] >= b'0' [0]: numb = 10 * numb + ((ord(s[i]) if py2 else s[i]) - 48) elif s[i] == b'-' [0]: sign = -1 elif s[i] != b'\r' [0]: A.append(sign * numb) numb, sign = var(0), 1 i += 1 ptr += i if ptr == buffsize and len(A) < n: A.append(sign * numb) self.stream.seek(ptr) return A class FastO(IOBase): def __init__(self, fd=1): stream = BytesIO() self.flush = lambda: os.write(1, stream.getvalue()) and not stream.truncate(0) and stream.seek(0) self.write = stream.write if py2 else lambda s: stream.write(s.encode()) sys.stdin, sys.stdout = FastI(), FastO() input = sys.stdin.readline big = 3E12 class segheap: def __init__(self, data): n = len(data) m = 1 while m < n: m *= 2 self.n = n self.m = m self.data = [big] * (2 * m) for i in range(n): self.data[i + m] = data[i] for i in reversed(range(m)): self.data[i] = min(self.data[2 * i], self.data[2 * i + 1]) def mini(self): i = 1 while i < self.m: if self.data[i] == self.data[2 * i]: i = 2 * i else: i = 2 * i + 1 i -= self.m self.setter(i, big) return i def setter(self, ind, val): ind += self.m if val < self.data[ind]: while ind > 0 and self.data[ind] > val: self.data[ind] = val ind //= 2 elif val > self.data[ind]: old_val = self.data[ind] self.data[ind] = val ind //= 2 while ind > 0 and self.data[ind] == old_val: self.data[ind] = min(self.data[2 * ind], self.data[2 * ind + 1]) ind //= 2 n, m = [int(x) for x in sys.stdin.readline().split()] inp = sys.stdin.readnumbers(3 * m, float) coupl = [[] for _ in range(n)] cost = [[] for _ in range(n)] for _ in range(m): v = int(inp[_ * 3 + 0] - 1) u = int(inp[_ * 3 + 1] - 1) w = inp[_ * 3 + 2] coupl[v].append(u) coupl[u].append(v) cost[u].append(w) cost[v].append(w) inp = sys.stdin.readnumbers(n, float) best = [inp[i] for i in range(n)] Q = segheap(best) while Q.data[1] != big: c = Q.data[1] node = Q.mini() if best[node] != c: continue for j in range(len(coupl[node])): nei = coupl[node][j] C = c + 2 * cost[node][j] if C < best[nei]: best[nei] = C Q.setter(nei, C) for x in best: sys.stdout.write(str(int(x))) sys.stdout.write(' ') ```
output
1
29,716
1
59,433
Provide tags and a correct Python 3 solution for this coding contest problem. Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well. There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route. Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is ai coins. You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). Formally, for every <image> you have to calculate <image>, where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large. Input The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105). Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input. The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city. Output Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). Examples Input 4 2 1 2 4 2 3 7 6 20 1 25 Output 6 14 1 25 Input 3 3 1 2 1 2 3 1 1 3 1 30 10 20 Output 12 10 12
instruction
0
29,717
1
59,434
Tags: data structures, graphs, shortest paths Correct Solution: ``` from __future__ import division, print_function py2 = round(0.5) # Testing small buffer size in readnumbers if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange import os, sys from io import BytesIO, IOBase # FastIO for PyPy2 and PyPy3 by Pajenegod, class FastI(object): def __init__(self, fd=0, buffersize=2**14): self.stream = stream = BytesIO(); self.bufendl = 0 def read2buffer(): curpos = stream.tell(); s = os.read(fd, buffersize + os.fstat(fd).st_size) stream.seek(0,2); stream.write(s); stream.seek(curpos); return s self.read2buffer = read2buffer def read(self): while self.read2buffer(): pass return self.stream.read() if self.stream.tell() else self.stream.getvalue() def readline(self): while self.bufendl == 0: s = self.read2buffer(); self.bufendl += s.count(b'\n') + (not s) self.bufendl -= 1; return self.stream.readline() def input(self): return self.readline().rstrip(b'\r\n') # Reads n integers (n=-1 is until end of input), use zero to change type def readnumbers(self, n=-1, zero=0): conv = ord if py2 else lambda x:x # Figure out curpos and buffer size curpos = self.stream.tell() buffsize = self.stream.seek(0,2) self.stream.seek(curpos) A = []; numb = zero; sign = 1 while len(A)!=n: # If at end of current buffer if curpos == buffsize: s = self.read2buffer() buffsize += len(s) self.bufendl += s.count(b'\n') + (not s) if curpos==buffsize: break for i,c in enumerate(self.stream.read(min(16, buffsize-curpos))): if c >= b'0'[0]: numb = numb*10 + conv(c) - 48 elif c == b'-'[0]: sign = -1 elif c != b'\r'[0]: # whitespace if c == b'\n'[0]: self.bufendl -= 1 A.append(sign*numb) if len(A)==n: break numb = zero; sign = 1 curpos += i + 1 # If no trailing whitespace if curpos == buffsize > 0 and (self.stream.seek(-1,2) >= 0) and self.stream.read(1)[0] >= b'0'[0]: self.bufendl -= 1 A.append(sign*numb) assert(n==-1 or len(A)==n) self.stream.seek(curpos) return A class FastO(IOBase): def __init__(self, fd=1): stream = BytesIO() self.flush = lambda: os.write(1, stream.getvalue()) and not stream.truncate(0) and stream.seek(0) self.write = stream.write if py2 else lambda s: stream.write(s.encode()) sys.stdin, sys.stdout = FastI(), FastO() input = sys.stdin.readline big = 3E12 class segheap: def __init__(self,data): n = len(data) m = 1 while m<n:m*=2 self.n = n self.m = m self.data = [big]*(2*m) for i in range(n): self.data[i+m] = data[i] for i in reversed(range(m)): self.data[i] = min(self.data[2*i],self.data[2*i+1]) def mini(self): i = 1 while i<self.m: if self.data[i]==self.data[2*i]: i = 2*i else: i = 2*i+1 i -= self.m self.setter(i,big) return i def setter(self,ind,val): ind += self.m if val<self.data[ind]: while ind>0 and self.data[ind]>val: self.data[ind] = val ind //= 2 elif val>self.data[ind]: old_val = self.data[ind] self.data[ind] = val ind //= 2 while ind>0 and self.data[ind]==old_val: self.data[ind] = min(self.data[2*ind],self.data[2*ind+1]) ind //= 2 n, m = sys.stdin.readnumbers(2, 0) inp = [sys.stdin.readnumbers(1, 0.0)[0] for _ in range(3*m)] coupl = [[] for _ in range(n)] cost = [[] for _ in range(n)] for _ in range(m): v = int(inp[_*3+0])-1 u = int(inp[_*3+1])-1 w = inp[_*3+2] coupl[v].append(u) coupl[u].append(v) cost[u].append(w) cost[v].append(w) best = [sys.stdin.readnumbers(1, 0.0)[0] for _ in range(n)] Q = segheap(best) while Q.data[1]!=big: c = Q.data[1] node = Q.mini() if best[node]!=c: continue for j in range(len(coupl[node])): nei = coupl[node][j] C = c+2*cost[node][j] if C<best[nei]: best[nei] = C Q.setter(nei,C) for x in best: sys.stdout.write(str(int(x))) sys.stdout.write(' ') ```
output
1
29,717
1
59,435
Provide tags and a correct Python 3 solution for this coding contest problem. Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well. There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route. Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is ai coins. You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). Formally, for every <image> you have to calculate <image>, where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large. Input The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105). Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input. The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city. Output Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). Examples Input 4 2 1 2 4 2 3 7 6 20 1 25 Output 6 14 1 25 Input 3 3 1 2 1 2 3 1 1 3 1 30 10 20 Output 12 10 12
instruction
0
29,718
1
59,436
Tags: data structures, graphs, shortest paths Correct Solution: ``` from __future__ import division, print_function py2 = round(0.5) # Should take 900 ms something, if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange import os, sys from io import BytesIO, IOBase # FastIO for PyPy2 and PyPy3 by Pajenegod, class FastI(object): def __init__(self, fd=0, buffersize=2**14): self.stream = stream = BytesIO(); self.bufendl = 0 def read2buffer(): curpos = stream.tell(); s = os.read(fd, buffersize + os.fstat(fd).st_size) stream.seek(0,2); stream.write(s); stream.seek(curpos); return s self.read2buffer = read2buffer def read(self): while self.read2buffer(): pass return self.stream.read() if self.stream.tell() else self.stream.getvalue() def readline(self): while self.bufendl == 0: s = self.read2buffer(); self.bufendl += s.count(b'\n') + (not s) self.bufendl -= 1; return self.stream.readline() def input(self): return self.readline().rstrip(b'\r\n') # Reads n integers (n=-1 is until end of input), use zero to change type def readnumbers(self, n=-1, zero=0): conv = ord if py2 else lambda x:x # Figure out curpos and buffer size curpos = self.stream.tell() self.stream.seek(0,2) buffsize = self.stream.tell() self.stream.seek(curpos) A = []; numb = zero; sign = 1 while len(A)!=n: # If at end of current buffer if curpos == buffsize: s = self.read2buffer() buffsize += len(s) self.bufendl += s.count(b'\n') + (not s) if curpos==buffsize: break for i,c in enumerate(self.stream.read(min(10**9, buffsize-curpos))): if c == b'\r'[0]: continue if c >= b'0'[0]: numb = numb*10 + conv(c) - 48 elif c == b'-'[0]: sign = -1 else: # whitespace if c == b'\n'[0]: self.bufendl -= 1 A.append(sign*numb) if len(A)==n: break numb = zero; sign = 1 curpos += i + 1 # If no trailing whitespace if curpos == buffsize and not self.stream.seek(-1,2) and self.stream.read(1)[0] >= b'0'[0]: self.bufendl -= 1 if positive: A.append(numb) else: A.append(-numb); positive = True assert(n==-1 or len(A)==n) self.stream.seek(curpos) return A class FastO(IOBase): def __init__(self, fd=1): stream = BytesIO() self.flush = lambda: os.write(1, stream.getvalue()) and not stream.truncate(0) and stream.seek(0) self.write = stream.write if py2 else lambda s: stream.write(s.encode()) sys.stdin, sys.stdout = FastI(), FastO() input = sys.stdin.readline big = 3E12 class segheap: def __init__(self,data): n = len(data) m = 1 while m<n:m*=2 self.n = n self.m = m self.data = [big]*(2*m) for i in range(n): self.data[i+m] = data[i] for i in reversed(range(m)): self.data[i] = min(self.data[2*i],self.data[2*i+1]) def mini(self): i = 1 while i<self.m: if self.data[i]==self.data[2*i]: i = 2*i else: i = 2*i+1 i -= self.m self.setter(i,big) return i def setter(self,ind,val): ind += self.m if val<self.data[ind]: while ind>0 and self.data[ind]>val: self.data[ind] = val ind //= 2 elif val>self.data[ind]: old_val = self.data[ind] self.data[ind] = val ind //= 2 while ind>0 and self.data[ind]==old_val: self.data[ind] = min(self.data[2*ind],self.data[2*ind+1]) ind //= 2 n, m = [int(x) for x in sys.stdin.readline().split()] inp = sys.stdin.readnumbers(3*m, 0.0) coupl = [[] for _ in range(n)] cost = [[] for _ in range(n)] for _ in range(m): v = int(inp[_*3+0])-1 u = int(inp[_*3+1])-1 w = inp[_*3+2] coupl[v].append(u) coupl[u].append(v) cost[u].append(w) cost[v].append(w) inp = sys.stdin.readnumbers(n, 0.0) best = [inp[i] for i in range(n)] Q = segheap(best) while Q.data[1]!=big: c = Q.data[1] node = Q.mini() if best[node]!=c: continue for j in range(len(coupl[node])): nei = coupl[node][j] C = c+2*cost[node][j] if C<best[nei]: best[nei] = C Q.setter(nei,C) for x in best: sys.stdout.write(str(int(x))) sys.stdout.write(' ') ```
output
1
29,718
1
59,437
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well. There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route. Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is ai coins. You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). Formally, for every <image> you have to calculate <image>, where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large. Input The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105). Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input. The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city. Output Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). Examples Input 4 2 1 2 4 2 3 7 6 20 1 25 Output 6 14 1 25 Input 3 3 1 2 1 2 3 1 1 3 1 30 10 20 Output 12 10 12 Submitted Solution: ``` from __future__ import division, print_function py2 = round(0.5) # Should take 900 ms something, if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange import os, sys from io import BytesIO, IOBase # FastIO for PyPy2 and PyPy3 by Pajenegod, class FastI(object): def __init__(self, fd=0, buffersize=2**14): self.stream = stream = BytesIO(); self.bufendl = 0 def read2buffer(): curpos = stream.tell(); s = os.read(fd, buffersize + os.fstat(fd).st_size) stream.seek(0,2); stream.write(s); stream.seek(curpos); return s self.read2buffer = read2buffer def read(self): while self.read2buffer(): pass return self.stream.read() if self.stream.tell() else self.stream.getvalue() def readline(self): while self.bufendl == 0: s = self.read2buffer(); self.bufendl += s.count(b'\n') + (not s) self.bufendl -= 1; return self.stream.readline() def input(self): return self.readline().rstrip(b'\r\n') # Reads n integers (n=-1 is until end of input), use zero to change type def readnumbers(self, n=-1, zero=0): conv = ord if py2 else lambda x:x # Figure out curpos and buffer size curpos = self.stream.tell() self.stream.seek(0,2) buffsize = self.stream.tell() self.stream.seek(curpos) A = []; numb = zero; sign = 1 while len(A)!=n: # If at end of current buffer if curpos == buffsize: s = self.read2buffer() buffsize += len(s) self.bufendl += s.count(b'\n') + (not s) if curpos==buffsize: break for i,c in enumerate(self.stream.read(min(32, buffsize-curpos))): if c >= b'0'[0]: numb = numb*10 + conv(c) - 48 elif c == b'-'[0]: sign = -1 elif c != b'\r'[0]: # whitespace if c == b'\n'[0]: self.bufendl -= 1 A.append(sign*numb) if len(A)==n: break numb = zero; sign = 1 curpos += i + 1 # If no trailing whitespace if curpos == buffsize and (self.stream.seek(-1,2) or True) and self.stream.read(1)[0] >= b'0'[0]: self.bufendl -= 1 A.append(sign*numb) assert(n==-1 or len(A)==n) self.stream.seek(curpos) return A class FastO(IOBase): def __init__(self, fd=1): stream = BytesIO() self.flush = lambda: os.write(1, stream.getvalue()) and not stream.truncate(0) and stream.seek(0) self.write = stream.write if py2 else lambda s: stream.write(s.encode()) sys.stdin, sys.stdout = FastI(), FastO() input = sys.stdin.readline big = 3E12 class segheap: def __init__(self,data): n = len(data) m = 1 while m<n:m*=2 self.n = n self.m = m self.data = [big]*(2*m) for i in range(n): self.data[i+m] = data[i] for i in reversed(range(m)): self.data[i] = min(self.data[2*i],self.data[2*i+1]) def mini(self): i = 1 while i<self.m: if self.data[i]==self.data[2*i]: i = 2*i else: i = 2*i+1 i -= self.m self.setter(i,big) return i def setter(self,ind,val): ind += self.m if val<self.data[ind]: while ind>0 and self.data[ind]>val: self.data[ind] = val ind //= 2 elif val>self.data[ind]: old_val = self.data[ind] self.data[ind] = val ind //= 2 while ind>0 and self.data[ind]==old_val: self.data[ind] = min(self.data[2*ind],self.data[2*ind+1]) ind //= 2 n, m = [int(x) for x in sys.stdin.readline().split()] inp = sys.stdin.readnumbers(3*m, 0.0) coupl = [[] for _ in range(n)] cost = [[] for _ in range(n)] for _ in range(m): v = int(inp[_*3+0])-1 u = int(inp[_*3+1])-1 w = inp[_*3+2] coupl[v].append(u) coupl[u].append(v) cost[u].append(w) cost[v].append(w) best = sys.stdin.readnumbers(n, 0.0) Q = segheap(best) while Q.data[1]!=big: c = Q.data[1] node = Q.mini() if best[node]!=c: continue for j in range(len(coupl[node])): nei = coupl[node][j] C = c+2*cost[node][j] if C<best[nei]: best[nei] = C Q.setter(nei,C) for x in best: sys.stdout.write(str(int(x))) sys.stdout.write(' ') ```
instruction
0
29,719
1
59,438
Yes
output
1
29,719
1
59,439
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well. There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route. Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is ai coins. You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). Formally, for every <image> you have to calculate <image>, where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large. Input The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105). Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input. The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city. Output Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). Examples Input 4 2 1 2 4 2 3 7 6 20 1 25 Output 6 14 1 25 Input 3 3 1 2 1 2 3 1 1 3 1 30 10 20 Output 12 10 12 Submitted Solution: ``` from heapq import heappush,heappop,heapify import sys input=sys.stdin.readline n,m=map(int,input().split()) g=[[] for i in range(n+1)] for _ in range(m): u,v,w=map(int,input().split()) g[u].append((v,w*2)) g[v].append((u,w*2)) a=['']+list(map(int,input().split())) ans=a.copy() hp=[(a[i],i) for i in range(1,n+1)] heapify(hp) # print(ans) # print(g) while hp: dcur,cur=heappop(hp) # print(dcur,cur) if dcur>ans[cur]:continue for v,w in g[cur]: if dcur+w<ans[v]: ans[v]=dcur+w heappush(hp,(ans[v],v)) print(*ans[1:]) ```
instruction
0
29,720
1
59,440
Yes
output
1
29,720
1
59,441
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well. There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route. Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is ai coins. You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). Formally, for every <image> you have to calculate <image>, where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large. Input The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105). Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input. The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city. Output Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). Examples Input 4 2 1 2 4 2 3 7 6 20 1 25 Output 6 14 1 25 Input 3 3 1 2 1 2 3 1 1 3 1 30 10 20 Output 12 10 12 Submitted Solution: ``` from __future__ import division, print_function py2 = round(0.5) if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange import os, sys from io import BytesIO, IOBase # FastIO for PyPy2 and PyPy3 by Pajenegod, class FastI(object): def __init__(self, fd=0, buffersize=2**14): self.stream = stream = BytesIO(); self.bufendl = 0 def read2buffer(): curpos = stream.tell(); s = os.read(fd, buffersize + os.fstat(fd).st_size) stream.seek(0,2); stream.write(s); stream.seek(curpos); return s self.read2buffer = read2buffer def read(self): while self.read2buffer(): pass return self.stream.read() if self.stream.tell() else self.stream.getvalue() def readline(self): while self.bufendl == 0: s = self.read2buffer(); self.bufendl += s.count(b'\n') + (not s) self.bufendl -= 1; return self.stream.readline() def input(self): return self.readline().rstrip(b'\r\n') def readnumbers(self, n,zero=0): conv = ord if py2 else lambda x:x A = []; numb = zero; sign = 1 curpos = self.stream.tell() self.stream.seek(0,2) buffsize = self.stream.tell() self.stream.seek(curpos) while len(A)<n: if curpos>=buffsize: self.read2buffer() self.stream.seek(0,2) buffsize = self.stream.tell() self.stream.seek(curpos) if curpos==buffsize: break s = self.stream.read(min(10000,buffsize-curpos)) i = 0 while i<len(s) and len(A)!=n: if s[i] >= b'0'[0]: numb = 10 * numb + (conv(s[i]) - 48) elif s[i] != b'\r'[0]: if s[i] == b'-'[0]: sign = -1 else: A.append(sign*numb); numb = zero; sign = 1 i += 1 curpos += i if curpos == buffsize and len(A)<n: A.append(sign*numb) assert(len(A)==n) self.stream.seek(curpos) return A class FastO(IOBase): def __init__(self, fd=1): stream = BytesIO() self.flush = lambda: os.write(1, stream.getvalue()) and not stream.truncate(0) and stream.seek(0) self.write = stream.write if py2 else lambda s: stream.write(s.encode()) sys.stdin, sys.stdout = FastI(), FastO() input = sys.stdin.readline big = 3E12 class segheap: def __init__(self,data): n = len(data) m = 1 while m<n:m*=2 self.n = n self.m = m self.data = [big]*(2*m) for i in range(n): self.data[i+m] = data[i] for i in reversed(range(m)): self.data[i] = min(self.data[2*i],self.data[2*i+1]) def mini(self): i = 1 while i<self.m: if self.data[i]==self.data[2*i]: i = 2*i else: i = 2*i+1 i -= self.m self.setter(i,big) return i def setter(self,ind,val): ind += self.m if val<self.data[ind]: while ind>0 and self.data[ind]>val: self.data[ind] = val ind //= 2 elif val>self.data[ind]: old_val = self.data[ind] self.data[ind] = val ind //= 2 while ind>0 and self.data[ind]==old_val: self.data[ind] = min(self.data[2*ind],self.data[2*ind+1]) ind //= 2 n, m = [int(x) for x in sys.stdin.readline().split()] inp = sys.stdin.readnumbers(3*m, 0.0) coupl = [[] for _ in range(n)] cost = [[] for _ in range(n)] for _ in range(m): v = int(inp[_*3+0]-1) u = int(inp[_*3+1]-1) w = inp[_*3+2] coupl[v].append(u) coupl[u].append(v) cost[u].append(w) cost[v].append(w) inp = sys.stdin.readnumbers(n, 0.0) best = [inp[i] for i in range(n)] Q = segheap(best) while Q.data[1]!=big: c = Q.data[1] node = Q.mini() if best[node]!=c: continue for j in range(len(coupl[node])): nei = coupl[node][j] C = c+2*cost[node][j] if C<best[nei]: best[nei] = C Q.setter(nei,C) for x in best: sys.stdout.write(str(int(x))) sys.stdout.write(' ') ```
instruction
0
29,721
1
59,442
Yes
output
1
29,721
1
59,443
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well. There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route. Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is ai coins. You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). Formally, for every <image> you have to calculate <image>, where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large. Input The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105). Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input. The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city. Output Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). Examples Input 4 2 1 2 4 2 3 7 6 20 1 25 Output 6 14 1 25 Input 3 3 1 2 1 2 3 1 1 3 1 30 10 20 Output 12 10 12 Submitted Solution: ``` from __future__ import division, print_function py2 = round(0.5) # Should take 900 ms something if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange import os, sys from io import BytesIO, IOBase # FastIO for PyPy2 and PyPy3 by Pajenegod, class FastI(object): def __init__(self, fd=0, buffersize=2**14): self.stream = stream = BytesIO(); self.bufendl = 0 def read2buffer(): curpos = stream.tell(); s = os.read(fd, buffersize + os.fstat(fd).st_size) stream.seek(0,2); stream.write(s); stream.seek(curpos); return s self.read2buffer = read2buffer def read(self): while self.read2buffer(): pass return self.stream.read() if self.stream.tell() else self.stream.getvalue() def readline(self): while self.bufendl == 0: s = self.read2buffer(); self.bufendl += s.count(b'\n') + (not s) self.bufendl -= 1; return self.stream.readline() def input(self): return self.readline().rstrip(b'\r\n') # Reads n integers (n=-1 is until end of input), use zero to change type def readnumbers(self, n=-1, zero=0): conv = ord if py2 else lambda x:x # Figure out curpos and buffer size curpos = self.stream.tell() self.stream.seek(0,2) buffsize = self.stream.tell() self.stream.seek(curpos) A = []; numb = zero; sign = 1 while n==-1 or len(A)<n: # If at end of current buffer if curpos == buffsize: s = self.read2buffer() buffsize += len(s) self.bufendl += s.count(b'\n') + (not s) if curpos == buffsize: break for i,c in enumerate(self.stream.read(min(32, buffsize-curpos))): if c >= b'0'[0]: numb = numb*10 + ((ord(c) if py2 else c) - 48) elif c == b'-'[0]: sign = -1 elif c != b'\r'[0]: # whitespace if c == b'\n'[0]: self.bufendl -= 1 A.append(sign*numb) if len(A)==n: break numb = zero; sign = 1 curpos += i + 1 # If no trailing whitespace if curpos == buffsize and not self.stream.seek(-1,2) and self.stream.read(1)[0] >= b'0'[0]: self.bufendl -= 1 A.append(sign*numb) assert(n==-1 or len(A)==n) self.stream.seek(curpos) return A class FastO(IOBase): def __init__(self, fd=1): stream = BytesIO() self.flush = lambda: os.write(1, stream.getvalue()) and not stream.truncate(0) and stream.seek(0) self.write = stream.write if py2 else lambda s: stream.write(s.encode()) sys.stdin, sys.stdout = FastI(), FastO() input = sys.stdin.readline big = 3E12 class segheap: def __init__(self,data): n = len(data) m = 1 while m<n:m*=2 self.n = n self.m = m self.data = [big]*(2*m) for i in range(n): self.data[i+m] = data[i] for i in reversed(range(m)): self.data[i] = min(self.data[2*i],self.data[2*i+1]) def mini(self): i = 1 while i<self.m: if self.data[i]==self.data[2*i]: i = 2*i else: i = 2*i+1 i -= self.m self.setter(i,big) return i def setter(self,ind,val): ind += self.m if val<self.data[ind]: while ind>0 and self.data[ind]>val: self.data[ind] = val ind //= 2 elif val>self.data[ind]: old_val = self.data[ind] self.data[ind] = val ind //= 2 while ind>0 and self.data[ind]==old_val: self.data[ind] = min(self.data[2*ind],self.data[2*ind+1]) ind //= 2 n, m = [int(x) for x in sys.stdin.readline().split()] inp = sys.stdin.readnumbers(3*m, 0.0) coupl = [[] for _ in range(n)] cost = [[] for _ in range(n)] for _ in range(m): v = int(inp[_*3+0])-1 u = int(inp[_*3+1])-1 w = inp[_*3+2] coupl[v].append(u) coupl[u].append(v) cost[u].append(w) cost[v].append(w) inp = sys.stdin.readnumbers(n, 0.0) best = [inp[i] for i in range(n)] Q = segheap(best) while Q.data[1]!=big: c = Q.data[1] node = Q.mini() if best[node]!=c: continue for j in range(len(coupl[node])): nei = coupl[node][j] C = c+2*cost[node][j] if C<best[nei]: best[nei] = C Q.setter(nei,C) for x in best: sys.stdout.write(str(int(x))) sys.stdout.write(' ') ```
instruction
0
29,722
1
59,444
Yes
output
1
29,722
1
59,445
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well. There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route. Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is ai coins. You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). Formally, for every <image> you have to calculate <image>, where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large. Input The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105). Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input. The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city. Output Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). Examples Input 4 2 1 2 4 2 3 7 6 20 1 25 Output 6 14 1 25 Input 3 3 1 2 1 2 3 1 1 3 1 30 10 20 Output 12 10 12 Submitted Solution: ``` from __future__ import division, print_function py2 = round(0.5) if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange import os, sys from io import BytesIO, IOBase # FastIO for PyPy2 and PyPy3 (works with interactive) by Pajenegod class FastI(object): def __init__(self, fd=0, buffersize=2**14): self.stream = stream = BytesIO(); self.bufendl = 0 def read2buffer(): s = os.read(fd, buffersize + os.fstat(fd).st_size); pos = stream.tell() stream.seek(0,2); stream.write(s); stream.seek(pos); return s self.read2buffer = read2buffer # Read entire input def read(self): while self.read2buffer(): pass return self.stream.read() if self.stream.tell() else self.stream.getvalue() def readline(self): while self.bufendl == 0: s = self.read2buffer(); self.bufendl += s.count(b'\n') + (not s) self.bufendl -= 1; return self.stream.readline() def input(self): return self.readline().rstrip(b'\r\n') # Read all remaining integers, type is given by optional argument def readnumbers(self, zero=0): conv = ord if py2 else lambda x:x A = []; numb = zero; sign = 1; c = b'-'[0] for c in self.read(): if c >= b'0'[0]: numb = 10 * numb + conv(c) - 48 elif c == b'-'[0]: sign = -1 elif c != b'\r'[0]: A.append(sign*numb); numb = zero; sign = 1 if c >= b'0'[0]: A.append(sign*numb) return A class FastO(IOBase): def __init__(self, fd=1): stream = BytesIO() self.flush = lambda: os.write(1, stream.getvalue()) and not stream.truncate(0) and stream.seek(0) self.write = stream.write if py2 else lambda s: stream.write(s.encode()) sys.stdin, sys.stdout = FastI(), FastO() input = sys.stdin.readline big = 3E12 class segheap: def __init__(self,data): n = len(data) m = 1 while m<n:m*=2 self.n = n self.m = m self.data = [big]*(2*m) for i in range(n): self.data[i+m] = data[i] for i in reversed(range(1, m)): self.data[i] = min(self.data[2*i],self.data[2*i^1]) def mini(self): val = self.data[1] i = 1 while i<self.m: i <<= 1 if self.data[i]!=val: i ^= 1 self.data[i] = big ind = i>>1 while ind: self.data[ind] = self.data[ind^1] ind >>= 1 return i-self.m def setter(self,ind,val): ind += self.m while ind: self.data[ind] = val val = min(val, self.data[ind^1]) ind //= 2 inp = sys.stdin.readnumbers(0.0) ind = 0 n = int(inp[ind]) ind += 1 m = int(inp[ind]) ind += 1 coupl = [[] for _ in range(n)] cost = [[] for _ in range(n)] for _ in range(m): v = int(inp[ind+0]) - 1 u = int(inp[ind+1]) - 1 w = inp[ind+2] ind += 3 coupl[v].append(u) coupl[u].append(v) cost[u].append(w) cost[v].append(w) best = inp[ind:] ind += n Q = segheap(best) while Q.data[1]!=big: c = Q.data[1] node = Q.mini() if best[node]!=c: continue for j in range(len(coupl[node])): nei = coupl[node][j] C = c + 2*cost[node][j] if C<best[nei]: best[nei] = C Q.setter(nei,C) for x in best: sys.stdout.write(str(int(x))) sys.stdout.write(' ') ```
instruction
0
29,723
1
59,446
No
output
1
29,723
1
59,447
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well. There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route. Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is ai coins. You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). Formally, for every <image> you have to calculate <image>, where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large. Input The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105). Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input. The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city. Output Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). Examples Input 4 2 1 2 4 2 3 7 6 20 1 25 Output 6 14 1 25 Input 3 3 1 2 1 2 3 1 1 3 1 30 10 20 Output 12 10 12 Submitted Solution: ``` from __future__ import division, print_function py2 = round(0.5) if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange import os, sys from io import BytesIO, IOBase # FastIO for PyPy2 and PyPy3 by Pajenegod class FastI(object): def __init__(self, fd=0, buffersize=2**14): self.stream = stream = BytesIO(); self.bufendl = 0 def read2buffer(): curpos = stream.tell(); s = os.read(fd, buffersize + os.fstat(fd).st_size) stream.seek(0,2); stream.write(s); stream.seek(curpos); return s self.read2buffer = read2buffer def read(self): while self.read2buffer(): pass return self.stream.read() if self.stream.tell() else self.stream.getvalue() def readline(self): while self.bufendl == 0: s = self.read2buffer(); self.bufendl += s.count(b'\n') + (not s) self.bufendl -= 1; return self.stream.readline() def input(self): return self.readline().rstrip(b'\r\n') class FastO(IOBase): def __init__(self, fd=1): stream = BytesIO() self.flush = os.write(1, stream.getvalue()) and not stream.truncate(0) and stream.seek(0) self.write = stream.write if py2 else lambda s: stream.write(s.encode()) sys.stdin, sys.stdout = FastI(), FastO() input = sys.stdin.readline big = 3E12 class segheap: def __init__(self,data): n = len(data) m = 1 while m<n:m*=2 self.n = n self.m = m self.data = [big]*(2*m) for i in range(n): self.data[i+m] = data[i] for i in reversed(range(m)): self.data[i] = min(self.data[2*i],self.data[2*i+1]) def mini(self): i = 1 while i<self.m: if self.data[i]==self.data[2*i]: i = 2*i else: i = 2*i+1 i -= self.m self.setter(i,big) return i def setter(self,ind,val): ind += self.m if val<self.data[ind]: while ind>0 and self.data[ind]>val: self.data[ind] = val ind //= 2 elif val>self.data[ind]: old_val = self.data[ind] self.data[ind] = val ind //= 2 while ind>0 and self.data[ind]==old_val: self.data[ind] = min(self.data[2*ind],self.data[2*ind+1]) ind //= 2 s = sys.stdin.read().replace(b'\r',b'') inp = [] numb = 0 for i in range(len(s)): if s[i]>=48: numb = 10*numb + s[i]-48 elif s[i]!=13: inp.append(numb) numb = 0 if s[-1]>=48: inp.append(numb) ind = 0 n = inp[ind] ind += 1 m = inp[ind] ind += 1 coupl = [[] for _ in range(n)] cost = [[] for _ in range(n)] for _ in range(m): v = inp[ind+0]-1 u = inp[ind+1]-1 w = 1.0*inp[ind+2] ind += 3 coupl[v].append(u) coupl[u].append(v) cost[u].append(w) cost[v].append(w) best = [1.0*inp[ind+i] for i in range(n)] Q = segheap(best) while Q.data[1]!=big: c = Q.data[1] node = Q.mini() if best[node]!=c: continue for j in range(len(coupl[node])): nei = coupl[node][j] C = c+2*cost[node][j] if C<best[nei]: best[nei] = C Q.setter(nei,C) for x in best: sys.stdout.write(str(int(x))) sys.stdout.write('\n') ```
instruction
0
29,724
1
59,448
No
output
1
29,724
1
59,449
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well. There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route. Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is ai coins. You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). Formally, for every <image> you have to calculate <image>, where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large. Input The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105). Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input. The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city. Output Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). Examples Input 4 2 1 2 4 2 3 7 6 20 1 25 Output 6 14 1 25 Input 3 3 1 2 1 2 3 1 1 3 1 30 10 20 Output 12 10 12 Submitted Solution: ``` from __future__ import division, print_function py2 = round(0.5) if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange import os, sys from io import BytesIO, IOBase # FastIO for PyPy2 and PyPy3 (works with interactive) by Pajenegod class FastI(object): def __init__(self, fd=0, buffersize=2**14): self.stream = stream = BytesIO(); self.bufendl = 0 def read2buffer(): s = os.read(fd, buffersize + os.fstat(fd).st_size); pos = stream.tell() stream.seek(0,2); stream.write(s); stream.seek(pos); return s self.read2buffer = read2buffer # Read entire input def read(self): while self.read2buffer(): pass return self.stream.read() if self.stream.tell() else self.stream.getvalue() def readline(self): while self.bufendl == 0: s = self.read2buffer(); self.bufendl += s.count(b'\n') + (not s) self.bufendl -= 1; return self.stream.readline() def input(self): return self.readline().rstrip(b'\r\n') # Read all remaining integers, type is given by optional argument def readnumbers(self, zero=0): conv = ord if py2 else lambda x:x A = []; numb = zero; sign = 1; c = b'-'[0] for c in self.read(): if c >= b'0'[0]: numb = 10 * numb + conv(c) - 48 elif c == b'-'[0]: sign = -1 elif c != b'\r'[0]: A.append(sign*numb); numb = zero; sign = 1 if c >= b'0'[0]: A.append(sign*numb) return A class FastO(IOBase): def __init__(self, fd=1): stream = BytesIO() self.flush = lambda: os.write(1, stream.getvalue()) and not stream.truncate(0) and stream.seek(0) self.write = stream.write if py2 else lambda s: stream.write(s.encode()) sys.stdin, sys.stdout = FastI(), FastO() input = sys.stdin.readline big = 3E12 class segheap: def __init__(self,data): n = len(data) m = 1 while m<n:m*=2 self.n = n self.m = m self.data = [big]*(2*m) for i in range(n): self.data[i+m] = data[i] for i in reversed(range(1, m)): self.data[i] = min(self.data[2*i],self.data[2*i^1]) def mini(self): val = self.data[1] i = 1 while i<self.m: i <<= 1 if self.data[i]!=val: i ^= 1 self.data[i] = big self.data[1] = big ind = i>>1 while ind: self.data[ind] = self.data[ind^1] ind >>= 1 return i-self.m def setter(self,ind,val): ind += self.m while ind: self.data[ind] = val val = min(val, self.data[ind^1]) ind //= 2 inp = sys.stdin.readnumbers(0.0) ind = 0 n = int(inp[ind]) ind += 1 m = int(inp[ind]) ind += 1 coupl = [[] for _ in range(n)] cost = [[] for _ in range(n)] for _ in range(m): v = int(inp[ind+0]) - 1 u = int(inp[ind+1]) - 1 w = inp[ind+2] ind += 3 coupl[v].append(u) coupl[u].append(v) cost[u].append(w) cost[v].append(w) best = inp[ind:] ind += n Q = segheap(best) while Q.data[1]!=big: c = Q.data[1] node = Q.mini() if best[node]!=c: continue for j in range(len(coupl[node])): nei = coupl[node][j] C = c + 2*cost[node][j] if C<best[nei]: best[nei] = C Q.setter(nei,C) for x in best: sys.stdout.write(str(int(x))) sys.stdout.write(' ') ```
instruction
0
29,725
1
59,450
No
output
1
29,725
1
59,451
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well. There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route. Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is ai coins. You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). Formally, for every <image> you have to calculate <image>, where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large. Input The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105). Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input. The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city. Output Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). Examples Input 4 2 1 2 4 2 3 7 6 20 1 25 Output 6 14 1 25 Input 3 3 1 2 1 2 3 1 1 3 1 30 10 20 Output 12 10 12 Submitted Solution: ``` from __future__ import division, print_function py2 = round(0.5) if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange import os, sys from io import BytesIO, IOBase # FastIO for PyPy2 and PyPy3 (works with interactive) by Pajenegod class FastI(object): def __init__(self, fd=0, buffersize=2**14): self.stream = stream = BytesIO(); self.bufendl = 0 def read2buffer(): s = os.read(fd, buffersize + os.fstat(fd).st_size); pos = stream.tell() stream.seek(0,2); stream.write(s); stream.seek(pos); return s self.read2buffer = read2buffer # Read entire input def read(self): while self.read2buffer(): pass return self.stream.read() if self.stream.tell() else self.stream.getvalue() def readline(self): while self.bufendl == 0: s = self.read2buffer(); self.bufendl += s.count(b'\n') + (not s) self.bufendl -= 1; return self.stream.readline() def input(self): return self.readline().rstrip(b'\r\n') # Read all remaining integers, type is given by optional argument def readnumbers(self, zero=0): conv = ord if py2 else lambda x:x A = []; numb = zero; sign = 1; c = b'-'[0] for c in self.read(): if c >= b'0'[0]: numb = 10 * numb + conv(c) - 48 elif c == b'-'[0]: sign = -1 elif c != b'\r'[0]: A.append(sign*numb); numb = zero; sign = 1 if c >= b'0'[0]: A.append(sign*numb) return A class FastO(IOBase): def __init__(self, fd=1): stream = BytesIO() self.flush = lambda: os.write(1, stream.getvalue()) and not stream.truncate(0) and stream.seek(0) self.write = stream.write if py2 else lambda s: stream.write(s.encode()) sys.stdin, sys.stdout = FastI(), FastO() input = sys.stdin.readline big = 3E12 class segheap: def __init__(self,data): n = len(data) m = 1 while m<n:m*=2 self.n = n self.m = m self.data = [big]*(2*m) for i in range(n): self.data[i+m] = data[i] for i in reversed(range(1, m)): self.data[i] = min(self.data[2*i],self.data[2*i^1]) def mini(self): val = self.data[1] self.data[1] = big i = 1 while i<self.m: i <<= 1 if self.data[i]!=val: i ^= 1 self.data[i] = big ind = i while ind: val = self.data[ind^1] ind >>= 1 while ind and self.data[ind^1]>val: ind >>= 1 self.data[ind] = val return i-self.m def setter(self,ind,val): ind += self.m while ind: self.data[ind] = val val = min(val, self.data[ind^1]) ind //= 2 inp = sys.stdin.readnumbers(0.0) ind = 0 n = int(inp[ind]) ind += 1 m = int(inp[ind]) ind += 1 coupl = [[] for _ in range(n)] cost = [[] for _ in range(n)] for _ in range(m): v = int(inp[ind+0]) - 1 u = int(inp[ind+1]) - 1 w = inp[ind+2] ind += 3 coupl[v].append(u) coupl[u].append(v) cost[u].append(w) cost[v].append(w) best = inp[ind:] ind += n Q = segheap(best) while Q.data[1]!=big: c = Q.data[1] node = Q.mini() if best[node]!=c: continue for j in range(len(coupl[node])): nei = coupl[node][j] C = c + 2*cost[node][j] if C<best[nei]: best[nei] = C Q.setter(nei,C) for x in best: sys.stdout.write(str(int(x))) sys.stdout.write(' ') ```
instruction
0
29,726
1
59,452
No
output
1
29,726
1
59,453
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This time you should help a team of researchers on an island in the Pacific Ocean. They research the culture of the ancient tribes that used to inhabit the island many years ago. Overall they've dug out n villages. Some pairs of villages were connected by roads. People could go on the roads in both directions. Overall there were exactly n - 1 roads, and from any village one could get to any other one. The tribes were not peaceful and they had many wars. As a result of the wars, some villages were destroyed completely. During more peaceful years some of the villages were restored. At each moment of time people used only those roads that belonged to some shortest way between two villages that existed at the given moment. In other words, people used the minimum subset of roads in such a way, that it was possible to get from any existing village to any other existing one. Note that throughout the island's whole history, there existed exactly n - 1 roads that have been found by the researchers. There never were any other roads. The researchers think that observing the total sum of used roads’ lengths at different moments of time can help to better understand the tribes' culture and answer several historical questions. You will be given the full history of the tribes' existence. Your task is to determine the total length of used roads at some moments of time. Input The first line contains an integer n (1 ≤ n ≤ 105) — the number of villages. The next n - 1 lines describe the roads. The i-th of these lines contains three integers ai, bi and ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 109, 1 ≤ i < n) — the numbers of villages that are connected by the i-th road and the road's length. The numbers in the lines are separated by a space. The next line contains an integer q (1 ≤ q ≤ 105) — the number of queries. Then follow q queries, one per line, ordered by time. Each query belongs to one of three types: * "+ x" — village number x is restored (1 ≤ x ≤ n). * "- x" — village number x is destroyed (1 ≤ x ≤ n). * "?" — the archaeologists want to know the total length of the roads which were used for that time period. It is guaranteed that the queries do not contradict each other, that is, there won't be queries to destroy non-existing villages or restore the already existing ones. It is guaranteed that we have at least one query of type "?". It is also guaranteed that one can get from any village to any other one by the given roads. At the initial moment of time no village is considered to exist. Output For each query of type "?" print the total length of used roads on a single line. You should print the answers to the queries in the order, in which they are given in the input. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier. Examples Input 6 1 2 1 1 3 5 4 1 7 4 5 3 6 4 2 10 + 3 + 1 ? + 6 ? + 5 ? - 6 - 3 ? Output 5 14 17 10 Submitted Solution: ``` from collections import defaultdict, deque from itertools import product def min_tuple(x, y): return min((x, y), (y, x)) num_villages = int(input()) road_lengths = {} neighbours = defaultdict(set) # dump = False for _ in range(num_villages - 1): x, y, l = map(int, input().split()) # if (x, y, l) == (6, 2, 808): # dump = True road_lengths[x, y] = l road_lengths[y, x] = l neighbours[x].add(y) neighbours[y].add(x) print(f'{x} -> {y} = {l}') spanning_tree = {} level = 0 roots = [(-1, 1)] visited = set() while roots: todo, roots = roots, [] for parent, child in todo: spanning_tree[child] = (parent, level) for n in neighbours[child]: if n != parent: roots.append((child, n)) level += 1 # print(f'{spanning_tree=}') paths = {} for frm, to in product(range(1, num_villages+1), range(1, num_villages+1)): if frm >= to: continue init_frm = frm init_to = to frm_path = [] to_path = [] frm_parent, frm_level = spanning_tree[frm] to_parent, to_level = spanning_tree[to] while frm_level > to_level: frm_path.append(min_tuple(frm, frm_parent)) frm = frm_parent frm_parent, frm_level = spanning_tree[frm] while frm_level < to_level: to_path.append(min_tuple(to, to_parent)) to = to_parent to_parent, to_level = spanning_tree[to] while frm_parent != to_parent: frm_path.append(min_tuple(frm, frm_parent)) frm = frm_parent frm_parent, frm_level = spanning_tree[frm] to_path.append(min_tuple(to, to_parent)) to = to_parent to_parent, to_level = spanning_tree[to] roads_to_parent = ( [min_tuple(frm, frm_parent), min_tuple(to, to_parent)] if frm != to else [] ) paths[init_frm, init_to] = set( frm_path + to_path + roads_to_parent ) live_villages = set() # for (frm, to), path in paths.items(): # print(f'{frm} -> {to} = {path}') # assert frm < to # 0 / 0 for _ in range(int(input())): query = input() # if dump: # q = query.replace(' ', '') # print(f'{q};', end='') if query[0] == '+': live_villages.add(int(query[2:])) elif query[0] == '-': live_villages.remove(int(query[2:])) else: # for frm, to in product(live_villages, live_villages): # if frm < to: # print(f'{frm} -> {to} = {paths[frm, to]}') roads_used = { road for frm, to in product(live_villages, live_villages) if frm < to for road in paths[frm, to] } # print(f'{roads_used=}') # for r in roads_used: # print(f'{r}\t{road_lengths[r]}') total = sum(map(road_lengths.__getitem__, roads_used)) print(total) ```
instruction
0
30,349
1
60,698
No
output
1
30,349
1
60,699
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This time you should help a team of researchers on an island in the Pacific Ocean. They research the culture of the ancient tribes that used to inhabit the island many years ago. Overall they've dug out n villages. Some pairs of villages were connected by roads. People could go on the roads in both directions. Overall there were exactly n - 1 roads, and from any village one could get to any other one. The tribes were not peaceful and they had many wars. As a result of the wars, some villages were destroyed completely. During more peaceful years some of the villages were restored. At each moment of time people used only those roads that belonged to some shortest way between two villages that existed at the given moment. In other words, people used the minimum subset of roads in such a way, that it was possible to get from any existing village to any other existing one. Note that throughout the island's whole history, there existed exactly n - 1 roads that have been found by the researchers. There never were any other roads. The researchers think that observing the total sum of used roads’ lengths at different moments of time can help to better understand the tribes' culture and answer several historical questions. You will be given the full history of the tribes' existence. Your task is to determine the total length of used roads at some moments of time. Input The first line contains an integer n (1 ≤ n ≤ 105) — the number of villages. The next n - 1 lines describe the roads. The i-th of these lines contains three integers ai, bi and ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 109, 1 ≤ i < n) — the numbers of villages that are connected by the i-th road and the road's length. The numbers in the lines are separated by a space. The next line contains an integer q (1 ≤ q ≤ 105) — the number of queries. Then follow q queries, one per line, ordered by time. Each query belongs to one of three types: * "+ x" — village number x is restored (1 ≤ x ≤ n). * "- x" — village number x is destroyed (1 ≤ x ≤ n). * "?" — the archaeologists want to know the total length of the roads which were used for that time period. It is guaranteed that the queries do not contradict each other, that is, there won't be queries to destroy non-existing villages or restore the already existing ones. It is guaranteed that we have at least one query of type "?". It is also guaranteed that one can get from any village to any other one by the given roads. At the initial moment of time no village is considered to exist. Output For each query of type "?" print the total length of used roads on a single line. You should print the answers to the queries in the order, in which they are given in the input. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier. Examples Input 6 1 2 1 1 3 5 4 1 7 4 5 3 6 4 2 10 + 3 + 1 ? + 6 ? + 5 ? - 6 - 3 ? Output 5 14 17 10 Submitted Solution: ``` from collections import defaultdict, deque from itertools import product def min_tuple(x, y): return min((x, y), (y, x)) num_villages = int(input()) road_lengths = {} neighbours = defaultdict(set) for _ in range(num_villages - 1): x, y, l = map(int, input().split()) road_lengths[x, y] = l road_lengths[y, x] = l neighbours[x].add(y) neighbours[y].add(x) # print(f'{x} -> {y} = {l}') spanning_tree = {} level = 0 roots = [(-1, 1)] visited = set() while roots: todo, roots = roots, [] for parent, child in todo: spanning_tree[child] = (parent, level) for n in neighbours[child]: if n != parent: roots.append((child, n)) level += 1 # print(f'{spanning_tree=}') paths = {} for frm, to in product(range(1, num_villages+1), range(1, num_villages+1)): if frm >= to: continue init_frm = frm init_to = to frm_path = [] to_path = [] frm_parent, frm_level = spanning_tree[frm] to_parent, to_level = spanning_tree[to] while frm_level > to_level: frm_path.append(min_tuple(frm, frm_parent)) frm = frm_parent frm_parent, frm_level = spanning_tree[frm] while frm_level < to_level: to_path.append(min_tuple(to, to_parent)) to = to_parent to_parent, to_level = spanning_tree[to] while frm_parent != to_parent: frm_path.append(min_tuple(frm, frm_parent)) frm = frm_parent frm_parent, frm_level = spanning_tree[frm] to_path.append(min_tuple(to, to_parent)) to = to_parent to_parent, to_level = spanning_tree[to] roads_to_parent = ( [min_tuple(frm, frm_parent), min_tuple(to, to_parent)] if frm_parent != -1 else [] ) paths[init_frm, init_to] = set( frm_path + to_path + roads_to_parent ) live_villages = set() # for (frm, to), path in paths.items(): # print(f'{frm} -> {to} = {path}') # assert frm < to # 0 / 0 for _ in range(int(input())): query = input() if query[0] == '+': live_villages.add(int(query[2:])) elif query[0] == '-': live_villages.remove(int(query[2:])) elif query[0] == '?': roads_used = { road for frm, to in product(live_villages, live_villages) if frm < to for road in paths[frm, to] } # print(f'{live_villages=}') # print(f'{roads_used=}') total = sum(map(road_lengths.__getitem__, roads_used)) print(total) else: raise Exception(query) ```
instruction
0
30,350
1
60,700
No
output
1
30,350
1
60,701
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This time you should help a team of researchers on an island in the Pacific Ocean. They research the culture of the ancient tribes that used to inhabit the island many years ago. Overall they've dug out n villages. Some pairs of villages were connected by roads. People could go on the roads in both directions. Overall there were exactly n - 1 roads, and from any village one could get to any other one. The tribes were not peaceful and they had many wars. As a result of the wars, some villages were destroyed completely. During more peaceful years some of the villages were restored. At each moment of time people used only those roads that belonged to some shortest way between two villages that existed at the given moment. In other words, people used the minimum subset of roads in such a way, that it was possible to get from any existing village to any other existing one. Note that throughout the island's whole history, there existed exactly n - 1 roads that have been found by the researchers. There never were any other roads. The researchers think that observing the total sum of used roads’ lengths at different moments of time can help to better understand the tribes' culture and answer several historical questions. You will be given the full history of the tribes' existence. Your task is to determine the total length of used roads at some moments of time. Input The first line contains an integer n (1 ≤ n ≤ 105) — the number of villages. The next n - 1 lines describe the roads. The i-th of these lines contains three integers ai, bi and ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 109, 1 ≤ i < n) — the numbers of villages that are connected by the i-th road and the road's length. The numbers in the lines are separated by a space. The next line contains an integer q (1 ≤ q ≤ 105) — the number of queries. Then follow q queries, one per line, ordered by time. Each query belongs to one of three types: * "+ x" — village number x is restored (1 ≤ x ≤ n). * "- x" — village number x is destroyed (1 ≤ x ≤ n). * "?" — the archaeologists want to know the total length of the roads which were used for that time period. It is guaranteed that the queries do not contradict each other, that is, there won't be queries to destroy non-existing villages or restore the already existing ones. It is guaranteed that we have at least one query of type "?". It is also guaranteed that one can get from any village to any other one by the given roads. At the initial moment of time no village is considered to exist. Output For each query of type "?" print the total length of used roads on a single line. You should print the answers to the queries in the order, in which they are given in the input. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier. Examples Input 6 1 2 1 1 3 5 4 1 7 4 5 3 6 4 2 10 + 3 + 1 ? + 6 ? + 5 ? - 6 - 3 ? Output 5 14 17 10 Submitted Solution: ``` from collections import defaultdict, deque from itertools import product def min_tuple(x, y): return min((x, y), (y, x)) num_villages = int(input()) road_lengths = {} neighbours = defaultdict(set) dump = False for _ in range(num_villages - 1): x, y, l = map(int, input().split()) if (x, y, l) == (6, 2, 808): dump = True road_lengths[x, y] = l road_lengths[y, x] = l neighbours[x].add(y) neighbours[y].add(x) # print(f'{x} -> {y} = {l}') spanning_tree = {} level = 0 roots = [(-1, 1)] visited = set() while roots: todo, roots = roots, [] for parent, child in todo: spanning_tree[child] = (parent, level) for n in neighbours[child]: if n != parent: roots.append((child, n)) level += 1 # print(f'{spanning_tree=}') paths = {} for frm, to in product(range(1, num_villages+1), range(1, num_villages+1)): if frm >= to: continue init_frm = frm init_to = to frm_path = [] to_path = [] frm_parent, frm_level = spanning_tree[frm] to_parent, to_level = spanning_tree[to] while frm_level > to_level: frm_path.append(min_tuple(frm, frm_parent)) frm = frm_parent frm_parent, frm_level = spanning_tree[frm] while frm_level < to_level: to_path.append(min_tuple(to, to_parent)) to = to_parent to_parent, to_level = spanning_tree[to] while frm_parent != to_parent: frm_path.append(min_tuple(frm, frm_parent)) frm = frm_parent frm_parent, frm_level = spanning_tree[frm] to_path.append(min_tuple(to, to_parent)) to = to_parent to_parent, to_level = spanning_tree[to] roads_to_parent = ( [min_tuple(frm, frm_parent), min_tuple(to, to_parent)] if frm_parent != -1 else [] ) paths[init_frm, init_to] = set( frm_path + to_path + roads_to_parent ) live_villages = set() # for (frm, to), path in paths.items(): # print(f'{frm} -> {to} = {path}') # assert frm < to # 0 / 0 for _ in range(int(input())): query = input() if dump: print(f'#{query}#', end='') if query[0] == '+': live_villages.add(int(query[2:])) elif query[0] == '-': live_villages.remove(int(query[2:])) else: roads_used = { road for frm, to in product(live_villages, live_villages) if frm < to for road in paths[frm, to] } # print(f'{live_villages=}') # print(f'{roads_used=}') total = sum(map(road_lengths.__getitem__, roads_used)) print(total) ```
instruction
0
30,351
1
60,702
No
output
1
30,351
1
60,703
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This time you should help a team of researchers on an island in the Pacific Ocean. They research the culture of the ancient tribes that used to inhabit the island many years ago. Overall they've dug out n villages. Some pairs of villages were connected by roads. People could go on the roads in both directions. Overall there were exactly n - 1 roads, and from any village one could get to any other one. The tribes were not peaceful and they had many wars. As a result of the wars, some villages were destroyed completely. During more peaceful years some of the villages were restored. At each moment of time people used only those roads that belonged to some shortest way between two villages that existed at the given moment. In other words, people used the minimum subset of roads in such a way, that it was possible to get from any existing village to any other existing one. Note that throughout the island's whole history, there existed exactly n - 1 roads that have been found by the researchers. There never were any other roads. The researchers think that observing the total sum of used roads’ lengths at different moments of time can help to better understand the tribes' culture and answer several historical questions. You will be given the full history of the tribes' existence. Your task is to determine the total length of used roads at some moments of time. Input The first line contains an integer n (1 ≤ n ≤ 105) — the number of villages. The next n - 1 lines describe the roads. The i-th of these lines contains three integers ai, bi and ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 109, 1 ≤ i < n) — the numbers of villages that are connected by the i-th road and the road's length. The numbers in the lines are separated by a space. The next line contains an integer q (1 ≤ q ≤ 105) — the number of queries. Then follow q queries, one per line, ordered by time. Each query belongs to one of three types: * "+ x" — village number x is restored (1 ≤ x ≤ n). * "- x" — village number x is destroyed (1 ≤ x ≤ n). * "?" — the archaeologists want to know the total length of the roads which were used for that time period. It is guaranteed that the queries do not contradict each other, that is, there won't be queries to destroy non-existing villages or restore the already existing ones. It is guaranteed that we have at least one query of type "?". It is also guaranteed that one can get from any village to any other one by the given roads. At the initial moment of time no village is considered to exist. Output For each query of type "?" print the total length of used roads on a single line. You should print the answers to the queries in the order, in which they are given in the input. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier. Examples Input 6 1 2 1 1 3 5 4 1 7 4 5 3 6 4 2 10 + 3 + 1 ? + 6 ? + 5 ? - 6 - 3 ? Output 5 14 17 10 Submitted Solution: ``` from collections import defaultdict, deque from itertools import product def min_tuple(x, y): return min((x, y), (y, x)) num_villages = int(input()) road_lengths = {} neighbours = defaultdict(set) for _ in range(num_villages - 1): x, y, l = map(int, input().split()) road_lengths[x, y] = l road_lengths[y, x] = l neighbours[x].add(y) neighbours[y].add(x) spanning_tree = {} level = 0 roots = [(-1, 1)] visited = set() while roots: todo, roots = roots, [] for parent, child in todo: spanning_tree[child] = (parent, level) for n in neighbours[child]: if n != parent: roots.append((child, n)) level += 1 paths = {} for frm, to in product(range(1, num_villages+1), range(1, num_villages+1)): if frm >= to: continue init_frm = frm init_to = to frm_path = [] to_path = [] frm_parent, frm_level = spanning_tree[frm] to_parent, to_level = spanning_tree[to] while frm_level > to_level: frm_path.append(min_tuple(frm, frm_parent)) frm = frm_parent frm_parent, frm_level = spanning_tree[frm] while frm_level < to_level: to_path.append(min_tuple(to, to_parent)) to = to_parent to_parent, to_level = spanning_tree[to] while frm_parent != to_parent: frm_path.append(min_tuple(frm, frm_parent)) frm = frm_parent frm_parent, frm_level = spanning_tree[frm] to_path.append(min_tuple(to, to_parent)) to = to_parent to_parent, to_level = spanning_tree[to] roads_to_parent = ( [min_tuple(frm, frm_parent), min_tuple(to, to_parent)] if frm_parent != -1 else [] ) paths[init_frm, init_to] = set( frm_path + to_path + roads_to_parent ) live_villages = set() for _ in range(int(input())): query = input() if query[0] == '+': live_villages.add(int(query[2:])) elif query[0] == '-': live_villages.remove(int(query[2:])) else: # ? roads_used = { road for frm, to in product(live_villages, live_villages) if frm < to for road in paths[frm, to] } total = sum(map(road_lengths.__getitem__, roads_used)) print(total) ```
instruction
0
30,352
1
60,704
No
output
1
30,352
1
60,705
Provide tags and a correct Python 3 solution for this coding contest problem. In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour. A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads. You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously. Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. Input The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. Output Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. Examples Input 4 2 1 3 3 4 Output 2 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output -1 Input 5 5 4 2 3 5 4 5 5 1 1 2 Output 3 Note In the first sample, the train can take the route <image> and the bus can take the route <image>. Note that they can arrive at town 4 at the same time. In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
instruction
0
30,492
1
60,984
Tags: graphs, shortest paths Correct Solution: ``` def bfs(V, start): D = [None] * (n + 1) D[start] = 0 Q = [start] Qstart = 0 while Qstart < len(Q): u = Q[Qstart] Qstart += 1 for v in V[u]: if D[v] is None: D[v] = D[u] + 1 Q.append(v) return D[n] n, m = tuple(map(int, input().split())) l1 = [set() for i in range(n + 1)] l = [set() for i in range(n + 1)] for i in range(m): edge = list(map(int, input().split())) l[edge[0]].add(edge[1]) l[edge[1]].add(edge[0]) if n not in l[1]: print(bfs(l, 1) if bfs(l, 1) != None else -1) else: for i in range(1, n + 1): for j in range(1, n + 1): if j not in l[i]: l1[i].add(j) print(bfs(l1, 1) if bfs(l1, 1) != None else -1) ```
output
1
30,492
1
60,985
Provide tags and a correct Python 3 solution for this coding contest problem. In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour. A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads. You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously. Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. Input The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. Output Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. Examples Input 4 2 1 3 3 4 Output 2 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output -1 Input 5 5 4 2 3 5 4 5 5 1 1 2 Output 3 Note In the first sample, the train can take the route <image> and the bus can take the route <image>. Note that they can arrive at town 4 at the same time. In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
instruction
0
30,493
1
60,986
Tags: graphs, shortest paths Correct Solution: ``` from queue import Queue import sys if __name__ == "__main__": def bfs(flag): vis = set() vis |= {1} q = Queue() q.put((1, 0)) while not q.empty(): u, dis = q.get() for v in range(1, n+1): if (v not in vis) and (((u, v) in h) == flag): vis |= {v} q.put((v, dis+1)) if v == n: return dis+1 return -1 n, m = map(int, input().split()) h = set() for _ in range(0, m): x, y = map(int, input().split()) h |= {(x, y)} h |= {(y, x)} dist1 = bfs(True) dist2 = bfs(False) # print(dist1, dist2) if dist1 == -1 or dist2 == -1: print(-1) else: print(max(dist1, dist2)) ```
output
1
30,493
1
60,987
Provide tags and a correct Python 3 solution for this coding contest problem. In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour. A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads. You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously. Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. Input The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. Output Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. Examples Input 4 2 1 3 3 4 Output 2 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output -1 Input 5 5 4 2 3 5 4 5 5 1 1 2 Output 3 Note In the first sample, the train can take the route <image> and the bus can take the route <image>. Note that they can arrive at town 4 at the same time. In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
instruction
0
30,494
1
60,988
Tags: graphs, shortest paths Correct Solution: ``` n, m = map(int, input().split()) d = [[0 for col in range(500)] for lin in range(500)] vet = [0] * 500 for i in range(m): x, y = map(int, input().split()) x -= 1 y -= 1 d[x][y] = 1 d[y][x] = 1 q = [0] l = 0 while l < len(q): for i in range(1, n): if d[0][n-1] != d[q[l]][i] and vet[i] == 0 : vet[i] = vet[q[l]] + 1 q.append(i) l += 1 if vet[n-1] == 0: print("-1") else: print(vet[n-1]) ```
output
1
30,494
1
60,989
Provide tags and a correct Python 3 solution for this coding contest problem. In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour. A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads. You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously. Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. Input The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. Output Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. Examples Input 4 2 1 3 3 4 Output 2 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output -1 Input 5 5 4 2 3 5 4 5 5 1 1 2 Output 3 Note In the first sample, the train can take the route <image> and the bus can take the route <image>. Note that they can arrive at town 4 at the same time. In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
instruction
0
30,495
1
60,990
Tags: graphs, shortest paths Correct Solution: ``` n, m = map(int,input().split()) rails = [set() for u in range(n+1)] for i in range(m): u, v = map(int,input().split()) rails[u].add(v) rails[v].add(u) roads = [set() for u in range(n+1)] for u in range(1,n+1): for v in range(u+1,n+1): if u not in rails[v]: roads[u].add(v) roads[v].add(u) def bfs(n,adj): # returns shortest dist from 1 to n dist = [-1 for i in range(n+1)] vis = [False for i in range(n+1)] frontier = [1] dist[1] = 0 ptr = 0 while ptr < len(frontier): u = frontier[ptr] if u==n: return dist[u] if not vis[u]: vis[u] = True for v in adj[u]: if dist[v]==-1: dist[v] = dist[u] + 1 frontier.append(v) ptr += 1 # we never reached n return -1 ans1, ans2 = bfs(n,rails), bfs(n,roads) if ans1==-1 or ans2==-1: print(-1) else: print(max(ans1,ans2)) ```
output
1
30,495
1
60,991
Provide tags and a correct Python 3 solution for this coding contest problem. In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour. A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads. You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously. Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. Input The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. Output Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. Examples Input 4 2 1 3 3 4 Output 2 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output -1 Input 5 5 4 2 3 5 4 5 5 1 1 2 Output 3 Note In the first sample, the train can take the route <image> and the bus can take the route <image>. Note that they can arrive at town 4 at the same time. In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
instruction
0
30,496
1
60,992
Tags: graphs, shortest paths Correct Solution: ``` import os import sys from io import BytesIO, IOBase import heapq as h from types import GeneratorType BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os 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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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: self.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 time start_time = time.time() import collections as col import math from functools import reduce def getInts(): return [int(s) for s in input().split()] def getInt(): return int(input()) def getStrs(): return [s for s in input().split()] def getStr(): return input() def listStr(): return list(input()) """ Construct a network of roads and a network of rails Note that it is always possible to go directly from 1 to N by road or rail, so as a starter we have that as an option, and the answer will be the result of a BFS starting at 1 on the other network. It is not possible to better this, since there is no shorter route on either service, and neither will clash. """ def solve(): rail = col.defaultdict(set) road = col.defaultdict(set) N, M = getInts() nodes = set() for i in range(1,N+1): for j in range(i+1,N+1): nodes.add((i,j)) for m in range(M): U, V = getInts() if U > V: U, V = V, U nodes.remove((U,V)) rail[U].add(V) rail[V].add(U) for U, V in nodes: road[U].add(V) road[V].add(U) def bfs(graph,start,end): visited = set() visited.add(start) queue = [(start,0)] queue = col.deque(queue) while queue: node, level = queue.popleft() for neighbour in graph[node]: if neighbour not in visited: visited.add(neighbour) queue.append((neighbour,level+1)) if neighbour == N: return level+1 return -1 if N in road[1]: return bfs(rail,1,N) return bfs(road,1,N) #for _ in range(getInt()): print(solve()) ```
output
1
30,496
1
60,993
Provide tags and a correct Python 3 solution for this coding contest problem. In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour. A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads. You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously. Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. Input The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. Output Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. Examples Input 4 2 1 3 3 4 Output 2 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output -1 Input 5 5 4 2 3 5 4 5 5 1 1 2 Output 3 Note In the first sample, the train can take the route <image> and the bus can take the route <image>. Note that they can arrive at town 4 at the same time. In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
instruction
0
30,497
1
60,994
Tags: graphs, shortest paths Correct Solution: ``` n,m=map(int,input().split()) f=[set() for i in range(n)] g,h=[0]+(n-1)*[10000],[0]+(n-1)*[10000] for i in range(m): u,v=map(int,input().split()) f[u-1].add(v-1) f[v-1].add(u-1) p={i for i in range(1,n)} def findrailway(t): if t==0: for c in f[t]: g[c]=g[t]+1 for c in f[t]: findrailway(c) if t!=n-1: pp=set() for c in(f[t]-f[0]): if g[c]!=min(g[c],g[t]+1): g[c]=g[t]+1 pp.add(c) for c in pp: findrailway(c) def findbusway(t): if t==0: for c in p-f[t]: h[c]=h[t]+1 for c in p-f[t]: findbusway(c) if t!=n-1: pp=set() for c in((p-f[t])-(p-f[0])): if h[c]!=min(h[c],h[t]+1): h[c]=h[t]+1 pp.add(c) for c in pp: findbusway(c) findrailway(0) findbusway(0) print(max(h[n-1],g[n-1]) if(h[n-1]!=g[n-1])and(h[n-1]<10000)and(g[n-1]<10000) else -1) ```
output
1
30,497
1
60,995
Provide tags and a correct Python 3 solution for this coding contest problem. In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour. A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads. You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously. Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. Input The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. Output Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. Examples Input 4 2 1 3 3 4 Output 2 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output -1 Input 5 5 4 2 3 5 4 5 5 1 1 2 Output 3 Note In the first sample, the train can take the route <image> and the bus can take the route <image>. Note that they can arrive at town 4 at the same time. In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
instruction
0
30,498
1
60,996
Tags: graphs, shortest paths Correct Solution: ``` def routes(n, m): distance = [0] * (n + 1) for i in range(n + 1): distance[i] = [1] * (n + 1) for x in range(m): a, b = map(int, input().split()) distance[a][b] = distance[b][a] = 2 x = 3 - distance[1][n] y = [0] * (n + 1) i = 1 d = [n + 1] * (n + 1) result = d[1] = 0 while (i != n): y[i] = 1 for j in range(1, n + 1): if (y[j] == 0 and distance[i][j] == x and d[j] > d[i] + 1): d[j] = d[i] + 1 end = n + 1 for j in range(1, n + 1): if (y[j] == 0 and d[j] < end): end = d[j] i = j if (end == n + 1): result = -1 break elif (i == n): result = d[n] break return result n, m = map(int, input().split()) print(routes(n, m)) ```
output
1
30,498
1
60,997
Provide tags and a correct Python 3 solution for this coding contest problem. In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour. A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads. You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously. Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. Input The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. Output Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. Examples Input 4 2 1 3 3 4 Output 2 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output -1 Input 5 5 4 2 3 5 4 5 5 1 1 2 Output 3 Note In the first sample, the train can take the route <image> and the bus can take the route <image>. Note that they can arrive at town 4 at the same time. In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
instruction
0
30,499
1
60,998
Tags: graphs, shortest paths Correct Solution: ``` # n m количество городов, количество железнодорожных перегонов from collections import deque n, m = map(int, input().split()) nodes = list() for i in range(n): nodes.append(set()) use_roads = False for i in range(m): rails_from, rails_to = map(int, input().split()) if (rails_from, rails_to) == (1, n) or \ (rails_from, rails_to) == (n, 1): use_roads = True nodes[rails_from - 1].add(rails_to - 1) nodes[rails_to - 1].add(rails_from - 1) if use_roads: for i_node, node in enumerate(nodes): nodes[i_node] = set(range(n)) - node - {i_node} q = deque() q.append(0) width = len(q) depth = 0 while True: try: if len(q) == 0: print(-1) exit(0) if width == 0: depth += 1 width = len(q) i_node = q.popleft() width -= 1 if i_node == n - 1: print(depth) exit(0) for node in nodes[i_node]: q.append(node) nodes[i_node].clear() except Exception as ex: print(ex) ```
output
1
30,499
1
60,999
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour. A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads. You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously. Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. Input The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. Output Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. Examples Input 4 2 1 3 3 4 Output 2 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output -1 Input 5 5 4 2 3 5 4 5 5 1 1 2 Output 3 Note In the first sample, the train can take the route <image> and the bus can take the route <image>. Note that they can arrive at town 4 at the same time. In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. Submitted Solution: ``` ex, ey = map(int, input().split()) c = [0] * (ex + 1) for l in range(ex + 1): c[l] = [1] * (ex + 1) for i in range(ey): a, b = map(int, input().split()) c[a][b] = c[b][a] = 2 x, v, i = 3 - c[1][ex], [0] * (ex + 1), 1 d = [ex + 1] * (ex + 1) time = d[1] = 0 while i != ex: v[i] = 1 for j in range(1, ex + 1): if v[j] == 0 and c[i][j] == x and d[j] > d[i] + 1: d[j] = d[i] + 1 m = ex + 1 for j in range(1, ex + 1): if v[j] == 0 and d[j] < m: m = d[j] i = j if m == ex + 1: time = -1 break elif i == ex: time = d[ex] break print(time) ```
instruction
0
30,500
1
61,000
Yes
output
1
30,500
1
61,001
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour. A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads. You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously. Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. Input The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. Output Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. Examples Input 4 2 1 3 3 4 Output 2 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output -1 Input 5 5 4 2 3 5 4 5 5 1 1 2 Output 3 Note In the first sample, the train can take the route <image> and the bus can take the route <image>. Note that they can arrive at town 4 at the same time. In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. Submitted Solution: ``` # -*- coding: utf-8 -*- """ Created on Tue Nov 28 20:27:33 2017 @author: alter027 """ import sys d=[[0 for col in range(500)] for row in range(500)] v=[0]*500 n, m=map(int, input().split()) for i in range(m): x, y=map(int, input().split()) x -= 1 y -= 1 d[x][y] = d[y][x]=1 q = [0] l = 0 while l < len(q): for i in range(1,n): if d[0][n-1] != d[q[l]][i] and v[i] == 0 : v[i] = v[q[l]] + 1 q.append(i) l += 1 if v[n-1] == 0: print(-1) else: print(v[n-1]) ```
instruction
0
30,501
1
61,002
Yes
output
1
30,501
1
61,003
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour. A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads. You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously. Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. Input The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. Output Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. Examples Input 4 2 1 3 3 4 Output 2 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output -1 Input 5 5 4 2 3 5 4 5 5 1 1 2 Output 3 Note In the first sample, the train can take the route <image> and the bus can take the route <image>. Note that they can arrive at town 4 at the same time. In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. Submitted Solution: ``` # maa chudaaye duniya from collections import defaultdict n, m = map(int, input().split()) temp = set([i for i in range(1, n+1)]) railway = defaultdict(list) for _ in range(m): u, v = map(int, input().split()) railway[u].append(v) railway[v].append(u) roads = defaultdict(list) for i in range(1, n+1): curr = set(railway[i]) curr = temp.difference(curr) curr.remove(i) roads[i] = list(curr) railway_trav = -1 queue = [[1, 0]] visited = [False for i in range(n+1)] visited[1] = True while(queue != []) : node, dist = queue[0] queue.pop(0) if node == n: railway_trav = dist break for child in railway[node]: if not visited[child]: visited[child] = True queue.append([child, dist+1]) roads_trav = -1 queue = [[1, 0]] visited = [False for i in range(n+1)] visited[1] = True while (queue != []): node, dist = queue[0] queue.pop(0) if node == n: roads_trav = dist break for child in roads[node]: if not visited[child]: visited[child] = True queue.append([child, dist+1]) if roads_trav == -1 or railway_trav == -1: print(-1) else: print(max(1, roads_trav, railway_trav)) ```
instruction
0
30,502
1
61,004
Yes
output
1
30,502
1
61,005
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour. A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads. You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously. Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. Input The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. Output Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. Examples Input 4 2 1 3 3 4 Output 2 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output -1 Input 5 5 4 2 3 5 4 5 5 1 1 2 Output 3 Note In the first sample, the train can take the route <image> and the bus can take the route <image>. Note that they can arrive at town 4 at the same time. In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. Submitted Solution: ``` n, m = map(int, input().split()) b = [[j for j in range(1,n+1) if j != i+1] for i in range(n)] b.insert(0,[]) t = [[] for i in range(n+1)] for _ in range(m): u, v = map(int, input().split()) b[u].remove(v) b[v].remove(u) t[u].append(v) t[v].append(u) def find_shorteset_path(n, start, des, adj): queue = [(start,0)] visited = [False for i in range(n+1)] visited[start] = True while queue != []: v = queue[0] if v[0] == des: return v[1] for neig in adj[v[0]]: if not visited[neig]: visited[neig]=True queue.append((neig, v[1]+1)) del queue[0] #print(queue) #print(visited) return False #print(b) bus_sol = find_shorteset_path(n, 1, n, b) #print(t) train_sol = find_shorteset_path(n, 1, n, t) if train_sol and bus_sol: print(max(train_sol, bus_sol)) else: print(-1) ```
instruction
0
30,503
1
61,006
Yes
output
1
30,503
1
61,007
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour. A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads. You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously. Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. Input The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. Output Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. Examples Input 4 2 1 3 3 4 Output 2 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output -1 Input 5 5 4 2 3 5 4 5 5 1 1 2 Output 3 Note In the first sample, the train can take the route <image> and the bus can take the route <image>. Note that they can arrive at town 4 at the same time. In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. Submitted Solution: ``` from heapq import * def short(v, g, u, d): heap = [] u[v] = True d[0] = 0 heappush(heap, (0, v)) while heap: w, v = heappop(heap) u[v] = True heap.clear() for i in g[v]: if not u[i[0]]: if w + i[1] < d[i[0]]: d[i[0]] = w + i[1] heappush(heap, (d[i[0]], i[0])) if __name__ == "__main__": n, m = map(int, input().split()) a = {} b = {} for i in range(n): a[i] = [(int(x), 1) for x in range(n)] b[i] = [] for i in range(m): u, v = map(int, input().split()) b[u - 1].append((v - 1, 1)) b[v - 1].append((u - 1, 1)) a[u - 1].remove((v - 1, 1)) a[v - 1].remove((u - 1, 1)) u_a = [False] * n u_b = [False] * n d_a = [500000] * n d_b = [500000] * n short(0, a, u_a, d_a) short(0, b, u_b, d_b) if (d_a[n - 1] == 500000 or d_b[n - 1] == 500000): print(-1) else: print(max(d_a[n - 1], d_b[n - 1])) ```
instruction
0
30,504
1
61,008
No
output
1
30,504
1
61,009
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour. A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads. You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously. Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. Input The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. Output Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. Examples Input 4 2 1 3 3 4 Output 2 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output -1 Input 5 5 4 2 3 5 4 5 5 1 1 2 Output 3 Note In the first sample, the train can take the route <image> and the bus can take the route <image>. Note that they can arrive at town 4 at the same time. In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. Submitted Solution: ``` import math def Floyd(id): for i in range(1, n+1): for j in range(1, n+1): for k in range(1, n+1): if dis[id][i][j] > dis[id][i][k]+dis[id][k][j]: dis[id][i][j] = dis[id][i][k]+dis[id][k][j] if dis[id][1][n] == math.inf: return -1 else: return dis[id][1][n] temp = input().split() n = int(temp[0]) m = int(temp[1]) dis = [[[None for i in range(1000)] for j in range(1000)] for k in range(2)] for i in range(1, 1+n): for j in range(1, 1+n): dis[0][i][j] = dis[1][i][j] = math.inf for i in range(m): temp = input().split() u = int(temp[0]) v = int(temp[1]) dis[0][u][v] = dis[0][v][u] = 1 for i in range(1, n+1): for j in range(1, n+1): if dis[0][i][j] == math.inf: dis[1][i][j] = 1 if dis[0][1][n] == 1: ans = Floyd(1) else: ans = Floyd(0) print(ans) ```
instruction
0
30,505
1
61,010
No
output
1
30,505
1
61,011
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour. A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads. You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously. Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. Input The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. Output Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. Examples Input 4 2 1 3 3 4 Output 2 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output -1 Input 5 5 4 2 3 5 4 5 5 1 1 2 Output 3 Note In the first sample, the train can take the route <image> and the bus can take the route <image>. Note that they can arrive at town 4 at the same time. In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. Submitted Solution: ``` n, m = map(int, input().split()) b = [[j for j in range(1,n+1) if j != i+1] for i in range(n)] b.insert(0,[]) t = [[] for i in range(n+1)] for _ in range(m): u, v = map(int, input().split()) b[u].remove(v) b[v].remove(u) t[u].append(v) t[v].append(u) def find_shorteset_path(n, start, des, adj): queue = [(start,0)] visited = [False for i in range(n+1)] visited[start] = True while queue != []: v = queue[0] if v[0] == des: return v[1] for neig in adj[v[0]]: if not visited[neig]: visited[neig]=True queue.append((neig, v[1]+1)) del queue[0] print(queue) print(visited) return False print(b) bus_sol = find_shorteset_path(n, 1, n, b) print(t) train_sol = find_shorteset_path(n, 1, n, t) if train_sol and bus_sol: print(max(train_sol, bus_sol)) else: print(-1) ```
instruction
0
30,506
1
61,012
No
output
1
30,506
1
61,013
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour. A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads. You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously. Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so. Input The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns. Output Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1. Examples Input 4 2 1 3 3 4 Output 2 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output -1 Input 5 5 4 2 3 5 4 5 5 1 1 2 Output 3 Note In the first sample, the train can take the route <image> and the bus can take the route <image>. Note that they can arrive at town 4 at the same time. In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4. Submitted Solution: ``` # n m количество городов, количество железнодорожных перегонов from collections import deque import sys sys.setrecursionlimit(1500) n, m = map(int, input().split()) nodes = list() for i in range(n): nodes.append(set()) use_roads = False for i in range(m): rails_from, rails_to = map(int, input().split()) if (rails_from, rails_to) == (1, n) or \ (rails_from, rails_to) == (n, 1): use_roads = True nodes[rails_from - 1].add(rails_to - 1) nodes[rails_to - 1].add(rails_from - 1) if use_roads: for i_node, node in enumerate(nodes): nodes[i_node] = set(range(n)) - node - {i_node} def bfs(nodes, q, depth, width): try: if len(q) == 0: print(-1) return if width == 0: depth += 1 width = len(q) i_node = q.popleft() width -= 1 if i_node == n - 1: print(depth) return for node in nodes[i_node]: q.append(node) nodes[i_node].clear() bfs(nodes, q, depth, width) except Exception as ex: print(ex) q = deque() q.append(0) width = len(q) depth = 0 bfs(nodes, q, depth, width) ```
instruction
0
30,507
1
61,014
No
output
1
30,507
1
61,015
Provide tags and a correct Python 3 solution for this coding contest problem. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
instruction
0
30,545
1
61,090
Tags: brute force, data structures, implementation, trees Correct Solution: ``` from math import log2 class Node: def __init__(self, level, left, right, parent, val): self.val = val self.level = level self.left = left self.right = right self.parent = parent tree = dict() def create_path(u): if u == 0 or u in tree: return node = Node(log2(u), [u+u, 0], [u+u+1, 0], [u//2, 0], u) tree[u] = node create_path(u//2) def ascend(x, cost, w=0): x.parent[1] += w cost += x.parent[1] tree[x.val] = x x = tree[x.parent[0]] return cost, x def common_ancestor(u, v, w=0): a = tree[u] b = tree[v] cost = 0 # Assuming the object passed as parameter is modified by fn # And cost is not modified while a != b: if a.level == b.level: cost,a = ascend(a, cost, w) cost,b = ascend(b, cost, w) elif a.level < b.level: cost,b = ascend(b, cost, w) elif b.level < a.level: cost,a = ascend(a, cost, w) return cost def update_path(u, v, w): if u not in tree: create_path(u) if v not in tree: create_path(v) # Cost of traveling from a to b # if w != 0 # also updates the cost during travel, and returns the correct cost cost = common_ancestor(u, v, w) return cost def main(): # n1 = Node(0, [2,0], [3,0], [0,0],1) # n2 = Node(1, [4,0], [5,0], [1,0],2) # n3 = Node(1, [6,0], [7,0], [1,0],3) # tree[1] = n1 # tree[2] = n2 # tree[3] = n3 # # cost,n2 = ascend(n2, 0, 4) # # print(cost, n2.level, n2.val) # print(cost, tree[2].parent) # # return q = int(input()) for i in range(q): str = input() w = None if str[0] == '1': z, v, u, w = [int(x) for x in str.split()] if v < u: u, v = v, u update_path(u, v, w) else: z, v, u = [int(x) for x in str.split()] if v < u: u, v = v, u print(update_path(u, v, 0)) main() ```
output
1
30,545
1
61,091
Provide tags and a correct Python 3 solution for this coding contest problem. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
instruction
0
30,546
1
61,092
Tags: brute force, data structures, implementation, trees Correct Solution: ``` def main(): d = {} for _ in range(int(input())): c, *l = input().split() if c == "1": v, u, w = map(int, l) while u != v: if u < v: d[v] = d.get(v, 0) + w u, v = v // 2, u else: d[u] = d.get(u, 0) + w u //= 2 else: res = 0 v, u = map(int, l) while u != v: if u < v: res += d.get(v, 0) u, v = v // 2, u else: res += d.get(u, 0) u //= 2 print(res) if __name__ == "__main__": main() ```
output
1
30,546
1
61,093
Provide tags and a correct Python 3 solution for this coding contest problem. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
instruction
0
30,547
1
61,094
Tags: brute force, data structures, implementation, trees Correct Solution: ``` def UCLN(a,b): while (a!=b): if a > b: a = a//2 else: b = b//2 return a def find_path(u,v): ucln = UCLN(u,v) arr1 = [] arr2 = [] while (u >= ucln): arr1.append(u) u = u//2 while (v > ucln): arr2.append(v) v = v//2 return arr1 + arr2[::-1] p = int(input()) dic = {} for i in range(p): value = list(map(int, input().split())) action = value[0] if action == 1: path = find_path(value[1], value[2]) for i in range(len(path)-1): if "{}{}".format(path[i],path[i+1]) not in dic and "{}{}".format(path[i+1],path[i]) not in dic: dic["{}{}".format(path[i],path[i+1])] = value[3] dic["{}{}".format(path[i+1],path[i])] = value[3] else: dic["{}{}".format(path[i],path[i+1])] += value[3] dic["{}{}".format(path[i+1],path[i])] += value[3] else: #action == 2 total = 0 path = find_path(value[1], value[2]) for i in range(len(path)-1): if "{}{}".format(path[i],path[i+1]) in dic: total += dic["{}{}".format(path[i],path[i+1])] print (total) ```
output
1
30,547
1
61,095
Provide tags and a correct Python 3 solution for this coding contest problem. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
instruction
0
30,548
1
61,096
Tags: brute force, data structures, implementation, trees Correct Solution: ``` def path_to_root(n): path = [n] while n != 1: if n % 2: path.append((n - 1) // 2) n = (n - 1) // 2 else: path.append(n // 2) n //= 2 return path def path_beetwen(a, b): p1 = path_to_root(a) p2 = path_to_root(b) l1 = len(p1) l2 = len(p2) x = 0 while x < l2: if p2[x] in p1: break x += 1 path = p1[:p1.index(p2[x]) + 1] + p2[:x][::-1] return path def fee_on_path(fees, a, b): path = path_beetwen(a, b) total_fee = 0 for x in range(len(path) - 1): fee = str(path[x]) + "_" + str(path[x + 1]) if fee in fees.keys(): total_fee += fees[fee] return total_fee def update_fees(fees, a, b, w): path = path_beetwen(a, b) for x in range(len(path) - 1): fee = str(path[x]) + "_" + str(path[x + 1]) fee2 = str(path[x + 1]) + "_" + str(path[x]) if fee in fees.keys(): fees[fee] += w else: fees[fee] = w if fee2 in fees.keys(): fees[fee2] += w else: fees[fee2] = w class CodeforcesTask696ASolution: def __init__(self): self.result = '' self.events_count = 0 self.events = [] def read_input(self): self.events_count = int(input()) for x in range(self.events_count): self.events.append([int(y) for y in input().split(" ")]) def process_task(self): fees = {} for x in range(self.events_count): if self.events[x][0] == 1: update_fees(fees, self.events[x][1], self.events[x][2], self.events[x][3]) else: print(fee_on_path(fees, self.events[x][1], self.events[x][2])) #print(fees) def get_result(self): return self.result if __name__ == "__main__": Solution = CodeforcesTask696ASolution() Solution.read_input() Solution.process_task() print(Solution.get_result()) ```
output
1
30,548
1
61,097
Provide tags and a correct Python 3 solution for this coding contest problem. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
instruction
0
30,549
1
61,098
Tags: brute force, data structures, implementation, trees Correct Solution: ``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jul 15 23:50:55 2020 @author: shailesh """ from collections import defaultdict def find_cost(node_1,node_2,intersect_dict): new_dict = defaultdict(lambda : 0) cost = 0 while node_1 != 0: new_dict[node_1] = 1 cost+= intersect_dict[node_1] # print(node_1,cost) node_1 //= 2 while node_2!=0: if new_dict[node_2]: cost -= intersect_dict[node_2] # print(node_2) break else: new_dict[node_2] = 1 cost += intersect_dict[node_2] node_2 //= 2 # print(node_2,cost) while node_2 != 0: node_2 //= 2 cost -= intersect_dict[node_2] return cost def increase_cost_on_path(node_1,node_2,inc_cost,intersect_dict): new_dict = defaultdict(lambda :0) while node_1 != 0: new_dict[node_1] = 1 intersect_dict[node_1] += inc_cost node_1 //= 2 while node_2 != 0 : if new_dict[node_2]: break else: intersect_dict[node_2] += inc_cost node_2//=2 while node_2 != 0: intersect_dict[node_2] -= inc_cost node_2 //= 2 return intersect_dict Q = int(input()) #arr = [0 for i in range(n+1)] intersect_dict = defaultdict(lambda : 0) for q in range(Q): query = [int(i) for i in input().split()] if query[0] == 1: v,u,w = query[1:] intersect_dict = increase_cost_on_path(v,u,w,intersect_dict) else: v,u = query[1:] cost = find_cost(u,v,intersect_dict) print(cost) ```
output
1
30,549
1
61,099
Provide tags and a correct Python 3 solution for this coding contest problem. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
instruction
0
30,550
1
61,100
Tags: brute force, data structures, implementation, trees Correct Solution: ``` q = int(input()) def get_path(u, v): u2 = u v2 = v u_visited = set() while u2 > 1: u_visited.add(u2) u2 = u2 // 2 u_visited.add(1) v2_path = [] while v2 not in u_visited: v2_path.append(v2) v2 = v2 // 2 path = v2_path + sorted([x for x in u_visited if x >= v2]) return path prices = {} for i in range(q): row = list(map(int, input().split())) if row[0] == 1: u, v, w = row[1:] path = get_path(*sorted([u, v])) for a_, b_ in zip(path, path[1:]): a, b = sorted([a_, b_]) prices.setdefault((a, b), 0) prices[(a, b)] += w else: u, v = row[1:] path = get_path(*sorted([u, v])) price = 0 for a_, b_ in zip(path, path[1:]): a, b = sorted([a_, b_]) price += prices.get((a, b), 0) print(price) ```
output
1
30,550
1
61,101
Provide tags and a correct Python 3 solution for this coding contest problem. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
instruction
0
30,551
1
61,102
Tags: brute force, data structures, implementation, trees Correct Solution: ``` q = int(input()) d = {} for sfsdfdsg in range(q): L = [int(x) for x in input().split()] if L[0] == 1: a, b, w = L[1:] while a != b: if a < b: a, b = b, a c = a>>1 if (c, a) not in d: d[(c, a)] = 0 d[(c, a)] += w a = c else: a, b = L[1:] cost = 0 while a != b: if a < b: a, b = b, a c = a>>1 if (c, a) not in d: d[(c, a)] = 0 cost += d[(c, a)] a = c print(cost) ```
output
1
30,551
1
61,103
Provide tags and a correct Python 3 solution for this coding contest problem. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
instruction
0
30,552
1
61,104
Tags: brute force, data structures, implementation, trees Correct Solution: ``` from sys import stdin from collections import * def arr_inp(n): return [int(x) for x in stdin.readline().split()] def lca(u, v, w): res = 0 while u != v: if u < v: u, v = v, u if w: mem[u, u >> 1] += w mem[u >> 1, u] += w else: res += mem[u, u >> 1] u >>= 1 return res ans, mem = [], defaultdict(int) for i in range(int(input())): arr = arr_inp(1) if arr[0] == 1: lca(arr[1], arr[2], arr[3]) else: ans.append(str(lca(arr[1], arr[2], 0))) print('\n'.join(ans)) ```
output
1
30,552
1
61,105
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). Submitted Solution: ``` def IncreaseCost(x, y, z): a = min(x, y) b = max(x, y) while a!=b: while b>a: if not str(b//2)+' '+str(b) in d: d[str(b//2)+' '+str(b)] = z else: d[str(b//2)+' '+str(b)] = d[str(b//2)+' '+str(b)]+z b = b//2 a, b = b, a def CountCost(x, y): res = 0 a = min(x, y) b = max(x, y) while a!=b: while b>a: if str(b//2)+' '+str(b) in d: res = res+d[str(b//2)+' '+str(b)] b = b//2 a, b = b, a return (res) q = int(input()) d = {} res = [] for i in range(0, q): line = input().split() if line[0]=='1': IncreaseCost(int(line[1]), int(line[2]), int(line[3])) else: res = res + [(CountCost(int(line[1]), int(line[2])))] for i in res: print (i) ```
instruction
0
30,553
1
61,106
Yes
output
1
30,553
1
61,107
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). Submitted Solution: ``` def find_path(x,y): p1,p2 = [],[] while x!=0: p1.append(x) x = x//2 while y!=0: p2.append(y) y = y//2 p1 = p1[::-1] p2 = p2[::-1] # print (p1,p2) for i in range(min(len(p1),len(p2))): if p1[i]==p2[i]: ind = i else: break path = [] for i in range(ind,len(p1)): path.append(p1[i]) path = path[::-1] for i in range(ind+1,len(p2)): path.append(p2[i]) return path q = int(input()) cost = {} for i in range(q): a = list(map(int,input().split())) b = find_path(a[1],a[2]) # print (b) if a[0] == 1: w = a[-1] for j in range(1,len(b)): if (b[j],b[j-1]) not in cost: cost[(b[j],b[j-1])] = w cost[(b[j-1],b[j])] = w else: cost[(b[j],b[j-1])] += w cost[(b[j-1],b[j])] += w else: ans = 0 for j in range(1,len(b)): if (b[j],b[j-1]) in cost: ans += cost[(b[j],b[j-1])] print (ans) ```
instruction
0
30,554
1
61,108
Yes
output
1
30,554
1
61,109
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). Submitted Solution: ``` def lca(u, v): x = list(bin(u)[2:]) y = list(bin(v)[2:]) res = [] pos = 0 k = min(len(x), len(y)) while pos < k and x[pos] == y[pos]: res.append(x[pos]) pos += 1 res = int(''.join(res), 2) return res read = lambda: map(int, input().split()) q = int(input()) from collections import Counter d = Counter() for i in range(q): s = input().split() t = int(s[0]) if t == 1: u, v, w = map(int, s[1:]) p = lca(u, v) cur = u while cur != p: d[cur] += w cur //= 2 cur = v while cur != p: d[cur] += w cur //= 2 if t == 2: u, v = map(int, s[1:]) p = lca(u, v) res = 0 cur = u while cur != p: res += d[cur] cur //= 2 cur = v while cur != p: res += d[cur] cur //= 2 print(res) ```
instruction
0
30,555
1
61,110
Yes
output
1
30,555
1
61,111
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). Submitted Solution: ``` from collections import Counter def read_int(): return int(input().strip()) def read_ints(): return list(map(int, input().strip().split(' '))) def shortest_path(i, j): path = [] while i != j: if i > j: path.append((i//2, i)) i //= 2 else: path.append((j//2, j)) j //= 2 return path def solve(): q = read_int() wage = Counter() for _ in range(q): l = read_ints() if l[0] == 1: u, v, w = l[1:] if u > v: u, v = v, u for pair in shortest_path(u, v): wage[pair] += w else: u, v = l[1:] if u > v: u, v = v, u T = 0 for pair in shortest_path(u, v): T += wage[pair] print(T) if __name__ == '__main__': solve() ```
instruction
0
30,556
1
61,112
Yes
output
1
30,556
1
61,113
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). Submitted Solution: ``` from sys import stdin from collections import defaultdict def path(v,w): result=[] while True: if v == w: return result if v < w: w2 = int(w/2) if (w2!=w): result = result + [(w2,w)] w=w2 if w < v: v2 = int(v/2) if (v2!=v): result = result + [(v2,v)] v=v2 d = defaultdict(lambda : 0) q = int(stdin.readline()) for line in stdin.readlines()[0:q]: vals = line.split() if vals[0]=='1': v,u,w = int(vals[1]), int(vals[2]), int(vals[3]) for edge in path(u,v): d[edge] = d[edge] + w if vals[0]=='2': v,u = int(vals[1]), int(vals[2]) cost = 0 for edge in path(u,v): cost = cost + d[edge] print(cost) ```
instruction
0
30,557
1
61,114
No
output
1
30,557
1
61,115
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). Submitted Solution: ``` q = int(input()) def get_path(u, v): u2 = u v2 = v u_visited = set() while u2 > 1: u_visited.add(u2) u2 = u2 // 2 u_visited.add(1) v2_path = [] while v2 not in u_visited: v2_path.append(v2) v2 = v2 // 2 path = v2_path + sorted([x for x in u_visited if x >= v2]) return path prices = {} for i in range(q): row = list(map(int, input().split())) if row[0] == 1: u, v, w = row[1:] path = get_path(*sorted([u, v])) for a, b in zip(path, path[1:]): prices.setdefault((a, b), 0) prices[(a, b)] += w else: u, v = row[1:] path = get_path(*sorted([u, v])) price = 0 for a, b in zip(path, path[1:]): price += prices.get((a, b), 0) print(price) ```
instruction
0
30,558
1
61,116
No
output
1
30,558
1
61,117
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). Submitted Solution: ``` from sys import stdin, stdout n = int(stdin.readline()) prices = {} for i in range(n): s = stdin.readline().strip() if int(s[0]) == 1: ind, a, b, w = map(int, s.split()) while a != b: if a > b: if (a, a // 2) not in prices: prices[(a, a // 2)] = w else: prices[(a, a // 2)] += w a //= 2 else: if (b, b // 2) not in prices: prices[(b, b // 2)] = w else: prices[(b, b // 2)] += w b //= 2 else: ind, a, b = map(int, s.split()) cnt = 0 while a != b: if a > b: if (a, a // 2) in prices: cnt += prices[(a, a // 2)] a //= 2 else: if (b, b // 2) in prices: cnt += prices[(b, b // 2)] b //= 2 stdout.write(str(cnt) + '\n') ```
instruction
0
30,559
1
61,118
No
output
1
30,559
1
61,119
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). Submitted Solution: ``` q = int(input()) def full_way(u): res = set() while u > 1: res.add(u) u //= 2 return res def get_way(u, v): res1 = full_way(u) res2 = full_way(v) m = min((res1 & res2) or [1]) res = set() for x in res1 | res2: if x > m: res.add(x) return res d = {} for i in range(q): a = input().split() if a[0] == '1': v, u, w = map(int, a[1:]) print(sorted(get_way(u, v))) for x in get_way(u, v): if x not in d: d[x] = 0 d[x] += w print(d) else: v, u = map(int, a[1:]) print(sorted(get_way(u, v))) res = 0 for x in get_way(u, v): if x in d: res += d[x] print(res) ```
instruction
0
30,560
1
61,120
No
output
1
30,560
1
61,121