message stringlengths 2 49.9k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 446 108k | cluster float64 13 13 | __index_level_0__ int64 892 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a positive integer D. Let's build the following graph from it:
* each vertex is a divisor of D (not necessarily prime, 1 and D itself are also included);
* two vertices x and y (x > y) have an undirected edge between them if x is divisible by y and \frac x y is a prime;
* the weight of an edge is the number of divisors of x that are not divisors of y.
For example, here is the graph for D=12:
<image>
Edge (4,12) has weight 3 because 12 has divisors [1,2,3,4,6,12] and 4 has divisors [1,2,4]. Thus, there are 3 divisors of 12 that are not divisors of 4 — [3,6,12].
There is no edge between 3 and 2 because 3 is not divisible by 2. There is no edge between 12 and 3 because 12/3=4 is not a prime.
Let the length of the path between some vertices v and u in the graph be the total weight of edges on it. For example, path [(1, 2), (2, 6), (6, 12), (12, 4), (4, 2), (2, 6)] has length 1+2+2+3+1+2=11. The empty path has length 0.
So the shortest path between two vertices v and u is the path that has the minimal possible length.
Two paths a and b are different if there is either a different number of edges in them or there is a position i such that a_i and b_i are different edges.
You are given q queries of the following form:
* v u — calculate the number of the shortest paths between vertices v and u.
The answer for each query might be large so print it modulo 998244353.
Input
The first line contains a single integer D (1 ≤ D ≤ 10^{15}) — the number the graph is built from.
The second line contains a single integer q (1 ≤ q ≤ 3 ⋅ 10^5) — the number of queries.
Each of the next q lines contains two integers v and u (1 ≤ v, u ≤ D). It is guaranteed that D is divisible by both v and u (both v and u are divisors of D).
Output
Print q integers — for each query output the number of the shortest paths between the two given vertices modulo 998244353.
Examples
Input
12
3
4 4
12 1
3 4
Output
1
3
1
Input
1
1
1 1
Output
1
Input
288807105787200
4
46 482955026400
12556830686400 897
414 12556830686400
4443186242880 325
Output
547558588
277147129
457421435
702277623
Note
In the first example:
* The first query is only the empty path — length 0;
* The second query are paths [(12, 4), (4, 2), (2, 1)] (length 3+1+1=5), [(12, 6), (6, 2), (2, 1)] (length 2+2+1=5) and [(12, 6), (6, 3), (3, 1)] (length 2+2+1=5).
* The third query is only the path [(3, 1), (1, 2), (2, 4)] (length 1+1+1=3). | instruction | 0 | 18,671 | 13 | 37,342 |
Tags: combinatorics, graphs, greedy, math, number theory
Correct Solution:
```
from collections import Counter
def gcd(x, y):
"""greatest common divisor of x and y"""
while y:
x, y = y, x % y
return x
def memodict(f):
"""memoization decorator for a function taking a single argument"""
class memodict(dict):
def __missing__(self, key):
ret = self[key] = f(key)
return ret
return memodict().__getitem__
def pollard_rho(n):
"""returns a random factor of n"""
if n & 1 == 0:
return 2
if n % 3 == 0:
return 3
s = ((n - 1) & (1 - n)).bit_length() - 1
d = n >> s
for a in [2, 325, 9375, 28178, 450775, 9780504, 1795265022]:
p = pow(a, d, n)
if p == 1 or p == n - 1 or a % n == 0:
continue
for _ in range(s):
prev = p
p = (p * p) % n
if p == 1:
return gcd(prev - 1, n)
if p == n - 1:
break
else:
for i in range(2, n):
x, y = i, (i * i + 1) % n
f = gcd(abs(x - y), n)
while f == 1:
x, y = (x * x + 1) % n, (y * y + 1) % n
y = (y * y + 1) % n
f = gcd(abs(x - y), n)
if f != n:
return f
return n
@memodict
def prime_factors(n):
"""returns a Counter of the prime factorization of n"""
if n <= 1:
return Counter()
f = pollard_rho(n)
return Counter([n]) if f == n else prime_factors(f) + prime_factors(n // f)
def distinct_factors(n, primes):
"""returns a list of all distinct factors of n"""
factors = [1]
for p, exp in primes.items():
factors += [p**i * factor for factor in factors for i in range(1, exp + 1)]
return factors
def all_factors(n):
"""returns a sorted list of all distinct factors of n"""
small, large = [], []
for i in range(1, int(n**0.5) + 1, 2 if n & 1 else 1):
if not n % i:
small.append(i)
large.append(n // i)
if small[-1] == large[-1]:
large.pop()
large.reverse()
small.extend(large)
return small
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from math import gcd, ceil
def prod(a, mod=10**9+7):
ans = 1
for each in a:
ans = (ans * each) % mod
return ans
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
for _ in range(int(input()) if not True else 1):
n = int(input())
mod = 998244353
primes = prime_factors(n)
all = set(distinct_factors(n, primes))
primes = [k for k in primes]
factorial = [1]
invfact = [1]
for i in range(1, 10**5 + 69):
factorial += [(factorial[-1] * i) % mod]
invfact += [pow(factorial[i], mod-2, mod)]
def f(x, y):
count = 0
x = y // x
denominator = 1
for prime in primes:
uniques = 0
while x % prime == 0:
x = x // prime
count += 1
uniques += 1
if uniques:
denominator *= invfact[uniques]
denominator %= mod
return (factorial[count] * denominator) % mod
for i in range(int(input())):
x, y = map(int, input().split())
x, y = max(x, y), min(x, y)
if x % y == 0:
print(f(y, x))
else:
print((f(gcd(x, y), y) * f(gcd(x, y), x)) % mod)
``` | output | 1 | 18,671 | 13 | 37,343 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a positive integer D. Let's build the following graph from it:
* each vertex is a divisor of D (not necessarily prime, 1 and D itself are also included);
* two vertices x and y (x > y) have an undirected edge between them if x is divisible by y and \frac x y is a prime;
* the weight of an edge is the number of divisors of x that are not divisors of y.
For example, here is the graph for D=12:
<image>
Edge (4,12) has weight 3 because 12 has divisors [1,2,3,4,6,12] and 4 has divisors [1,2,4]. Thus, there are 3 divisors of 12 that are not divisors of 4 — [3,6,12].
There is no edge between 3 and 2 because 3 is not divisible by 2. There is no edge between 12 and 3 because 12/3=4 is not a prime.
Let the length of the path between some vertices v and u in the graph be the total weight of edges on it. For example, path [(1, 2), (2, 6), (6, 12), (12, 4), (4, 2), (2, 6)] has length 1+2+2+3+1+2=11. The empty path has length 0.
So the shortest path between two vertices v and u is the path that has the minimal possible length.
Two paths a and b are different if there is either a different number of edges in them or there is a position i such that a_i and b_i are different edges.
You are given q queries of the following form:
* v u — calculate the number of the shortest paths between vertices v and u.
The answer for each query might be large so print it modulo 998244353.
Input
The first line contains a single integer D (1 ≤ D ≤ 10^{15}) — the number the graph is built from.
The second line contains a single integer q (1 ≤ q ≤ 3 ⋅ 10^5) — the number of queries.
Each of the next q lines contains two integers v and u (1 ≤ v, u ≤ D). It is guaranteed that D is divisible by both v and u (both v and u are divisors of D).
Output
Print q integers — for each query output the number of the shortest paths between the two given vertices modulo 998244353.
Examples
Input
12
3
4 4
12 1
3 4
Output
1
3
1
Input
1
1
1 1
Output
1
Input
288807105787200
4
46 482955026400
12556830686400 897
414 12556830686400
4443186242880 325
Output
547558588
277147129
457421435
702277623
Note
In the first example:
* The first query is only the empty path — length 0;
* The second query are paths [(12, 4), (4, 2), (2, 1)] (length 3+1+1=5), [(12, 6), (6, 2), (2, 1)] (length 2+2+1=5) and [(12, 6), (6, 3), (3, 1)] (length 2+2+1=5).
* The third query is only the path [(3, 1), (1, 2), (2, 4)] (length 1+1+1=3). | instruction | 0 | 18,672 | 13 | 37,344 |
Tags: combinatorics, graphs, greedy, math, number theory
Correct Solution:
```
# region fastio # from https://codeforces.com/contest/1333/submission/75948789
import sys, io, os
BUFSIZE = 8192
class FastIO(io.IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = io.BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(io.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")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
from functools import lru_cache
@lru_cache(maxsize=None)
def prime_decomposition(n):
i = 2
table = []
while i * i <= n:
while n % i == 0:
n //= i
table.append(i)
i += 1
if n > 1:
table.append(n)
return table
from math import gcd
#from collections import Counter
from itertools import groupby
D = int(input())
Q = int(input())
VU = [list(map(int, input().split())) for _ in range(Q)]
mod = 998244353
factorial = [1] * 100
for i in range(1, 100):
factorial[i] = factorial[i-1] * i % mod
for v, u in VU:
g = gcd(v, u)
vg, ug = v//g, u//g
numer = denom = 1
for val in [vg, ug]:
primes = prime_decomposition(val)
primes.sort()
numer = numer * factorial[len(primes)] % mod
for _, group in groupby(primes):
denom = denom * factorial[len(list(group))] % mod
print(numer * pow(denom, mod-2, mod) % mod)
``` | output | 1 | 18,672 | 13 | 37,345 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a positive integer D. Let's build the following graph from it:
* each vertex is a divisor of D (not necessarily prime, 1 and D itself are also included);
* two vertices x and y (x > y) have an undirected edge between them if x is divisible by y and \frac x y is a prime;
* the weight of an edge is the number of divisors of x that are not divisors of y.
For example, here is the graph for D=12:
<image>
Edge (4,12) has weight 3 because 12 has divisors [1,2,3,4,6,12] and 4 has divisors [1,2,4]. Thus, there are 3 divisors of 12 that are not divisors of 4 — [3,6,12].
There is no edge between 3 and 2 because 3 is not divisible by 2. There is no edge between 12 and 3 because 12/3=4 is not a prime.
Let the length of the path between some vertices v and u in the graph be the total weight of edges on it. For example, path [(1, 2), (2, 6), (6, 12), (12, 4), (4, 2), (2, 6)] has length 1+2+2+3+1+2=11. The empty path has length 0.
So the shortest path between two vertices v and u is the path that has the minimal possible length.
Two paths a and b are different if there is either a different number of edges in them or there is a position i such that a_i and b_i are different edges.
You are given q queries of the following form:
* v u — calculate the number of the shortest paths between vertices v and u.
The answer for each query might be large so print it modulo 998244353.
Input
The first line contains a single integer D (1 ≤ D ≤ 10^{15}) — the number the graph is built from.
The second line contains a single integer q (1 ≤ q ≤ 3 ⋅ 10^5) — the number of queries.
Each of the next q lines contains two integers v and u (1 ≤ v, u ≤ D). It is guaranteed that D is divisible by both v and u (both v and u are divisors of D).
Output
Print q integers — for each query output the number of the shortest paths between the two given vertices modulo 998244353.
Examples
Input
12
3
4 4
12 1
3 4
Output
1
3
1
Input
1
1
1 1
Output
1
Input
288807105787200
4
46 482955026400
12556830686400 897
414 12556830686400
4443186242880 325
Output
547558588
277147129
457421435
702277623
Note
In the first example:
* The first query is only the empty path — length 0;
* The second query are paths [(12, 4), (4, 2), (2, 1)] (length 3+1+1=5), [(12, 6), (6, 2), (2, 1)] (length 2+2+1=5) and [(12, 6), (6, 3), (3, 1)] (length 2+2+1=5).
* The third query is only the path [(3, 1), (1, 2), (2, 4)] (length 1+1+1=3). | instruction | 0 | 18,673 | 13 | 37,346 |
Tags: combinatorics, graphs, greedy, math, number theory
Correct Solution:
```
import io, os
import sys
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
D=int(input())
q=int(input())
mod=998244353
Q=[tuple(map(int,input().split())) for i in range(q)]
from math import gcd
from math import sqrt
L=[]
Q2=[]
for x,y in Q:
GCD=gcd(x,y)
x//=GCD
y//=GCD
Q2.append((x,y))
L.append(x)
L.append(y)
L.sort()
FACTOR=set()
for l in L:
for f in FACTOR:
while l%f==0:
l//=f
if l==1:
continue
else:
L=int(sqrt(l))
for i in range(2,L+2):
while l%i==0:
FACTOR.add(i)
l//=i
if l!=1:
FACTOR.add(l)
FACT=[1]
for i in range(1,2*10**5+1):
FACT.append(FACT[-1]*i%mod)
FACT_INV=[pow(FACT[-1],mod-2,mod)]
for i in range(2*10**5,0,-1):
FACT_INV.append(FACT_INV[-1]*i%mod)
FACT_INV.reverse()
def Combi(a,b):
if 0<=b<=a:
return FACT[a]*FACT_INV[b]*FACT_INV[a-b]%mod
else:
return 0
def FACTORIZE(x):
F=[]
for f in FACTOR:
#print(f,x)
a=0
while x%f==0:
a+=1
x//=f
if a!=0:
F.append(a)
return F
for x,y in Q2:
ANS=1
F=FACTORIZE(x)
S=sum(F)
for f in F:
ANS=ANS*Combi(S,f)%mod
S-=f
F=FACTORIZE(y)
S=sum(F)
for f in F:
ANS=ANS*Combi(S,f)%mod
S-=f
sys.stdout.write(str(ANS%mod)+"\n")
``` | output | 1 | 18,673 | 13 | 37,347 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a positive integer D. Let's build the following graph from it:
* each vertex is a divisor of D (not necessarily prime, 1 and D itself are also included);
* two vertices x and y (x > y) have an undirected edge between them if x is divisible by y and \frac x y is a prime;
* the weight of an edge is the number of divisors of x that are not divisors of y.
For example, here is the graph for D=12:
<image>
Edge (4,12) has weight 3 because 12 has divisors [1,2,3,4,6,12] and 4 has divisors [1,2,4]. Thus, there are 3 divisors of 12 that are not divisors of 4 — [3,6,12].
There is no edge between 3 and 2 because 3 is not divisible by 2. There is no edge between 12 and 3 because 12/3=4 is not a prime.
Let the length of the path between some vertices v and u in the graph be the total weight of edges on it. For example, path [(1, 2), (2, 6), (6, 12), (12, 4), (4, 2), (2, 6)] has length 1+2+2+3+1+2=11. The empty path has length 0.
So the shortest path between two vertices v and u is the path that has the minimal possible length.
Two paths a and b are different if there is either a different number of edges in them or there is a position i such that a_i and b_i are different edges.
You are given q queries of the following form:
* v u — calculate the number of the shortest paths between vertices v and u.
The answer for each query might be large so print it modulo 998244353.
Input
The first line contains a single integer D (1 ≤ D ≤ 10^{15}) — the number the graph is built from.
The second line contains a single integer q (1 ≤ q ≤ 3 ⋅ 10^5) — the number of queries.
Each of the next q lines contains two integers v and u (1 ≤ v, u ≤ D). It is guaranteed that D is divisible by both v and u (both v and u are divisors of D).
Output
Print q integers — for each query output the number of the shortest paths between the two given vertices modulo 998244353.
Examples
Input
12
3
4 4
12 1
3 4
Output
1
3
1
Input
1
1
1 1
Output
1
Input
288807105787200
4
46 482955026400
12556830686400 897
414 12556830686400
4443186242880 325
Output
547558588
277147129
457421435
702277623
Note
In the first example:
* The first query is only the empty path — length 0;
* The second query are paths [(12, 4), (4, 2), (2, 1)] (length 3+1+1=5), [(12, 6), (6, 2), (2, 1)] (length 2+2+1=5) and [(12, 6), (6, 3), (3, 1)] (length 2+2+1=5).
* The third query is only the path [(3, 1), (1, 2), (2, 4)] (length 1+1+1=3). | instruction | 0 | 18,674 | 13 | 37,348 |
Tags: combinatorics, graphs, greedy, math, number theory
Correct Solution:
```
def gcd(a, b):
while b: a, b = b, a % b
return a
def isPrimeMR(n):
d = n - 1
d = d // (d & -d)
L = [2, 3, 5, 7, 11, 13, 17]
for a in L:
t = d
y = pow(a, t, n)
if y == 1: continue
while y != n - 1:
y = (y * y) % n
if y == 1 or t == n - 1: return 0
t <<= 1
return 1
def findFactorRho(n):
m = 1 << n.bit_length() // 8
for c in range(1, 99):
f = lambda x: (x * x + c) % n
y, r, q, g = 2, 1, 1, 1
while g == 1:
x = y
for i in range(r):
y = f(y)
k = 0
while k < r and g == 1:
ys = y
for i in range(min(m, r - k)):
y = f(y)
q = q * abs(x - y) % n
g = gcd(q, n)
k += m
r <<= 1
if g == n:
g = 1
while g == 1:
ys = f(ys)
g = gcd(abs(x - ys), n)
if g < n:
if isPrimeMR(g): return g
elif isPrimeMR(n // g): return n // g
return findFactorRho(g)
def primeFactor(n):
i = 2
ret = {}
rhoFlg = 0
while i*i <= n:
k = 0
while n % i == 0:
n //= i
k += 1
if k: ret[i] = k
i += 1 + i % 2
if i == 101 and n >= 2 ** 20:
while n > 1:
if isPrimeMR(n):
ret[n], n = 1, 1
else:
rhoFlg = 1
j = findFactorRho(n)
k = 0
while n % j == 0:
n //= j
k += 1
ret[j] = k
if n > 1: ret[n] = 1
if rhoFlg: ret = {x: ret[x] for x in sorted(ret)}
return ret
def divisors(n):
res = [1]
prime = primeFactor(n)
for p in prime:
newres = []
for d in res:
for j in range(prime[p]+1):
newres.append(d*p**j)
res = newres
res.sort()
return res
mod = 998244353
import heapq
class Dijkstra():
class Edge():
def __init__(self, _to, _cost):
self.to = _to
self.cost = _cost
def __init__(self, V):
self.G = [[] for i in range(V)] # 隣接リストG[u][i] := 頂点uのi個目の隣接辺
self._E = 0 # 辺の数
self._V = V # 頂点の数
@property
def E(self):
return self._E
@property
def V(self):
return self._V
def add(self, _from, _to, _cost):
self.G[_from].append(self.Edge(_to, _cost))
def shortest_path(self, s):
import heapq
que = []
d = [10**15] * self.V
d[s] = 0
cnt=[0]*self.V
cnt[s]=1
heapq.heappush(que, (0, s))
while len(que) != 0:
cost, v = heapq.heappop(que)
#print(cost,v)
if d[v] < cost: continue
for i in range(len(self.G[v])):
e = self.G[v][i]
if d[e.to] > d[v] + e.cost:
d[e.to] = d[v] + e.cost
heapq.heappush(que, (d[e.to], e.to))
cnt[e.to]=cnt[v]%mod
elif d[e.to]==d[v]+e.cost:
cnt[e.to]+=cnt[v]
cnt[e.to]%=mod
return d,cnt
import sys
from heapq import heappush,heappop,heapify
from math import gcd
input = sys.stdin.buffer.readline
D = int(input())
prime = primeFactor(D)
div = divisors(D)
div_dic = {e:i for i,e in enumerate(div)}
div_factors = [1 for i in range(len(div))]
n = len(div)
for i in range(n):
d = div[i]
for p in prime:
tmp_d = d
cnt = 0
while tmp_d%p==0:
cnt += 1
tmp_d //= p
div_factors[i] *= cnt + 1
#print(div)
#print(div_factors)
G = Dijkstra(n)
for i in range(n):
for p in prime:
nv = div[i]*p
if nv in div_dic:
j = div_dic[nv]
#print(i,j,div_factors[j]-div_factors[i])
G.add(i,j,div_factors[j]-div_factors[i])
G.add(j,i,div_factors[j]-div_factors[i])
base = G.shortest_path(0)[1]
#print(base)
def dist(a,b):
assert b%a==0
b //= a
return base[div_dic[b]]
for _ in range(int(input())):
u,v = map(int,input().split())
g = gcd(u,v)
print(dist(g,u)*dist(g,v)%mod)
``` | output | 1 | 18,674 | 13 | 37,349 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a positive integer D. Let's build the following graph from it:
* each vertex is a divisor of D (not necessarily prime, 1 and D itself are also included);
* two vertices x and y (x > y) have an undirected edge between them if x is divisible by y and \frac x y is a prime;
* the weight of an edge is the number of divisors of x that are not divisors of y.
For example, here is the graph for D=12:
<image>
Edge (4,12) has weight 3 because 12 has divisors [1,2,3,4,6,12] and 4 has divisors [1,2,4]. Thus, there are 3 divisors of 12 that are not divisors of 4 — [3,6,12].
There is no edge between 3 and 2 because 3 is not divisible by 2. There is no edge between 12 and 3 because 12/3=4 is not a prime.
Let the length of the path between some vertices v and u in the graph be the total weight of edges on it. For example, path [(1, 2), (2, 6), (6, 12), (12, 4), (4, 2), (2, 6)] has length 1+2+2+3+1+2=11. The empty path has length 0.
So the shortest path between two vertices v and u is the path that has the minimal possible length.
Two paths a and b are different if there is either a different number of edges in them or there is a position i such that a_i and b_i are different edges.
You are given q queries of the following form:
* v u — calculate the number of the shortest paths between vertices v and u.
The answer for each query might be large so print it modulo 998244353.
Input
The first line contains a single integer D (1 ≤ D ≤ 10^{15}) — the number the graph is built from.
The second line contains a single integer q (1 ≤ q ≤ 3 ⋅ 10^5) — the number of queries.
Each of the next q lines contains two integers v and u (1 ≤ v, u ≤ D). It is guaranteed that D is divisible by both v and u (both v and u are divisors of D).
Output
Print q integers — for each query output the number of the shortest paths between the two given vertices modulo 998244353.
Examples
Input
12
3
4 4
12 1
3 4
Output
1
3
1
Input
1
1
1 1
Output
1
Input
288807105787200
4
46 482955026400
12556830686400 897
414 12556830686400
4443186242880 325
Output
547558588
277147129
457421435
702277623
Note
In the first example:
* The first query is only the empty path — length 0;
* The second query are paths [(12, 4), (4, 2), (2, 1)] (length 3+1+1=5), [(12, 6), (6, 2), (2, 1)] (length 2+2+1=5) and [(12, 6), (6, 3), (3, 1)] (length 2+2+1=5).
* The third query is only the path [(3, 1), (1, 2), (2, 4)] (length 1+1+1=3).
Submitted Solution:
```
import sys
input = sys.stdin.buffer.readline
mod=998244353
d=int(input())
div=[]
x=2
di=0
t=0
while d>1 and x*x<=d:
if d%x==0:
div.append(x)
d//=x
di+=1
t+=1
while d%x==0:
d//=x
t+=1
x+=1
if d>1:
div.append(d)
di+=1
t+=1
fac=[1]
for i in range(1,t+1):
fac.append(i*fac[-1]%mod)
for f in range(int(input())):
v,u=map(int,input().split())
divs1=[]
divs2=[]
tot1=0
tot2=0
for i in range(di):
while v%div[i]==0 and u%div[i]==0:
v//=div[i]
u//=div[i]
if v%div[i]==0:
divs1.append(0)
if u%div[i]==0:
divs2.append(0)
while v%div[i]==0:
v//=div[i]
divs1[-1]+=1
tot1+=1
while u%div[i]==0:
u//=div[i]
divs2[-1]+=1
tot2+=1
res=fac[tot1]*fac[tot2]
tod=1
for x in divs1:
tod*=fac[x]
tod%=mod
for x in divs2:
tod*=fac[x]
tod%=mod
res*=pow(tod,mod-2,mod)
res%=mod
print(res)
``` | instruction | 0 | 18,675 | 13 | 37,350 |
Yes | output | 1 | 18,675 | 13 | 37,351 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a positive integer D. Let's build the following graph from it:
* each vertex is a divisor of D (not necessarily prime, 1 and D itself are also included);
* two vertices x and y (x > y) have an undirected edge between them if x is divisible by y and \frac x y is a prime;
* the weight of an edge is the number of divisors of x that are not divisors of y.
For example, here is the graph for D=12:
<image>
Edge (4,12) has weight 3 because 12 has divisors [1,2,3,4,6,12] and 4 has divisors [1,2,4]. Thus, there are 3 divisors of 12 that are not divisors of 4 — [3,6,12].
There is no edge between 3 and 2 because 3 is not divisible by 2. There is no edge between 12 and 3 because 12/3=4 is not a prime.
Let the length of the path between some vertices v and u in the graph be the total weight of edges on it. For example, path [(1, 2), (2, 6), (6, 12), (12, 4), (4, 2), (2, 6)] has length 1+2+2+3+1+2=11. The empty path has length 0.
So the shortest path between two vertices v and u is the path that has the minimal possible length.
Two paths a and b are different if there is either a different number of edges in them or there is a position i such that a_i and b_i are different edges.
You are given q queries of the following form:
* v u — calculate the number of the shortest paths between vertices v and u.
The answer for each query might be large so print it modulo 998244353.
Input
The first line contains a single integer D (1 ≤ D ≤ 10^{15}) — the number the graph is built from.
The second line contains a single integer q (1 ≤ q ≤ 3 ⋅ 10^5) — the number of queries.
Each of the next q lines contains two integers v and u (1 ≤ v, u ≤ D). It is guaranteed that D is divisible by both v and u (both v and u are divisors of D).
Output
Print q integers — for each query output the number of the shortest paths between the two given vertices modulo 998244353.
Examples
Input
12
3
4 4
12 1
3 4
Output
1
3
1
Input
1
1
1 1
Output
1
Input
288807105787200
4
46 482955026400
12556830686400 897
414 12556830686400
4443186242880 325
Output
547558588
277147129
457421435
702277623
Note
In the first example:
* The first query is only the empty path — length 0;
* The second query are paths [(12, 4), (4, 2), (2, 1)] (length 3+1+1=5), [(12, 6), (6, 2), (2, 1)] (length 2+2+1=5) and [(12, 6), (6, 3), (3, 1)] (length 2+2+1=5).
* The third query is only the path [(3, 1), (1, 2), (2, 4)] (length 1+1+1=3).
Submitted Solution:
```
def main():
import sys
input=sys.stdin.readline
mod=998244353
N=10**5+3
fac=[1]*(N+1)
for i in range(1,N+1):
fac[i]=fac[i-1]*i%mod
inv_fac=[1]*(N+1)
inv_fac[N]=pow(fac[N],mod-2,mod)
for i in range(N-1,0,-1):
inv_fac[i]=inv_fac[i+1]*(i+1)%mod
D=int(input())
A=[]
for i in range(2,int(D**.5)+1):
c=0
while D%i==0:
D//=i
c+=1
if c!=0:
A.append(i)
if D>=2:
A.append(D)
l=len(A)
q=int(input())
for _ in range(q):
u,v=map(int,input().split())
l1=[0]*l
l2=[0]*l
l3=[0]*l
for i in range(l):
while u%A[i]==0:
l1[i]+=1
u//=A[i]
while v%A[i]==0:
l2[i]+=1
v//=A[i]
l3[i]=l1[i]-l2[i]
ans1=1
ans2=1
s1=0
s2=0
for i in range(l):
if l3[i]>=0:
ans1=ans1*inv_fac[l3[i]]%mod
s1+=l3[i]
else:
ans2=ans2*inv_fac[-l3[i]]%mod
s2-=l3[i]
ans1=ans1*fac[s1]%mod
ans2=ans2*fac[s2]%mod
print(ans1*ans2%mod)
if __name__ == '__main__':
main()
``` | instruction | 0 | 18,676 | 13 | 37,352 |
Yes | output | 1 | 18,676 | 13 | 37,353 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a positive integer D. Let's build the following graph from it:
* each vertex is a divisor of D (not necessarily prime, 1 and D itself are also included);
* two vertices x and y (x > y) have an undirected edge between them if x is divisible by y and \frac x y is a prime;
* the weight of an edge is the number of divisors of x that are not divisors of y.
For example, here is the graph for D=12:
<image>
Edge (4,12) has weight 3 because 12 has divisors [1,2,3,4,6,12] and 4 has divisors [1,2,4]. Thus, there are 3 divisors of 12 that are not divisors of 4 — [3,6,12].
There is no edge between 3 and 2 because 3 is not divisible by 2. There is no edge between 12 and 3 because 12/3=4 is not a prime.
Let the length of the path between some vertices v and u in the graph be the total weight of edges on it. For example, path [(1, 2), (2, 6), (6, 12), (12, 4), (4, 2), (2, 6)] has length 1+2+2+3+1+2=11. The empty path has length 0.
So the shortest path between two vertices v and u is the path that has the minimal possible length.
Two paths a and b are different if there is either a different number of edges in them or there is a position i such that a_i and b_i are different edges.
You are given q queries of the following form:
* v u — calculate the number of the shortest paths between vertices v and u.
The answer for each query might be large so print it modulo 998244353.
Input
The first line contains a single integer D (1 ≤ D ≤ 10^{15}) — the number the graph is built from.
The second line contains a single integer q (1 ≤ q ≤ 3 ⋅ 10^5) — the number of queries.
Each of the next q lines contains two integers v and u (1 ≤ v, u ≤ D). It is guaranteed that D is divisible by both v and u (both v and u are divisors of D).
Output
Print q integers — for each query output the number of the shortest paths between the two given vertices modulo 998244353.
Examples
Input
12
3
4 4
12 1
3 4
Output
1
3
1
Input
1
1
1 1
Output
1
Input
288807105787200
4
46 482955026400
12556830686400 897
414 12556830686400
4443186242880 325
Output
547558588
277147129
457421435
702277623
Note
In the first example:
* The first query is only the empty path — length 0;
* The second query are paths [(12, 4), (4, 2), (2, 1)] (length 3+1+1=5), [(12, 6), (6, 2), (2, 1)] (length 2+2+1=5) and [(12, 6), (6, 3), (3, 1)] (length 2+2+1=5).
* The third query is only the path [(3, 1), (1, 2), (2, 4)] (length 1+1+1=3).
Submitted Solution:
```
# region fastio # from https://codeforces.com/contest/1333/submission/75948789
import sys, io, os
BUFSIZE = 8192
class FastIO(io.IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = io.BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(io.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")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
cache = {}
def prime_decomposition(n):
if n in cache:
return cache[n]
n_ = n
i = 2
table = []
while i * i <= n:
while n % i == 0:
n //= i
table.append(i)
i += 1
if n > 1:
table.append(n)
cache[n_] = table
return table
from math import gcd
from itertools import groupby
D = int(input())
Q = int(input())
VU = [list(map(int, input().split())) for _ in range(Q)]
mod = 998244353
factorial = [1] * 100
for i in range(1, 100):
factorial[i] = factorial[i-1] * i % mod
for v, u in VU:
g = gcd(v, u)
vg, ug = v//g, u//g
numer = denom = 1
for val in [vg, ug]:
primes = prime_decomposition(val)
primes.sort()
numer = numer * factorial[len(primes)] % mod
for _, group in groupby(primes):
denom = denom * factorial[len(list(group))] % mod
print(numer * pow(denom, mod-2, mod) % mod)
``` | instruction | 0 | 18,677 | 13 | 37,354 |
Yes | output | 1 | 18,677 | 13 | 37,355 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a positive integer D. Let's build the following graph from it:
* each vertex is a divisor of D (not necessarily prime, 1 and D itself are also included);
* two vertices x and y (x > y) have an undirected edge between them if x is divisible by y and \frac x y is a prime;
* the weight of an edge is the number of divisors of x that are not divisors of y.
For example, here is the graph for D=12:
<image>
Edge (4,12) has weight 3 because 12 has divisors [1,2,3,4,6,12] and 4 has divisors [1,2,4]. Thus, there are 3 divisors of 12 that are not divisors of 4 — [3,6,12].
There is no edge between 3 and 2 because 3 is not divisible by 2. There is no edge between 12 and 3 because 12/3=4 is not a prime.
Let the length of the path between some vertices v and u in the graph be the total weight of edges on it. For example, path [(1, 2), (2, 6), (6, 12), (12, 4), (4, 2), (2, 6)] has length 1+2+2+3+1+2=11. The empty path has length 0.
So the shortest path between two vertices v and u is the path that has the minimal possible length.
Two paths a and b are different if there is either a different number of edges in them or there is a position i such that a_i and b_i are different edges.
You are given q queries of the following form:
* v u — calculate the number of the shortest paths between vertices v and u.
The answer for each query might be large so print it modulo 998244353.
Input
The first line contains a single integer D (1 ≤ D ≤ 10^{15}) — the number the graph is built from.
The second line contains a single integer q (1 ≤ q ≤ 3 ⋅ 10^5) — the number of queries.
Each of the next q lines contains two integers v and u (1 ≤ v, u ≤ D). It is guaranteed that D is divisible by both v and u (both v and u are divisors of D).
Output
Print q integers — for each query output the number of the shortest paths between the two given vertices modulo 998244353.
Examples
Input
12
3
4 4
12 1
3 4
Output
1
3
1
Input
1
1
1 1
Output
1
Input
288807105787200
4
46 482955026400
12556830686400 897
414 12556830686400
4443186242880 325
Output
547558588
277147129
457421435
702277623
Note
In the first example:
* The first query is only the empty path — length 0;
* The second query are paths [(12, 4), (4, 2), (2, 1)] (length 3+1+1=5), [(12, 6), (6, 2), (2, 1)] (length 2+2+1=5) and [(12, 6), (6, 3), (3, 1)] (length 2+2+1=5).
* The third query is only the path [(3, 1), (1, 2), (2, 4)] (length 1+1+1=3).
Submitted Solution:
```
# region fastio # from https://codeforces.com/contest/1333/submission/75948789
import sys, io, os
BUFSIZE = 8192
class FastIO(io.IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = io.BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(io.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")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
cache = {}
def prime_decomposition(n):
if n in cache:
return cache[n]
n_ = n
i = 2
table = []
while i * i <= n:
while n % i == 0:
n //= i
table.append(i)
i += 1
if n > 1:
table.append(n)
cache[n_] = table
return table
from math import gcd
from itertools import groupby
D = int(input())
Q = int(input())
VU = [list(map(int, input().split())) for _ in range(Q)]
mod = 998244353
factorial = [1] * 100
for i in range(1, 100):
factorial[i] = factorial[i-1] * i % mod
for v, u in VU:
g = gcd(v, u)
vg, ug = v//g, u//g
numer = denom = 1
for val in [vg, ug]:
primes = prime_decomposition(val)
numer = numer * factorial[len(primes)] % mod
for _, group in groupby(primes):
denom = denom * factorial[len(list(group))] % mod
print(numer * pow(denom, mod-2, mod) % mod)
``` | instruction | 0 | 18,678 | 13 | 37,356 |
Yes | output | 1 | 18,678 | 13 | 37,357 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a positive integer D. Let's build the following graph from it:
* each vertex is a divisor of D (not necessarily prime, 1 and D itself are also included);
* two vertices x and y (x > y) have an undirected edge between them if x is divisible by y and \frac x y is a prime;
* the weight of an edge is the number of divisors of x that are not divisors of y.
For example, here is the graph for D=12:
<image>
Edge (4,12) has weight 3 because 12 has divisors [1,2,3,4,6,12] and 4 has divisors [1,2,4]. Thus, there are 3 divisors of 12 that are not divisors of 4 — [3,6,12].
There is no edge between 3 and 2 because 3 is not divisible by 2. There is no edge between 12 and 3 because 12/3=4 is not a prime.
Let the length of the path between some vertices v and u in the graph be the total weight of edges on it. For example, path [(1, 2), (2, 6), (6, 12), (12, 4), (4, 2), (2, 6)] has length 1+2+2+3+1+2=11. The empty path has length 0.
So the shortest path between two vertices v and u is the path that has the minimal possible length.
Two paths a and b are different if there is either a different number of edges in them or there is a position i such that a_i and b_i are different edges.
You are given q queries of the following form:
* v u — calculate the number of the shortest paths between vertices v and u.
The answer for each query might be large so print it modulo 998244353.
Input
The first line contains a single integer D (1 ≤ D ≤ 10^{15}) — the number the graph is built from.
The second line contains a single integer q (1 ≤ q ≤ 3 ⋅ 10^5) — the number of queries.
Each of the next q lines contains two integers v and u (1 ≤ v, u ≤ D). It is guaranteed that D is divisible by both v and u (both v and u are divisors of D).
Output
Print q integers — for each query output the number of the shortest paths between the two given vertices modulo 998244353.
Examples
Input
12
3
4 4
12 1
3 4
Output
1
3
1
Input
1
1
1 1
Output
1
Input
288807105787200
4
46 482955026400
12556830686400 897
414 12556830686400
4443186242880 325
Output
547558588
277147129
457421435
702277623
Note
In the first example:
* The first query is only the empty path — length 0;
* The second query are paths [(12, 4), (4, 2), (2, 1)] (length 3+1+1=5), [(12, 6), (6, 2), (2, 1)] (length 2+2+1=5) and [(12, 6), (6, 3), (3, 1)] (length 2+2+1=5).
* The third query is only the path [(3, 1), (1, 2), (2, 4)] (length 1+1+1=3).
Submitted Solution:
```
from sys import stdin
input = stdin.readline
d = int(input())
n = int(input())
p = 998244353
dz = []
kan = 2
dd = d
def wynik(pary):
dlu = len(pary)
mini = 1529238948239
kan = - 1
wyn = 0
for j in range(dlu):
if pary[j][0] < mini and pary[j][0] != pary[j][1]:
mini = pary[j][0]
kan = j
if kan == -1:
return 1
najmn = 0
for j in range(dlu):
if pary[j][0] == mini and pary[j][0] != pary[j][1]:
new_pary = pary.copy()
new_pary[j][0] += 1
wyn += wynik(new_pary)
return wyn
while True:
if dd%kan == 0:
dz.append(kan)
dd //= kan
else:
kan += 1
if dd == 1:
break
if kan ** 2 > d:
dz.append(dd)
break
dick = {}
for i in dz:
dick[i] = 0
baza = dick.copy()
for i in dz:
dick[i] += 1
for i in range(n):
v,u = map(int,input().split())
dv = baza.copy()
du = baza.copy()
#print(dv,du)
for i in dz:
while True:
if v%i == 0:
dv[i] += 1
v //= i
else:
break
while True:
if u%i == 0:
du[i] += 1
u //= i
else:
break
#print(dv,du)
pary = []
for i in dz:
if du[i] != dv[i]:
pary.append([min(du[i],dv[i]), max(du[i],dv[i])])
print(wynik(pary)%p)
``` | instruction | 0 | 18,679 | 13 | 37,358 |
No | output | 1 | 18,679 | 13 | 37,359 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a positive integer D. Let's build the following graph from it:
* each vertex is a divisor of D (not necessarily prime, 1 and D itself are also included);
* two vertices x and y (x > y) have an undirected edge between them if x is divisible by y and \frac x y is a prime;
* the weight of an edge is the number of divisors of x that are not divisors of y.
For example, here is the graph for D=12:
<image>
Edge (4,12) has weight 3 because 12 has divisors [1,2,3,4,6,12] and 4 has divisors [1,2,4]. Thus, there are 3 divisors of 12 that are not divisors of 4 — [3,6,12].
There is no edge between 3 and 2 because 3 is not divisible by 2. There is no edge between 12 and 3 because 12/3=4 is not a prime.
Let the length of the path between some vertices v and u in the graph be the total weight of edges on it. For example, path [(1, 2), (2, 6), (6, 12), (12, 4), (4, 2), (2, 6)] has length 1+2+2+3+1+2=11. The empty path has length 0.
So the shortest path between two vertices v and u is the path that has the minimal possible length.
Two paths a and b are different if there is either a different number of edges in them or there is a position i such that a_i and b_i are different edges.
You are given q queries of the following form:
* v u — calculate the number of the shortest paths between vertices v and u.
The answer for each query might be large so print it modulo 998244353.
Input
The first line contains a single integer D (1 ≤ D ≤ 10^{15}) — the number the graph is built from.
The second line contains a single integer q (1 ≤ q ≤ 3 ⋅ 10^5) — the number of queries.
Each of the next q lines contains two integers v and u (1 ≤ v, u ≤ D). It is guaranteed that D is divisible by both v and u (both v and u are divisors of D).
Output
Print q integers — for each query output the number of the shortest paths between the two given vertices modulo 998244353.
Examples
Input
12
3
4 4
12 1
3 4
Output
1
3
1
Input
1
1
1 1
Output
1
Input
288807105787200
4
46 482955026400
12556830686400 897
414 12556830686400
4443186242880 325
Output
547558588
277147129
457421435
702277623
Note
In the first example:
* The first query is only the empty path — length 0;
* The second query are paths [(12, 4), (4, 2), (2, 1)] (length 3+1+1=5), [(12, 6), (6, 2), (2, 1)] (length 2+2+1=5) and [(12, 6), (6, 3), (3, 1)] (length 2+2+1=5).
* The third query is only the path [(3, 1), (1, 2), (2, 4)] (length 1+1+1=3).
Submitted Solution:
```
def main():
import sys
input=sys.stdin.readline
mod=998244353
N=10**5+3
fac=[1]*(N+1)
for i in range(1,N+1):
fac[i]=fac[i-1]*i%mod
inv_fac=[1]*(N+1)
inv_fac[N]=pow(fac[N],mod-2,mod)
for i in range(N-1,0,-1):
inv_fac[i]=inv_fac[i+1]*(i+1)%mod
D=int(input())
A=[]
for i in range(2,int(D**.5)+1):
c=0
while D%i==0:
D//=i
c+=1
if c!=0:
A.append(i)
l=len(A)
q=int(input())
for _ in range(q):
u,v=map(int,input().split())
l1=[0]*l
l2=[0]*l
l3=[0]*l
for i in range(l):
while u%A[i]==0:
l1[i]+=1
u//=A[i]
while v%A[i]==0:
l2[i]+=1
v//=A[i]
l3[i]=l1[i]-l2[i]
ans1=1
ans2=1
s1=0
s2=0
for i in range(l):
if l3[i]>=0:
ans1=ans1*inv_fac[l3[i]]%mod
s1+=l3[i]
else:
ans2=ans2*inv_fac[-l3[i]]%mod
s2-=l3[i]
ans1=ans1*fac[s1]%mod
ans2=ans2*fac[s2]%mod
print(ans1*ans2%mod)
if __name__ == '__main__':
main()
``` | instruction | 0 | 18,680 | 13 | 37,360 |
No | output | 1 | 18,680 | 13 | 37,361 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a positive integer D. Let's build the following graph from it:
* each vertex is a divisor of D (not necessarily prime, 1 and D itself are also included);
* two vertices x and y (x > y) have an undirected edge between them if x is divisible by y and \frac x y is a prime;
* the weight of an edge is the number of divisors of x that are not divisors of y.
For example, here is the graph for D=12:
<image>
Edge (4,12) has weight 3 because 12 has divisors [1,2,3,4,6,12] and 4 has divisors [1,2,4]. Thus, there are 3 divisors of 12 that are not divisors of 4 — [3,6,12].
There is no edge between 3 and 2 because 3 is not divisible by 2. There is no edge between 12 and 3 because 12/3=4 is not a prime.
Let the length of the path between some vertices v and u in the graph be the total weight of edges on it. For example, path [(1, 2), (2, 6), (6, 12), (12, 4), (4, 2), (2, 6)] has length 1+2+2+3+1+2=11. The empty path has length 0.
So the shortest path between two vertices v and u is the path that has the minimal possible length.
Two paths a and b are different if there is either a different number of edges in them or there is a position i such that a_i and b_i are different edges.
You are given q queries of the following form:
* v u — calculate the number of the shortest paths between vertices v and u.
The answer for each query might be large so print it modulo 998244353.
Input
The first line contains a single integer D (1 ≤ D ≤ 10^{15}) — the number the graph is built from.
The second line contains a single integer q (1 ≤ q ≤ 3 ⋅ 10^5) — the number of queries.
Each of the next q lines contains two integers v and u (1 ≤ v, u ≤ D). It is guaranteed that D is divisible by both v and u (both v and u are divisors of D).
Output
Print q integers — for each query output the number of the shortest paths between the two given vertices modulo 998244353.
Examples
Input
12
3
4 4
12 1
3 4
Output
1
3
1
Input
1
1
1 1
Output
1
Input
288807105787200
4
46 482955026400
12556830686400 897
414 12556830686400
4443186242880 325
Output
547558588
277147129
457421435
702277623
Note
In the first example:
* The first query is only the empty path — length 0;
* The second query are paths [(12, 4), (4, 2), (2, 1)] (length 3+1+1=5), [(12, 6), (6, 2), (2, 1)] (length 2+2+1=5) and [(12, 6), (6, 3), (3, 1)] (length 2+2+1=5).
* The third query is only the path [(3, 1), (1, 2), (2, 4)] (length 1+1+1=3).
Submitted Solution:
```
from sys import stdin
input = stdin.readline
d = int(input())
n = int(input())
p = 998244353
dz = []
kan = 2
dd = d
while True:
if dd%kan == 0:
dz.append(kan)
dd //= kan
else:
kan += 1
if dd == 1:
break
if kan ** 2 > d:
dz.append(dd)
break
dick = {}
for i in dz:
dick[i] = 0
baza = dick.copy()
for i in dz:
dick[i] += 1
for i in range(n):
v,u = map(int,input().split())
dv = baza.copy()
du = baza.copy()
#print(dv,du)
for i in dz:
while True:
if v%i == 0:
dv[i] += 1
v //= i
else:
break
while True:
if u%i == 0:
du[i] += 1
u //= i
else:
break
#print(dv,du)
pary = []
for i in dz:
if du[i] != dv[i]:
pary.append([min(du[i],dv[i]), max(du[i],dv[i])])
pary.sort()
#print(pary)
dlu = len(pary)
wyn = 1
while True:
mini = 1529238948239
kan = - 1
for j in range(dlu):
if pary[j][0] < mini and pary[j][0] != pary[j][1]:
mini = pary[j][0]
kan = j
if kan == -1:
break
najmn = 0
for j in range(dlu):
if pary[j][0] == mini and pary[j][0] != pary[j][1]:
najmn += 1
wyn = (wyn * najmn)%p
pary[kan][0] += 1
print(wyn)
``` | instruction | 0 | 18,681 | 13 | 37,362 |
No | output | 1 | 18,681 | 13 | 37,363 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a positive integer D. Let's build the following graph from it:
* each vertex is a divisor of D (not necessarily prime, 1 and D itself are also included);
* two vertices x and y (x > y) have an undirected edge between them if x is divisible by y and \frac x y is a prime;
* the weight of an edge is the number of divisors of x that are not divisors of y.
For example, here is the graph for D=12:
<image>
Edge (4,12) has weight 3 because 12 has divisors [1,2,3,4,6,12] and 4 has divisors [1,2,4]. Thus, there are 3 divisors of 12 that are not divisors of 4 — [3,6,12].
There is no edge between 3 and 2 because 3 is not divisible by 2. There is no edge between 12 and 3 because 12/3=4 is not a prime.
Let the length of the path between some vertices v and u in the graph be the total weight of edges on it. For example, path [(1, 2), (2, 6), (6, 12), (12, 4), (4, 2), (2, 6)] has length 1+2+2+3+1+2=11. The empty path has length 0.
So the shortest path between two vertices v and u is the path that has the minimal possible length.
Two paths a and b are different if there is either a different number of edges in them or there is a position i such that a_i and b_i are different edges.
You are given q queries of the following form:
* v u — calculate the number of the shortest paths between vertices v and u.
The answer for each query might be large so print it modulo 998244353.
Input
The first line contains a single integer D (1 ≤ D ≤ 10^{15}) — the number the graph is built from.
The second line contains a single integer q (1 ≤ q ≤ 3 ⋅ 10^5) — the number of queries.
Each of the next q lines contains two integers v and u (1 ≤ v, u ≤ D). It is guaranteed that D is divisible by both v and u (both v and u are divisors of D).
Output
Print q integers — for each query output the number of the shortest paths between the two given vertices modulo 998244353.
Examples
Input
12
3
4 4
12 1
3 4
Output
1
3
1
Input
1
1
1 1
Output
1
Input
288807105787200
4
46 482955026400
12556830686400 897
414 12556830686400
4443186242880 325
Output
547558588
277147129
457421435
702277623
Note
In the first example:
* The first query is only the empty path — length 0;
* The second query are paths [(12, 4), (4, 2), (2, 1)] (length 3+1+1=5), [(12, 6), (6, 2), (2, 1)] (length 2+2+1=5) and [(12, 6), (6, 3), (3, 1)] (length 2+2+1=5).
* The third query is only the path [(3, 1), (1, 2), (2, 4)] (length 1+1+1=3).
Submitted Solution:
```
import io, os
import sys
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
D=int(input())
q=int(input())
mod=998244353
Q=[tuple(map(int,input().split())) for i in range(q)]
from math import gcd
from math import sqrt
L=[]
Q2=[]
for x,y in Q:
GCD=gcd(x,y)
x//=GCD
y//=GCD
Q2.append((x,y))
L.append(x)
L.append(y)
FACTOR=set()
for l in L:
for f in FACTOR:
while l%f==0:
l//=f
if l==1:
continue
else:
L=int(sqrt(l))
for i in range(2,L+2):
while l%i==0:
FACTOR.add(i)
l//=i
if l!=1:
FACTOR.add(l)
FACT=[1]
for i in range(1,2*10**2+1):
FACT.append(FACT[-1]*i%mod)
FACT_INV=[pow(FACT[-1],mod-2,mod)]
for i in range(2*10**5,0,-1):
FACT_INV.append(FACT_INV[-1]*i%mod)
FACT_INV.reverse()
def Combi(a,b):
if 0<=b<=a:
return FACT[a]*FACT_INV[b]*FACT_INV[a-b]%mod
else:
return 0
def FACTORIZE(x):
F=[]
for f in FACTOR:
#print(f,x)
a=0
while x%f==0:
a+=1
x//=f
if a!=0:
F.append(a)
return F
for x,y in Q2:
ANS=1
F=FACTORIZE(x)
S=sum(F)
for f in F:
ANS=ANS*Combi(S,f)%mod
S-=f
F=FACTORIZE(y)
S=sum(F)
for f in F:
ANS=ANS*Combi(S,f)%mod
S-=f
sys.stdout.write(str(ANS%mod)+"\n")
``` | instruction | 0 | 18,682 | 13 | 37,364 |
No | output | 1 | 18,682 | 13 | 37,365 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of n (n ≥ 2) positive integers and an integer p. Consider an undirected weighted graph of n vertices numbered from 1 to n for which the edges between the vertices i and j (i<j) are added in the following manner:
* If gcd(a_i, a_{i+1}, a_{i+2}, ..., a_{j}) = min(a_i, a_{i+1}, a_{i+2}, ..., a_j), then there is an edge of weight min(a_i, a_{i+1}, a_{i+2}, ..., a_j) between i and j.
* If i+1=j, then there is an edge of weight p between i and j.
Here gcd(x, y, …) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers x, y, ....
Note that there could be multiple edges between i and j if both of the above conditions are true, and if both the conditions fail for i and j, then there is no edge between these vertices.
The goal is to find the weight of the [minimum spanning tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree) of this graph.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases.
The first line of each test case contains two integers n (2 ≤ n ≤ 2 ⋅ 10^5) and p (1 ≤ p ≤ 10^9) — the number of nodes and the parameter p.
The second line contains n integers a_1, a_2, a_3, ..., a_n (1 ≤ a_i ≤ 10^9).
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5.
Output
Output t lines. For each test case print the weight of the corresponding graph.
Example
Input
4
2 5
10 10
2 5
3 3
4 5
5 2 4 9
8 8
5 3 3 6 10 100 9 15
Output
5
3
12
46
Note
Here are the graphs for the four test cases of the example (the edges of a possible MST of the graphs are marked pink):
For test case 1
<image>
For test case 2
<image>
For test case 3
<image>
For test case 4
<image> | instruction | 0 | 18,772 | 13 | 37,544 |
Tags: constructive algorithms, dsu, graphs, greedy, number theory, sortings
Correct Solution:
```
'''Author- Akshit Monga'''
from sys import stdin, stdout
input = stdin.readline
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
t = int(input())
for _ in range(t):
n,m=map(int,input().split())
a=[int(x) for x in input().split()]
vals=[]
d={}
for i in range(n):
vals.append((a[i],i))
d[i]=a[i]
vals=SortedList(vals)
ok=[]
taken=set()
while len(vals):
p=vals[0]
vals.remove(p)
val=p[0]
ind=p[1]
taken.add(ind)
org=ind
a=b=org
while 1:
org-=1
if org<0:
a=0
break
if d[org]%val!=0:
a=org+1
break
else:
if org in taken:
a=org
break
vals.remove((d[org],org))
taken.add(org)
while 1:
ind+=1
if ind==n:
b=n-1
break
if d[ind]%val!=0:
b=ind-1
break
else:
if ind in taken:
b=ind
break
vals.remove((d[ind], ind))
taken.add(ind)
ok.append((a,b,val))
ok=sorted(ok)
ans=min(ok[0][2],m)*(ok[0][1]-ok[0][0])
last=ok[0][1]
for i in ok[1:]:
ans+=(i[0]-last)*m
ans+=min(i[2],m)*(i[1]-i[0])
last=i[1]
print(ans)
``` | output | 1 | 18,772 | 13 | 37,545 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of n (n ≥ 2) positive integers and an integer p. Consider an undirected weighted graph of n vertices numbered from 1 to n for which the edges between the vertices i and j (i<j) are added in the following manner:
* If gcd(a_i, a_{i+1}, a_{i+2}, ..., a_{j}) = min(a_i, a_{i+1}, a_{i+2}, ..., a_j), then there is an edge of weight min(a_i, a_{i+1}, a_{i+2}, ..., a_j) between i and j.
* If i+1=j, then there is an edge of weight p between i and j.
Here gcd(x, y, …) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers x, y, ....
Note that there could be multiple edges between i and j if both of the above conditions are true, and if both the conditions fail for i and j, then there is no edge between these vertices.
The goal is to find the weight of the [minimum spanning tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree) of this graph.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases.
The first line of each test case contains two integers n (2 ≤ n ≤ 2 ⋅ 10^5) and p (1 ≤ p ≤ 10^9) — the number of nodes and the parameter p.
The second line contains n integers a_1, a_2, a_3, ..., a_n (1 ≤ a_i ≤ 10^9).
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5.
Output
Output t lines. For each test case print the weight of the corresponding graph.
Example
Input
4
2 5
10 10
2 5
3 3
4 5
5 2 4 9
8 8
5 3 3 6 10 100 9 15
Output
5
3
12
46
Note
Here are the graphs for the four test cases of the example (the edges of a possible MST of the graphs are marked pink):
For test case 1
<image>
For test case 2
<image>
For test case 3
<image>
For test case 4
<image> | instruction | 0 | 18,773 | 13 | 37,546 |
Tags: constructive algorithms, dsu, graphs, greedy, number theory, sortings
Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
n,p = map(int,input().split())
a = list(map(int,input().split()))
locs = []
for i in range(n):
locs.append([a[i],i])
locs.sort()
weight = 0
comps = n
used = [0]*n
parent = list(range(n))
sizes = [1]*n
def find_parent(i):
if parent[i] == i:
return i
parent[i] = find_parent(parent[i])
return parent[i]
def union_sets(a,b):
a = find_parent(a)
b = find_parent(b)
if a != b:
if sizes[a] < sizes[b]:
a,b = b,a
sizes[a] += sizes[b]
parent[b] = a
for mn, i in locs:
if mn >= p:
break
if used[i]:
continue
l = i
r = i
while l > 0 and a[l-1] % mn == 0 and not used[l-1]:
l -= 1
while r < n-1 and a[r+1] % mn == 0 and not used[r+1]:
r += 1
if l != r:
used[l] = 1
for i in range(l+1,r+1):
used[i] = 1
union_sets(i-1,i)
comps -= r - l
weight += mn*(r-l)
if l > 0 and a[l-1] % mn == 0:
used[l] = 1
union_sets(l-1,l)
weight += mn
comps -= 1
if r < n-1 and a[r+1] % mn == 0:
used[r] = 1
union_sets(r,r+1)
weight += mn
comps -= 1
print(weight + (comps-1)*p)
``` | output | 1 | 18,773 | 13 | 37,547 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of n (n ≥ 2) positive integers and an integer p. Consider an undirected weighted graph of n vertices numbered from 1 to n for which the edges between the vertices i and j (i<j) are added in the following manner:
* If gcd(a_i, a_{i+1}, a_{i+2}, ..., a_{j}) = min(a_i, a_{i+1}, a_{i+2}, ..., a_j), then there is an edge of weight min(a_i, a_{i+1}, a_{i+2}, ..., a_j) between i and j.
* If i+1=j, then there is an edge of weight p between i and j.
Here gcd(x, y, …) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers x, y, ....
Note that there could be multiple edges between i and j if both of the above conditions are true, and if both the conditions fail for i and j, then there is no edge between these vertices.
The goal is to find the weight of the [minimum spanning tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree) of this graph.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases.
The first line of each test case contains two integers n (2 ≤ n ≤ 2 ⋅ 10^5) and p (1 ≤ p ≤ 10^9) — the number of nodes and the parameter p.
The second line contains n integers a_1, a_2, a_3, ..., a_n (1 ≤ a_i ≤ 10^9).
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5.
Output
Output t lines. For each test case print the weight of the corresponding graph.
Example
Input
4
2 5
10 10
2 5
3 3
4 5
5 2 4 9
8 8
5 3 3 6 10 100 9 15
Output
5
3
12
46
Note
Here are the graphs for the four test cases of the example (the edges of a possible MST of the graphs are marked pink):
For test case 1
<image>
For test case 2
<image>
For test case 3
<image>
For test case 4
<image> | instruction | 0 | 18,774 | 13 | 37,548 |
Tags: constructive algorithms, dsu, graphs, greedy, number theory, sortings
Correct Solution:
```
def find(x):
while(par[x]!=x):
x=par[x]
return x
def union(x,y):
if (rank[x]>rank[y]):
par[y]=x
elif (rank[y]>rank[x]):
par[x]=y
else:
par[x]=y
rank[y]+=1
for _ in range(int(input())):
n,p=map(int,input().split())
A=list(map(int,input().split()))
s=[[A[i],i] for i in range(n)]
s.sort()
vis=[0 for i in range(n)]
par=[i for i in range(n)]
rank=[0 for i in range(n)]
ans=p*(n-1)
for i in range(n-1):
val,ind=s[i]
if (val>=p):
break
vis[ind]=1
for j in range(ind-1,-1,-1):
if (A[j]%val!=0):
break
x,y=find(ind),find(j)
if (x==y):
break
vis[j]=1
union(x,y)
ans=ans+(val-p)
for j in range(ind+1,n):
if (A[j]%val!=0):
break
x,y=find(ind),find(j)
if (x==y):
break
vis[j]=1
#print(i,j,ans,par)
union(x,y)
ans=ans+(val-p)
print(ans)
``` | output | 1 | 18,774 | 13 | 37,549 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of n (n ≥ 2) positive integers and an integer p. Consider an undirected weighted graph of n vertices numbered from 1 to n for which the edges between the vertices i and j (i<j) are added in the following manner:
* If gcd(a_i, a_{i+1}, a_{i+2}, ..., a_{j}) = min(a_i, a_{i+1}, a_{i+2}, ..., a_j), then there is an edge of weight min(a_i, a_{i+1}, a_{i+2}, ..., a_j) between i and j.
* If i+1=j, then there is an edge of weight p between i and j.
Here gcd(x, y, …) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers x, y, ....
Note that there could be multiple edges between i and j if both of the above conditions are true, and if both the conditions fail for i and j, then there is no edge between these vertices.
The goal is to find the weight of the [minimum spanning tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree) of this graph.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases.
The first line of each test case contains two integers n (2 ≤ n ≤ 2 ⋅ 10^5) and p (1 ≤ p ≤ 10^9) — the number of nodes and the parameter p.
The second line contains n integers a_1, a_2, a_3, ..., a_n (1 ≤ a_i ≤ 10^9).
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5.
Output
Output t lines. For each test case print the weight of the corresponding graph.
Example
Input
4
2 5
10 10
2 5
3 3
4 5
5 2 4 9
8 8
5 3 3 6 10 100 9 15
Output
5
3
12
46
Note
Here are the graphs for the four test cases of the example (the edges of a possible MST of the graphs are marked pink):
For test case 1
<image>
For test case 2
<image>
For test case 3
<image>
For test case 4
<image> | instruction | 0 | 18,775 | 13 | 37,550 |
Tags: constructive algorithms, dsu, graphs, greedy, number theory, sortings
Correct Solution:
```
import sys,os,io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
for _ in range (int(input())):
n,p = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
cost = [0]*n
mini = a[0]
for i in range (1,n):
if a[i]%mini==0:
mini = min(a[i],mini)
cost[i] = min(mini,p)
else:
cost[i]=p
mini = a[i]
mini = a[-1]
for i in range (n-2,-1,-1):
if a[i]%mini == 0:
mini = min(a[i],mini)
cost[i+1]=min(mini,cost[i+1])
else:
mini = a[i]
print(sum(cost))
``` | output | 1 | 18,775 | 13 | 37,551 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of n (n ≥ 2) positive integers and an integer p. Consider an undirected weighted graph of n vertices numbered from 1 to n for which the edges between the vertices i and j (i<j) are added in the following manner:
* If gcd(a_i, a_{i+1}, a_{i+2}, ..., a_{j}) = min(a_i, a_{i+1}, a_{i+2}, ..., a_j), then there is an edge of weight min(a_i, a_{i+1}, a_{i+2}, ..., a_j) between i and j.
* If i+1=j, then there is an edge of weight p between i and j.
Here gcd(x, y, …) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers x, y, ....
Note that there could be multiple edges between i and j if both of the above conditions are true, and if both the conditions fail for i and j, then there is no edge between these vertices.
The goal is to find the weight of the [minimum spanning tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree) of this graph.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases.
The first line of each test case contains two integers n (2 ≤ n ≤ 2 ⋅ 10^5) and p (1 ≤ p ≤ 10^9) — the number of nodes and the parameter p.
The second line contains n integers a_1, a_2, a_3, ..., a_n (1 ≤ a_i ≤ 10^9).
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5.
Output
Output t lines. For each test case print the weight of the corresponding graph.
Example
Input
4
2 5
10 10
2 5
3 3
4 5
5 2 4 9
8 8
5 3 3 6 10 100 9 15
Output
5
3
12
46
Note
Here are the graphs for the four test cases of the example (the edges of a possible MST of the graphs are marked pink):
For test case 1
<image>
For test case 2
<image>
For test case 3
<image>
For test case 4
<image> | instruction | 0 | 18,776 | 13 | 37,552 |
Tags: constructive algorithms, dsu, graphs, greedy, number theory, sortings
Correct Solution:
```
def I(): return map(int, input().split())
t, = I()
r = range
for _ in r(t):
n, p = I()
a = *I(),
b = [p]*(n-1)
c = a[0]
for i in r(1, n):
if a[i] % c:
c = a[i]
else:
b[i-1] = min(c, b[i-1])
c = a[n-1]
for i in r(n-2, -1, -1):
if a[i] % c:
c = a[i]
else:
b[i] = min(c, b[i])
print(sum(b))
``` | output | 1 | 18,776 | 13 | 37,553 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of n (n ≥ 2) positive integers and an integer p. Consider an undirected weighted graph of n vertices numbered from 1 to n for which the edges between the vertices i and j (i<j) are added in the following manner:
* If gcd(a_i, a_{i+1}, a_{i+2}, ..., a_{j}) = min(a_i, a_{i+1}, a_{i+2}, ..., a_j), then there is an edge of weight min(a_i, a_{i+1}, a_{i+2}, ..., a_j) between i and j.
* If i+1=j, then there is an edge of weight p between i and j.
Here gcd(x, y, …) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers x, y, ....
Note that there could be multiple edges between i and j if both of the above conditions are true, and if both the conditions fail for i and j, then there is no edge between these vertices.
The goal is to find the weight of the [minimum spanning tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree) of this graph.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases.
The first line of each test case contains two integers n (2 ≤ n ≤ 2 ⋅ 10^5) and p (1 ≤ p ≤ 10^9) — the number of nodes and the parameter p.
The second line contains n integers a_1, a_2, a_3, ..., a_n (1 ≤ a_i ≤ 10^9).
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5.
Output
Output t lines. For each test case print the weight of the corresponding graph.
Example
Input
4
2 5
10 10
2 5
3 3
4 5
5 2 4 9
8 8
5 3 3 6 10 100 9 15
Output
5
3
12
46
Note
Here are the graphs for the four test cases of the example (the edges of a possible MST of the graphs are marked pink):
For test case 1
<image>
For test case 2
<image>
For test case 3
<image>
For test case 4
<image> | instruction | 0 | 18,777 | 13 | 37,554 |
Tags: constructive algorithms, dsu, graphs, greedy, number theory, sortings
Correct Solution:
```
I=lambda:map(int,input().split())
t,=I();r=range
for _ in r(t):
n,p=I();a=*I(),;b=[p]*(n-1);c=a[0]
for i in r(1,n):
if a[i]%c<1:b[i-1]=min(c,b[i-1])
else:c=a[i]
c=a[n-1]
for i in r(n-2,-1,-1):
if a[i]%c<1:b[i]=min(c,b[i])
else:c=a[i]
print(sum(b))
``` | output | 1 | 18,777 | 13 | 37,555 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of n (n ≥ 2) positive integers and an integer p. Consider an undirected weighted graph of n vertices numbered from 1 to n for which the edges between the vertices i and j (i<j) are added in the following manner:
* If gcd(a_i, a_{i+1}, a_{i+2}, ..., a_{j}) = min(a_i, a_{i+1}, a_{i+2}, ..., a_j), then there is an edge of weight min(a_i, a_{i+1}, a_{i+2}, ..., a_j) between i and j.
* If i+1=j, then there is an edge of weight p between i and j.
Here gcd(x, y, …) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers x, y, ....
Note that there could be multiple edges between i and j if both of the above conditions are true, and if both the conditions fail for i and j, then there is no edge between these vertices.
The goal is to find the weight of the [minimum spanning tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree) of this graph.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases.
The first line of each test case contains two integers n (2 ≤ n ≤ 2 ⋅ 10^5) and p (1 ≤ p ≤ 10^9) — the number of nodes and the parameter p.
The second line contains n integers a_1, a_2, a_3, ..., a_n (1 ≤ a_i ≤ 10^9).
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5.
Output
Output t lines. For each test case print the weight of the corresponding graph.
Example
Input
4
2 5
10 10
2 5
3 3
4 5
5 2 4 9
8 8
5 3 3 6 10 100 9 15
Output
5
3
12
46
Note
Here are the graphs for the four test cases of the example (the edges of a possible MST of the graphs are marked pink):
For test case 1
<image>
For test case 2
<image>
For test case 3
<image>
For test case 4
<image> | instruction | 0 | 18,778 | 13 | 37,556 |
Tags: constructive algorithms, dsu, graphs, greedy, number theory, sortings
Correct Solution:
```
import sys
sys.setrecursionlimit(10**5)
int1 = lambda x: int(x)-1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.buffer.readline())
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def LI1(): return list(map(int1, sys.stdin.buffer.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def LLI1(rows_number): return [LI1() for _ in range(rows_number)]
def BI(): return sys.stdin.buffer.readline().rstrip()
def SI(): return sys.stdin.buffer.readline().rstrip().decode()
# dij = [(0, 1), (-1, 0), (0, -1), (1, 0)]
dij = [(0, 1), (-1, 0), (0, -1), (1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
inf = 10**16
# md = 998244353
md = 10**9+7
class UnionFind:
def __init__(self, n):
self.state = [-1]*n
self.size_table = [1]*n
# cntはグループ数
self.cnt = n
def root(self, u):
stack = []
while self.state[u] >= 0:
stack.append(u)
u = self.state[u]
for v in stack: self.state[v] = u
return u
def merge(self, u, v):
u = self.root(u)
v = self.root(v)
if u == v: return
du = -self.state[u]
dv = -self.state[v]
if du < dv: u, v = v, u
if du == dv: self.state[u] -= 1
self.state[v] = u
self.cnt -= 1
self.size_table[u] += self.size_table[v]
return
def same(self, u, v):
return self.root(u) == self.root(v)
# グループの要素数
def size(self, u):
return self.size_table[self.root(u)]
for _ in range(II()):
n, p = LI()
aa = LI()
ai = [(a, i) for i, a in enumerate(aa)]
ai.sort(key=lambda x: x[0])
uf = UnionFind(n)
ans = 0
fin = [False]*n
for a, i in ai:
if a >= p: break
if fin[i]: continue
for j in range(i-1, -1, -1):
if aa[j]%a: break
if uf.same(i, j): break
ans += a
uf.merge(i, j)
fin[j] = True
for j in range(i+1, n):
if aa[j]%a: break
if uf.same(i, j): break
ans += a
uf.merge(i, j)
fin[j] = True
ans += (uf.cnt-1)*p
print(ans)
``` | output | 1 | 18,778 | 13 | 37,557 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of n (n ≥ 2) positive integers and an integer p. Consider an undirected weighted graph of n vertices numbered from 1 to n for which the edges between the vertices i and j (i<j) are added in the following manner:
* If gcd(a_i, a_{i+1}, a_{i+2}, ..., a_{j}) = min(a_i, a_{i+1}, a_{i+2}, ..., a_j), then there is an edge of weight min(a_i, a_{i+1}, a_{i+2}, ..., a_j) between i and j.
* If i+1=j, then there is an edge of weight p between i and j.
Here gcd(x, y, …) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers x, y, ....
Note that there could be multiple edges between i and j if both of the above conditions are true, and if both the conditions fail for i and j, then there is no edge between these vertices.
The goal is to find the weight of the [minimum spanning tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree) of this graph.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases.
The first line of each test case contains two integers n (2 ≤ n ≤ 2 ⋅ 10^5) and p (1 ≤ p ≤ 10^9) — the number of nodes and the parameter p.
The second line contains n integers a_1, a_2, a_3, ..., a_n (1 ≤ a_i ≤ 10^9).
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5.
Output
Output t lines. For each test case print the weight of the corresponding graph.
Example
Input
4
2 5
10 10
2 5
3 3
4 5
5 2 4 9
8 8
5 3 3 6 10 100 9 15
Output
5
3
12
46
Note
Here are the graphs for the four test cases of the example (the edges of a possible MST of the graphs are marked pink):
For test case 1
<image>
For test case 2
<image>
For test case 3
<image>
For test case 4
<image> | instruction | 0 | 18,779 | 13 | 37,558 |
Tags: constructive algorithms, dsu, graphs, greedy, number theory, sortings
Correct Solution:
```
from sys import stdin,stdout
from math import gcd,sqrt,factorial,pi,inf
from collections import deque,defaultdict
from bisect import bisect,bisect_left
from time import time
from itertools import permutations as per
input=stdin.readline
R=lambda:map(int,input().split())
I=lambda:int(input())
S=lambda:input().rstrip('\r\n')
L=lambda:list(R())
P=lambda x:stdout.write(str(x)+'\n')
lcm=lambda x,y:(x*y)//gcd(x,y)
nCr=lambda x,y:(f[x]*inv((f[y]*f[x-y])%N))%N
inv=lambda x:pow(x,N-2,N)
sm=lambda x:(x**2+x)//2
N=10**9+7
for _ in range(I()):
n,k=R()
*a,=R()
v=[k]*(n-1)
mn=a[0]
g=a[0]
for i in range(n-1):
g=gcd(g,a[i+1])
if g==mn:
v[i]=min(v[i],mn)
else:
g=a[i+1]
mn=a[i+1]
g=a[-1]
mn=a[-1]
for i in range(n-1,0,-1):
g=gcd(g,a[i-1])
if g==mn:
v[i-1]=min(v[i-1],mn)
else:
g=a[i-1]
mn=a[i-1]
print(sum(v))
``` | output | 1 | 18,779 | 13 | 37,559 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of n (n ≥ 2) positive integers and an integer p. Consider an undirected weighted graph of n vertices numbered from 1 to n for which the edges between the vertices i and j (i<j) are added in the following manner:
* If gcd(a_i, a_{i+1}, a_{i+2}, ..., a_{j}) = min(a_i, a_{i+1}, a_{i+2}, ..., a_j), then there is an edge of weight min(a_i, a_{i+1}, a_{i+2}, ..., a_j) between i and j.
* If i+1=j, then there is an edge of weight p between i and j.
Here gcd(x, y, …) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers x, y, ....
Note that there could be multiple edges between i and j if both of the above conditions are true, and if both the conditions fail for i and j, then there is no edge between these vertices.
The goal is to find the weight of the [minimum spanning tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree) of this graph.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases.
The first line of each test case contains two integers n (2 ≤ n ≤ 2 ⋅ 10^5) and p (1 ≤ p ≤ 10^9) — the number of nodes and the parameter p.
The second line contains n integers a_1, a_2, a_3, ..., a_n (1 ≤ a_i ≤ 10^9).
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5.
Output
Output t lines. For each test case print the weight of the corresponding graph.
Example
Input
4
2 5
10 10
2 5
3 3
4 5
5 2 4 9
8 8
5 3 3 6 10 100 9 15
Output
5
3
12
46
Note
Here are the graphs for the four test cases of the example (the edges of a possible MST of the graphs are marked pink):
For test case 1
<image>
For test case 2
<image>
For test case 3
<image>
For test case 4
<image>
Submitted Solution:
```
import random
import collections
import string
import math
import copy
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
def input(): return sys.stdin.readline().rstrip("\r\n")
# n = 0
# m = 0
# n = int(input())
# li = [int(i) for i in input().split()]
# s = sorted(li)
"""
from dataclasses import dataclass
@dataclass
class point:
x: float
y: float
@dataclass
class line:
A: float
B: float
C: float
def gety(self, x):
return (self.A*x+self.C)/-self.B
def getx(self, y):
return (self.B*y+self.C)/-self.A
def k(self):
return -self.A/self.B
def b(self):
return -self.C/self.B
def dist(self, p: point):
return abs((self.A*p.x+self.B*p.y+self.C)/(self.A**2+self.B**2)**0.5)
def calc_line(u: point, v: point):
return line(A=u.y-v.y, B=v.x-u.x, C=u.y*(u.x-v.x)-u.x*(u.y-v.y))
def is_parallel(u: line, v: line) -> bool:
f1 = False
f2 = False
try:
k1 = u.k()
except:
f1 = True
try:
k2 = v.k()
except:
f2 = True
if f1 != f2:
return False
return f1 or k1 == k2
def seg_len(_from: point, _to: point):
return ((_from.x - _to.x)**2 + (_from.y - _to.y)**2) ** 0.5
def in_range(_from: point, _to: point, _point: point) -> bool:
if _from.x < _to.x:
if _from.y < _to.y:
return _from.x <= _point.x <= _to.x and _from.y <= _point.y <= _to.y
else:
return _from.x <= _point.x <= _to.x and _from.y >= _point.y >= _to.y
else:
if _from.y < _to.y:
return _from.x >= _point.x >= _to.x and _from.y <= _point.y <= _to.y
else:
return _from.x >= _point.x >= _to.x and _from.y >= _point.y >= _to.y
def intersect(u: line, v: line) -> point:
tx = (u.B*v.C-v.B*u.C)/(v.B*u.A-u.B*v.A)
if u.B!=0.0:
ty = -u.A*tx/u.B - u.C/u.B
else:
ty = -v.A*tx/v.B - v.C/v.B
return point(x=tx, y=ty)
def in_direction(_from: point, _to: point, _point: point) -> bool:
if _from.x < _to.x:
if _from.y < _to.y:
return _to.x < _point.x and _to.y < _point.y
else:
return _to.x < _point.x and _point.y <= _to.y
else:
if _from.y < _to.y:
return _to.x >= _point.x and _to.y < _point.y
else:
return _to.x >= _point.x and _point.y <= _to.y
"""
mo = int(1e9+7)
def exgcd(a, b):
if not b:
return 1, 0
y, x = exgcd(b, a % b)
y -= a//b * x
return x, y
def getinv(a, m):
x, y = exgcd(a, m)
return -1 if x == 1 else x % m
def comb(n, b):
res = 1
b = min(b, n-b)
for i in range(b):
res = res*(n-i)*getinv(i+1, mo) % mo
# res %= mo
return res % mo
def quickpower(a, n):
res = 1
while n:
if n & 1:
res = res * a % mo
n >>= 1
a = a*a % mo
return res
def dis(a, b):
return abs(a[0]-b[0]) + abs(a[1]-b[1])
def getpref(x):
if x > 1:
return (x)*(x-1) >> 1
else:
return 0
def orafli(upp):
primes = []
marked = [False for i in range(upp+3)]
prvs = [i for i in range(upp+3)]
for i in range(2, upp):
if not marked[i]:
primes.append(i)
for j in primes:
if i*j >= upp:
break
marked[i*j] = True
prvs[i*j] = j
if i % j == 0:
break
return primes, prvs
def lower_ord(c: str) -> int:
return ord(c)-97
def upper_ord(c: str) -> int:
return ord(c) - 65
def read_list():
return [int(i) for i in input().split()]
def read_int():
s = input().split()
if len(s) == 1:
return int(s[0])
else:
return map(int, s)
def ask(s):
print(f"? {s}", flush=True)
def answer(s):
print(f"{s}", flush=True)
import traceback
def solve():
n, p = read_int()
lsorce = read_list()
li = [(int(i), p) for p, i in enumerate(lsorce)]
li.sort()
vis = [False for i in li]
# ans = (n-1) * p
ans = 0
ato = n-1
for val, pid in li:
if val>=p:
break
else:
if vis[pid]:
continue
# ctr = 0
ll = pid
rr = pid
while ll<len(lsorce)-1 and not vis[ll] and lsorce[ll+1] % val == 0:
# vis[pid+ctr] = True
# vis[ll] = True
ll+=1
# ctr+=1
# pos = -1
while rr>=1 and not vis[rr] and lsorce[rr-1] % val == 0:
# vis[pid+pos] = True
# vis[rr] = True
rr-=1
for ppp in range(rr, ll+1):
vis[ppp] = True
# ctr+=1
# pos-=1
ctr = ll - rr + 1
ato -= ctr - 1
ans += val * (ctr - 1)
ans+= ato * p
print(ans)
# fi = open('C:\\cppHeaders\\CF2020.12.17\\test.data', 'r')
# def input(): return fi.readline().rstrip("\r\n")
# primes, prv = orafli(10001)
# solve()
t = int(input())
for ti in range(t):
# try:
# print(f"Case #{ti+1}: ", end='')
solve()
# except:
# traceback.print_exc()
``` | instruction | 0 | 18,780 | 13 | 37,560 |
Yes | output | 1 | 18,780 | 13 | 37,561 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of n (n ≥ 2) positive integers and an integer p. Consider an undirected weighted graph of n vertices numbered from 1 to n for which the edges between the vertices i and j (i<j) are added in the following manner:
* If gcd(a_i, a_{i+1}, a_{i+2}, ..., a_{j}) = min(a_i, a_{i+1}, a_{i+2}, ..., a_j), then there is an edge of weight min(a_i, a_{i+1}, a_{i+2}, ..., a_j) between i and j.
* If i+1=j, then there is an edge of weight p between i and j.
Here gcd(x, y, …) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers x, y, ....
Note that there could be multiple edges between i and j if both of the above conditions are true, and if both the conditions fail for i and j, then there is no edge between these vertices.
The goal is to find the weight of the [minimum spanning tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree) of this graph.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases.
The first line of each test case contains two integers n (2 ≤ n ≤ 2 ⋅ 10^5) and p (1 ≤ p ≤ 10^9) — the number of nodes and the parameter p.
The second line contains n integers a_1, a_2, a_3, ..., a_n (1 ≤ a_i ≤ 10^9).
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5.
Output
Output t lines. For each test case print the weight of the corresponding graph.
Example
Input
4
2 5
10 10
2 5
3 3
4 5
5 2 4 9
8 8
5 3 3 6 10 100 9 15
Output
5
3
12
46
Note
Here are the graphs for the four test cases of the example (the edges of a possible MST of the graphs are marked pink):
For test case 1
<image>
For test case 2
<image>
For test case 3
<image>
For test case 4
<image>
Submitted Solution:
```
import sys,os,io
import math,bisect,operator
inf,mod = float('inf'),10**9+7
# sys.setrecursionlimit(10 ** 6)
from itertools import groupby,accumulate
from heapq import heapify,heappop,heappush
from collections import deque,Counter,defaultdict
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
Neo = lambda : list(map(int,input().split()))
test, = Neo()
for _ in range(test):
n,p = Neo()
A = Neo()
vis = set()
Ans = [p]*(n-1)
for i,val in enumerate(A):
if i not in vis:
for j in range(i-1,-1,-1):
if A[j]%val == 0:
Ans[j] = min(Ans[j],val)
vis.add(j)
else:
break
for j in range(i+1,n):
if A[j]%val == 0:
Ans[j-1] = min(Ans[j-1],val)
vis.add(j)
else:
break
print(sum(Ans))
``` | instruction | 0 | 18,781 | 13 | 37,562 |
Yes | output | 1 | 18,781 | 13 | 37,563 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of n (n ≥ 2) positive integers and an integer p. Consider an undirected weighted graph of n vertices numbered from 1 to n for which the edges between the vertices i and j (i<j) are added in the following manner:
* If gcd(a_i, a_{i+1}, a_{i+2}, ..., a_{j}) = min(a_i, a_{i+1}, a_{i+2}, ..., a_j), then there is an edge of weight min(a_i, a_{i+1}, a_{i+2}, ..., a_j) between i and j.
* If i+1=j, then there is an edge of weight p between i and j.
Here gcd(x, y, …) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers x, y, ....
Note that there could be multiple edges between i and j if both of the above conditions are true, and if both the conditions fail for i and j, then there is no edge between these vertices.
The goal is to find the weight of the [minimum spanning tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree) of this graph.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases.
The first line of each test case contains two integers n (2 ≤ n ≤ 2 ⋅ 10^5) and p (1 ≤ p ≤ 10^9) — the number of nodes and the parameter p.
The second line contains n integers a_1, a_2, a_3, ..., a_n (1 ≤ a_i ≤ 10^9).
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5.
Output
Output t lines. For each test case print the weight of the corresponding graph.
Example
Input
4
2 5
10 10
2 5
3 3
4 5
5 2 4 9
8 8
5 3 3 6 10 100 9 15
Output
5
3
12
46
Note
Here are the graphs for the four test cases of the example (the edges of a possible MST of the graphs are marked pink):
For test case 1
<image>
For test case 2
<image>
For test case 3
<image>
For test case 4
<image>
Submitted Solution:
```
for _ in range(int(input())):
n, p = map(int, input().split())
a = list(map(int, input().split()))
Answer = [p] * (n-1)
c = a[0]
for i in range(1, n):
if a[i]%c < 1:
Answer[i-1] = min(c, Answer[i-1])
else:
c = a[i]
c = a[n-1]
for i in range(n-2, -1, -1):
if a[i]%c < 1:
Answer[i] = min(c, Answer[i])
else:
c = a[i]
print(sum(Answer))
``` | instruction | 0 | 18,782 | 13 | 37,564 |
Yes | output | 1 | 18,782 | 13 | 37,565 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of n (n ≥ 2) positive integers and an integer p. Consider an undirected weighted graph of n vertices numbered from 1 to n for which the edges between the vertices i and j (i<j) are added in the following manner:
* If gcd(a_i, a_{i+1}, a_{i+2}, ..., a_{j}) = min(a_i, a_{i+1}, a_{i+2}, ..., a_j), then there is an edge of weight min(a_i, a_{i+1}, a_{i+2}, ..., a_j) between i and j.
* If i+1=j, then there is an edge of weight p between i and j.
Here gcd(x, y, …) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers x, y, ....
Note that there could be multiple edges between i and j if both of the above conditions are true, and if both the conditions fail for i and j, then there is no edge between these vertices.
The goal is to find the weight of the [minimum spanning tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree) of this graph.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases.
The first line of each test case contains two integers n (2 ≤ n ≤ 2 ⋅ 10^5) and p (1 ≤ p ≤ 10^9) — the number of nodes and the parameter p.
The second line contains n integers a_1, a_2, a_3, ..., a_n (1 ≤ a_i ≤ 10^9).
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5.
Output
Output t lines. For each test case print the weight of the corresponding graph.
Example
Input
4
2 5
10 10
2 5
3 3
4 5
5 2 4 9
8 8
5 3 3 6 10 100 9 15
Output
5
3
12
46
Note
Here are the graphs for the four test cases of the example (the edges of a possible MST of the graphs are marked pink):
For test case 1
<image>
For test case 2
<image>
For test case 3
<image>
For test case 4
<image>
Submitted Solution:
```
from math import gcd
for _ in range(int(input())):
n,p = map(int,input().split())
arr = [int(x) for x in input().split()]
total = [p] * (n-1)
curr = arr[0]
for i in range(1, n):
if(arr[i] % curr == 0):
total[i-1] = min(total[i-1], curr)
else:
curr = arr[i]
curr = arr[n-1]
for i in range(n-2, -1, -1):
if(arr[i] % curr == 0):
total[i] = min(total[i], curr)
else:
curr = arr[i]
print(sum(total))
``` | instruction | 0 | 18,783 | 13 | 37,566 |
Yes | output | 1 | 18,783 | 13 | 37,567 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of n (n ≥ 2) positive integers and an integer p. Consider an undirected weighted graph of n vertices numbered from 1 to n for which the edges between the vertices i and j (i<j) are added in the following manner:
* If gcd(a_i, a_{i+1}, a_{i+2}, ..., a_{j}) = min(a_i, a_{i+1}, a_{i+2}, ..., a_j), then there is an edge of weight min(a_i, a_{i+1}, a_{i+2}, ..., a_j) between i and j.
* If i+1=j, then there is an edge of weight p between i and j.
Here gcd(x, y, …) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers x, y, ....
Note that there could be multiple edges between i and j if both of the above conditions are true, and if both the conditions fail for i and j, then there is no edge between these vertices.
The goal is to find the weight of the [minimum spanning tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree) of this graph.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases.
The first line of each test case contains two integers n (2 ≤ n ≤ 2 ⋅ 10^5) and p (1 ≤ p ≤ 10^9) — the number of nodes and the parameter p.
The second line contains n integers a_1, a_2, a_3, ..., a_n (1 ≤ a_i ≤ 10^9).
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5.
Output
Output t lines. For each test case print the weight of the corresponding graph.
Example
Input
4
2 5
10 10
2 5
3 3
4 5
5 2 4 9
8 8
5 3 3 6 10 100 9 15
Output
5
3
12
46
Note
Here are the graphs for the four test cases of the example (the edges of a possible MST of the graphs are marked pink):
For test case 1
<image>
For test case 2
<image>
For test case 3
<image>
For test case 4
<image>
Submitted Solution:
```
import random
import collections
import string
import math
import copy
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
def input(): return sys.stdin.readline().rstrip("\r\n")
# n = 0
# m = 0
# n = int(input())
# li = [int(i) for i in input().split()]
# s = sorted(li)
"""
from dataclasses import dataclass
@dataclass
class point:
x: float
y: float
@dataclass
class line:
A: float
B: float
C: float
def gety(self, x):
return (self.A*x+self.C)/-self.B
def getx(self, y):
return (self.B*y+self.C)/-self.A
def k(self):
return -self.A/self.B
def b(self):
return -self.C/self.B
def dist(self, p: point):
return abs((self.A*p.x+self.B*p.y+self.C)/(self.A**2+self.B**2)**0.5)
def calc_line(u: point, v: point):
return line(A=u.y-v.y, B=v.x-u.x, C=u.y*(u.x-v.x)-u.x*(u.y-v.y))
def is_parallel(u: line, v: line) -> bool:
f1 = False
f2 = False
try:
k1 = u.k()
except:
f1 = True
try:
k2 = v.k()
except:
f2 = True
if f1 != f2:
return False
return f1 or k1 == k2
def seg_len(_from: point, _to: point):
return ((_from.x - _to.x)**2 + (_from.y - _to.y)**2) ** 0.5
def in_range(_from: point, _to: point, _point: point) -> bool:
if _from.x < _to.x:
if _from.y < _to.y:
return _from.x <= _point.x <= _to.x and _from.y <= _point.y <= _to.y
else:
return _from.x <= _point.x <= _to.x and _from.y >= _point.y >= _to.y
else:
if _from.y < _to.y:
return _from.x >= _point.x >= _to.x and _from.y <= _point.y <= _to.y
else:
return _from.x >= _point.x >= _to.x and _from.y >= _point.y >= _to.y
def intersect(u: line, v: line) -> point:
tx = (u.B*v.C-v.B*u.C)/(v.B*u.A-u.B*v.A)
if u.B!=0.0:
ty = -u.A*tx/u.B - u.C/u.B
else:
ty = -v.A*tx/v.B - v.C/v.B
return point(x=tx, y=ty)
def in_direction(_from: point, _to: point, _point: point) -> bool:
if _from.x < _to.x:
if _from.y < _to.y:
return _to.x < _point.x and _to.y < _point.y
else:
return _to.x < _point.x and _point.y <= _to.y
else:
if _from.y < _to.y:
return _to.x >= _point.x and _to.y < _point.y
else:
return _to.x >= _point.x and _point.y <= _to.y
"""
mo = int(1e9+7)
def exgcd(a, b):
if not b:
return 1, 0
y, x = exgcd(b, a % b)
y -= a//b * x
return x, y
def getinv(a, m):
x, y = exgcd(a, m)
return -1 if x == 1 else x % m
def comb(n, b):
res = 1
b = min(b, n-b)
for i in range(b):
res = res*(n-i)*getinv(i+1, mo) % mo
# res %= mo
return res % mo
def quickpower(a, n):
res = 1
while n:
if n & 1:
res = res * a % mo
n >>= 1
a = a*a % mo
return res
def dis(a, b):
return abs(a[0]-b[0]) + abs(a[1]-b[1])
def getpref(x):
if x > 1:
return (x)*(x-1) >> 1
else:
return 0
def orafli(upp):
primes = []
marked = [False for i in range(upp+3)]
prvs = [i for i in range(upp+3)]
for i in range(2, upp):
if not marked[i]:
primes.append(i)
for j in primes:
if i*j >= upp:
break
marked[i*j] = True
prvs[i*j] = j
if i % j == 0:
break
return primes, prvs
def lower_ord(c: str) -> int:
return ord(c)-97
def upper_ord(c: str) -> int:
return ord(c) - 65
def read_list():
return [int(i) for i in input().split()]
def read_int():
s = input().split()
if len(s) == 1:
return int(s[0])
else:
return map(int, s)
def ask(s):
print(f"? {s}", flush=True)
def answer(s):
print(f"{s}", flush=True)
import traceback
def solve():
n, p = read_int()
lsorce = read_list()
li = [(int(i), p) for p, i in enumerate(lsorce)]
li.sort()
vis = [False for i in li]
ans = (n-1) * p
for val, pid in li:
if val>=p:
break
else:
if vis[pid]:
continue
# ctr = 0
ll = pid
rr = pid
while ll<len(lsorce) and not vis[ll] and math.gcd(lsorce[ll], val) == val:
# vis[pid+ctr] = True
vis[ll] = True
ll+=1
# ctr+=1
# pos = -1
while rr>=0 and not vis[rr] and math.gcd(lsorce[rr], val) == val:
# vis[pid+pos] = True
vis[rr] = True
rr-=1
# ctr+=1
# pos-=1
ctr = ll - rr
ans -= (p-val) * (ctr-1)
print(ans)
# fi = open('C:\\cppHeaders\\CF2020.12.17\\test.data', 'r')
# def input(): return fi.readline().rstrip("\r\n")
# primes, prv = orafli(10001)
# solve()
t = int(input())
for ti in range(t):
# try:
# print(f"Case #{ti+1}: ", end='')
solve()
# except:
# traceback.print_exc()
``` | instruction | 0 | 18,784 | 13 | 37,568 |
No | output | 1 | 18,784 | 13 | 37,569 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of n (n ≥ 2) positive integers and an integer p. Consider an undirected weighted graph of n vertices numbered from 1 to n for which the edges between the vertices i and j (i<j) are added in the following manner:
* If gcd(a_i, a_{i+1}, a_{i+2}, ..., a_{j}) = min(a_i, a_{i+1}, a_{i+2}, ..., a_j), then there is an edge of weight min(a_i, a_{i+1}, a_{i+2}, ..., a_j) between i and j.
* If i+1=j, then there is an edge of weight p between i and j.
Here gcd(x, y, …) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers x, y, ....
Note that there could be multiple edges between i and j if both of the above conditions are true, and if both the conditions fail for i and j, then there is no edge between these vertices.
The goal is to find the weight of the [minimum spanning tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree) of this graph.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases.
The first line of each test case contains two integers n (2 ≤ n ≤ 2 ⋅ 10^5) and p (1 ≤ p ≤ 10^9) — the number of nodes and the parameter p.
The second line contains n integers a_1, a_2, a_3, ..., a_n (1 ≤ a_i ≤ 10^9).
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5.
Output
Output t lines. For each test case print the weight of the corresponding graph.
Example
Input
4
2 5
10 10
2 5
3 3
4 5
5 2 4 9
8 8
5 3 3 6 10 100 9 15
Output
5
3
12
46
Note
Here are the graphs for the four test cases of the example (the edges of a possible MST of the graphs are marked pink):
For test case 1
<image>
For test case 2
<image>
For test case 3
<image>
For test case 4
<image>
Submitted Solution:
```
import sys,os,io
# input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
input = sys.stdin.readline
for _ in range (int(input())):
n,p = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
cost = [0]*n
mini = 10**10
for i in range (1,n):
if a[i]%mini==0 or a[i]%a[i-1]==0:
mini = min(a[i],a[i-1],mini)
cost[i] = min(mini,p)
else:
cost[i]=p
mini = 10**10
print(sum(cost))
``` | instruction | 0 | 18,785 | 13 | 37,570 |
No | output | 1 | 18,785 | 13 | 37,571 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of n (n ≥ 2) positive integers and an integer p. Consider an undirected weighted graph of n vertices numbered from 1 to n for which the edges between the vertices i and j (i<j) are added in the following manner:
* If gcd(a_i, a_{i+1}, a_{i+2}, ..., a_{j}) = min(a_i, a_{i+1}, a_{i+2}, ..., a_j), then there is an edge of weight min(a_i, a_{i+1}, a_{i+2}, ..., a_j) between i and j.
* If i+1=j, then there is an edge of weight p between i and j.
Here gcd(x, y, …) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers x, y, ....
Note that there could be multiple edges between i and j if both of the above conditions are true, and if both the conditions fail for i and j, then there is no edge between these vertices.
The goal is to find the weight of the [minimum spanning tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree) of this graph.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases.
The first line of each test case contains two integers n (2 ≤ n ≤ 2 ⋅ 10^5) and p (1 ≤ p ≤ 10^9) — the number of nodes and the parameter p.
The second line contains n integers a_1, a_2, a_3, ..., a_n (1 ≤ a_i ≤ 10^9).
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5.
Output
Output t lines. For each test case print the weight of the corresponding graph.
Example
Input
4
2 5
10 10
2 5
3 3
4 5
5 2 4 9
8 8
5 3 3 6 10 100 9 15
Output
5
3
12
46
Note
Here are the graphs for the four test cases of the example (the edges of a possible MST of the graphs are marked pink):
For test case 1
<image>
For test case 2
<image>
For test case 3
<image>
For test case 4
<image>
Submitted Solution:
```
t=int(input())
for _ in range(t):
n,p=map(int,input().split())
arr=list(map(int,input().split()))
small=[-1]*n
arr2=[]
for i in range(n):
arr2.append([arr[i],i])
arr2.sort()
for i in range(n):
pos=arr2[i][1]
val=arr2[i][0]
while((pos>=0) and (small[pos]==-1)):
if((arr[pos]%val)==0):
small[pos]=val
else:
break
pos-=1
pos=arr2[i][1]+1
while((pos<n) and (small[pos]==-1)):
if((arr[pos]%val)==0):
small[pos]=val
else:
break
pos+=1
small.append(-1)
ans=0
pos=0
while(pos<n):
if(pos==(n-1)):
break
temp=pos
while((pos<n) and (small[pos+1]==small[pos])):
pos+=1
l=pos-temp
if(l==0):
ans+=p
else:
ans+=min(p,small[pos])*l
if(pos<(n-1)):
ans+=p
pos+=1
print(ans)
``` | instruction | 0 | 18,786 | 13 | 37,572 |
No | output | 1 | 18,786 | 13 | 37,573 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of n (n ≥ 2) positive integers and an integer p. Consider an undirected weighted graph of n vertices numbered from 1 to n for which the edges between the vertices i and j (i<j) are added in the following manner:
* If gcd(a_i, a_{i+1}, a_{i+2}, ..., a_{j}) = min(a_i, a_{i+1}, a_{i+2}, ..., a_j), then there is an edge of weight min(a_i, a_{i+1}, a_{i+2}, ..., a_j) between i and j.
* If i+1=j, then there is an edge of weight p between i and j.
Here gcd(x, y, …) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers x, y, ....
Note that there could be multiple edges between i and j if both of the above conditions are true, and if both the conditions fail for i and j, then there is no edge between these vertices.
The goal is to find the weight of the [minimum spanning tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree) of this graph.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases.
The first line of each test case contains two integers n (2 ≤ n ≤ 2 ⋅ 10^5) and p (1 ≤ p ≤ 10^9) — the number of nodes and the parameter p.
The second line contains n integers a_1, a_2, a_3, ..., a_n (1 ≤ a_i ≤ 10^9).
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5.
Output
Output t lines. For each test case print the weight of the corresponding graph.
Example
Input
4
2 5
10 10
2 5
3 3
4 5
5 2 4 9
8 8
5 3 3 6 10 100 9 15
Output
5
3
12
46
Note
Here are the graphs for the four test cases of the example (the edges of a possible MST of the graphs are marked pink):
For test case 1
<image>
For test case 2
<image>
For test case 3
<image>
For test case 4
<image>
Submitted Solution:
```
test =int(input())
def gcd(a,b):
if b==0:
return a
return gcd(b,a%b)
def lul(l,t):
mini=min(a[l:t])
mi=l+a[l:t].index(min(a[l:t]))
bi=mi-1
fi=mi+1
while bi>=l and gcd(a[mi],a[bi])==a[mi] :
if ao[bi]==-1:
ao[bi]=a[mi]
ao[mi]=a[mi]
bi-=1
# if bi>=0:
# if gcd(a[mi],a[bi])==a[mi]:
# if ao[bi][]
while fi<t and gcd(a[mi],a[fi])==a[mi] :
if ao[fi]==-1:
ao[fi]=a[mi]
ao[mi]=a[mi]
fi+=1
if l<mi-1:
lul(l,mi-1)
if mi+1<t:
lul(mi+1,t)
for t in range(test):
n,p = [int(i) for i in input().split(' ')]
a = [int(i) for i in input().split(' ')]
edge=[]
ao=[-1 for i in range(n)]
lul(0,n)
ans=0
for i in range(0,n-1):
if ao[i]==ao[i+1] and ao[i]!=-1:
ans+=min(ao[i],p)
else:
ans+=p
print(ans)
``` | instruction | 0 | 18,787 | 13 | 37,574 |
No | output | 1 | 18,787 | 13 | 37,575 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.
Input
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge.
It is possible that the graph has loops and multiple edges between pair of vertices.
Output
Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.
Examples
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5 | instruction | 0 | 18,800 | 13 | 37,600 |
Tags: graphs, shortest paths
Correct Solution:
```
#!/usr/bin/env python
from heapq import heappop, heappush
def dijkstra(graph, start=0):
n = len(graph)
dist, parents = [float('inf')] * n, [-1] * n
dist[start] = 0
queue = [(0, start)]
while queue:
path_len, v = heappop(queue)
if path_len == dist[v]:
for w, edge_len in graph[v]:
if edge_len + path_len < dist[w]:
dist[w], parents[w] = edge_len + path_len, v
heappush(queue, (edge_len + path_len, w))
return dist, parents
def main():
n, m = map(int, input().split())
graph = [[] for _ in range(n)]
for i in range(m):
_a, _b, _w = input().split()
a, b, w = int(_a) - 1, int(_b) - 1, float(_w)
graph[a].append((b, w))
graph[b].append((a, w))
_, parents = dijkstra(graph)
if parents[n - 1] == -1:
print(-1)
else:
res, parent = [], n - 1
while parent != parents[0]:
res.append(parent + 1)
parent = parents[parent]
res.reverse()
print(*res)
if __name__ == "__main__":
main()
``` | output | 1 | 18,800 | 13 | 37,601 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.
Input
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge.
It is possible that the graph has loops and multiple edges between pair of vertices.
Output
Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.
Examples
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5 | instruction | 0 | 18,801 | 13 | 37,602 |
Tags: graphs, shortest paths
Correct Solution:
```
import heapq
n,m=map(int,input().split())
g={i:[] for i in range(1,n+1)}
dis=[float('inf') for i in range(n+1)]
visited=[False for i in range(n+1)]
for i in range(m):
a,b,w=map(int,input().split())
g[a].append((b,w))
g[b].append((a,w))
q=[]
p=[-1 for i in range(n+1)]
dis[1]=0
heapq.heappush(q,[0,1])
while q:
a=heapq.heappop(q)
curdis,curnode=a
if visited[curnode]==True:
continue
visited[curnode]=True
for child,distance in g[curnode]:
if visited[child]==False and distance+curdis<dis[child]:
dis[child]=distance+curdis
p[child]=curnode
heapq.heappush(q,[dis[child],child])
if dis[n]==float('inf'):
print(-1)
else:
path = []
while n>0:
path.append(n)
n= p[n]
path.reverse()
print(*path)
``` | output | 1 | 18,801 | 13 | 37,603 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.
Input
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge.
It is possible that the graph has loops and multiple edges between pair of vertices.
Output
Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.
Examples
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5 | instruction | 0 | 18,802 | 13 | 37,604 |
Tags: graphs, shortest paths
Correct Solution:
```
from heapq import heappush, heappop
n, m = map(int, input().split())
g = [[] for _ in range(n + 1)]
for _ in range(m):
a, b, w = map(int, input().split())
g[a].append((b, w))
g[b].append((a, w))
h, tt, parent = [(0, 1)], [2 ** 40] * (n + 1), [0] * (n + 1)
while h:
d, v = heappop(h)
for u, w in g[v]:
w += d
if tt[u] > w:
parent[u] = v
tt[u] = w
heappush(h, (w, u))
if not parent[n]:
exit(print(-1))
res, v = [n], n
while v != 1:
v = parent[v]
res.append(v)
print(' '.join(map(str, reversed(res))))
``` | output | 1 | 18,802 | 13 | 37,605 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.
Input
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge.
It is possible that the graph has loops and multiple edges between pair of vertices.
Output
Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.
Examples
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5 | instruction | 0 | 18,803 | 13 | 37,606 |
Tags: graphs, shortest paths
Correct Solution:
```
import sys
from collections import defaultdict
import heapq
input = sys.stdin.readline
def get_adj_mat(src, dst, weight):
matrix = defaultdict(list)
for src_i, dst_i, weight_i in zip(src, dst, weight):
matrix[src_i].append((weight_i, dst_i))
matrix[dst_i].append((weight_i, src_i))
return matrix
def dikjstra(root, destination, adj_mat, n):
costs = [-1] * n
back = [-1] * n
root_cost = 0
min_queue = []
heapq.heappush(min_queue, (root_cost, -1, root))
while min_queue:
src_cost, src_edge_par, src_edge = heapq.heappop(min_queue)
if costs[src_edge] == -1:
costs[src_edge] = src_cost
back[src_edge] = src_edge_par
if src_edge == destination:
break
for dst_cost, dst_edge in adj_mat[src_edge]:
if costs[dst_edge] == -1:
heapq.heappush(min_queue, (src_cost+dst_cost, src_edge, dst_edge))
if costs[destination] == -1:
return [-1]
else:
pos = destination
ans = [pos+1]
while pos > 0:
ans.append(back[pos]+1)
pos = back[pos]
return ans[::-1]
def solve(src, dst, weight, n):
adj_mat = get_adj_mat(src, dst, weight)
print(*dikjstra(0, n-1, adj_mat, n))
if __name__ == "__main__":
n, m = [int(val) for val in input().split()]
src, dst, weight = [], [], []
for _ in range(m):
src_i, dst_i, weight_i = [int(val) for val in input().split()]
src.append(src_i-1), dst.append(dst_i-1), weight.append(weight_i)
solve(src, dst, weight, n)
``` | output | 1 | 18,803 | 13 | 37,607 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.
Input
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge.
It is possible that the graph has loops and multiple edges between pair of vertices.
Output
Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.
Examples
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5 | instruction | 0 | 18,804 | 13 | 37,608 |
Tags: graphs, shortest paths
Correct Solution:
```
from heapq import *
import sys
input=sys.stdin.readline
n,m=map(int,input().split())
g=[[] for i in range(n+1)]
for i in range(m):
x,y,w=map(int,input().split())
if x!=y:
g[x].append((y,w))
g[y].append((x,w))
path=[i for i in range(n+1)]
dis=[float('inf')]*(n+1)
hp=[(0,1)]
while hp:
dcur,cur=heappop(hp)
for v,w in g[cur]:
if dcur+w<dis[v]:
dis[v]=dcur+w
path[v]=cur
heappush(hp,(dis[v],v))
l=[n]
x=n
if dis[n]!=float('inf'):
while x!=1:
x=path[x]
l.append(x)
print(*l[::-1])
else:print(-1)
``` | output | 1 | 18,804 | 13 | 37,609 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.
Input
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge.
It is possible that the graph has loops and multiple edges between pair of vertices.
Output
Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.
Examples
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5 | instruction | 0 | 18,805 | 13 | 37,610 |
Tags: graphs, shortest paths
Correct Solution:
```
from collections import defaultdict,deque,Counter,OrderedDict
from heapq import heappop,heappush
def main():
n,m = map(int,input().split())
adj = [[] for i in range(n+1)]
for i in range(m):
a,b,c = map(int,input().split())
adj[a].append((b,c))
adj[b].append((a,c))
Q,dist,parent = [(0,1)],[10**13]*(n+1),[0]*(n+1)
dist[1] = 0
while Q:
d,v = heappop(Q)
for (u,w) in adj[v]:
w += d
if dist[u] > w:
dist[u] = w
parent[u] = v
heappush(Q,(w,u))
if not parent[n]:
print("-1")
else:
res,v = [],n
while v != 0:
res.append(v)
v = parent[v]
print(" ".join(map(str,reversed(res))))
if __name__ == "__main__":
main()
``` | output | 1 | 18,805 | 13 | 37,611 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.
Input
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge.
It is possible that the graph has loops and multiple edges between pair of vertices.
Output
Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.
Examples
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5 | instruction | 0 | 18,806 | 13 | 37,612 |
Tags: graphs, shortest paths
Correct Solution:
```
# from debug import debug
import sys
from heapq import *
inf = int(1e12)
n, m = map(int, input().split())
parent = [-1]*n
dis = [inf]*n
graph = [[] for i in range(n)]
dis[0] = 0
for i in range(m):
a,b,c = map(int, input().split())
graph[a-1].append((b-1,c))
graph[b-1].append((a-1,c))
q = [(0, 0)]
while q:
w, node = heappop(q)
for nodes in graph[node]:
if dis[nodes[0]] > dis[node]+nodes[1]:
dis[nodes[0]] = dis[node]+nodes[1]
parent[nodes[0]] = node
heappush(q, (dis[nodes[0]], nodes[0]))
if parent[n-1] == -1:
print(-1)
else:
path = []
s = n-1
while s != -1:
path.append(s+1)
s = parent[s]
path.reverse()
print(*path)
``` | output | 1 | 18,806 | 13 | 37,613 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.
Input
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge.
It is possible that the graph has loops and multiple edges between pair of vertices.
Output
Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.
Examples
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5 | instruction | 0 | 18,807 | 13 | 37,614 |
Tags: graphs, shortest paths
Correct Solution:
```
import heapq
INF = 10**13
def dijk(st, d, p, g):
q = [(d[st], st)]
while q:
ln, v = heapq.heappop(q)
if(ln > d[v]):
continue
for (to, w) in (g[v]):
if d[to] > ln + w:
d[to] = ln + w
p[to] = v
heapq.heappush(q, (d[to], to))
def main():
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))
g[v].append((u, w))
d = [INF] * (n + 1)
p = [-1] * (n + 1)
d[1] = 0
dijk(1, d, p, g)
if d[n] == INF:
print(-1)
exit()
path = []
while n != -1:
path.append(n)
n = p[n]
path.reverse()
print(' '.join(map(str, path)))
if __name__ == '__main__':
main()
``` | output | 1 | 18,807 | 13 | 37,615 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.
Input
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge.
It is possible that the graph has loops and multiple edges between pair of vertices.
Output
Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.
Examples
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5
Submitted Solution:
```
import heapq
# Dijktra's shortest path algorithm. Prints the path from source to target.
# If no path exists -1 is printed
# update: test if using the reversed(list) for the stack yields a faster runtime
def dijkstra(adj, source, target):
INF = ((1<<63) - 1)//2
n = len(adj)
pred = [ - 1 for x in range(n) ]
dist = [ INF for i in range(n) ]
dist[source] = 0
Q = []
heapq.heappush(Q, [dist[source], source])
while(Q):
u = heapq.heappop(Q) # u is a list of tuples [u_dist, u_id]
u_dist = u[0]
u_id = u[1]
if u_id == target:
break
if u_dist > dist[u_id]:
continue
for v in adj[u_id]:
v_id = v[0]
w_uv = v[1]
if dist[u_id] + w_uv < dist[v_id]:
dist[v_id] = dist[u_id] + w_uv
heapq.heappush(Q, [dist[v_id], v_id])
pred[v_id] = u_id
if dist[target]==INF:
print(-1)
else:
st = []
node = target
while(True):
st.append(node)
node = pred[node]
if(node==-1):
break
for num in reversed(st):
print(num+1, end=' ')
#path = st[::-1]
#for num in path:
# print(num+1, end=' ')
#----------------------------------------------------------
n, m = map(int, input().split())
adj = [ [] for x in range(n) ]
for i in range(m):
a, b, w = map(int, input().split())
adj[a-1].append([b-1, w])
adj[b-1].append([a-1, w])
source = 0
target = n-1
dijkstra(adj, 0, n-1)
``` | instruction | 0 | 18,808 | 13 | 37,616 |
Yes | output | 1 | 18,808 | 13 | 37,617 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.
Input
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge.
It is possible that the graph has loops and multiple edges between pair of vertices.
Output
Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.
Examples
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5
Submitted Solution:
```
from collections import defaultdict
import heapq
I=1<<60
n,m= map(int, input().split())
# g=Graph(n)
# graph = [[] for _ in range(n)]
graph=defaultdict(list)
dist=[0]+[I]*(n)
path=[-1]*n
minheap=[(0,0)]
for _ in range(m):
a,b,w= map(int, input().split())
graph[a-1] += [(w, b-1)]
graph[b-1] += [(w, a-1)]
# print(graph)
while minheap:
u=heapq.heappop(minheap)[1]
for node in graph[u]:
temp,data=dist[u]+node[0],node[1]
if(temp<dist[data]):
dist[data],path[data]=temp,u
# path[data]=u
heapq.heappush(minheap,(dist[data],data))
# print(dist,path)
if dist[n-1]==I:
print(-1)
else:
x,y=n-1,[]
while x!=-1:
y+=[x+1]
x=path[x]
y.reverse()
print(" ".join(map(str,y)))
``` | instruction | 0 | 18,809 | 13 | 37,618 |
Yes | output | 1 | 18,809 | 13 | 37,619 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.
Input
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge.
It is possible that the graph has loops and multiple edges between pair of vertices.
Output
Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.
Examples
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5
Submitted Solution:
```
import sys, heapq
n, m = [int(x) for x in sys.stdin.readline().split()]
e = {}
for i in range(1, n+1):
e[i] = {}
for i in range(m):
v, u, w = [int(x) for x in sys.stdin.readline().split()]
if not u in e[v] or e[v][u] > w: e[v][u] = w
if not v in e[u] or e[u][v] > w: e[u][v] = w
INF = 1000000000000
pq = []
heapq.heappush(pq, (0, n))
prev = [-1]*(n+1)
dist = [INF]*(n+1)
vis = [False]*(n+1)
dist[n] = 0
while len(pq) > 0:
d, v = heapq.heappop(pq)
if vis[v]: continue
vis[v] = True
if v == 1: break
for u in e[v]:
alt = dist[v] + e[v][u]
if alt < dist[u]:
dist[u] = alt
prev[u] = v
heapq.heappush(pq, (alt, u))
p = 1
patth = []
while p != -1:
patth.append(str(p))
p = prev[p]
if patth[-1] != str(n): print(-1)
else: print(" ".join(patth))
``` | instruction | 0 | 18,810 | 13 | 37,620 |
Yes | output | 1 | 18,810 | 13 | 37,621 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.
Input
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge.
It is possible that the graph has loops and multiple edges between pair of vertices.
Output
Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.
Examples
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5
Submitted Solution:
```
'''input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
'''
'''input
4 7
1 2 2
1 2 1
1 2 8
2 3 5
3 3 3
3 4 23
3 4 1
'''
'''
https://www.hackerearth.com/practice/algorithms/graphs/shortest-path-algorithms/tutorial/
Input #1 No self loop/multiple edges
Input #2 With self loop and multiple edges
'''
INF=float('inf')
import heapq as hq
from collections import defaultdict as dd
def dijkstra(g,source): # Time complexity O(E log(V))
heap=[]
heaplen=0
hq.heapify(heap)
dist_to=[INF]*(n+1) # distance from source to all vertices = infinity
dist_to[source]=0 # distance from source to source = 0
hq.heappush(heap,(dist_to[source],source)) # Push the source vertex in a min-priority queue in the form (distance , vertex)
heaplen=1
prev=[source]*(n+1)
prev[source]=-1
while heaplen>0: # until the priority queue is empty
temp=hq.heappop(heap) # Take the (distance,vertex) with the minimum distance
heaplen-=1
for edge in g[temp[1]]: # recalculate distances for nodes connected to the vertex
if dist_to[temp[1]]+edge[0]<dist_to[edge[1]]: # current vertex distance + edge weight < next vertex distance
dist_to[edge[1]]=dist_to[temp[1]]+edge[0]
hq.heappush(heap,(edge[0],edge[1]))
heaplen+=1
prev[edge[1]]=temp[1]
return dist_to,prev
n,m=map(int,input().strip().split(' ')) # number of verties and edges
g=dd(list)
for _ in range(m):
u,v,w=[int(i) for i in input().split()]
g[u].append((w,v))
g[v].append((w,u))
source=1
destination=n
dist,prev=dijkstra(g,source)
#print(*dist)
if dist[destination]==INF:
print(-1)
else:
p=prev[destination]
path=[destination]
while p!=-1:
path.append(p)
p=prev[p]
# print(dist[destination])
print(*path[::-1])
'''Practice
https://www.codechef.com/problems/PAC6
http://codeforces.com/problemset/problem/20/C
https://www.hackerrank.com/challenges/dijkstrashortreach/problem
'''
``` | instruction | 0 | 18,811 | 13 | 37,622 |
Yes | output | 1 | 18,811 | 13 | 37,623 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.
Input
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge.
It is possible that the graph has loops and multiple edges between pair of vertices.
Output
Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.
Examples
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5
Submitted Solution:
```
from heapq import heappush, heappop
def main():
n, m = input_tuple(int)
adj_list = {i: [] for i in range(1, n+1)}
for _ in range(m):
u, v, w = input_tuple(int)
adj_list[u].append((v, w))
pred = {1:-1}
dist = {i: float('inf') for i in range(2, n+1)}
dist[1] = 0
heap = [(0, 1)]
while heap:
_, u = heappop(heap)
for v, w in adj_list[u]:
if dist[v] > dist[u] + w:
dist[v] = dist[u] + w
pred[v] = u
heappush(heap, (dist[v], v))
if n in pred:
print(' '.join(get_path(n, pred)))
else:
print(-1)
def get_path(i, pred):
if i > 0:
for j in get_path(pred[i], pred):
yield str(j)
yield str(i)
def input_tuple(f):
return tuple(map(f, input().rstrip().split()))
if __name__ == '__main__':
main()
``` | instruction | 0 | 18,812 | 13 | 37,624 |
No | output | 1 | 18,812 | 13 | 37,625 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.
Input
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge.
It is possible that the graph has loops and multiple edges between pair of vertices.
Output
Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.
Examples
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5
Submitted Solution:
```
import heapq
line1 = input()
# line1 = lines[0]
line1 = line1.split(" ")
goal, m = int(line1[0]), int(line1[1])
g = {}
cost_dir = {}
for i in range(1, goal+1):
cost_dir[i] = float('inf')
for i in range(m):
# temp_line = lines[i+1]
temp_line = input()
temp_line = temp_line.split(" ")
u, v, c = float(temp_line[0]), float(temp_line[1]), float(temp_line[2])
# s = miles per hour, l = miles; time_cost = miles/miles_per_hou
if u in g:
g[u].append((v, c))
else:
g[u] = [(v, c)]
pq = [(0, 1, [1])]
while pq:
cost, node, path = heapq.heappop(pq)
# print(node, cost)
if node == goal:
p = str(path[0])
for i in range(1, len(path)):
p+= " " + str(path[i])
print(p)
break
if node in g:
for neigh in g[node]:
# print(neigh)
dest, t_cost = neigh
new_cost = cost + t_cost
# print(cost[n])
if new_cost < cost_dir[dest]:
heapq.heappush(pq, (new_cost, dest, path +[int(dest)]))
# print(pq)
cost_dir[dest] = new_cost
print(-1)
# print("TOO MUCH")
# print(int(round(3.6, 0)))
``` | instruction | 0 | 18,813 | 13 | 37,626 |
No | output | 1 | 18,813 | 13 | 37,627 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.
Input
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge.
It is possible that the graph has loops and multiple edges between pair of vertices.
Output
Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.
Examples
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5
Submitted Solution:
```
import heapq
from collections import defaultdict
def solve(n):
distances = [10**9 for i in range(n + 5)]
Q = list()
heapq.heappush(Q, (0, 1))
paths[1] = 1
distances[1] = 0
while Q:
c, u = heapq.heappop(Q)
if u == n:
return c
if distances[u] < c:
continue
for w, v in Graph[u]:
if distances[v] > c + w:
distances[v] = c + w
heapq.heappush(Q, (distances[v], v))
paths[v] = u
return -1
Graph = defaultdict(list)
paths = defaultdict(int)
arr = list()
n, m = map(int, input().split())
for i in range(m):
x, y, c = map(int, input().split())
Graph[x].append((c, y))
Graph[y].append((c, x))
if solve(n) != -1:
while(paths[n] != n):
arr.append(n)
n = paths[n]
else:
print(-1)
exit()
arr.append(1)
print(' '.join(map(str, arr[::-1])))
``` | instruction | 0 | 18,814 | 13 | 37,628 |
No | output | 1 | 18,814 | 13 | 37,629 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.
Input
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge.
It is possible that the graph has loops and multiple edges between pair of vertices.
Output
Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.
Examples
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5
Submitted Solution:
```
class Graph:
def __init__(self):
self.nodes = set()
self.edges = defaultdict(list)
self.distances = {}
def add_node(self, value):
self.nodes.add(value)
def add_edge(self, from_node, to_node, distance):
self.edges[from_node].append(to_node)
self.edges[to_node].append(from_node)
self.distances[(from_node, to_node)] = distance
def dijsktra(graph, initial):
visited = {initial: 0}
path = {}
nodes = set(graph.nodes)
while nodes:
min_node = None
for node in nodes:
if node in visited:
if min_node is None:
min_node = node
elif visited[node] < visited[min_node]:
min_node = node
if min_node is None:
break
nodes.remove(min_node)
current_weight = visited[min_node]
for edge in graph.edges[min_node]:
weight = current_weight + graph.distance[(min_node, edge)]
if edge not in visited or weight < visited[edge]:
visited[edge] = weight
path[edge] = min_node
print("-1")
``` | instruction | 0 | 18,815 | 13 | 37,630 |
No | output | 1 | 18,815 | 13 | 37,631 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bogdan has a birthday today and mom gave him a tree consisting of n vertecies. For every edge of the tree i, some number xi was written on it. In case you forget, a tree is a connected non-directed graph without cycles. After the present was granted, m guests consecutively come to Bogdan's party. When the i-th guest comes, he performs exactly one of the two possible operations:
1. Chooses some number yi, and two vertecies ai and bi. After that, he moves along the edges of the tree from vertex ai to vertex bi using the shortest path (of course, such a path is unique in the tree). Every time he moves along some edge j, he replaces his current number yi by <image>, that is, by the result of integer division yi div xj.
2. Chooses some edge pi and replaces the value written in it xpi by some positive integer ci < xpi.
As Bogdan cares about his guests, he decided to ease the process. Write a program that performs all the operations requested by guests and outputs the resulting value yi for each i of the first type.
Input
The first line of the input contains integers, n and m (2 ≤ n ≤ 200 000, 1 ≤ m ≤ 200 000) — the number of vertecies in the tree granted to Bogdan by his mom and the number of guests that came to the party respectively.
Next n - 1 lines contain the description of the edges. The i-th of these lines contains three integers ui, vi and xi (1 ≤ ui, vi ≤ n, ui ≠ vi, 1 ≤ xi ≤ 1018), denoting an edge that connects vertecies ui and vi, with the number xi initially written on it.
The following m lines describe operations, requested by Bogdan's guests. Each description contains three or four integers and has one of the two possible forms:
* 1 ai bi yi corresponds to a guest, who chooses the operation of the first type.
* 2 pi ci corresponds to a guests, who chooses the operation of the second type.
It is guaranteed that all the queries are correct, namely 1 ≤ ai, bi ≤ n, 1 ≤ pi ≤ n - 1, 1 ≤ yi ≤ 1018 and 1 ≤ ci < xpi, where xpi represents a number written on edge pi at this particular moment of time that is not necessarily equal to the initial value xpi, as some decreases may have already been applied to it. The edges are numbered from 1 to n - 1 in the order they appear in the input.
Output
For each guest who chooses the operation of the first type, print the result of processing the value yi through the path from ai to bi.
Examples
Input
6 6
1 2 1
1 3 7
1 4 4
2 5 5
2 6 2
1 4 6 17
2 3 2
1 4 6 17
1 5 5 20
2 4 1
1 5 1 3
Output
2
4
20
3
Input
5 4
1 2 7
1 3 3
3 4 2
3 5 5
1 4 2 100
1 5 4 1
2 2 2
1 1 3 4
Output
2
0
2
Note
Initially the tree looks like this:
<image>
The response to the first query is: <image> = 2
After the third edge is changed, the tree looks like this:
<image>
The response to the second query is: <image> = 4
In the third query the initial and final vertex coincide, that is, the answer will be the initial number 20.
After the change in the fourth edge the tree looks like this:
<image>
In the last query the answer will be: <image> = 3
Submitted Solution:
```
n, m = map(int, input().split())
c, g = [0] * 200002, [[] for i in range(200002)]
p, w = [0] * 200002, [0] * 200002
u, v = [0] * 200002, [0] * 200002
C = 0
for i in range(1, n):
a, b, c[i] = map(int, input().split())
g[a].append((b,i))
g[b].append((a,i))
def r(i):
global C
C += 1
u[i] = C
for e in g[i]:
if p[i] != e[0]:
p[e[0]] = i
w[e[0]] = e[1]
r(e[0])
v[i] = C
r(1)
def find(i):
if c[w[i]] == 1:
p[i] = find(p[i])
return p[i]
else:
return i
global z
def go(x, y, z):
if x == 0 or z == 0: return
if u[x] <= u[y] and v[x] >= v[y]: return
p[x] = find(p[x])
z //= c[w[x]]
go(p[x], y, z)
return
for i in range(m):
y = list(map(int, input().split()))
if len(y) == 3:
c[y[1]] = y[2]
else:
z = y[3]
go(y[1],y[2],z)
go(y[2],y[1],z)
print(z)
``` | instruction | 0 | 18,965 | 13 | 37,930 |
No | output | 1 | 18,965 | 13 | 37,931 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bogdan has a birthday today and mom gave him a tree consisting of n vertecies. For every edge of the tree i, some number xi was written on it. In case you forget, a tree is a connected non-directed graph without cycles. After the present was granted, m guests consecutively come to Bogdan's party. When the i-th guest comes, he performs exactly one of the two possible operations:
1. Chooses some number yi, and two vertecies ai and bi. After that, he moves along the edges of the tree from vertex ai to vertex bi using the shortest path (of course, such a path is unique in the tree). Every time he moves along some edge j, he replaces his current number yi by <image>, that is, by the result of integer division yi div xj.
2. Chooses some edge pi and replaces the value written in it xpi by some positive integer ci < xpi.
As Bogdan cares about his guests, he decided to ease the process. Write a program that performs all the operations requested by guests and outputs the resulting value yi for each i of the first type.
Input
The first line of the input contains integers, n and m (2 ≤ n ≤ 200 000, 1 ≤ m ≤ 200 000) — the number of vertecies in the tree granted to Bogdan by his mom and the number of guests that came to the party respectively.
Next n - 1 lines contain the description of the edges. The i-th of these lines contains three integers ui, vi and xi (1 ≤ ui, vi ≤ n, ui ≠ vi, 1 ≤ xi ≤ 1018), denoting an edge that connects vertecies ui and vi, with the number xi initially written on it.
The following m lines describe operations, requested by Bogdan's guests. Each description contains three or four integers and has one of the two possible forms:
* 1 ai bi yi corresponds to a guest, who chooses the operation of the first type.
* 2 pi ci corresponds to a guests, who chooses the operation of the second type.
It is guaranteed that all the queries are correct, namely 1 ≤ ai, bi ≤ n, 1 ≤ pi ≤ n - 1, 1 ≤ yi ≤ 1018 and 1 ≤ ci < xpi, where xpi represents a number written on edge pi at this particular moment of time that is not necessarily equal to the initial value xpi, as some decreases may have already been applied to it. The edges are numbered from 1 to n - 1 in the order they appear in the input.
Output
For each guest who chooses the operation of the first type, print the result of processing the value yi through the path from ai to bi.
Examples
Input
6 6
1 2 1
1 3 7
1 4 4
2 5 5
2 6 2
1 4 6 17
2 3 2
1 4 6 17
1 5 5 20
2 4 1
1 5 1 3
Output
2
4
20
3
Input
5 4
1 2 7
1 3 3
3 4 2
3 5 5
1 4 2 100
1 5 4 1
2 2 2
1 1 3 4
Output
2
0
2
Note
Initially the tree looks like this:
<image>
The response to the first query is: <image> = 2
After the third edge is changed, the tree looks like this:
<image>
The response to the second query is: <image> = 4
In the third query the initial and final vertex coincide, that is, the answer will be the initial number 20.
After the change in the fourth edge the tree looks like this:
<image>
In the last query the answer will be: <image> = 3
Submitted Solution:
```
n, m = map(int, input().split())
c, g = [0] * 200002, [[] for i in range(200002)]
p, d = [0] * 200002, [0] * 200002
u, v = [0] * 200002, [0] * 200002
C, w = 0, [0] * 200002
for i in range(1, n):
a, b, c[i] = map(int, input().split())
g[a].append((b,i))
g[b].append((a,i))
def r(i):
global C
C += 1
u[i] = C
for e in g[i]:
if p[i] != e[0]:
p[e[0]] = i
w[e[0]] = e[1]
r(e[0])
v[i] = C
r(1)
def find(i):
if c[w[i]] == 1:
p[i] = find(p[i])
return p[i]
def go(x, y, z):
if x == 0 or z == 0 or (u[x] <= u[y] and v[x] >= v[y]): return z
return go(find(x), y, z//c[w[x]])
for i in range(m):
y = list(map(int, input().split()))
if len(y) == 3:
c[y[1]] = y[2]
else:
y[3] = go(y[1],y[2],y[3])
y[3] = go(y[2],y[1],y[3])
``` | instruction | 0 | 18,966 | 13 | 37,932 |
No | output | 1 | 18,966 | 13 | 37,933 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bogdan has a birthday today and mom gave him a tree consisting of n vertecies. For every edge of the tree i, some number xi was written on it. In case you forget, a tree is a connected non-directed graph without cycles. After the present was granted, m guests consecutively come to Bogdan's party. When the i-th guest comes, he performs exactly one of the two possible operations:
1. Chooses some number yi, and two vertecies ai and bi. After that, he moves along the edges of the tree from vertex ai to vertex bi using the shortest path (of course, such a path is unique in the tree). Every time he moves along some edge j, he replaces his current number yi by <image>, that is, by the result of integer division yi div xj.
2. Chooses some edge pi and replaces the value written in it xpi by some positive integer ci < xpi.
As Bogdan cares about his guests, he decided to ease the process. Write a program that performs all the operations requested by guests and outputs the resulting value yi for each i of the first type.
Input
The first line of the input contains integers, n and m (2 ≤ n ≤ 200 000, 1 ≤ m ≤ 200 000) — the number of vertecies in the tree granted to Bogdan by his mom and the number of guests that came to the party respectively.
Next n - 1 lines contain the description of the edges. The i-th of these lines contains three integers ui, vi and xi (1 ≤ ui, vi ≤ n, ui ≠ vi, 1 ≤ xi ≤ 1018), denoting an edge that connects vertecies ui and vi, with the number xi initially written on it.
The following m lines describe operations, requested by Bogdan's guests. Each description contains three or four integers and has one of the two possible forms:
* 1 ai bi yi corresponds to a guest, who chooses the operation of the first type.
* 2 pi ci corresponds to a guests, who chooses the operation of the second type.
It is guaranteed that all the queries are correct, namely 1 ≤ ai, bi ≤ n, 1 ≤ pi ≤ n - 1, 1 ≤ yi ≤ 1018 and 1 ≤ ci < xpi, where xpi represents a number written on edge pi at this particular moment of time that is not necessarily equal to the initial value xpi, as some decreases may have already been applied to it. The edges are numbered from 1 to n - 1 in the order they appear in the input.
Output
For each guest who chooses the operation of the first type, print the result of processing the value yi through the path from ai to bi.
Examples
Input
6 6
1 2 1
1 3 7
1 4 4
2 5 5
2 6 2
1 4 6 17
2 3 2
1 4 6 17
1 5 5 20
2 4 1
1 5 1 3
Output
2
4
20
3
Input
5 4
1 2 7
1 3 3
3 4 2
3 5 5
1 4 2 100
1 5 4 1
2 2 2
1 1 3 4
Output
2
0
2
Note
Initially the tree looks like this:
<image>
The response to the first query is: <image> = 2
After the third edge is changed, the tree looks like this:
<image>
The response to the second query is: <image> = 4
In the third query the initial and final vertex coincide, that is, the answer will be the initial number 20.
After the change in the fourth edge the tree looks like this:
<image>
In the last query the answer will be: <image> = 3
Submitted Solution:
```
n, m = map(int, input().split())
c, g = [0] * 200002, [[] for i in range(200002)]
p, d = [0] * 200002, [0] * 200002
u, v = [0] * 200002, [0] * 200002
C, w = 0, [0] * 200002
for i in range(1, n):
a, b, c[i] = map(int, input().split())
g[a].append((b,i))
g[b].append((a,i))
def r(i):
global C
C += 1
u[i] = C
for e in g[i]:
if p[i] != e[0]:
p[e[0]] = i
w[e[0]] = e[1]
r(e[0])
v[i] = C
r(1)
def find(i):
if c[w[i]] == 1:
p[i] = find(p[i])
return p[i]
else:
return i
def go(x, y, z):
if x == 0 or z == 0 or (u[x] <= u[y] and v[x] >= v[y]): return z
return go(find(x), y, z//c[w[x]])
for i in range(m):
y = list(map(int, input().split()))
if len(y) == 3:
c[y[1]] = y[2]
else:
y[3] = go(y[1],y[2],y[3])
y[3] = go(y[2],y[1],y[3])
print(y[3])
``` | instruction | 0 | 18,967 | 13 | 37,934 |
No | output | 1 | 18,967 | 13 | 37,935 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree of n nodes. The tree is rooted at node 1, which is not considered as a leaf regardless of its degree.
Each leaf of the tree has one of the two colors: red or blue. Leaf node v initially has color s_{v}.
The color of each of the internal nodes (including the root) is determined as follows.
* Let b be the number of blue immediate children, and r be the number of red immediate children of a given vertex.
* Then the color of this vertex is blue if and only if b - r ≥ k, otherwise red.
Integer k is a parameter that is same for all the nodes.
You need to handle the following types of queries:
* 1 v: print the color of node v;
* 2 v c: change the color of leaf v to c (c = 0 means red, c = 1 means blue);
* 3 h: update the current value of k to h.
Input
The first line of the input consists of two integers n and k (2 ≤ n ≤ 10^{5}, -n ≤ k ≤ n) — the number of nodes and the initial parameter k.
Each of the next n - 1 lines contains two integers u and v (1 ≤ u,v ≤ n), denoting that there is an edge between vertices u and v.
The next line consists of n space separated integers — the initial array s (-1 ≤ s_i ≤ 1). s_{i} = 0 means that the color of node i is red. s_{i} = 1 means that the color of node i is blue. s_{i} = -1 means that the node i is not a leaf.
The next line contains an integer q (1 ≤ q ≤ 10^5), the number of queries.
q lines follow, each containing a query in one of the following queries:
* 1 v (1 ≤ v ≤ n): print the color of node v;
* 2 v c (1 ≤ v ≤ n, c = 0 or c = 1): change the color of leaf v to c (c = 0 means red, c = 1 means blue). It is guaranteed that v is a leaf;
* 3 h (-n ≤ h ≤ n): update the current value of k to h.
Output
For each query of the first type, print 0 if the color of vertex v is red, and 1 otherwise.
Example
Input
5 2
1 2
1 3
2 4
2 5
-1 -1 0 1 0
9
1 1
1 2
3 -2
1 1
1 2
3 1
2 5 1
1 1
1 2
Output
0
0
1
1
0
1
Note
Figures:
(i) The initial tree
(ii) The tree after the 3rd query
(iii) The tree after the 7th query
<image>
Submitted Solution:
```
nn,k = list(map(int,input().split()))
uv = {}
for i in range(nn-1):
u,v = list(map(int,input().split()))
if u not in uv:
uv[u] = []
uv[u].append(v)
c = list(map(int,input().split()))
def init_color(c_,i=0):
if i >= nn or c[i] != -1:
return
b,r = 0,0
childs = uv.get(i+1,[])
for child in childs:
if c_[child-1] == -1:
init_color(c_,child-1)
if c_[child-1] == 0:
r += 1
if c_[child-1] == 1:
b += 1
c_[i] = int(b-r>=k)
init_color(c_,i+1)
return c_
c_ = init_color(c[:])
nq = int(input())
for i in range(nq):
q = list(map(int,input().split()))
if q[0] == 1:
print(c_[q[1]-1])
if q[0] == 2:
c[q[1]-1] = q[2]
c_ = init_color(c[:])
if q[0] == 3:
k = q[1]
c_ = init_color(c[:])
``` | instruction | 0 | 20,367 | 13 | 40,734 |
No | output | 1 | 20,367 | 13 | 40,735 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree of n nodes. The tree is rooted at node 1, which is not considered as a leaf regardless of its degree.
Each leaf of the tree has one of the two colors: red or blue. Leaf node v initially has color s_{v}.
The color of each of the internal nodes (including the root) is determined as follows.
* Let b be the number of blue immediate children, and r be the number of red immediate children of a given vertex.
* Then the color of this vertex is blue if and only if b - r ≥ k, otherwise red.
Integer k is a parameter that is same for all the nodes.
You need to handle the following types of queries:
* 1 v: print the color of node v;
* 2 v c: change the color of leaf v to c (c = 0 means red, c = 1 means blue);
* 3 h: update the current value of k to h.
Input
The first line of the input consists of two integers n and k (2 ≤ n ≤ 10^{5}, -n ≤ k ≤ n) — the number of nodes and the initial parameter k.
Each of the next n - 1 lines contains two integers u and v (1 ≤ u,v ≤ n), denoting that there is an edge between vertices u and v.
The next line consists of n space separated integers — the initial array s (-1 ≤ s_i ≤ 1). s_{i} = 0 means that the color of node i is red. s_{i} = 1 means that the color of node i is blue. s_{i} = -1 means that the node i is not a leaf.
The next line contains an integer q (1 ≤ q ≤ 10^5), the number of queries.
q lines follow, each containing a query in one of the following queries:
* 1 v (1 ≤ v ≤ n): print the color of node v;
* 2 v c (1 ≤ v ≤ n, c = 0 or c = 1): change the color of leaf v to c (c = 0 means red, c = 1 means blue). It is guaranteed that v is a leaf;
* 3 h (-n ≤ h ≤ n): update the current value of k to h.
Output
For each query of the first type, print 0 if the color of vertex v is red, and 1 otherwise.
Example
Input
5 2
1 2
1 3
2 4
2 5
-1 -1 0 1 0
9
1 1
1 2
3 -2
1 1
1 2
3 1
2 5 1
1 1
1 2
Output
0
0
1
1
0
1
Note
Figures:
(i) The initial tree
(ii) The tree after the 3rd query
(iii) The tree after the 7th query
<image>
Submitted Solution:
```
nn,k = list(map(int,input().split()))
uv = {}
for i in range(nn-1):
u,v = list(map(int,input().split()))
if u not in uv:
uv[u] = []
uv[u].append(v)
c = list(map(int,input().split()))
def init_color(c_,i=0):
if i >= nn:
return c_
b,r = 0,0
childs = uv.get(i+1,[])
for child in childs:
if c_[child-1] == -1:
init_color(c_,child-1)
if c_[child-1] == 0:
r += 1
if c_[child-1] == 1:
b += 1
c_[i] = int(b-r>=k)
return init_color(c_,i+1)
c_ = init_color(c[:])
nq = int(input())
for i in range(nq):
q = list(map(int,input().split()))
if q[0] == 1:
print(c_[q[1]-1])
if q[0] == 2:
c[q[1]-1] = q[2]
c_ = init_color(c[:])
if q[0] == 3:
k = q[1]
init_color(c[:])
``` | instruction | 0 | 20,368 | 13 | 40,736 |
No | output | 1 | 20,368 | 13 | 40,737 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree of n nodes. The tree is rooted at node 1, which is not considered as a leaf regardless of its degree.
Each leaf of the tree has one of the two colors: red or blue. Leaf node v initially has color s_{v}.
The color of each of the internal nodes (including the root) is determined as follows.
* Let b be the number of blue immediate children, and r be the number of red immediate children of a given vertex.
* Then the color of this vertex is blue if and only if b - r ≥ k, otherwise red.
Integer k is a parameter that is same for all the nodes.
You need to handle the following types of queries:
* 1 v: print the color of node v;
* 2 v c: change the color of leaf v to c (c = 0 means red, c = 1 means blue);
* 3 h: update the current value of k to h.
Input
The first line of the input consists of two integers n and k (2 ≤ n ≤ 10^{5}, -n ≤ k ≤ n) — the number of nodes and the initial parameter k.
Each of the next n - 1 lines contains two integers u and v (1 ≤ u,v ≤ n), denoting that there is an edge between vertices u and v.
The next line consists of n space separated integers — the initial array s (-1 ≤ s_i ≤ 1). s_{i} = 0 means that the color of node i is red. s_{i} = 1 means that the color of node i is blue. s_{i} = -1 means that the node i is not a leaf.
The next line contains an integer q (1 ≤ q ≤ 10^5), the number of queries.
q lines follow, each containing a query in one of the following queries:
* 1 v (1 ≤ v ≤ n): print the color of node v;
* 2 v c (1 ≤ v ≤ n, c = 0 or c = 1): change the color of leaf v to c (c = 0 means red, c = 1 means blue). It is guaranteed that v is a leaf;
* 3 h (-n ≤ h ≤ n): update the current value of k to h.
Output
For each query of the first type, print 0 if the color of vertex v is red, and 1 otherwise.
Example
Input
5 2
1 2
1 3
2 4
2 5
-1 -1 0 1 0
9
1 1
1 2
3 -2
1 1
1 2
3 1
2 5 1
1 1
1 2
Output
0
0
1
1
0
1
Note
Figures:
(i) The initial tree
(ii) The tree after the 3rd query
(iii) The tree after the 7th query
<image>
Submitted Solution:
```
class Node:
def __init__(self):
self.color = -1
self.children = list()
self.child_red = 0
self.child_blue = 0
self.parent = 0
self.is_leaf = False
def get_color(self, k):
if self.color == -1:
for child in self.children:
if child.get_color(k) == 0:
self.child_red += 1
else:
self.child_blue += 1
self.color = 0 if self.child_blue - self.child_red < k else 1
return self.color
n, k = map(int, input().split())
l_node = [Node() for i in range(n + 1)]
l_cn = [set() for i in range(n + 1)]
s_v = set()
for i in range(1, n):
a, b = map(int, input().split())
l_cn[a].add(b)
l_cn[b].add(a)
to_go = [1]
while to_go:
s = to_go.pop()
if s not in s_v:
s_v.add(s)
for x in l_cn[s] - s_v:
l_node[s].children.append(l_node[x])
l_node[x].parent = s
to_go.append(x)
l_init = [int(x) for x in input().split()]
for i in range(n):
if l_init[i] != -1:
l_node[i + 1].color = l_init[i]
l_node[i + 1].is_leaf = True
cmd = int(input())
for i in range(cmd):
arr = [int(x) for x in input().split()]
if arr[0] == 1:
print(l_node[arr[1]].get_color(k))
elif arr[0] == 2:
now_node = l_node[arr[1]]
now_node.color = arr[2]
while now_node.parent != 0:
l_node[now_node.parent].color = -1
now_node = l_node[now_node.parent]
elif arr[0] == 3:
k = arr[1]
for i in range(1, n + 1):
if not l_node[i].is_leaf:
l_node[i].color = -1
``` | instruction | 0 | 20,369 | 13 | 40,738 |
No | output | 1 | 20,369 | 13 | 40,739 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.