description stringlengths 171 4k | code stringlengths 94 3.98k | normalized_code stringlengths 57 4.99k |
|---|---|---|
You have a simple undirected graph consisting of $n$ vertices and $m$ edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Let's make a definition.
Let $v_1$ and $v_2$ be two some nonempty subsets of vertices that do not intersect. Let $f(v_{1}, v_{2})$ be true if and only if all the conditions are satisfied: There are no edges with both endpoints in vertex set $v_1$. There are no edges with both endpoints in vertex set $v_2$. For every two vertices $x$ and $y$ such that $x$ is in $v_1$ and $y$ is in $v_2$, there is an edge between $x$ and $y$.
Create three vertex sets ($v_{1}$, $v_{2}$, $v_{3}$) which satisfy the conditions below; All vertex sets should not be empty. Each vertex should be assigned to only one vertex set. $f(v_{1}, v_{2})$, $f(v_{2}, v_{3})$, $f(v_{3}, v_{1})$ are all true.
Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.
-----Input-----
The first line contains two integers $n$ and $m$ ($3 \le n \le 10^{5}$, $0 \le m \le \text{min}(3 \cdot 10^{5}, \frac{n(n-1)}{2})$)Β β the number of vertices and edges in the graph.
The $i$-th of the next $m$ lines contains two integers $a_{i}$ and $b_{i}$ ($1 \le a_{i} \lt b_{i} \le n$)Β β it means there is an edge between $a_{i}$ and $b_{i}$. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
-----Output-----
If the answer exists, print $n$ integers. $i$-th integer means the vertex set number (from $1$ to $3$) of $i$-th vertex. Otherwise, print $-1$.
If there are multiple answers, print any.
-----Examples-----
Input
6 11
1 2
1 3
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
Output
1 2 2 3 3 3
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
-1
-----Note-----
In the first example, if $v_{1} = \{ 1 \}$, $v_{2} = \{ 2, 3 \}$, and $v_{3} = \{ 4, 5, 6 \}$ then vertex sets will satisfy all conditions. But you can assign vertices to vertex sets in a different way; Other answers like "2 3 3 1 1 1" will be accepted as well. [Image]
In the second example, it's impossible to make such vertex sets. | import sys
readline = sys.stdin.readline
n, m = map(int, input().split())
ans = True
graph = [[] for i in range(n)]
for _ in range(m):
a, b = map(int, readline().split())
a -= 1
b -= 1
graph[a].append(b)
graph[b].append(a)
s1 = set(graph[0])
s2 = set()
if len(graph[0]) != 0:
s2 = set(graph[graph[0][0]])
else:
ans = False
s3 = set(s1.union(s2)) - (s1 & s2)
s21 = s2 & s3
s22 = s1 & s3
s23 = s2 & s1
if len(s21) + len(s22) + len(s23) != n:
ans = False
if len(s21) == 0 or len(s22) == 0 or len(s23) == 0:
ans = False
if ans:
for x in s21:
if set(graph[x]) != s1:
ans = False
break
if ans:
for x in s22:
if set(graph[x]) != s2:
ans = False
break
if ans:
for x in s23:
if set(graph[x]) != s3:
ans = False
break
if not ans:
print(-1)
else:
for i in range(n):
if i in s21:
print(1, end=" ")
elif i in s22:
print(2, end=" ")
else:
print(3, end=" ") | IMPORT ASSIGN VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR NUMBER ASSIGN VAR LIST VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR IF FUNC_CALL VAR VAR NUMBER NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR NUMBER NUMBER ASSIGN VAR NUMBER ASSIGN VAR BIN_OP FUNC_CALL VAR FUNC_CALL VAR VAR BIN_OP VAR VAR ASSIGN VAR BIN_OP VAR VAR ASSIGN VAR BIN_OP VAR VAR ASSIGN VAR BIN_OP VAR VAR IF BIN_OP BIN_OP FUNC_CALL VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR VAR ASSIGN VAR NUMBER IF FUNC_CALL VAR VAR NUMBER FUNC_CALL VAR VAR NUMBER FUNC_CALL VAR VAR NUMBER ASSIGN VAR NUMBER IF VAR FOR VAR VAR IF FUNC_CALL VAR VAR VAR VAR ASSIGN VAR NUMBER IF VAR FOR VAR VAR IF FUNC_CALL VAR VAR VAR VAR ASSIGN VAR NUMBER IF VAR FOR VAR VAR IF FUNC_CALL VAR VAR VAR VAR ASSIGN VAR NUMBER IF VAR EXPR FUNC_CALL VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR EXPR FUNC_CALL VAR NUMBER STRING IF VAR VAR EXPR FUNC_CALL VAR NUMBER STRING EXPR FUNC_CALL VAR NUMBER STRING |
You have a simple undirected graph consisting of $n$ vertices and $m$ edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Let's make a definition.
Let $v_1$ and $v_2$ be two some nonempty subsets of vertices that do not intersect. Let $f(v_{1}, v_{2})$ be true if and only if all the conditions are satisfied: There are no edges with both endpoints in vertex set $v_1$. There are no edges with both endpoints in vertex set $v_2$. For every two vertices $x$ and $y$ such that $x$ is in $v_1$ and $y$ is in $v_2$, there is an edge between $x$ and $y$.
Create three vertex sets ($v_{1}$, $v_{2}$, $v_{3}$) which satisfy the conditions below; All vertex sets should not be empty. Each vertex should be assigned to only one vertex set. $f(v_{1}, v_{2})$, $f(v_{2}, v_{3})$, $f(v_{3}, v_{1})$ are all true.
Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.
-----Input-----
The first line contains two integers $n$ and $m$ ($3 \le n \le 10^{5}$, $0 \le m \le \text{min}(3 \cdot 10^{5}, \frac{n(n-1)}{2})$)Β β the number of vertices and edges in the graph.
The $i$-th of the next $m$ lines contains two integers $a_{i}$ and $b_{i}$ ($1 \le a_{i} \lt b_{i} \le n$)Β β it means there is an edge between $a_{i}$ and $b_{i}$. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
-----Output-----
If the answer exists, print $n$ integers. $i$-th integer means the vertex set number (from $1$ to $3$) of $i$-th vertex. Otherwise, print $-1$.
If there are multiple answers, print any.
-----Examples-----
Input
6 11
1 2
1 3
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
Output
1 2 2 3 3 3
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
-1
-----Note-----
In the first example, if $v_{1} = \{ 1 \}$, $v_{2} = \{ 2, 3 \}$, and $v_{3} = \{ 4, 5, 6 \}$ then vertex sets will satisfy all conditions. But you can assign vertices to vertex sets in a different way; Other answers like "2 3 3 1 1 1" will be accepted as well. [Image]
In the second example, it's impossible to make such vertex sets. | def main():
vertex, edge = map(int, input().split())
data = {key: set() for key in range(1, vertex + 1)}
for i in range(edge):
a, b = map(int, input().split())
data[a].add(b)
data[b].add(a)
v = []
temp = [None, None, None]
for node in data.values():
if temp[0] and temp[1] and temp[2]:
break
elif temp[0] is None:
temp[0] = node
elif temp[1] is None and node != temp[0]:
temp[1] = node
elif temp[2] is None and node != temp[1] and node != temp[0]:
temp[2] = node
dec = False
if temp[0] and temp[1] and temp[2]:
for i in range(1, vertex + 1):
if data[i] == temp[0]:
v.append(1)
elif data[i] == temp[1]:
v.append(2)
elif data[i] == temp[2]:
v.append(3)
else:
dec = True
break
else:
dec = True
if dec:
print(-1)
else:
for team in v:
print(team, end=" ")
main() | FUNC_DEF ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR LIST ASSIGN VAR LIST NONE NONE NONE FOR VAR FUNC_CALL VAR IF VAR NUMBER VAR NUMBER VAR NUMBER IF VAR NUMBER NONE ASSIGN VAR NUMBER VAR IF VAR NUMBER NONE VAR VAR NUMBER ASSIGN VAR NUMBER VAR IF VAR NUMBER NONE VAR VAR NUMBER VAR VAR NUMBER ASSIGN VAR NUMBER VAR ASSIGN VAR NUMBER IF VAR NUMBER VAR NUMBER VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER IF VAR VAR VAR NUMBER EXPR FUNC_CALL VAR NUMBER IF VAR VAR VAR NUMBER EXPR FUNC_CALL VAR NUMBER IF VAR VAR VAR NUMBER EXPR FUNC_CALL VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER IF VAR EXPR FUNC_CALL VAR NUMBER FOR VAR VAR EXPR FUNC_CALL VAR VAR STRING EXPR FUNC_CALL VAR |
You have a simple undirected graph consisting of $n$ vertices and $m$ edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Let's make a definition.
Let $v_1$ and $v_2$ be two some nonempty subsets of vertices that do not intersect. Let $f(v_{1}, v_{2})$ be true if and only if all the conditions are satisfied: There are no edges with both endpoints in vertex set $v_1$. There are no edges with both endpoints in vertex set $v_2$. For every two vertices $x$ and $y$ such that $x$ is in $v_1$ and $y$ is in $v_2$, there is an edge between $x$ and $y$.
Create three vertex sets ($v_{1}$, $v_{2}$, $v_{3}$) which satisfy the conditions below; All vertex sets should not be empty. Each vertex should be assigned to only one vertex set. $f(v_{1}, v_{2})$, $f(v_{2}, v_{3})$, $f(v_{3}, v_{1})$ are all true.
Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.
-----Input-----
The first line contains two integers $n$ and $m$ ($3 \le n \le 10^{5}$, $0 \le m \le \text{min}(3 \cdot 10^{5}, \frac{n(n-1)}{2})$)Β β the number of vertices and edges in the graph.
The $i$-th of the next $m$ lines contains two integers $a_{i}$ and $b_{i}$ ($1 \le a_{i} \lt b_{i} \le n$)Β β it means there is an edge between $a_{i}$ and $b_{i}$. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
-----Output-----
If the answer exists, print $n$ integers. $i$-th integer means the vertex set number (from $1$ to $3$) of $i$-th vertex. Otherwise, print $-1$.
If there are multiple answers, print any.
-----Examples-----
Input
6 11
1 2
1 3
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
Output
1 2 2 3 3 3
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
-1
-----Note-----
In the first example, if $v_{1} = \{ 1 \}$, $v_{2} = \{ 2, 3 \}$, and $v_{3} = \{ 4, 5, 6 \}$ then vertex sets will satisfy all conditions. But you can assign vertices to vertex sets in a different way; Other answers like "2 3 3 1 1 1" will be accepted as well. [Image]
In the second example, it's impossible to make such vertex sets. | n, m = map(int, input().split())
G = [[] for _ in range(n)]
for i in range(m):
a, b = map(int, input().split())
a -= 1
b -= 1
G[a].append(b)
G[b].append(a)
if len(G[0]) < 2:
print(-1)
return
res = [1] * n
for a in G[0]:
res[a] = 2
a2 = G[0][0]
for b in G[a2]:
if res[b] == 2:
res[b] = 3
sizes = [n - len(G[0]), n - len(G[a2]), len(G[0]) + len(G[a2]) - n]
if 0 in sizes:
print(-1)
return
for i in range(n):
g = res[i]
s = sizes[g - 1]
if len(G[i]) != n - s:
print(-1)
return
for j in G[i]:
if res[j] == g:
print(-1)
return
print(*res) | ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR LIST VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR IF FUNC_CALL VAR VAR NUMBER NUMBER EXPR FUNC_CALL VAR NUMBER RETURN ASSIGN VAR BIN_OP LIST NUMBER VAR FOR VAR VAR NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR VAR NUMBER NUMBER FOR VAR VAR VAR IF VAR VAR NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR LIST BIN_OP VAR FUNC_CALL VAR VAR NUMBER BIN_OP VAR FUNC_CALL VAR VAR VAR BIN_OP BIN_OP FUNC_CALL VAR VAR NUMBER FUNC_CALL VAR VAR VAR VAR IF NUMBER VAR EXPR FUNC_CALL VAR NUMBER RETURN FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR BIN_OP VAR NUMBER IF FUNC_CALL VAR VAR VAR BIN_OP VAR VAR EXPR FUNC_CALL VAR NUMBER RETURN FOR VAR VAR VAR IF VAR VAR VAR EXPR FUNC_CALL VAR NUMBER RETURN EXPR FUNC_CALL VAR VAR |
You have a simple undirected graph consisting of $n$ vertices and $m$ edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Let's make a definition.
Let $v_1$ and $v_2$ be two some nonempty subsets of vertices that do not intersect. Let $f(v_{1}, v_{2})$ be true if and only if all the conditions are satisfied: There are no edges with both endpoints in vertex set $v_1$. There are no edges with both endpoints in vertex set $v_2$. For every two vertices $x$ and $y$ such that $x$ is in $v_1$ and $y$ is in $v_2$, there is an edge between $x$ and $y$.
Create three vertex sets ($v_{1}$, $v_{2}$, $v_{3}$) which satisfy the conditions below; All vertex sets should not be empty. Each vertex should be assigned to only one vertex set. $f(v_{1}, v_{2})$, $f(v_{2}, v_{3})$, $f(v_{3}, v_{1})$ are all true.
Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.
-----Input-----
The first line contains two integers $n$ and $m$ ($3 \le n \le 10^{5}$, $0 \le m \le \text{min}(3 \cdot 10^{5}, \frac{n(n-1)}{2})$)Β β the number of vertices and edges in the graph.
The $i$-th of the next $m$ lines contains two integers $a_{i}$ and $b_{i}$ ($1 \le a_{i} \lt b_{i} \le n$)Β β it means there is an edge between $a_{i}$ and $b_{i}$. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
-----Output-----
If the answer exists, print $n$ integers. $i$-th integer means the vertex set number (from $1$ to $3$) of $i$-th vertex. Otherwise, print $-1$.
If there are multiple answers, print any.
-----Examples-----
Input
6 11
1 2
1 3
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
Output
1 2 2 3 3 3
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
-1
-----Note-----
In the first example, if $v_{1} = \{ 1 \}$, $v_{2} = \{ 2, 3 \}$, and $v_{3} = \{ 4, 5, 6 \}$ then vertex sets will satisfy all conditions. But you can assign vertices to vertex sets in a different way; Other answers like "2 3 3 1 1 1" will be accepted as well. [Image]
In the second example, it's impossible to make such vertex sets. | import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline
class UnionFind:
def __init__(self, N):
self.parent = [i for i in range(N)]
self.size = [(1) for _ in range(N)]
def find(self, x):
if self.parent[x] == x:
return x
else:
return self.find(self.parent[x])
def union(self, x, y):
px = self.find(x)
py = self.find(y)
if px == py:
return
if self.size[px] < self.size[py]:
self.parent[px] = py
self.size[py] += self.size[px]
else:
self.parent[py] = px
self.size[px] += self.size[py]
def same(self, x, y):
return self.find(x) == self.find(y)
def connectedNum(self, x):
return self.size[self.find(x)]
def component_NUM(self):
par = set()
for i in self.parent:
par.add(self.find(i))
return len(par)
N, M = list(map(int, input().split()))
adj = [set() for _ in range(N)]
Un = UnionFind(N)
for _ in range(M):
a, b = [(int(x) - 1) for x in input().split()]
adj[a].add(b)
adj[b].add(a)
added = set()
representative = set()
for i in range(N):
if i in added:
continue
added.add(i)
representative.add(i)
for j in range(i + 1, N):
if j in added:
continue
if adj[i] == adj[j]:
added.add(j)
Un.union(i, j)
if len(representative) > 3:
print(-1)
return
if Un.component_NUM() == 3:
group = {}
ans = []
for p in range(N):
par = Un.find(p)
if par not in list(group.keys()):
group[par] = len(group) + 1
ans.append(group[par])
print(" ".join(map(str, ans)))
else:
print(-1) | IMPORT EXPR FUNC_CALL VAR BIN_OP NUMBER NUMBER ASSIGN VAR VAR CLASS_DEF FUNC_DEF ASSIGN VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER VAR FUNC_CALL VAR VAR FUNC_DEF IF VAR VAR VAR RETURN VAR RETURN FUNC_CALL VAR VAR VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR VAR RETURN IF VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR FUNC_DEF RETURN FUNC_CALL VAR VAR FUNC_CALL VAR VAR FUNC_DEF RETURN VAR FUNC_CALL VAR VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR FOR VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR VAR RETURN FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR BIN_OP FUNC_CALL VAR VAR NUMBER VAR FUNC_CALL FUNC_CALL VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR IF VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER VAR IF VAR VAR IF VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR IF FUNC_CALL VAR VAR NUMBER EXPR FUNC_CALL VAR NUMBER RETURN IF FUNC_CALL VAR NUMBER ASSIGN VAR DICT ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR VAR BIN_OP FUNC_CALL VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR FUNC_CALL STRING FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR NUMBER |
You have a simple undirected graph consisting of $n$ vertices and $m$ edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Let's make a definition.
Let $v_1$ and $v_2$ be two some nonempty subsets of vertices that do not intersect. Let $f(v_{1}, v_{2})$ be true if and only if all the conditions are satisfied: There are no edges with both endpoints in vertex set $v_1$. There are no edges with both endpoints in vertex set $v_2$. For every two vertices $x$ and $y$ such that $x$ is in $v_1$ and $y$ is in $v_2$, there is an edge between $x$ and $y$.
Create three vertex sets ($v_{1}$, $v_{2}$, $v_{3}$) which satisfy the conditions below; All vertex sets should not be empty. Each vertex should be assigned to only one vertex set. $f(v_{1}, v_{2})$, $f(v_{2}, v_{3})$, $f(v_{3}, v_{1})$ are all true.
Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.
-----Input-----
The first line contains two integers $n$ and $m$ ($3 \le n \le 10^{5}$, $0 \le m \le \text{min}(3 \cdot 10^{5}, \frac{n(n-1)}{2})$)Β β the number of vertices and edges in the graph.
The $i$-th of the next $m$ lines contains two integers $a_{i}$ and $b_{i}$ ($1 \le a_{i} \lt b_{i} \le n$)Β β it means there is an edge between $a_{i}$ and $b_{i}$. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
-----Output-----
If the answer exists, print $n$ integers. $i$-th integer means the vertex set number (from $1$ to $3$) of $i$-th vertex. Otherwise, print $-1$.
If there are multiple answers, print any.
-----Examples-----
Input
6 11
1 2
1 3
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
Output
1 2 2 3 3 3
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
-1
-----Note-----
In the first example, if $v_{1} = \{ 1 \}$, $v_{2} = \{ 2, 3 \}$, and $v_{3} = \{ 4, 5, 6 \}$ then vertex sets will satisfy all conditions. But you can assign vertices to vertex sets in a different way; Other answers like "2 3 3 1 1 1" will be accepted as well. [Image]
In the second example, it's impossible to make such vertex sets. | n, m = map(int, input().split())
ad = [[] for _ in range(n)]
es = []
for _ in range(m):
v, u = map(int, input().split())
v -= 1
u -= 1
es.append((min(v, u), max(v, u)))
es = sorted(es, key=lambda x: (x[0], x[1]))
for e in es:
v, u = e
ad[v].append(str(u))
ad[u].append(str(v))
ad = ["".join(a) for a in ad]
d = {}
for t in ad:
if t not in d:
d[t] = str(len(d) + 1)
if len(d) > 3:
print(-1)
exit()
if len(d) != 3:
print(-1)
exit()
ans = []
for t in ad:
ans.append(d[t])
print(" ".join(ans)) | ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR LIST VAR FUNC_CALL VAR VAR ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR NUMBER VAR NUMBER FOR VAR VAR ASSIGN VAR VAR VAR EXPR FUNC_CALL VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL STRING VAR VAR VAR ASSIGN VAR DICT FOR VAR VAR IF VAR VAR ASSIGN VAR VAR FUNC_CALL VAR BIN_OP FUNC_CALL VAR VAR NUMBER IF FUNC_CALL VAR VAR NUMBER EXPR FUNC_CALL VAR NUMBER EXPR FUNC_CALL VAR IF FUNC_CALL VAR VAR NUMBER EXPR FUNC_CALL VAR NUMBER EXPR FUNC_CALL VAR ASSIGN VAR LIST FOR VAR VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR FUNC_CALL STRING VAR |
Konrad is a Human Relations consultant working for VoltModder, a large electrical equipment producer. Today, he has been tasked with evaluating the level of happiness in the company.
There are $n$ people working for VoltModder, numbered from $1$ to $n$. Each employee earns a different amount of money in the company β initially, the $i$-th person earns $i$ rubles per day.
On each of $q$ following days, the salaries will be revised. At the end of the $i$-th day, employee $v_i$ will start earning $n+i$ rubles per day and will become the best-paid person in the company. The employee will keep his new salary until it gets revised again.
Some pairs of people don't like each other. This creates a great psychological danger in the company. Formally, if two people $a$ and $b$ dislike each other and $a$ earns more money than $b$, employee $a$ will brag about this to $b$. A dangerous triple is a triple of three employees $a$, $b$ and $c$, such that $a$ brags to $b$, who in turn brags to $c$. If $a$ dislikes $b$, then $b$ dislikes $a$.
At the beginning of each day, Konrad needs to evaluate the number of dangerous triples in the company. Can you help him do it?
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \le n \le 100\,000$, $0 \le m \le 100\,000$) β the number of employees in the company and the number of pairs of people who don't like each other. Each of the following $m$ lines contains two integers $a_i$, $b_i$ ($1 \le a_i, b_i \le n$, $a_i \neq b_i$) denoting that employees $a_i$ and $b_i$ hate each other (that is, $a_i$ dislikes $b_i$ and $b_i$ dislikes $a_i$). Each such relationship will be mentioned exactly once.
The next line contains an integer $q$ ($0 \le q \le 100\,000$) β the number of salary revisions. The $i$-th of the following $q$ lines contains a single integer $v_i$ ($1 \le v_i \le n$) denoting that at the end of the $i$-th day, employee $v_i$ will earn the most.
-----Output-----
Output $q + 1$ integers. The $i$-th of them should contain the number of dangerous triples in the company at the beginning of the $i$-th day.
-----Examples-----
Input
4 5
1 2
2 4
1 3
3 4
2 3
2
2
3
Output
4
3
2
Input
3 3
1 2
2 3
1 3
5
1
2
2
1
3
Output
1
1
1
1
1
1
-----Note-----
Consider the first sample test. The $i$-th row in the following image shows the structure of the company at the beginning of the $i$-th day. A directed edge from $a$ to $b$ denotes that employee $a$ brags to employee $b$. The dangerous triples are marked by highlighted edges. [Image] | import sys
n, m = list(map(int, sys.stdin.readline().strip().split()))
L = [(0) for i in range(0, n)]
H = [[] for i in range(0, n)]
for i in range(0, m):
x, y = list(map(int, sys.stdin.readline().strip().split()))
x = x - 1
y = y - 1
if x > y:
x, y = y, x
L[y] = L[y] + 1
H[x].append(y)
ans = 0
for i in range(0, n):
ans = ans + L[i] * len(H[i])
print(ans)
q = int(sys.stdin.readline().strip())
for i in range(0, q):
v = int(sys.stdin.readline().strip()) - 1
ans = ans - L[v] * len(H[v])
L[v] = L[v] + len(H[v])
while len(H[v]) > 0:
w = H[v].pop()
H[w].append(v)
L[w] = L[w] - 1
ans = ans + L[w] - len(H[w]) + 1
print(ans) | IMPORT ASSIGN VAR VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL FUNC_CALL VAR ASSIGN VAR NUMBER VAR FUNC_CALL VAR NUMBER VAR ASSIGN VAR LIST VAR FUNC_CALL VAR NUMBER VAR FOR VAR FUNC_CALL VAR NUMBER VAR ASSIGN VAR VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL FUNC_CALL VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER IF VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR BIN_OP VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR ASSIGN VAR BIN_OP VAR BIN_OP VAR VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL FUNC_CALL VAR FOR VAR FUNC_CALL VAR NUMBER VAR ASSIGN VAR BIN_OP FUNC_CALL VAR FUNC_CALL FUNC_CALL VAR NUMBER ASSIGN VAR BIN_OP VAR BIN_OP VAR VAR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR BIN_OP VAR VAR FUNC_CALL VAR VAR VAR WHILE FUNC_CALL VAR VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR BIN_OP VAR VAR NUMBER ASSIGN VAR BIN_OP BIN_OP BIN_OP VAR VAR VAR FUNC_CALL VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR |
Konrad is a Human Relations consultant working for VoltModder, a large electrical equipment producer. Today, he has been tasked with evaluating the level of happiness in the company.
There are $n$ people working for VoltModder, numbered from $1$ to $n$. Each employee earns a different amount of money in the company β initially, the $i$-th person earns $i$ rubles per day.
On each of $q$ following days, the salaries will be revised. At the end of the $i$-th day, employee $v_i$ will start earning $n+i$ rubles per day and will become the best-paid person in the company. The employee will keep his new salary until it gets revised again.
Some pairs of people don't like each other. This creates a great psychological danger in the company. Formally, if two people $a$ and $b$ dislike each other and $a$ earns more money than $b$, employee $a$ will brag about this to $b$. A dangerous triple is a triple of three employees $a$, $b$ and $c$, such that $a$ brags to $b$, who in turn brags to $c$. If $a$ dislikes $b$, then $b$ dislikes $a$.
At the beginning of each day, Konrad needs to evaluate the number of dangerous triples in the company. Can you help him do it?
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \le n \le 100\,000$, $0 \le m \le 100\,000$) β the number of employees in the company and the number of pairs of people who don't like each other. Each of the following $m$ lines contains two integers $a_i$, $b_i$ ($1 \le a_i, b_i \le n$, $a_i \neq b_i$) denoting that employees $a_i$ and $b_i$ hate each other (that is, $a_i$ dislikes $b_i$ and $b_i$ dislikes $a_i$). Each such relationship will be mentioned exactly once.
The next line contains an integer $q$ ($0 \le q \le 100\,000$) β the number of salary revisions. The $i$-th of the following $q$ lines contains a single integer $v_i$ ($1 \le v_i \le n$) denoting that at the end of the $i$-th day, employee $v_i$ will earn the most.
-----Output-----
Output $q + 1$ integers. The $i$-th of them should contain the number of dangerous triples in the company at the beginning of the $i$-th day.
-----Examples-----
Input
4 5
1 2
2 4
1 3
3 4
2 3
2
2
3
Output
4
3
2
Input
3 3
1 2
2 3
1 3
5
1
2
2
1
3
Output
1
1
1
1
1
1
-----Note-----
Consider the first sample test. The $i$-th row in the following image shows the structure of the company at the beginning of the $i$-th day. A directed edge from $a$ to $b$ denotes that employee $a$ brags to employee $b$. The dangerous triples are marked by highlighted edges. [Image] | import sys
input = sys.stdin.readline
n, m = list(map(int, input().split()))
IN = [0] * n
OUT = [0] * n
INSET = [[] for i in range(n)]
for i in range(m):
x, y = sorted(map(int, input().split()))
IN[x - 1] += 1
OUT[y - 1] += 1
INSET[x - 1].append(y - 1)
ANS = 0
for i in range(n):
ANS += IN[i] * OUT[i]
print(ANS)
Q = int(input())
for i in range(Q):
q = int(input()) - 1
ANS -= IN[q] * OUT[q]
OUT[q] += IN[q]
IN[q] = 0
for x in INSET[q]:
INSET[x].append(q)
ANS += (IN[x] + 1) * (OUT[x] - 1) - IN[x] * OUT[x]
IN[x] += 1
OUT[x] -= 1
INSET[q] = []
print(ANS) | IMPORT ASSIGN VAR VAR ASSIGN VAR VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR BIN_OP LIST NUMBER VAR ASSIGN VAR BIN_OP LIST NUMBER VAR ASSIGN VAR LIST VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR VAR BIN_OP VAR NUMBER NUMBER VAR BIN_OP VAR NUMBER NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR VAR BIN_OP VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP FUNC_CALL VAR FUNC_CALL VAR NUMBER VAR BIN_OP VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR NUMBER FOR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR BIN_OP BIN_OP BIN_OP VAR VAR NUMBER BIN_OP VAR VAR NUMBER BIN_OP VAR VAR VAR VAR VAR VAR NUMBER VAR VAR NUMBER ASSIGN VAR VAR LIST EXPR FUNC_CALL VAR VAR |
Konrad is a Human Relations consultant working for VoltModder, a large electrical equipment producer. Today, he has been tasked with evaluating the level of happiness in the company.
There are $n$ people working for VoltModder, numbered from $1$ to $n$. Each employee earns a different amount of money in the company β initially, the $i$-th person earns $i$ rubles per day.
On each of $q$ following days, the salaries will be revised. At the end of the $i$-th day, employee $v_i$ will start earning $n+i$ rubles per day and will become the best-paid person in the company. The employee will keep his new salary until it gets revised again.
Some pairs of people don't like each other. This creates a great psychological danger in the company. Formally, if two people $a$ and $b$ dislike each other and $a$ earns more money than $b$, employee $a$ will brag about this to $b$. A dangerous triple is a triple of three employees $a$, $b$ and $c$, such that $a$ brags to $b$, who in turn brags to $c$. If $a$ dislikes $b$, then $b$ dislikes $a$.
At the beginning of each day, Konrad needs to evaluate the number of dangerous triples in the company. Can you help him do it?
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \le n \le 100\,000$, $0 \le m \le 100\,000$) β the number of employees in the company and the number of pairs of people who don't like each other. Each of the following $m$ lines contains two integers $a_i$, $b_i$ ($1 \le a_i, b_i \le n$, $a_i \neq b_i$) denoting that employees $a_i$ and $b_i$ hate each other (that is, $a_i$ dislikes $b_i$ and $b_i$ dislikes $a_i$). Each such relationship will be mentioned exactly once.
The next line contains an integer $q$ ($0 \le q \le 100\,000$) β the number of salary revisions. The $i$-th of the following $q$ lines contains a single integer $v_i$ ($1 \le v_i \le n$) denoting that at the end of the $i$-th day, employee $v_i$ will earn the most.
-----Output-----
Output $q + 1$ integers. The $i$-th of them should contain the number of dangerous triples in the company at the beginning of the $i$-th day.
-----Examples-----
Input
4 5
1 2
2 4
1 3
3 4
2 3
2
2
3
Output
4
3
2
Input
3 3
1 2
2 3
1 3
5
1
2
2
1
3
Output
1
1
1
1
1
1
-----Note-----
Consider the first sample test. The $i$-th row in the following image shows the structure of the company at the beginning of the $i$-th day. A directed edge from $a$ to $b$ denotes that employee $a$ brags to employee $b$. The dangerous triples are marked by highlighted edges. [Image] | n, m = map(int, input().split())
out, inp = [0] * (n + 1), [0] * (n + 1)
inset = [[] for i in range(n + 1)]
for i in range(m):
x, y = map(int, input().split())
if x > y:
z = x
x = y
y = z
out[y] += 1
inp[x] += 1
inset[x].append(y)
q = int(input())
res = 0
for ind in range(1, n + 1):
res += inp[ind] * out[ind]
print(res)
for i in range(q):
best = int(input())
res -= out[best] * inp[best]
for pred_ind in inset[best]:
res += -out[pred_ind] * inp[pred_ind] + (out[pred_ind] - 1) * (
inp[pred_ind] + 1
)
out[pred_ind] -= 1
inp[pred_ind] += 1
inset[pred_ind].append(best)
out[best] += inp[best]
inp[best] = 0
inset[best] = []
print(res) | ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR VAR BIN_OP LIST NUMBER BIN_OP VAR NUMBER BIN_OP LIST NUMBER BIN_OP VAR NUMBER ASSIGN VAR LIST VAR FUNC_CALL VAR BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR IF VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR VAR VAR NUMBER VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER VAR BIN_OP VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR BIN_OP VAR VAR VAR VAR FOR VAR VAR VAR VAR BIN_OP BIN_OP VAR VAR VAR VAR BIN_OP BIN_OP VAR VAR NUMBER BIN_OP VAR VAR NUMBER VAR VAR NUMBER VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR NUMBER ASSIGN VAR VAR LIST EXPR FUNC_CALL VAR VAR |
The Tower of Hanoi is a famous game consisting of $3$ rods and a number of discs of incrementally different diameters. The puzzle starts with the discs neatly stacked on one rod, ordered by ascending size with the smallest disc at the top. The game's objective is to move the entire stack to another rod, obeying the following rules:
Only one disk can be moved at a time.
In one move, remove the topmost disk from one rod and move it to another rod.
No disk may be placed on top of a smaller disk.
Gena has a modified version of the Tower of Hanoi. This game of Hanoi has $4$ rods and $n$ disks ordered by ascending size. Gena has already made a few moves following the rules above. Given the state of Gena's Hanoi, determine the minimum number of moves needed to restore the tower to its original state with all disks on rod $1$.
Note: Gena's rods are numbered from $1$ to $4$. The radius of a disk is its index in the input array, so disk $1$ is the smallest disk with a radius of $1$, and disk $n$ is the largest with a radius of $n$.
Example
$posts=[4,3,2,1]$
In this case, the disks are arranged from large to small across the four rods. The largest disk, disk $4$, is already on rod $1$, so move disks $3,2$ and $1$ to rod $1$, in that order. It takes $3$ moves to reset the game.
$posts=[4,2,2,1]$
The largest disk, disk $4$ with radius $4$, is already on rod $1$. Disk $3$ is on rod $2$ and must be below disk $2$. Move disk $2$ to rod $3$, disk $3$ to rod $1$ and disk $2$ to rod $1$. Now move disk $1$ to rod $1$. It takes $3$ moves to reset the game.
Function Description
Complete the hanoi function below.
hanoi has the following parameters:
int posts[n]: $posts[i]$ is the location of the disk with radius $\boldsymbol{i}$
Returns
int: the minimum moves to reset the game to its initial state
Input Format
The first line contains a single integer, $n$, the number of disks.
The second line contains $n$ space-separated integers, where the $i^{\mbox{th}}$ integer is the index of the rod where the disk with diameter $\boldsymbol{i}$ is located.
Constraints
$1\leq n\leq10$
Sample Input
STDIN Function
----- --------
3 size of posts[] n = 3
1 4 1 posts = [1, 4, 1]
Sample Output
3
Explanation
$3$ moves are enough to build the tower. Here is one possible solution: | listed = set()
def goal(x):
return all([(len(x[i]) == 0) for i in range(1, len(x))])
def moves(x):
for i in range(len(x)):
if x[i]:
for j in range(len(x)):
if len(x[j]) == 0 or x[i][-1] < x[j][-1]:
yield i, j
def bfs(x):
def tt(d):
return tuple(tuple(t) for t in d)
def move(node, m):
y = [list(t) for t in node]
y[m[1]].append(y[m[0]].pop())
y[1:4] = sorted(y[1:4], key=lambda t: t[-1] if t else 0)
return tt(y)
start = tt(x), 0
q = [start]
while q:
u, depth = q.pop(0)
if goal(u):
return depth
for x in moves(u):
cal = move(u, x)
if cal not in listed:
q.append((cal, depth + 1))
listed.add(cal)
n = int(input())
a = [int(x) for x in input().split()]
g = [[] for x in range(4)]
for x in range(0, n):
g[a[x] - 1] = [x + 1] + g[a[x] - 1]
print(bfs(g)) | ASSIGN VAR FUNC_CALL VAR FUNC_DEF RETURN FUNC_CALL VAR FUNC_CALL VAR VAR VAR NUMBER VAR FUNC_CALL VAR NUMBER FUNC_CALL VAR VAR FUNC_DEF FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR IF VAR VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR IF FUNC_CALL VAR VAR VAR NUMBER VAR VAR NUMBER VAR VAR NUMBER EXPR VAR VAR FUNC_DEF FUNC_DEF RETURN FUNC_CALL VAR FUNC_CALL VAR VAR VAR VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR NUMBER FUNC_CALL VAR VAR NUMBER ASSIGN VAR NUMBER NUMBER FUNC_CALL VAR VAR NUMBER NUMBER VAR VAR NUMBER NUMBER RETURN FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR NUMBER ASSIGN VAR LIST VAR WHILE VAR ASSIGN VAR VAR FUNC_CALL VAR NUMBER IF FUNC_CALL VAR VAR RETURN VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR IF VAR VAR EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR LIST VAR FUNC_CALL VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR ASSIGN VAR BIN_OP VAR VAR NUMBER BIN_OP LIST BIN_OP VAR NUMBER VAR BIN_OP VAR VAR NUMBER EXPR FUNC_CALL VAR FUNC_CALL VAR VAR |
The Tower of Hanoi is a famous game consisting of $3$ rods and a number of discs of incrementally different diameters. The puzzle starts with the discs neatly stacked on one rod, ordered by ascending size with the smallest disc at the top. The game's objective is to move the entire stack to another rod, obeying the following rules:
Only one disk can be moved at a time.
In one move, remove the topmost disk from one rod and move it to another rod.
No disk may be placed on top of a smaller disk.
Gena has a modified version of the Tower of Hanoi. This game of Hanoi has $4$ rods and $n$ disks ordered by ascending size. Gena has already made a few moves following the rules above. Given the state of Gena's Hanoi, determine the minimum number of moves needed to restore the tower to its original state with all disks on rod $1$.
Note: Gena's rods are numbered from $1$ to $4$. The radius of a disk is its index in the input array, so disk $1$ is the smallest disk with a radius of $1$, and disk $n$ is the largest with a radius of $n$.
Example
$posts=[4,3,2,1]$
In this case, the disks are arranged from large to small across the four rods. The largest disk, disk $4$, is already on rod $1$, so move disks $3,2$ and $1$ to rod $1$, in that order. It takes $3$ moves to reset the game.
$posts=[4,2,2,1]$
The largest disk, disk $4$ with radius $4$, is already on rod $1$. Disk $3$ is on rod $2$ and must be below disk $2$. Move disk $2$ to rod $3$, disk $3$ to rod $1$ and disk $2$ to rod $1$. Now move disk $1$ to rod $1$. It takes $3$ moves to reset the game.
Function Description
Complete the hanoi function below.
hanoi has the following parameters:
int posts[n]: $posts[i]$ is the location of the disk with radius $\boldsymbol{i}$
Returns
int: the minimum moves to reset the game to its initial state
Input Format
The first line contains a single integer, $n$, the number of disks.
The second line contains $n$ space-separated integers, where the $i^{\mbox{th}}$ integer is the index of the rod where the disk with diameter $\boldsymbol{i}$ is located.
Constraints
$1\leq n\leq10$
Sample Input
STDIN Function
----- --------
3 size of posts[] n = 3
1 4 1 posts = [1, 4, 1]
Sample Output
3
Explanation
$3$ moves are enough to build the tower. Here is one possible solution: | import sys
def generate(move, N):
next = []
i = 0
available = [1, 2, 3, 4]
while i < N:
if len(available) == 0:
break
elif move[i] in available:
available.remove(move[i])
else:
i = i + 1
continue
for m in available:
amove = list(move)
amove[i] = m
next.append(tuple(amove))
i = i + 1
return set(next)
N = int(input().strip())
a = [int(a_temp) for a_temp in input().strip().split(" ")]
initial = []
i = 0
while i < N:
initial.append(1)
i = i + 1
moves = set()
moves.add(tuple(initial))
current = set(moves)
gen = 0
while True:
next = set()
for move in current:
next.update(generate(move, N))
gen = gen + 1
next.difference_update(moves)
moves.update(next)
if tuple(a) in next:
print(gen)
break
current = set(next) | IMPORT FUNC_DEF ASSIGN VAR LIST ASSIGN VAR NUMBER ASSIGN VAR LIST NUMBER NUMBER NUMBER NUMBER WHILE VAR VAR IF FUNC_CALL VAR VAR NUMBER IF VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER FOR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR NUMBER RETURN FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL FUNC_CALL VAR STRING ASSIGN VAR LIST ASSIGN VAR NUMBER WHILE VAR VAR EXPR FUNC_CALL VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR FUNC_CALL VAR EXPR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER WHILE NUMBER ASSIGN VAR FUNC_CALL VAR FOR VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR IF FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR |
The Tower of Hanoi is a famous game consisting of $3$ rods and a number of discs of incrementally different diameters. The puzzle starts with the discs neatly stacked on one rod, ordered by ascending size with the smallest disc at the top. The game's objective is to move the entire stack to another rod, obeying the following rules:
Only one disk can be moved at a time.
In one move, remove the topmost disk from one rod and move it to another rod.
No disk may be placed on top of a smaller disk.
Gena has a modified version of the Tower of Hanoi. This game of Hanoi has $4$ rods and $n$ disks ordered by ascending size. Gena has already made a few moves following the rules above. Given the state of Gena's Hanoi, determine the minimum number of moves needed to restore the tower to its original state with all disks on rod $1$.
Note: Gena's rods are numbered from $1$ to $4$. The radius of a disk is its index in the input array, so disk $1$ is the smallest disk with a radius of $1$, and disk $n$ is the largest with a radius of $n$.
Example
$posts=[4,3,2,1]$
In this case, the disks are arranged from large to small across the four rods. The largest disk, disk $4$, is already on rod $1$, so move disks $3,2$ and $1$ to rod $1$, in that order. It takes $3$ moves to reset the game.
$posts=[4,2,2,1]$
The largest disk, disk $4$ with radius $4$, is already on rod $1$. Disk $3$ is on rod $2$ and must be below disk $2$. Move disk $2$ to rod $3$, disk $3$ to rod $1$ and disk $2$ to rod $1$. Now move disk $1$ to rod $1$. It takes $3$ moves to reset the game.
Function Description
Complete the hanoi function below.
hanoi has the following parameters:
int posts[n]: $posts[i]$ is the location of the disk with radius $\boldsymbol{i}$
Returns
int: the minimum moves to reset the game to its initial state
Input Format
The first line contains a single integer, $n$, the number of disks.
The second line contains $n$ space-separated integers, where the $i^{\mbox{th}}$ integer is the index of the rod where the disk with diameter $\boldsymbol{i}$ is located.
Constraints
$1\leq n\leq10$
Sample Input
STDIN Function
----- --------
3 size of posts[] n = 3
1 4 1 posts = [1, 4, 1]
Sample Output
3
Explanation
$3$ moves are enough to build the tower. Here is one possible solution: | N = int(input().strip())
a = [int(a_temp) for a_temp in input().strip().split(" ")]
goal_state = tuple(reversed(range(N))), tuple(), tuple(), tuple()
initial_state = [[], [], [], []]
for i, rod in enumerate(a):
initial_state[rod - 1].insert(0, i)
initial_state = tuple(tuple(rod) for rod in initial_state)
initial_state = initial_state[:1] + tuple(sorted(initial_state[1:]))
def try_brute_force():
moves = {}
moves[initial_state] = 0
state_queue = [initial_state]
while len(state_queue) > 0:
state = state_queue.pop(0)
for src in range(4):
if len(state[src]) > 0:
src_size = state[src][-1]
for dst in range(4):
if src != dst and (
len(state[dst]) == 0 or state[dst][-1] > src_size
):
new_state = list(state)
new_state[src] = state[src][:-1]
new_state[dst] = state[dst] + (src_size,)
new_state = tuple(new_state[:1]) + tuple(sorted(new_state[1:]))
if new_state not in moves:
moves[new_state] = moves[state] + 1
state_queue.append(new_state)
if new_state == goal_state:
return moves[new_state]
print(try_brute_force()) | ASSIGN VAR FUNC_CALL VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL FUNC_CALL VAR STRING ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR LIST LIST LIST LIST LIST FOR VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR NUMBER NUMBER VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER FUNC_CALL VAR FUNC_CALL VAR VAR NUMBER FUNC_DEF ASSIGN VAR DICT ASSIGN VAR VAR NUMBER ASSIGN VAR LIST VAR WHILE FUNC_CALL VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER IF FUNC_CALL VAR VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER IF VAR VAR FUNC_CALL VAR VAR VAR NUMBER VAR VAR NUMBER VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR NUMBER ASSIGN VAR VAR BIN_OP VAR VAR VAR ASSIGN VAR BIN_OP FUNC_CALL VAR VAR NUMBER FUNC_CALL VAR FUNC_CALL VAR VAR NUMBER IF VAR VAR ASSIGN VAR VAR BIN_OP VAR VAR NUMBER EXPR FUNC_CALL VAR VAR IF VAR VAR RETURN VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR |
The Tower of Hanoi is a famous game consisting of $3$ rods and a number of discs of incrementally different diameters. The puzzle starts with the discs neatly stacked on one rod, ordered by ascending size with the smallest disc at the top. The game's objective is to move the entire stack to another rod, obeying the following rules:
Only one disk can be moved at a time.
In one move, remove the topmost disk from one rod and move it to another rod.
No disk may be placed on top of a smaller disk.
Gena has a modified version of the Tower of Hanoi. This game of Hanoi has $4$ rods and $n$ disks ordered by ascending size. Gena has already made a few moves following the rules above. Given the state of Gena's Hanoi, determine the minimum number of moves needed to restore the tower to its original state with all disks on rod $1$.
Note: Gena's rods are numbered from $1$ to $4$. The radius of a disk is its index in the input array, so disk $1$ is the smallest disk with a radius of $1$, and disk $n$ is the largest with a radius of $n$.
Example
$posts=[4,3,2,1]$
In this case, the disks are arranged from large to small across the four rods. The largest disk, disk $4$, is already on rod $1$, so move disks $3,2$ and $1$ to rod $1$, in that order. It takes $3$ moves to reset the game.
$posts=[4,2,2,1]$
The largest disk, disk $4$ with radius $4$, is already on rod $1$. Disk $3$ is on rod $2$ and must be below disk $2$. Move disk $2$ to rod $3$, disk $3$ to rod $1$ and disk $2$ to rod $1$. Now move disk $1$ to rod $1$. It takes $3$ moves to reset the game.
Function Description
Complete the hanoi function below.
hanoi has the following parameters:
int posts[n]: $posts[i]$ is the location of the disk with radius $\boldsymbol{i}$
Returns
int: the minimum moves to reset the game to its initial state
Input Format
The first line contains a single integer, $n$, the number of disks.
The second line contains $n$ space-separated integers, where the $i^{\mbox{th}}$ integer is the index of the rod where the disk with diameter $\boldsymbol{i}$ is located.
Constraints
$1\leq n\leq10$
Sample Input
STDIN Function
----- --------
3 size of posts[] n = 3
1 4 1 posts = [1, 4, 1]
Sample Output
3
Explanation
$3$ moves are enough to build the tower. Here is one possible solution: | def allowed_moves(x):
for i in range(len(x)):
if x[i]:
for j in range(len(x)):
if not x[j] or x[i][-1] < x[j][-1]:
yield i, j
def reached_goal(x):
return all([(len(x[i]) == 0) for i in range(1, len(x))])
def tupler(z):
z[1:4] = sorted(z[1:4], key=lambda t: t[-1] if t else 0)
return tuple(tuple(t) for t in z)
def mover(g, m):
y = [list(t) for t in g]
y[m[1]].append(y[m[0]].pop())
return tupler(y)
def bfs(x):
visited = set()
start = [tupler(x), 0]
q = list([start])
visited.add(start[0])
while q:
node, depth = q.pop(0)
if reached_goal(node):
return depth
for move in allowed_moves(node):
child = mover(node, move)
if child not in visited:
visited.add(child)
q.extend([[child, depth + 1]])
N = int(input())
R = [int(t) for t in input().split()]
A = [[] for i in range(4)]
for i in range(N):
A[R[i] - 1] = [i + 1] + A[R[i] - 1]
print(bfs(A)) | FUNC_DEF FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR IF VAR VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR NUMBER VAR VAR NUMBER EXPR VAR VAR FUNC_DEF RETURN FUNC_CALL VAR FUNC_CALL VAR VAR VAR NUMBER VAR FUNC_CALL VAR NUMBER FUNC_CALL VAR VAR FUNC_DEF ASSIGN VAR NUMBER NUMBER FUNC_CALL VAR VAR NUMBER NUMBER VAR VAR NUMBER NUMBER RETURN FUNC_CALL VAR FUNC_CALL VAR VAR VAR VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR NUMBER FUNC_CALL VAR VAR NUMBER RETURN FUNC_CALL VAR VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR ASSIGN VAR LIST FUNC_CALL VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR LIST VAR EXPR FUNC_CALL VAR VAR NUMBER WHILE VAR ASSIGN VAR VAR FUNC_CALL VAR NUMBER IF FUNC_CALL VAR VAR RETURN VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR IF VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR LIST LIST VAR BIN_OP VAR NUMBER ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR LIST VAR FUNC_CALL VAR NUMBER FOR VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR VAR NUMBER BIN_OP LIST BIN_OP VAR NUMBER VAR BIN_OP VAR VAR NUMBER EXPR FUNC_CALL VAR FUNC_CALL VAR VAR |
The Tower of Hanoi is a famous game consisting of $3$ rods and a number of discs of incrementally different diameters. The puzzle starts with the discs neatly stacked on one rod, ordered by ascending size with the smallest disc at the top. The game's objective is to move the entire stack to another rod, obeying the following rules:
Only one disk can be moved at a time.
In one move, remove the topmost disk from one rod and move it to another rod.
No disk may be placed on top of a smaller disk.
Gena has a modified version of the Tower of Hanoi. This game of Hanoi has $4$ rods and $n$ disks ordered by ascending size. Gena has already made a few moves following the rules above. Given the state of Gena's Hanoi, determine the minimum number of moves needed to restore the tower to its original state with all disks on rod $1$.
Note: Gena's rods are numbered from $1$ to $4$. The radius of a disk is its index in the input array, so disk $1$ is the smallest disk with a radius of $1$, and disk $n$ is the largest with a radius of $n$.
Example
$posts=[4,3,2,1]$
In this case, the disks are arranged from large to small across the four rods. The largest disk, disk $4$, is already on rod $1$, so move disks $3,2$ and $1$ to rod $1$, in that order. It takes $3$ moves to reset the game.
$posts=[4,2,2,1]$
The largest disk, disk $4$ with radius $4$, is already on rod $1$. Disk $3$ is on rod $2$ and must be below disk $2$. Move disk $2$ to rod $3$, disk $3$ to rod $1$ and disk $2$ to rod $1$. Now move disk $1$ to rod $1$. It takes $3$ moves to reset the game.
Function Description
Complete the hanoi function below.
hanoi has the following parameters:
int posts[n]: $posts[i]$ is the location of the disk with radius $\boldsymbol{i}$
Returns
int: the minimum moves to reset the game to its initial state
Input Format
The first line contains a single integer, $n$, the number of disks.
The second line contains $n$ space-separated integers, where the $i^{\mbox{th}}$ integer is the index of the rod where the disk with diameter $\boldsymbol{i}$ is located.
Constraints
$1\leq n\leq10$
Sample Input
STDIN Function
----- --------
3 size of posts[] n = 3
1 4 1 posts = [1, 4, 1]
Sample Output
3
Explanation
$3$ moves are enough to build the tower. Here is one possible solution: | import sys
N = int(input().strip())
a = [int(a_temp) for a_temp in input().strip().split(" ")]
def move1(a, c):
p, q = c
if not p in a:
return False
i = a.index(p)
if q in a[:i]:
return False
return a[:i] + tuple([q]) + a[i + 1 :]
def func(N, a):
changes = [
(1, 2),
(1, 3),
(1, 4),
(2, 1),
(2, 3),
(2, 4),
(3, 1),
(3, 2),
(3, 4),
(4, 1),
(4, 2),
(4, 3),
]
pool = set()
pool.add(tuple(a))
states = set()
states.add(tuple(a))
state2 = set()
counter = 0
while True:
counter = counter + 1
for s in states:
for c in changes:
t = move1(s, c)
if t:
if not t in pool:
if all(map(lambda x: x == 1, t)):
print(counter)
return
else:
state2.add(t)
states = set(state2)
pool.update(state2)
state2 = set()
func(N, a) | IMPORT ASSIGN VAR FUNC_CALL VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL FUNC_CALL VAR STRING FUNC_DEF ASSIGN VAR VAR VAR IF VAR VAR RETURN NUMBER ASSIGN VAR FUNC_CALL VAR VAR IF VAR VAR VAR RETURN NUMBER RETURN BIN_OP BIN_OP VAR VAR FUNC_CALL VAR LIST VAR VAR BIN_OP VAR NUMBER FUNC_DEF ASSIGN VAR LIST NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER ASSIGN VAR FUNC_CALL VAR EXPR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR EXPR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR ASSIGN VAR NUMBER WHILE NUMBER ASSIGN VAR BIN_OP VAR NUMBER FOR VAR VAR FOR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR IF VAR IF VAR VAR IF FUNC_CALL VAR FUNC_CALL VAR VAR NUMBER VAR EXPR FUNC_CALL VAR VAR RETURN EXPR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR EXPR FUNC_CALL VAR VAR VAR |
The Tower of Hanoi is a famous game consisting of $3$ rods and a number of discs of incrementally different diameters. The puzzle starts with the discs neatly stacked on one rod, ordered by ascending size with the smallest disc at the top. The game's objective is to move the entire stack to another rod, obeying the following rules:
Only one disk can be moved at a time.
In one move, remove the topmost disk from one rod and move it to another rod.
No disk may be placed on top of a smaller disk.
Gena has a modified version of the Tower of Hanoi. This game of Hanoi has $4$ rods and $n$ disks ordered by ascending size. Gena has already made a few moves following the rules above. Given the state of Gena's Hanoi, determine the minimum number of moves needed to restore the tower to its original state with all disks on rod $1$.
Note: Gena's rods are numbered from $1$ to $4$. The radius of a disk is its index in the input array, so disk $1$ is the smallest disk with a radius of $1$, and disk $n$ is the largest with a radius of $n$.
Example
$posts=[4,3,2,1]$
In this case, the disks are arranged from large to small across the four rods. The largest disk, disk $4$, is already on rod $1$, so move disks $3,2$ and $1$ to rod $1$, in that order. It takes $3$ moves to reset the game.
$posts=[4,2,2,1]$
The largest disk, disk $4$ with radius $4$, is already on rod $1$. Disk $3$ is on rod $2$ and must be below disk $2$. Move disk $2$ to rod $3$, disk $3$ to rod $1$ and disk $2$ to rod $1$. Now move disk $1$ to rod $1$. It takes $3$ moves to reset the game.
Function Description
Complete the hanoi function below.
hanoi has the following parameters:
int posts[n]: $posts[i]$ is the location of the disk with radius $\boldsymbol{i}$
Returns
int: the minimum moves to reset the game to its initial state
Input Format
The first line contains a single integer, $n$, the number of disks.
The second line contains $n$ space-separated integers, where the $i^{\mbox{th}}$ integer is the index of the rod where the disk with diameter $\boldsymbol{i}$ is located.
Constraints
$1\leq n\leq10$
Sample Input
STDIN Function
----- --------
3 size of posts[] n = 3
1 4 1 posts = [1, 4, 1]
Sample Output
3
Explanation
$3$ moves are enough to build the tower. Here is one possible solution: | import sys
def getRod(position, disc):
return position >> disc * 2 & 3
def setRod(position, disc, rod):
position = position & ~(3 << disc * 2) | rod << disc * 2
return position
def getPosition(rods):
position = 0
for i in range(len(rods)):
position = setRod(position, i, rods[i])
return position
def getRods(position):
return [getRod(position, disc) for disc in range(N)]
N = int(input().strip())
a = [(int(a_temp) - 1) for a_temp in input().strip().split(" ")]
searchQueue = [getPosition(a)]
distances = {getPosition(a)}
currentDistance = 0
targetPosition = 0
while targetPosition not in distances and len(searchQueue):
oldSearchQueue = searchQueue
searchQueue = []
currentDistance += 1
for position in oldSearchQueue:
topDisc = [100, 100, 100, 100]
for i in range(N - 1, -1, -1):
rod = position >> i * 2 & 3
topDisc[rod] = i
for rod1 in range(4):
for rod2 in range(4):
if rod1 != rod2 and topDisc[rod1] < topDisc[rod2]:
disc = topDisc[rod1]
newPosition = position & ~(3 << disc * 2) | rod2 << disc * 2
if newPosition not in distances:
searchQueue.append(newPosition)
distances.add(newPosition)
print(currentDistance) | IMPORT FUNC_DEF RETURN BIN_OP BIN_OP VAR BIN_OP VAR NUMBER NUMBER FUNC_DEF ASSIGN VAR BIN_OP BIN_OP VAR BIN_OP NUMBER BIN_OP VAR NUMBER BIN_OP VAR BIN_OP VAR NUMBER RETURN VAR FUNC_DEF ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR VAR RETURN VAR FUNC_DEF RETURN FUNC_CALL VAR VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR BIN_OP FUNC_CALL VAR VAR NUMBER VAR FUNC_CALL FUNC_CALL FUNC_CALL VAR STRING ASSIGN VAR LIST FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER ASSIGN VAR NUMBER WHILE VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR ASSIGN VAR LIST VAR NUMBER FOR VAR VAR ASSIGN VAR LIST NUMBER NUMBER NUMBER NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER NUMBER NUMBER ASSIGN VAR BIN_OP BIN_OP VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR VAR VAR FOR VAR FUNC_CALL VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER IF VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR BIN_OP NUMBER BIN_OP VAR NUMBER BIN_OP VAR BIN_OP VAR NUMBER IF VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR |
The Tower of Hanoi is a famous game consisting of $3$ rods and a number of discs of incrementally different diameters. The puzzle starts with the discs neatly stacked on one rod, ordered by ascending size with the smallest disc at the top. The game's objective is to move the entire stack to another rod, obeying the following rules:
Only one disk can be moved at a time.
In one move, remove the topmost disk from one rod and move it to another rod.
No disk may be placed on top of a smaller disk.
Gena has a modified version of the Tower of Hanoi. This game of Hanoi has $4$ rods and $n$ disks ordered by ascending size. Gena has already made a few moves following the rules above. Given the state of Gena's Hanoi, determine the minimum number of moves needed to restore the tower to its original state with all disks on rod $1$.
Note: Gena's rods are numbered from $1$ to $4$. The radius of a disk is its index in the input array, so disk $1$ is the smallest disk with a radius of $1$, and disk $n$ is the largest with a radius of $n$.
Example
$posts=[4,3,2,1]$
In this case, the disks are arranged from large to small across the four rods. The largest disk, disk $4$, is already on rod $1$, so move disks $3,2$ and $1$ to rod $1$, in that order. It takes $3$ moves to reset the game.
$posts=[4,2,2,1]$
The largest disk, disk $4$ with radius $4$, is already on rod $1$. Disk $3$ is on rod $2$ and must be below disk $2$. Move disk $2$ to rod $3$, disk $3$ to rod $1$ and disk $2$ to rod $1$. Now move disk $1$ to rod $1$. It takes $3$ moves to reset the game.
Function Description
Complete the hanoi function below.
hanoi has the following parameters:
int posts[n]: $posts[i]$ is the location of the disk with radius $\boldsymbol{i}$
Returns
int: the minimum moves to reset the game to its initial state
Input Format
The first line contains a single integer, $n$, the number of disks.
The second line contains $n$ space-separated integers, where the $i^{\mbox{th}}$ integer is the index of the rod where the disk with diameter $\boldsymbol{i}$ is located.
Constraints
$1\leq n\leq10$
Sample Input
STDIN Function
----- --------
3 size of posts[] n = 3
1 4 1 posts = [1, 4, 1]
Sample Output
3
Explanation
$3$ moves are enough to build the tower. Here is one possible solution: | import sys
n = int(input().strip())
A = [int(a_temp) for a_temp in input().strip().split(" ")]
def fewestmovesHanoi(n, A):
if A == [1] * n:
return 0
forward = set(["1" * n])
countf = 0
reverse = set(["".join(str(a) for a in A)])
countr = 0
while True:
if countf == countr:
countf += 1
newforward = set()
for f in forward:
ind = list()
for rod in "1234":
if rod in f:
ind.append((f.index(rod), rod))
else:
ind.append((n, rod))
ind = sorted(ind)
while len(ind) > 1:
i, rod = ind[0]
if i != n:
for j in range(1, len(ind)):
newf = f[:i] + ind[j][1] + f[i + 1 :]
if newf in reverse:
return countf + countr
else:
newforward.add(newf)
ind.remove((i, rod))
forward = newforward
else:
countr += 1
newreverse = set()
for r in reverse:
ind = list()
for rod in "1234":
if rod in r:
ind.append((r.index(rod), rod))
else:
ind.append((n, rod))
ind = sorted(ind)
while len(ind) > 1:
i, rod = ind[0]
if i != n:
for j in range(1, len(ind)):
newr = r[:i] + ind[j][1] + r[i + 1 :]
if newr in forward:
return countf + countr
else:
newreverse.add(newr)
ind.remove((i, rod))
reverse = newreverse
print(fewestmovesHanoi(n, A)) | IMPORT ASSIGN VAR FUNC_CALL VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL FUNC_CALL VAR STRING FUNC_DEF IF VAR BIN_OP LIST NUMBER VAR RETURN NUMBER ASSIGN VAR FUNC_CALL VAR LIST BIN_OP STRING VAR ASSIGN VAR NUMBER ASSIGN VAR FUNC_CALL VAR LIST FUNC_CALL STRING FUNC_CALL VAR VAR VAR VAR ASSIGN VAR NUMBER WHILE NUMBER IF VAR VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR FOR VAR VAR ASSIGN VAR FUNC_CALL VAR FOR VAR STRING IF VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR WHILE FUNC_CALL VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER IF VAR VAR FOR VAR FUNC_CALL VAR NUMBER FUNC_CALL VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR VAR NUMBER VAR BIN_OP VAR NUMBER IF VAR VAR RETURN BIN_OP VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR FOR VAR VAR ASSIGN VAR FUNC_CALL VAR FOR VAR STRING IF VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR WHILE FUNC_CALL VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER IF VAR VAR FOR VAR FUNC_CALL VAR NUMBER FUNC_CALL VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR VAR NUMBER VAR BIN_OP VAR NUMBER IF VAR VAR RETURN BIN_OP VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR VAR VAR |
The Tower of Hanoi is a famous game consisting of $3$ rods and a number of discs of incrementally different diameters. The puzzle starts with the discs neatly stacked on one rod, ordered by ascending size with the smallest disc at the top. The game's objective is to move the entire stack to another rod, obeying the following rules:
Only one disk can be moved at a time.
In one move, remove the topmost disk from one rod and move it to another rod.
No disk may be placed on top of a smaller disk.
Gena has a modified version of the Tower of Hanoi. This game of Hanoi has $4$ rods and $n$ disks ordered by ascending size. Gena has already made a few moves following the rules above. Given the state of Gena's Hanoi, determine the minimum number of moves needed to restore the tower to its original state with all disks on rod $1$.
Note: Gena's rods are numbered from $1$ to $4$. The radius of a disk is its index in the input array, so disk $1$ is the smallest disk with a radius of $1$, and disk $n$ is the largest with a radius of $n$.
Example
$posts=[4,3,2,1]$
In this case, the disks are arranged from large to small across the four rods. The largest disk, disk $4$, is already on rod $1$, so move disks $3,2$ and $1$ to rod $1$, in that order. It takes $3$ moves to reset the game.
$posts=[4,2,2,1]$
The largest disk, disk $4$ with radius $4$, is already on rod $1$. Disk $3$ is on rod $2$ and must be below disk $2$. Move disk $2$ to rod $3$, disk $3$ to rod $1$ and disk $2$ to rod $1$. Now move disk $1$ to rod $1$. It takes $3$ moves to reset the game.
Function Description
Complete the hanoi function below.
hanoi has the following parameters:
int posts[n]: $posts[i]$ is the location of the disk with radius $\boldsymbol{i}$
Returns
int: the minimum moves to reset the game to its initial state
Input Format
The first line contains a single integer, $n$, the number of disks.
The second line contains $n$ space-separated integers, where the $i^{\mbox{th}}$ integer is the index of the rod where the disk with diameter $\boldsymbol{i}$ is located.
Constraints
$1\leq n\leq10$
Sample Input
STDIN Function
----- --------
3 size of posts[] n = 3
1 4 1 posts = [1, 4, 1]
Sample Output
3
Explanation
$3$ moves are enough to build the tower. Here is one possible solution: | N = 10
a = [0] * (2 << 2 * N + 1)
b = [0] * 4
n = int(input())
K = 0
t = 0
for x in map(int, input().split()):
K |= x - 1 << t * 2
t += 1
a[0] = 1
Q = []
Q.append(0)
ind = 0
while True:
x = Q[ind]
ind += 1
if x == K:
print(a[x] - 1)
exit(0)
for i in range(4):
b[i] = 1000
for i in range(n - 1, -1, -1):
b[3 & x >> i * 2] = i
for i in range(4):
for j in range(4):
if b[i] < b[j]:
y = x + (j - i << b[i] * 2)
if a[y] == 0:
a[y] = a[x] + 1
Q.append(y) | ASSIGN VAR NUMBER ASSIGN VAR BIN_OP LIST NUMBER BIN_OP NUMBER BIN_OP BIN_OP NUMBER VAR NUMBER ASSIGN VAR BIN_OP LIST NUMBER NUMBER ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR VAR BIN_OP BIN_OP VAR NUMBER BIN_OP VAR NUMBER VAR NUMBER ASSIGN VAR NUMBER NUMBER ASSIGN VAR LIST EXPR FUNC_CALL VAR NUMBER ASSIGN VAR NUMBER WHILE NUMBER ASSIGN VAR VAR VAR VAR NUMBER IF VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR VAR NUMBER EXPR FUNC_CALL VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER ASSIGN VAR VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER NUMBER NUMBER ASSIGN VAR BIN_OP NUMBER BIN_OP VAR BIN_OP VAR NUMBER VAR FOR VAR FUNC_CALL VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER IF VAR VAR VAR VAR ASSIGN VAR BIN_OP VAR BIN_OP BIN_OP VAR VAR BIN_OP VAR VAR NUMBER IF VAR VAR NUMBER ASSIGN VAR VAR BIN_OP VAR VAR NUMBER EXPR FUNC_CALL VAR VAR |
The Tower of Hanoi is a famous game consisting of $3$ rods and a number of discs of incrementally different diameters. The puzzle starts with the discs neatly stacked on one rod, ordered by ascending size with the smallest disc at the top. The game's objective is to move the entire stack to another rod, obeying the following rules:
Only one disk can be moved at a time.
In one move, remove the topmost disk from one rod and move it to another rod.
No disk may be placed on top of a smaller disk.
Gena has a modified version of the Tower of Hanoi. This game of Hanoi has $4$ rods and $n$ disks ordered by ascending size. Gena has already made a few moves following the rules above. Given the state of Gena's Hanoi, determine the minimum number of moves needed to restore the tower to its original state with all disks on rod $1$.
Note: Gena's rods are numbered from $1$ to $4$. The radius of a disk is its index in the input array, so disk $1$ is the smallest disk with a radius of $1$, and disk $n$ is the largest with a radius of $n$.
Example
$posts=[4,3,2,1]$
In this case, the disks are arranged from large to small across the four rods. The largest disk, disk $4$, is already on rod $1$, so move disks $3,2$ and $1$ to rod $1$, in that order. It takes $3$ moves to reset the game.
$posts=[4,2,2,1]$
The largest disk, disk $4$ with radius $4$, is already on rod $1$. Disk $3$ is on rod $2$ and must be below disk $2$. Move disk $2$ to rod $3$, disk $3$ to rod $1$ and disk $2$ to rod $1$. Now move disk $1$ to rod $1$. It takes $3$ moves to reset the game.
Function Description
Complete the hanoi function below.
hanoi has the following parameters:
int posts[n]: $posts[i]$ is the location of the disk with radius $\boldsymbol{i}$
Returns
int: the minimum moves to reset the game to its initial state
Input Format
The first line contains a single integer, $n$, the number of disks.
The second line contains $n$ space-separated integers, where the $i^{\mbox{th}}$ integer is the index of the rod where the disk with diameter $\boldsymbol{i}$ is located.
Constraints
$1\leq n\leq10$
Sample Input
STDIN Function
----- --------
3 size of posts[] n = 3
1 4 1 posts = [1, 4, 1]
Sample Output
3
Explanation
$3$ moves are enough to build the tower. Here is one possible solution: | from itertools import product
P = [*product(range(4), repeat=2)]
def gen_moves(arrangement, n):
tops = [-1] * 4
arr = arrangement
for j in range(n):
tops[arr % 4] = j
arr //= 4
for i, j in P:
if tops[i] > tops[j]:
yield arrangement + 4 ** tops[i] * (j - i)
def distances(N):
curr = 0
distance = {curr: 0}
frontier = {curr}
while frontier:
nF = set()
for x in frontier:
for y in gen_moves(x, N):
if y not in distance:
distance[y] = distance[x] + 1
nF.add(y)
frontier = nF
return distance
N = int(input())
a = tuple(map(lambda x: int(x) - 1, input().rstrip().split()))
D = distances(N)
q = sum(4 ** (N - n - 1) * x for n, x in enumerate(a))
print(D[q]) | ASSIGN VAR LIST FUNC_CALL VAR FUNC_CALL VAR NUMBER NUMBER FUNC_DEF ASSIGN VAR BIN_OP LIST NUMBER NUMBER ASSIGN VAR VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR NUMBER VAR VAR NUMBER FOR VAR VAR VAR IF VAR VAR VAR VAR EXPR BIN_OP VAR BIN_OP BIN_OP NUMBER VAR VAR BIN_OP VAR VAR FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR DICT VAR NUMBER ASSIGN VAR VAR WHILE VAR ASSIGN VAR FUNC_CALL VAR FOR VAR VAR FOR VAR FUNC_CALL VAR VAR VAR IF VAR VAR ASSIGN VAR VAR BIN_OP VAR VAR NUMBER EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR RETURN VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR BIN_OP FUNC_CALL VAR VAR NUMBER FUNC_CALL FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR BIN_OP BIN_OP NUMBER BIN_OP BIN_OP VAR VAR NUMBER VAR VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR |
The Tower of Hanoi is a famous game consisting of $3$ rods and a number of discs of incrementally different diameters. The puzzle starts with the discs neatly stacked on one rod, ordered by ascending size with the smallest disc at the top. The game's objective is to move the entire stack to another rod, obeying the following rules:
Only one disk can be moved at a time.
In one move, remove the topmost disk from one rod and move it to another rod.
No disk may be placed on top of a smaller disk.
Gena has a modified version of the Tower of Hanoi. This game of Hanoi has $4$ rods and $n$ disks ordered by ascending size. Gena has already made a few moves following the rules above. Given the state of Gena's Hanoi, determine the minimum number of moves needed to restore the tower to its original state with all disks on rod $1$.
Note: Gena's rods are numbered from $1$ to $4$. The radius of a disk is its index in the input array, so disk $1$ is the smallest disk with a radius of $1$, and disk $n$ is the largest with a radius of $n$.
Example
$posts=[4,3,2,1]$
In this case, the disks are arranged from large to small across the four rods. The largest disk, disk $4$, is already on rod $1$, so move disks $3,2$ and $1$ to rod $1$, in that order. It takes $3$ moves to reset the game.
$posts=[4,2,2,1]$
The largest disk, disk $4$ with radius $4$, is already on rod $1$. Disk $3$ is on rod $2$ and must be below disk $2$. Move disk $2$ to rod $3$, disk $3$ to rod $1$ and disk $2$ to rod $1$. Now move disk $1$ to rod $1$. It takes $3$ moves to reset the game.
Function Description
Complete the hanoi function below.
hanoi has the following parameters:
int posts[n]: $posts[i]$ is the location of the disk with radius $\boldsymbol{i}$
Returns
int: the minimum moves to reset the game to its initial state
Input Format
The first line contains a single integer, $n$, the number of disks.
The second line contains $n$ space-separated integers, where the $i^{\mbox{th}}$ integer is the index of the rod where the disk with diameter $\boldsymbol{i}$ is located.
Constraints
$1\leq n\leq10$
Sample Input
STDIN Function
----- --------
3 size of posts[] n = 3
1 4 1 posts = [1, 4, 1]
Sample Output
3
Explanation
$3$ moves are enough to build the tower. Here is one possible solution: | N = int(input().strip())
a = [(int(_) - 1) for _ in input().split(" ")]
rep = [""] * 4
for ii in range(N):
rep[a[ii]] += str(ii)
rep[0] += ";"
for ii in range(1, 4):
rep[ii] += ":"
rep.sort()
key = "".join(rep)
used = set([key])
moves = [[][:]] * 6
bfs, substr, count = [rep], str(N - 1) + ";", 0
while substr[0] > "0":
substr = chr(ord(substr[0]) - 1) + substr
substr += ":::"
finished = False
while not finished:
count += 1
new_bfs = list()
while bfs:
entry = bfs.pop()
moves[0] = ["0" + entry[1], entry[0][1:], entry[2], entry[3]]
moves[1] = ["0" + entry[2], entry[0][1:], entry[1], entry[3]]
moves[2] = ["0" + entry[3], entry[0][1:], entry[1], entry[2]]
moves[3] = [entry[0], entry[1][1:], entry[1][0] + entry[2], entry[3]]
moves[4] = [entry[0], entry[1][1:], entry[2], entry[1][0] + entry[3]]
moves[5] = (
[entry[0], entry[1], entry[2][1:], entry[2][0] + entry[3]]
if len(entry[2]) > 1
else []
)
for mv in moves:
if mv:
mv.sort()
key = "".join(mv)
if key not in used:
if key == substr:
finished = True
else:
used.add(key)
new_bfs.append(mv)
bfs = new_bfs
print(count) | ASSIGN VAR FUNC_CALL VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR BIN_OP FUNC_CALL VAR VAR NUMBER VAR FUNC_CALL FUNC_CALL VAR STRING ASSIGN VAR BIN_OP LIST STRING NUMBER FOR VAR FUNC_CALL VAR VAR VAR VAR VAR FUNC_CALL VAR VAR VAR NUMBER STRING FOR VAR FUNC_CALL VAR NUMBER NUMBER VAR VAR STRING EXPR FUNC_CALL VAR ASSIGN VAR FUNC_CALL STRING VAR ASSIGN VAR FUNC_CALL VAR LIST VAR ASSIGN VAR BIN_OP LIST LIST NUMBER ASSIGN VAR VAR VAR LIST VAR BIN_OP FUNC_CALL VAR BIN_OP VAR NUMBER STRING NUMBER WHILE VAR NUMBER STRING ASSIGN VAR BIN_OP FUNC_CALL VAR BIN_OP FUNC_CALL VAR VAR NUMBER NUMBER VAR VAR STRING ASSIGN VAR NUMBER WHILE VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR WHILE VAR ASSIGN VAR FUNC_CALL VAR ASSIGN VAR NUMBER LIST BIN_OP STRING VAR NUMBER VAR NUMBER NUMBER VAR NUMBER VAR NUMBER ASSIGN VAR NUMBER LIST BIN_OP STRING VAR NUMBER VAR NUMBER NUMBER VAR NUMBER VAR NUMBER ASSIGN VAR NUMBER LIST BIN_OP STRING VAR NUMBER VAR NUMBER NUMBER VAR NUMBER VAR NUMBER ASSIGN VAR NUMBER LIST VAR NUMBER VAR NUMBER NUMBER BIN_OP VAR NUMBER NUMBER VAR NUMBER VAR NUMBER ASSIGN VAR NUMBER LIST VAR NUMBER VAR NUMBER NUMBER VAR NUMBER BIN_OP VAR NUMBER NUMBER VAR NUMBER ASSIGN VAR NUMBER FUNC_CALL VAR VAR NUMBER NUMBER LIST VAR NUMBER VAR NUMBER VAR NUMBER NUMBER BIN_OP VAR NUMBER NUMBER VAR NUMBER LIST FOR VAR VAR IF VAR EXPR FUNC_CALL VAR ASSIGN VAR FUNC_CALL STRING VAR IF VAR VAR IF VAR VAR ASSIGN VAR NUMBER EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR EXPR FUNC_CALL VAR VAR |
The Tower of Hanoi is a famous game consisting of $3$ rods and a number of discs of incrementally different diameters. The puzzle starts with the discs neatly stacked on one rod, ordered by ascending size with the smallest disc at the top. The game's objective is to move the entire stack to another rod, obeying the following rules:
Only one disk can be moved at a time.
In one move, remove the topmost disk from one rod and move it to another rod.
No disk may be placed on top of a smaller disk.
Gena has a modified version of the Tower of Hanoi. This game of Hanoi has $4$ rods and $n$ disks ordered by ascending size. Gena has already made a few moves following the rules above. Given the state of Gena's Hanoi, determine the minimum number of moves needed to restore the tower to its original state with all disks on rod $1$.
Note: Gena's rods are numbered from $1$ to $4$. The radius of a disk is its index in the input array, so disk $1$ is the smallest disk with a radius of $1$, and disk $n$ is the largest with a radius of $n$.
Example
$posts=[4,3,2,1]$
In this case, the disks are arranged from large to small across the four rods. The largest disk, disk $4$, is already on rod $1$, so move disks $3,2$ and $1$ to rod $1$, in that order. It takes $3$ moves to reset the game.
$posts=[4,2,2,1]$
The largest disk, disk $4$ with radius $4$, is already on rod $1$. Disk $3$ is on rod $2$ and must be below disk $2$. Move disk $2$ to rod $3$, disk $3$ to rod $1$ and disk $2$ to rod $1$. Now move disk $1$ to rod $1$. It takes $3$ moves to reset the game.
Function Description
Complete the hanoi function below.
hanoi has the following parameters:
int posts[n]: $posts[i]$ is the location of the disk with radius $\boldsymbol{i}$
Returns
int: the minimum moves to reset the game to its initial state
Input Format
The first line contains a single integer, $n$, the number of disks.
The second line contains $n$ space-separated integers, where the $i^{\mbox{th}}$ integer is the index of the rod where the disk with diameter $\boldsymbol{i}$ is located.
Constraints
$1\leq n\leq10$
Sample Input
STDIN Function
----- --------
3 size of posts[] n = 3
1 4 1 posts = [1, 4, 1]
Sample Output
3
Explanation
$3$ moves are enough to build the tower. Here is one possible solution: | import sys
MAX_MOVES = 100
def valid_moves(state, K):
pegs, tops = [-1] * K, []
for r, peg in enumerate(state):
if pegs[peg] < 0:
pegs[peg] = r
for top_r, top_peg in tops:
yield top_r, top_peg, peg
tops.append((r, peg))
for dst_peg, peg_r in enumerate(pegs):
if peg_r < 0:
for top_r, top_peg in tops:
yield top_r, top_peg, dst_peg
def move_apply(state, move):
r, src, dst = move
return state[:r] + (dst,) + state[r + 1 :]
def solve_bfs(initial_state, final_state, K):
known_states = set()
next_states = [(initial_state, [])]
depth = 0
while next_states and depth < MAX_MOVES:
states, next_states = next_states, []
for state, moves in states:
for move in valid_moves(state, K):
new_state = move_apply(state, move)
if new_state in known_states:
continue
new_moves = moves + [move]
if new_state == final_state:
return new_moves
next_states.append((new_state, new_moves))
known_states.add(new_state)
depth += 1
N = int(input().strip())
a = [int(a_temp) for a_temp in input().strip().split()]
initial_state = tuple(int(i) - 1 for i in a)
final_state = tuple(0 for _ in range(N))
solution = solve_bfs(initial_state, final_state, 4)
if solution:
print(len(solution)) | IMPORT ASSIGN VAR NUMBER FUNC_DEF ASSIGN VAR VAR BIN_OP LIST NUMBER VAR LIST FOR VAR VAR FUNC_CALL VAR VAR IF VAR VAR NUMBER ASSIGN VAR VAR VAR FOR VAR VAR VAR EXPR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR FOR VAR VAR FUNC_CALL VAR VAR IF VAR NUMBER FOR VAR VAR VAR EXPR VAR VAR VAR FUNC_DEF ASSIGN VAR VAR VAR VAR RETURN BIN_OP BIN_OP VAR VAR VAR VAR BIN_OP VAR NUMBER FUNC_DEF ASSIGN VAR FUNC_CALL VAR ASSIGN VAR LIST VAR LIST ASSIGN VAR NUMBER WHILE VAR VAR VAR ASSIGN VAR VAR VAR LIST FOR VAR VAR VAR FOR VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR IF VAR VAR ASSIGN VAR BIN_OP VAR LIST VAR IF VAR VAR RETURN VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR BIN_OP FUNC_CALL VAR VAR NUMBER VAR VAR ASSIGN VAR FUNC_CALL VAR NUMBER VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR NUMBER IF VAR EXPR FUNC_CALL VAR FUNC_CALL VAR VAR |
The Tower of Hanoi is a famous game consisting of $3$ rods and a number of discs of incrementally different diameters. The puzzle starts with the discs neatly stacked on one rod, ordered by ascending size with the smallest disc at the top. The game's objective is to move the entire stack to another rod, obeying the following rules:
Only one disk can be moved at a time.
In one move, remove the topmost disk from one rod and move it to another rod.
No disk may be placed on top of a smaller disk.
Gena has a modified version of the Tower of Hanoi. This game of Hanoi has $4$ rods and $n$ disks ordered by ascending size. Gena has already made a few moves following the rules above. Given the state of Gena's Hanoi, determine the minimum number of moves needed to restore the tower to its original state with all disks on rod $1$.
Note: Gena's rods are numbered from $1$ to $4$. The radius of a disk is its index in the input array, so disk $1$ is the smallest disk with a radius of $1$, and disk $n$ is the largest with a radius of $n$.
Example
$posts=[4,3,2,1]$
In this case, the disks are arranged from large to small across the four rods. The largest disk, disk $4$, is already on rod $1$, so move disks $3,2$ and $1$ to rod $1$, in that order. It takes $3$ moves to reset the game.
$posts=[4,2,2,1]$
The largest disk, disk $4$ with radius $4$, is already on rod $1$. Disk $3$ is on rod $2$ and must be below disk $2$. Move disk $2$ to rod $3$, disk $3$ to rod $1$ and disk $2$ to rod $1$. Now move disk $1$ to rod $1$. It takes $3$ moves to reset the game.
Function Description
Complete the hanoi function below.
hanoi has the following parameters:
int posts[n]: $posts[i]$ is the location of the disk with radius $\boldsymbol{i}$
Returns
int: the minimum moves to reset the game to its initial state
Input Format
The first line contains a single integer, $n$, the number of disks.
The second line contains $n$ space-separated integers, where the $i^{\mbox{th}}$ integer is the index of the rod where the disk with diameter $\boldsymbol{i}$ is located.
Constraints
$1\leq n\leq10$
Sample Input
STDIN Function
----- --------
3 size of posts[] n = 3
1 4 1 posts = [1, 4, 1]
Sample Output
3
Explanation
$3$ moves are enough to build the tower. Here is one possible solution: | N = 4
n = int(input())
a = tuple(map(lambda x: int(x) - 1, input().split()))
def next_states(state):
has = [False] * N
for i, v in enumerate(state):
if has[v]:
continue
has[v] = True
for j in range(N):
if not has[j]:
yield state[:i] + (j,) + state[i + 1 :]
def search(start, goal):
if start == goal:
return 0
current = [start]
visited = {start}
moves = 1
while current:
neighbors = []
for state in current:
for neighbor in next_states(state):
if neighbor == goal:
return moves
if neighbor not in visited:
visited.add(neighbor)
neighbors.append(neighbor)
moves += 1
current = neighbors
return -1
print(search(a, (0,) * n)) | ASSIGN VAR NUMBER ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR BIN_OP FUNC_CALL VAR VAR NUMBER FUNC_CALL FUNC_CALL VAR FUNC_DEF ASSIGN VAR BIN_OP LIST NUMBER VAR FOR VAR VAR FUNC_CALL VAR VAR IF VAR VAR ASSIGN VAR VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR EXPR BIN_OP BIN_OP VAR VAR VAR VAR BIN_OP VAR NUMBER FUNC_DEF IF VAR VAR RETURN NUMBER ASSIGN VAR LIST VAR ASSIGN VAR VAR ASSIGN VAR NUMBER WHILE VAR ASSIGN VAR LIST FOR VAR VAR FOR VAR FUNC_CALL VAR VAR IF VAR VAR RETURN VAR IF VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR NUMBER ASSIGN VAR VAR RETURN NUMBER EXPR FUNC_CALL VAR FUNC_CALL VAR VAR BIN_OP NUMBER VAR |
The Tower of Hanoi is a famous game consisting of $3$ rods and a number of discs of incrementally different diameters. The puzzle starts with the discs neatly stacked on one rod, ordered by ascending size with the smallest disc at the top. The game's objective is to move the entire stack to another rod, obeying the following rules:
Only one disk can be moved at a time.
In one move, remove the topmost disk from one rod and move it to another rod.
No disk may be placed on top of a smaller disk.
Gena has a modified version of the Tower of Hanoi. This game of Hanoi has $4$ rods and $n$ disks ordered by ascending size. Gena has already made a few moves following the rules above. Given the state of Gena's Hanoi, determine the minimum number of moves needed to restore the tower to its original state with all disks on rod $1$.
Note: Gena's rods are numbered from $1$ to $4$. The radius of a disk is its index in the input array, so disk $1$ is the smallest disk with a radius of $1$, and disk $n$ is the largest with a radius of $n$.
Example
$posts=[4,3,2,1]$
In this case, the disks are arranged from large to small across the four rods. The largest disk, disk $4$, is already on rod $1$, so move disks $3,2$ and $1$ to rod $1$, in that order. It takes $3$ moves to reset the game.
$posts=[4,2,2,1]$
The largest disk, disk $4$ with radius $4$, is already on rod $1$. Disk $3$ is on rod $2$ and must be below disk $2$. Move disk $2$ to rod $3$, disk $3$ to rod $1$ and disk $2$ to rod $1$. Now move disk $1$ to rod $1$. It takes $3$ moves to reset the game.
Function Description
Complete the hanoi function below.
hanoi has the following parameters:
int posts[n]: $posts[i]$ is the location of the disk with radius $\boldsymbol{i}$
Returns
int: the minimum moves to reset the game to its initial state
Input Format
The first line contains a single integer, $n$, the number of disks.
The second line contains $n$ space-separated integers, where the $i^{\mbox{th}}$ integer is the index of the rod where the disk with diameter $\boldsymbol{i}$ is located.
Constraints
$1\leq n\leq10$
Sample Input
STDIN Function
----- --------
3 size of posts[] n = 3
1 4 1 posts = [1, 4, 1]
Sample Output
3
Explanation
$3$ moves are enough to build the tower. Here is one possible solution: | import itertools as it
import sys
N = int(input().strip())
InitialLoc = [int(a_temp) for a_temp in input().strip().split(" ")]
Transformations = list(it.permutations(range(4), 2))
nBlock = len(InitialLoc)
StateSize = 2 * nBlock
powersOf2 = [(2**m) for m in range(StateSize - 1, -1, -1)]
InitialLoc = [(m - 1) for m in InitialLoc]
InitialState = "".join(
[("0" + format(m, "b") if m < 2 else format(m, "b")) for m in InitialLoc]
)
InitialState = int(InitialState, 2)
AlreadyVisited = [(False) for m in range(2**StateSize)]
AlreadyVisited[InitialState] = True
def GetBin(nIn):
Output = []
for i in powersOf2:
if nIn >= i:
nIn -= i
Output.append(1)
else:
Output.append(0)
return Output
def GetLegalResults(nIn):
BinList = GetBin(nIn)
Stacks = [[] for m in range(4)]
for i in range(nBlock - 1, -1, -1):
Stacks[BinList[i * 2] * 2 + BinList[i * 2 + 1]].append(i)
LegalTransform = []
for i in Transformations:
if len(Stacks[i[0]]) > 0:
if len(Stacks[i[1]]) == 0 and len(Stacks[i[0]]) > 1:
LegalTransform.append(i)
elif len(Stacks[i[1]]) > 0 and Stacks[i[0]][-1] < Stacks[i[1]][-1]:
LegalTransform.append(i)
elif min(i) == 0 and len(Stacks[i[1]]) == 0:
LegalTransform.append(i)
OutputStates = []
for i in LegalTransform:
BlockMoved = Stacks[i[0]][-1]
StateDelta = 2 ** (2 * (nBlock - 1 - BlockMoved)) * (i[1] - i[0])
OutputStates.append(nIn + StateDelta)
return OutputStates
CurrentStates = [InitialState]
FoundSoln = False
Count = 0
while True:
Count += 1
NewStates = []
for j in CurrentStates:
for i in GetLegalResults(j):
if i == 0:
FoundSoln = True
break
if not AlreadyVisited[i]:
AlreadyVisited[i] = True
NewStates.append(i)
if FoundSoln:
break
CurrentStates = NewStates
print(Count) | IMPORT IMPORT ASSIGN VAR FUNC_CALL VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL FUNC_CALL VAR STRING ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR NUMBER NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP NUMBER VAR ASSIGN VAR BIN_OP NUMBER VAR VAR FUNC_CALL VAR BIN_OP VAR NUMBER NUMBER NUMBER ASSIGN VAR BIN_OP VAR NUMBER VAR VAR ASSIGN VAR FUNC_CALL STRING VAR NUMBER BIN_OP STRING FUNC_CALL VAR VAR STRING FUNC_CALL VAR VAR STRING VAR VAR ASSIGN VAR FUNC_CALL VAR VAR NUMBER ASSIGN VAR NUMBER VAR FUNC_CALL VAR BIN_OP NUMBER VAR ASSIGN VAR VAR NUMBER FUNC_DEF ASSIGN VAR LIST FOR VAR VAR IF VAR VAR VAR VAR EXPR FUNC_CALL VAR NUMBER EXPR FUNC_CALL VAR NUMBER RETURN VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR LIST VAR FUNC_CALL VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER NUMBER NUMBER EXPR FUNC_CALL VAR BIN_OP BIN_OP VAR BIN_OP VAR NUMBER NUMBER VAR BIN_OP BIN_OP VAR NUMBER NUMBER VAR ASSIGN VAR LIST FOR VAR VAR IF FUNC_CALL VAR VAR VAR NUMBER NUMBER IF FUNC_CALL VAR VAR VAR NUMBER NUMBER FUNC_CALL VAR VAR VAR NUMBER NUMBER EXPR FUNC_CALL VAR VAR IF FUNC_CALL VAR VAR VAR NUMBER NUMBER VAR VAR NUMBER NUMBER VAR VAR NUMBER NUMBER EXPR FUNC_CALL VAR VAR IF FUNC_CALL VAR VAR NUMBER FUNC_CALL VAR VAR VAR NUMBER NUMBER EXPR FUNC_CALL VAR VAR ASSIGN VAR LIST FOR VAR VAR ASSIGN VAR VAR VAR NUMBER NUMBER ASSIGN VAR BIN_OP BIN_OP NUMBER BIN_OP NUMBER BIN_OP BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR VAR RETURN VAR ASSIGN VAR LIST VAR ASSIGN VAR NUMBER ASSIGN VAR NUMBER WHILE NUMBER VAR NUMBER ASSIGN VAR LIST FOR VAR VAR FOR VAR FUNC_CALL VAR VAR IF VAR NUMBER ASSIGN VAR NUMBER IF VAR VAR ASSIGN VAR VAR NUMBER EXPR FUNC_CALL VAR VAR IF VAR ASSIGN VAR VAR EXPR FUNC_CALL VAR VAR |
The Tower of Hanoi is a famous game consisting of $3$ rods and a number of discs of incrementally different diameters. The puzzle starts with the discs neatly stacked on one rod, ordered by ascending size with the smallest disc at the top. The game's objective is to move the entire stack to another rod, obeying the following rules:
Only one disk can be moved at a time.
In one move, remove the topmost disk from one rod and move it to another rod.
No disk may be placed on top of a smaller disk.
Gena has a modified version of the Tower of Hanoi. This game of Hanoi has $4$ rods and $n$ disks ordered by ascending size. Gena has already made a few moves following the rules above. Given the state of Gena's Hanoi, determine the minimum number of moves needed to restore the tower to its original state with all disks on rod $1$.
Note: Gena's rods are numbered from $1$ to $4$. The radius of a disk is its index in the input array, so disk $1$ is the smallest disk with a radius of $1$, and disk $n$ is the largest with a radius of $n$.
Example
$posts=[4,3,2,1]$
In this case, the disks are arranged from large to small across the four rods. The largest disk, disk $4$, is already on rod $1$, so move disks $3,2$ and $1$ to rod $1$, in that order. It takes $3$ moves to reset the game.
$posts=[4,2,2,1]$
The largest disk, disk $4$ with radius $4$, is already on rod $1$. Disk $3$ is on rod $2$ and must be below disk $2$. Move disk $2$ to rod $3$, disk $3$ to rod $1$ and disk $2$ to rod $1$. Now move disk $1$ to rod $1$. It takes $3$ moves to reset the game.
Function Description
Complete the hanoi function below.
hanoi has the following parameters:
int posts[n]: $posts[i]$ is the location of the disk with radius $\boldsymbol{i}$
Returns
int: the minimum moves to reset the game to its initial state
Input Format
The first line contains a single integer, $n$, the number of disks.
The second line contains $n$ space-separated integers, where the $i^{\mbox{th}}$ integer is the index of the rod where the disk with diameter $\boldsymbol{i}$ is located.
Constraints
$1\leq n\leq10$
Sample Input
STDIN Function
----- --------
3 size of posts[] n = 3
1 4 1 posts = [1, 4, 1]
Sample Output
3
Explanation
$3$ moves are enough to build the tower. Here is one possible solution: | N = int(input().strip())
bitfull = 4**N - 1
def move(state, size, rto):
shift = (size - 1) * 2
mask = 3 << shift
invmask = bitfull ^ mask
rbit = rto << shift
return state & invmask | rbit
def getmins(state):
mins = [N + 1] * 4
size = 1
mask = 3
found = 0
while found < 4 and size <= N:
rod = state & mask
if mins[rod] > N:
found += 1
mins[rod] = size
state >>= 2
size += 1
return mins
def BFS(state):
if state == 0:
return 0
visited = [False] * (bitfull + 1)
stack = [state]
visited[state] = True
depth = 0
while True:
depth += 1
nstack = set()
for u in stack:
mins = getmins(u)
for r1 in range(3):
for r2 in range(r1 + 1, 4):
rfrom, rto = (r1, r2) if mins[r1] < mins[r2] else (r2, r1)
if mins[rfrom] > N:
continue
v = move(u, mins[rfrom], rto)
if v == 0:
return depth
if not visited[v]:
nstack.add(v)
visited[v] = True
stack = nstack
state = 0
for rod in list(map(int, input().strip().split()))[::-1]:
state <<= 2
state |= rod - 1
print(BFS(state)) | ASSIGN VAR FUNC_CALL VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR BIN_OP BIN_OP NUMBER VAR NUMBER FUNC_DEF ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER ASSIGN VAR BIN_OP NUMBER VAR ASSIGN VAR BIN_OP VAR VAR ASSIGN VAR BIN_OP VAR VAR RETURN BIN_OP BIN_OP VAR VAR VAR FUNC_DEF ASSIGN VAR BIN_OP LIST BIN_OP VAR NUMBER NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER WHILE VAR NUMBER VAR VAR ASSIGN VAR BIN_OP VAR VAR IF VAR VAR VAR VAR NUMBER ASSIGN VAR VAR VAR VAR NUMBER VAR NUMBER RETURN VAR FUNC_DEF IF VAR NUMBER RETURN NUMBER ASSIGN VAR BIN_OP LIST NUMBER BIN_OP VAR NUMBER ASSIGN VAR LIST VAR ASSIGN VAR VAR NUMBER ASSIGN VAR NUMBER WHILE NUMBER VAR NUMBER ASSIGN VAR FUNC_CALL VAR FOR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR IF VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR VAR IF VAR NUMBER RETURN VAR IF VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR NUMBER ASSIGN VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL FUNC_CALL VAR NUMBER VAR NUMBER VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR FUNC_CALL VAR VAR |
The Tower of Hanoi is a famous game consisting of $3$ rods and a number of discs of incrementally different diameters. The puzzle starts with the discs neatly stacked on one rod, ordered by ascending size with the smallest disc at the top. The game's objective is to move the entire stack to another rod, obeying the following rules:
Only one disk can be moved at a time.
In one move, remove the topmost disk from one rod and move it to another rod.
No disk may be placed on top of a smaller disk.
Gena has a modified version of the Tower of Hanoi. This game of Hanoi has $4$ rods and $n$ disks ordered by ascending size. Gena has already made a few moves following the rules above. Given the state of Gena's Hanoi, determine the minimum number of moves needed to restore the tower to its original state with all disks on rod $1$.
Note: Gena's rods are numbered from $1$ to $4$. The radius of a disk is its index in the input array, so disk $1$ is the smallest disk with a radius of $1$, and disk $n$ is the largest with a radius of $n$.
Example
$posts=[4,3,2,1]$
In this case, the disks are arranged from large to small across the four rods. The largest disk, disk $4$, is already on rod $1$, so move disks $3,2$ and $1$ to rod $1$, in that order. It takes $3$ moves to reset the game.
$posts=[4,2,2,1]$
The largest disk, disk $4$ with radius $4$, is already on rod $1$. Disk $3$ is on rod $2$ and must be below disk $2$. Move disk $2$ to rod $3$, disk $3$ to rod $1$ and disk $2$ to rod $1$. Now move disk $1$ to rod $1$. It takes $3$ moves to reset the game.
Function Description
Complete the hanoi function below.
hanoi has the following parameters:
int posts[n]: $posts[i]$ is the location of the disk with radius $\boldsymbol{i}$
Returns
int: the minimum moves to reset the game to its initial state
Input Format
The first line contains a single integer, $n$, the number of disks.
The second line contains $n$ space-separated integers, where the $i^{\mbox{th}}$ integer is the index of the rod where the disk with diameter $\boldsymbol{i}$ is located.
Constraints
$1\leq n\leq10$
Sample Input
STDIN Function
----- --------
3 size of posts[] n = 3
1 4 1 posts = [1, 4, 1]
Sample Output
3
Explanation
$3$ moves are enough to build the tower. Here is one possible solution: | def bfs(start, num):
def move(data):
res_temp = [11, 11, 11, 11]
res = []
data_temp = data
for i in range(1, num + 1):
temp = data_temp % 4
data_temp >>= 2
if res_temp[temp] == 11:
res_temp[temp] = i
for i in range(4):
for j in range(i + 1, 4):
if res_temp[i] < res_temp[j]:
bit = (res_temp[i] - 1) * 2
num_temp = num_max - (3 << bit)
res.append(data & num_temp | j << bit)
elif res_temp[i] > res_temp[j]:
bit = (res_temp[j] - 1) * 2
num_temp = num_max - (3 << bit)
res.append(data & num_temp | i << bit)
else:
pass
return res
res = 0
num_max = 4**num - 1
stat_noted = (num_max + 1) * [0]
stat_noted[start] = 1
temp = [start]
while True:
res += 1
tetemp = []
for i in temp:
res_step = move(i)
for j in res_step:
if j == 0:
return res
if stat_noted[j] == 0:
stat_noted[j] = 1
tetemp.append(j)
temp = tetemp
num = int(input().strip())
cache_rod = list(map(int, input().strip().split()))
start = 0
for i in range(num):
start += cache_rod[i] - 1 << 2 * i
print(bfs(start, num)) | FUNC_DEF FUNC_DEF ASSIGN VAR LIST NUMBER NUMBER NUMBER NUMBER ASSIGN VAR LIST ASSIGN VAR VAR FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER VAR NUMBER IF VAR VAR NUMBER ASSIGN VAR VAR VAR FOR VAR FUNC_CALL VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER NUMBER IF VAR VAR VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER NUMBER ASSIGN VAR BIN_OP VAR BIN_OP NUMBER VAR EXPR FUNC_CALL VAR BIN_OP BIN_OP VAR VAR BIN_OP VAR VAR IF VAR VAR VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER NUMBER ASSIGN VAR BIN_OP VAR BIN_OP NUMBER VAR EXPR FUNC_CALL VAR BIN_OP BIN_OP VAR VAR BIN_OP VAR VAR RETURN VAR ASSIGN VAR NUMBER ASSIGN VAR BIN_OP BIN_OP NUMBER VAR NUMBER ASSIGN VAR BIN_OP BIN_OP VAR NUMBER LIST NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR LIST VAR WHILE NUMBER VAR NUMBER ASSIGN VAR LIST FOR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR FOR VAR VAR IF VAR NUMBER RETURN VAR IF VAR VAR NUMBER ASSIGN VAR VAR NUMBER EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL FUNC_CALL VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR VAR BIN_OP BIN_OP VAR VAR NUMBER BIN_OP NUMBER VAR EXPR FUNC_CALL VAR FUNC_CALL VAR VAR VAR |
qd ucyhf yi q fhycu dkcruh mxeiu huluhiu yi q tyvvuhudj fhycu dkcruh. oekh jqia yi je vydt jxu djx ucyhf.
Input
jxu ydfkj sediyiji ev q iydwbu ydjuwuh d (1 β€ d β€ 11184) β jxu edu-rqiut ydtun ev jxu ucyhf je vydt.
Output
ekjfkj q iydwbu dkcruh.
Examples
Input
1
Output
13 | def primesieve(n):
primes = [2]
table = [0, 0, 1] + [1, 0] * (n // 2 - 1)
if len(table) == n:
table.append(1)
i = 3
while i <= n:
if table[i] == 1:
primes.append(i)
for k in range(i, n // i + 1, 2):
table[i * k] = 0
i += 2
return primes, table
primes, table = primesieve(10**6)
def isprime(n):
return table[n]
n = int(input())
emirp = []
for p in primes:
rev = int(str(p)[::-1])
if rev == p:
continue
if isprime(rev):
emirp.append(p)
if len(emirp) == n:
print(p)
break | FUNC_DEF ASSIGN VAR LIST NUMBER ASSIGN VAR BIN_OP LIST NUMBER NUMBER NUMBER BIN_OP LIST NUMBER NUMBER BIN_OP BIN_OP VAR NUMBER NUMBER IF FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR NUMBER ASSIGN VAR NUMBER WHILE VAR VAR IF VAR VAR NUMBER EXPR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR BIN_OP BIN_OP VAR VAR NUMBER NUMBER ASSIGN VAR BIN_OP VAR VAR NUMBER VAR NUMBER RETURN VAR VAR ASSIGN VAR VAR FUNC_CALL VAR BIN_OP NUMBER NUMBER FUNC_DEF RETURN VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR LIST FOR VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR NUMBER IF VAR VAR IF FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR IF FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR |
qd ucyhf yi q fhycu dkcruh mxeiu huluhiu yi q tyvvuhudj fhycu dkcruh. oekh jqia yi je vydt jxu djx ucyhf.
Input
jxu ydfkj sediyiji ev q iydwbu ydjuwuh d (1 β€ d β€ 11184) β jxu edu-rqiut ydtun ev jxu ucyhf je vydt.
Output
ekjfkj q iydwbu dkcruh.
Examples
Input
1
Output
13 | from sys import stdin, stdout
def get():
return stdin.readline().strip()
def getf(sp=" "):
return [int(i) for i in get().split(sp)]
def put(a, end="\n"):
stdout.write(str(a) + end)
def putf(a, sep=" ", end="\n"):
stdout.write(sep.join([str(i) for i in a]) + end)
def prime(n):
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True
def rev(n):
ans = 0
while n > 0:
ans = ans * 10 + n % 10
n //= 10
return ans
def main():
p = [True] * (10**6 + 1)
p[1] = False
pr = []
i = 2
while i * i <= 10**6:
if p[i] == True:
j = i * 2
while j <= 10**6:
p[j] = False
j += i
i += 1
for i in range(13, 10**6 + 1):
if p[i] == True:
pr += [i]
n = int(get())
i = -1
ans = 13
while n > 0:
i += 1
r = rev(pr[i])
if r == pr[i]:
continue
if r <= 10**6:
if p[r] == True:
ans = pr[i]
n -= 1
elif prime(t) == True:
ans = pr[i]
n -= 1
put(ans)
main() | FUNC_DEF RETURN FUNC_CALL FUNC_CALL VAR FUNC_DEF STRING RETURN FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL VAR VAR FUNC_DEF STRING EXPR FUNC_CALL VAR BIN_OP FUNC_CALL VAR VAR VAR FUNC_DEF STRING STRING EXPR FUNC_CALL VAR BIN_OP FUNC_CALL VAR FUNC_CALL VAR VAR VAR VAR VAR FUNC_DEF ASSIGN VAR NUMBER WHILE BIN_OP VAR VAR VAR IF BIN_OP VAR VAR NUMBER RETURN NUMBER VAR NUMBER RETURN NUMBER FUNC_DEF ASSIGN VAR NUMBER WHILE VAR NUMBER ASSIGN VAR BIN_OP BIN_OP VAR NUMBER BIN_OP VAR NUMBER VAR NUMBER RETURN VAR FUNC_DEF ASSIGN VAR BIN_OP LIST NUMBER BIN_OP BIN_OP NUMBER NUMBER NUMBER ASSIGN VAR NUMBER NUMBER ASSIGN VAR LIST ASSIGN VAR NUMBER WHILE BIN_OP VAR VAR BIN_OP NUMBER NUMBER IF VAR VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER WHILE VAR BIN_OP NUMBER NUMBER ASSIGN VAR VAR NUMBER VAR VAR VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP BIN_OP NUMBER NUMBER NUMBER IF VAR VAR NUMBER VAR LIST VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR NUMBER ASSIGN VAR NUMBER WHILE VAR NUMBER VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR IF VAR VAR VAR IF VAR BIN_OP NUMBER NUMBER IF VAR VAR NUMBER ASSIGN VAR VAR VAR VAR NUMBER IF FUNC_CALL VAR VAR NUMBER ASSIGN VAR VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR |
qd ucyhf yi q fhycu dkcruh mxeiu huluhiu yi q tyvvuhudj fhycu dkcruh. oekh jqia yi je vydt jxu djx ucyhf.
Input
jxu ydfkj sediyiji ev q iydwbu ydjuwuh d (1 β€ d β€ 11184) β jxu edu-rqiut ydtun ev jxu ucyhf je vydt.
Output
ekjfkj q iydwbu dkcruh.
Examples
Input
1
Output
13 | import sys
def main():
nb = 1000 * 1000
tab = [True] * (nb + 1)
premier = [2]
tab[0] = False
tab[1] = False
for i in range(2, nb + 1):
if tab[i]:
j = i * i
while j < nb + 1:
tab[j] = False
j += i
cible = int(input())
x = 0
for i in range(nb):
if tab[i]:
rev = int(str(i)[::-1])
if rev < nb and rev != i and tab[rev]:
x += 1
if x == cible:
print(i)
return
main() | IMPORT FUNC_DEF ASSIGN VAR BIN_OP NUMBER NUMBER ASSIGN VAR BIN_OP LIST NUMBER BIN_OP VAR NUMBER ASSIGN VAR LIST NUMBER ASSIGN VAR NUMBER NUMBER ASSIGN VAR NUMBER NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER IF VAR VAR ASSIGN VAR BIN_OP VAR VAR WHILE VAR BIN_OP VAR NUMBER ASSIGN VAR VAR NUMBER VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR NUMBER IF VAR VAR VAR VAR VAR VAR VAR NUMBER IF VAR VAR EXPR FUNC_CALL VAR VAR RETURN EXPR FUNC_CALL VAR |
qd ucyhf yi q fhycu dkcruh mxeiu huluhiu yi q tyvvuhudj fhycu dkcruh. oekh jqia yi je vydt jxu djx ucyhf.
Input
jxu ydfkj sediyiji ev q iydwbu ydjuwuh d (1 β€ d β€ 11184) β jxu edu-rqiut ydtun ev jxu ucyhf je vydt.
Output
ekjfkj q iydwbu dkcruh.
Examples
Input
1
Output
13 | import sys
def solve():
(d,) = rv()
cur = 2
while d > 0:
if isprime(cur):
rev = int(str(cur)[::-1])
if rev != cur and isprime(rev):
d -= 1
if d > 0:
cur += 1
print(cur)
def isprime(cur):
check = 2
while check * check <= cur:
if cur % check == 0:
return False
check += 1
return True
def prt(l):
return print("".join(l))
def rv():
return map(int, input().split())
def rl(n):
return [list(map(int, input().split())) for _ in range(n)]
if sys.hexversion == 50594544:
sys.stdin = open("test.txt")
solve() | IMPORT FUNC_DEF ASSIGN VAR FUNC_CALL VAR ASSIGN VAR NUMBER WHILE VAR NUMBER IF FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR NUMBER IF VAR VAR FUNC_CALL VAR VAR VAR NUMBER IF VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR VAR FUNC_DEF ASSIGN VAR NUMBER WHILE BIN_OP VAR VAR VAR IF BIN_OP VAR VAR NUMBER RETURN NUMBER VAR NUMBER RETURN NUMBER FUNC_DEF RETURN FUNC_CALL VAR FUNC_CALL STRING VAR FUNC_DEF RETURN FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR FUNC_DEF RETURN FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR VAR FUNC_CALL VAR VAR IF VAR NUMBER ASSIGN VAR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR |
qd ucyhf yi q fhycu dkcruh mxeiu huluhiu yi q tyvvuhudj fhycu dkcruh. oekh jqia yi je vydt jxu djx ucyhf.
Input
jxu ydfkj sediyiji ev q iydwbu ydjuwuh d (1 β€ d β€ 11184) β jxu edu-rqiut ydtun ev jxu ucyhf je vydt.
Output
ekjfkj q iydwbu dkcruh.
Examples
Input
1
Output
13 | N = 1000000
def rev(z):
res = 0
while z:
res *= 10
res += z % 10
z //= 10
return res
def revv(z):
res = rev(z)
if res != z:
return res
def rwh_primes_x(n):
sieve = [True] * n
for i in range(3, int(n**0.5) + 1, 2):
if sieve[i]:
sieve[i * i :: 2 * i] = [False] * ((n - i * i - 1) // (2 * i) + 1)
return [i for i in range(3, n, 2) if sieve[i]]
primes = rwh_primes_x(N)
test = set(primes)
found = [v for v in primes if revv(v) in test]
n = int(input())
print(found[n - 1]) | ASSIGN VAR NUMBER FUNC_DEF ASSIGN VAR NUMBER WHILE VAR VAR NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER RETURN VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR IF VAR VAR RETURN VAR FUNC_DEF ASSIGN VAR BIN_OP LIST NUMBER VAR FOR VAR FUNC_CALL VAR NUMBER BIN_OP FUNC_CALL VAR BIN_OP VAR NUMBER NUMBER NUMBER IF VAR VAR ASSIGN VAR BIN_OP VAR VAR BIN_OP NUMBER VAR BIN_OP LIST NUMBER BIN_OP BIN_OP BIN_OP BIN_OP VAR BIN_OP VAR VAR NUMBER BIN_OP NUMBER VAR NUMBER RETURN VAR VAR FUNC_CALL VAR NUMBER VAR NUMBER VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER |
qd ucyhf yi q fhycu dkcruh mxeiu huluhiu yi q tyvvuhudj fhycu dkcruh. oekh jqia yi je vydt jxu djx ucyhf.
Input
jxu ydfkj sediyiji ev q iydwbu ydjuwuh d (1 β€ d β€ 11184) β jxu edu-rqiut ydtun ev jxu ucyhf je vydt.
Output
ekjfkj q iydwbu dkcruh.
Examples
Input
1
Output
13 | def prime(x):
if x == 2:
return 1
if ~x & 1:
return 0
i = 3
while i * i <= x:
if x % i == 0:
return 0
i += 1
return 1
n = int(input())
cnt = 0
for i in range(2, int(1000000000.0), 1):
if not prime(i):
continue
if i == int(str(i)[::-1]):
continue
if not prime(int(str(i)[::-1])):
continue
cnt += 1
if cnt == n:
exit(print(i)) | FUNC_DEF IF VAR NUMBER RETURN NUMBER IF BIN_OP VAR NUMBER RETURN NUMBER ASSIGN VAR NUMBER WHILE BIN_OP VAR VAR VAR IF BIN_OP VAR VAR NUMBER RETURN NUMBER VAR NUMBER RETURN NUMBER ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER FUNC_CALL VAR NUMBER NUMBER IF FUNC_CALL VAR VAR IF VAR FUNC_CALL VAR FUNC_CALL VAR VAR NUMBER IF FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR NUMBER VAR NUMBER IF VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR VAR |
qd ucyhf yi q fhycu dkcruh mxeiu huluhiu yi q tyvvuhudj fhycu dkcruh. oekh jqia yi je vydt jxu djx ucyhf.
Input
jxu ydfkj sediyiji ev q iydwbu ydjuwuh d (1 β€ d β€ 11184) β jxu edu-rqiut ydtun ev jxu ucyhf je vydt.
Output
ekjfkj q iydwbu dkcruh.
Examples
Input
1
Output
13 | def f(n):
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True
n = int(input())
for i in range(10, 1000000):
if i != int(str(i)[::-1]) and f(i) and f(int(str(i)[::-1])):
n -= 1
if n == 0:
print(i)
break | FUNC_DEF ASSIGN VAR NUMBER WHILE BIN_OP VAR VAR VAR IF BIN_OP VAR VAR NUMBER RETURN NUMBER VAR NUMBER RETURN NUMBER ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR NUMBER NUMBER IF VAR FUNC_CALL VAR FUNC_CALL VAR VAR NUMBER FUNC_CALL VAR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR NUMBER VAR NUMBER IF VAR NUMBER EXPR FUNC_CALL VAR VAR |
Alice thinks of a non-decreasing sequence of non-negative integers and wants Bob to guess it by providing him the set of all its K-sums with repetitions.
What is this? Let the sequence be {A[1], A[2], ..., A[N]} and K be some positive integer that both Alice and Bob know. Alice gives Bob the set of all possible values that can be genereated by this - A[i_{1}] + A[i_{2}] + ... + A[i_{K}], where 1 β€ i_{1} β€ i_{2} β€ ... β€ i_{K} β€ N. She can provide the values generated in any order she wishes to. Bob's task is to restore the initial sequence.
Consider an example. Let N = 3 and K = 2. The sequence is {A[1], A[2], A[3]}. The sequence of its 2-sums with repetitions is {A[1] + A[1], A[1] + A[2], A[1] + A[3], A[2] + A[2], A[2] + A[3], A[3] + A[3]}. But its elements could be provided in any order. For example any permutation of {2, 3, 4, 4, 5, 6} corresponds to the sequence {1, 2, 3}.
Input Format
The first line of the input contains an integer T denoting the number of test cases.
The description of T test cases follows.
The first line of each test case contains two space separated integers N and K.
The second line contains the sequence S_{i} of all K-sums with repetitions of the sequence Alice initially thought of.
Constraints
$1\leq T\leq10^5$
$1\leq N\leq10^5$
$1\leq K\leq10^9$
$2\leq S_i\leq10^{18}$
Note
The total number of elements in any input sequence does not exceed 10^{5}
Each element of each input sequence is non-negative integer not exceeding 10^{18}.
Each input sequence is a correct sequence of all K-sums with repetitions of some non-decreasing sequence of non-negative integers.
Output Format
For each test case, output a single line containing the space separated list of elements of the non-decreasing sequence Alice thinks of. If there are several possible outputs you can output any of them.
Sample Input 0
3
1 3
3
2 2
12 34 56
3 2
2 3 4 4 5 6
Sample Output 0
1
6 28
1 2 3
Explanation 0
Sample case #00: When N = 1 and K = 3 the only K-sum is
S[1] = 3 * A[1]. Hence A[1] = S[1] / 3 = 3 / 3 = 1.
Sample case #01: Since 6 + 6 = 12, 6 + 28 = 34, 28 + 28 =
56, then Alice indeed could think of the sequence {6, 28}.
Sample case #02: It corresponds to the example in the problem
statement. | import sys
sys.setrecursionlimit(5000)
tests = int(input())
def generateKsum(seq, k, prevInd):
if k == 1:
return seq[prevInd:]
result = []
for i in range(prevInd, len(seq)):
elem = seq[i]
for sums in generateKsum(seq, k - 1, i):
result.append(elem + sums)
return result
for test in range(tests):
n, k = [int(s) for s in input().split()]
seq = [int(s) for s in input().split()]
seq.sort()
delete = {}
found = [seq[0] // k]
for i, val in enumerate(seq[1:]):
if val in delete and delete[val] > 0:
delete[val] -= 1
else:
found.append(val - (k - 1) * found[0])
if len(found) == n:
break
for j in generateKsum(found, k, 0):
delete[j] = delete.get(j, 0) + 1
for j in generateKsum(found[:-1], k, 0):
delete[j] -= 1
for i in range(0, len(found) - 1):
rem = found[i] + (k - 1) * found[0]
delete[rem] += 1
for i in range(0, len(found)):
rem = found[i] + (k - 1) * found[0]
delete[rem] -= 1
print(" ".join([str(i) for i in found])) | IMPORT EXPR FUNC_CALL VAR NUMBER ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_DEF IF VAR NUMBER RETURN VAR VAR ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR FOR VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR EXPR FUNC_CALL VAR BIN_OP VAR VAR RETURN VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL VAR EXPR FUNC_CALL VAR ASSIGN VAR DICT ASSIGN VAR LIST BIN_OP VAR NUMBER VAR FOR VAR VAR FUNC_CALL VAR VAR NUMBER IF VAR VAR VAR VAR NUMBER VAR VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR BIN_OP BIN_OP VAR NUMBER VAR NUMBER IF FUNC_CALL VAR VAR VAR FOR VAR FUNC_CALL VAR VAR VAR NUMBER ASSIGN VAR VAR BIN_OP FUNC_CALL VAR VAR NUMBER NUMBER FOR VAR FUNC_CALL VAR VAR NUMBER VAR NUMBER VAR VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP FUNC_CALL VAR VAR NUMBER ASSIGN VAR BIN_OP VAR VAR BIN_OP BIN_OP VAR NUMBER VAR NUMBER VAR VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR VAR BIN_OP BIN_OP VAR NUMBER VAR NUMBER VAR VAR NUMBER EXPR FUNC_CALL VAR FUNC_CALL STRING FUNC_CALL VAR VAR VAR VAR |
Alice thinks of a non-decreasing sequence of non-negative integers and wants Bob to guess it by providing him the set of all its K-sums with repetitions.
What is this? Let the sequence be {A[1], A[2], ..., A[N]} and K be some positive integer that both Alice and Bob know. Alice gives Bob the set of all possible values that can be genereated by this - A[i_{1}] + A[i_{2}] + ... + A[i_{K}], where 1 β€ i_{1} β€ i_{2} β€ ... β€ i_{K} β€ N. She can provide the values generated in any order she wishes to. Bob's task is to restore the initial sequence.
Consider an example. Let N = 3 and K = 2. The sequence is {A[1], A[2], A[3]}. The sequence of its 2-sums with repetitions is {A[1] + A[1], A[1] + A[2], A[1] + A[3], A[2] + A[2], A[2] + A[3], A[3] + A[3]}. But its elements could be provided in any order. For example any permutation of {2, 3, 4, 4, 5, 6} corresponds to the sequence {1, 2, 3}.
Input Format
The first line of the input contains an integer T denoting the number of test cases.
The description of T test cases follows.
The first line of each test case contains two space separated integers N and K.
The second line contains the sequence S_{i} of all K-sums with repetitions of the sequence Alice initially thought of.
Constraints
$1\leq T\leq10^5$
$1\leq N\leq10^5$
$1\leq K\leq10^9$
$2\leq S_i\leq10^{18}$
Note
The total number of elements in any input sequence does not exceed 10^{5}
Each element of each input sequence is non-negative integer not exceeding 10^{18}.
Each input sequence is a correct sequence of all K-sums with repetitions of some non-decreasing sequence of non-negative integers.
Output Format
For each test case, output a single line containing the space separated list of elements of the non-decreasing sequence Alice thinks of. If there are several possible outputs you can output any of them.
Sample Input 0
3
1 3
3
2 2
12 34 56
3 2
2 3 4 4 5 6
Sample Output 0
1
6 28
1 2 3
Explanation 0
Sample case #00: When N = 1 and K = 3 the only K-sum is
S[1] = 3 * A[1]. Hence A[1] = S[1] / 3 = 3 / 3 = 1.
Sample case #01: Since 6 + 6 = 12, 6 + 28 = 34, 28 + 28 =
56, then Alice indeed could think of the sequence {6, 28}.
Sample case #02: It corresponds to the example in the problem
statement. | import itertools as it
T = int(input().strip())
for Loopi in range(T):
N, k = [int(m) for m in input().strip().split()]
S = [int(m) for m in input().strip().split()]
SCount = {}
for i1 in S:
if SCount.get(i1) == None:
SCount[i1] = 1
else:
SCount[i1] += 1
SUniq = sorted(SCount.keys())
A1 = [int(SUniq[0] / k)]
SCount[SUniq[0]] -= 1
if SCount[SUniq[0]] == 0:
del SUniq[0]
while len(SUniq) > 0:
A1.append(SUniq[0] - A1[0] * (k - 1))
for i1 in it.combinations_with_replacement(A1, k - 1):
STemp = sum(i1) + A1[-1]
SCount[STemp] -= 1
SUniqNew = []
for i1 in SUniq:
if SCount[i1] > 0:
SUniqNew.append(i1)
SUniq = SUniqNew
Space = ""
for i1 in A1:
print(Space + str(i1), end="")
Space = " "
print("") | IMPORT ASSIGN VAR FUNC_CALL VAR FUNC_CALL FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL FUNC_CALL VAR ASSIGN VAR DICT FOR VAR VAR IF FUNC_CALL VAR VAR NONE ASSIGN VAR VAR NUMBER VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR LIST FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR VAR NUMBER NUMBER IF VAR VAR NUMBER NUMBER VAR NUMBER WHILE FUNC_CALL VAR VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP FUNC_CALL VAR VAR VAR NUMBER VAR VAR NUMBER ASSIGN VAR LIST FOR VAR VAR IF VAR VAR NUMBER EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR ASSIGN VAR STRING FOR VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR FUNC_CALL VAR VAR STRING ASSIGN VAR STRING EXPR FUNC_CALL VAR STRING |
Alice thinks of a non-decreasing sequence of non-negative integers and wants Bob to guess it by providing him the set of all its K-sums with repetitions.
What is this? Let the sequence be {A[1], A[2], ..., A[N]} and K be some positive integer that both Alice and Bob know. Alice gives Bob the set of all possible values that can be genereated by this - A[i_{1}] + A[i_{2}] + ... + A[i_{K}], where 1 β€ i_{1} β€ i_{2} β€ ... β€ i_{K} β€ N. She can provide the values generated in any order she wishes to. Bob's task is to restore the initial sequence.
Consider an example. Let N = 3 and K = 2. The sequence is {A[1], A[2], A[3]}. The sequence of its 2-sums with repetitions is {A[1] + A[1], A[1] + A[2], A[1] + A[3], A[2] + A[2], A[2] + A[3], A[3] + A[3]}. But its elements could be provided in any order. For example any permutation of {2, 3, 4, 4, 5, 6} corresponds to the sequence {1, 2, 3}.
Input Format
The first line of the input contains an integer T denoting the number of test cases.
The description of T test cases follows.
The first line of each test case contains two space separated integers N and K.
The second line contains the sequence S_{i} of all K-sums with repetitions of the sequence Alice initially thought of.
Constraints
$1\leq T\leq10^5$
$1\leq N\leq10^5$
$1\leq K\leq10^9$
$2\leq S_i\leq10^{18}$
Note
The total number of elements in any input sequence does not exceed 10^{5}
Each element of each input sequence is non-negative integer not exceeding 10^{18}.
Each input sequence is a correct sequence of all K-sums with repetitions of some non-decreasing sequence of non-negative integers.
Output Format
For each test case, output a single line containing the space separated list of elements of the non-decreasing sequence Alice thinks of. If there are several possible outputs you can output any of them.
Sample Input 0
3
1 3
3
2 2
12 34 56
3 2
2 3 4 4 5 6
Sample Output 0
1
6 28
1 2 3
Explanation 0
Sample case #00: When N = 1 and K = 3 the only K-sum is
S[1] = 3 * A[1]. Hence A[1] = S[1] / 3 = 3 / 3 = 1.
Sample case #01: Since 6 + 6 = 12, 6 + 28 = 34, 28 + 28 =
56, then Alice indeed could think of the sequence {6, 28}.
Sample case #02: It corresponds to the example in the problem
statement. | t = int(input())
for tk in range(t):
[n, k] = [int(x) for x in input().split()]
ksums = [int(x) for x in input().split()]
ksums.sort()
seq = []
seq.append(ksums.pop(0) // k)
if n == 1:
print(seq[0])
continue
partitions = []
def addItem(listsofar, maxn):
if len(listsofar) == k - 1:
partitions[-1].append([x for x in listsofar])
return
minm = 0
if len(listsofar) > 0:
minm = listsofar[-1]
for m in range(minm, maxn):
listsofar.append(m)
addItem(listsofar, maxn)
listsofar.pop()
for m in range(1, n + 1):
partitions.append([])
addItem([], m)
for p in partitions:
p.pop(0)
valuestoskip = {}
while True:
nextvalue = ksums.pop(0)
if valuestoskip.setdefault(nextvalue, 0) == 0:
seq.append(nextvalue - seq[0] * (k - 1))
if len(seq) == n:
break
for p in partitions[len(seq) - 1]:
valuetoskip = sum([seq[x] for x in p]) + seq[-1]
valuestoskip[valuetoskip] = valuestoskip.setdefault(valuetoskip, 0) + 1
else:
valuestoskip[nextvalue] -= 1
print(*seq) | ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN LIST VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL VAR EXPR FUNC_CALL VAR ASSIGN VAR LIST EXPR FUNC_CALL VAR BIN_OP FUNC_CALL VAR NUMBER VAR IF VAR NUMBER EXPR FUNC_CALL VAR VAR NUMBER ASSIGN VAR LIST FUNC_DEF IF FUNC_CALL VAR VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR NUMBER VAR VAR VAR RETURN ASSIGN VAR NUMBER IF FUNC_CALL VAR VAR NUMBER ASSIGN VAR VAR NUMBER FOR VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER EXPR FUNC_CALL VAR LIST EXPR FUNC_CALL VAR LIST VAR FOR VAR VAR EXPR FUNC_CALL VAR NUMBER ASSIGN VAR DICT WHILE NUMBER ASSIGN VAR FUNC_CALL VAR NUMBER IF FUNC_CALL VAR VAR NUMBER NUMBER EXPR FUNC_CALL VAR BIN_OP VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER IF FUNC_CALL VAR VAR VAR FOR VAR VAR BIN_OP FUNC_CALL VAR VAR NUMBER ASSIGN VAR BIN_OP FUNC_CALL VAR VAR VAR VAR VAR VAR NUMBER ASSIGN VAR VAR BIN_OP FUNC_CALL VAR VAR NUMBER NUMBER VAR VAR NUMBER EXPR FUNC_CALL VAR VAR |
Alice thinks of a non-decreasing sequence of non-negative integers and wants Bob to guess it by providing him the set of all its K-sums with repetitions.
What is this? Let the sequence be {A[1], A[2], ..., A[N]} and K be some positive integer that both Alice and Bob know. Alice gives Bob the set of all possible values that can be genereated by this - A[i_{1}] + A[i_{2}] + ... + A[i_{K}], where 1 β€ i_{1} β€ i_{2} β€ ... β€ i_{K} β€ N. She can provide the values generated in any order she wishes to. Bob's task is to restore the initial sequence.
Consider an example. Let N = 3 and K = 2. The sequence is {A[1], A[2], A[3]}. The sequence of its 2-sums with repetitions is {A[1] + A[1], A[1] + A[2], A[1] + A[3], A[2] + A[2], A[2] + A[3], A[3] + A[3]}. But its elements could be provided in any order. For example any permutation of {2, 3, 4, 4, 5, 6} corresponds to the sequence {1, 2, 3}.
Input Format
The first line of the input contains an integer T denoting the number of test cases.
The description of T test cases follows.
The first line of each test case contains two space separated integers N and K.
The second line contains the sequence S_{i} of all K-sums with repetitions of the sequence Alice initially thought of.
Constraints
$1\leq T\leq10^5$
$1\leq N\leq10^5$
$1\leq K\leq10^9$
$2\leq S_i\leq10^{18}$
Note
The total number of elements in any input sequence does not exceed 10^{5}
Each element of each input sequence is non-negative integer not exceeding 10^{18}.
Each input sequence is a correct sequence of all K-sums with repetitions of some non-decreasing sequence of non-negative integers.
Output Format
For each test case, output a single line containing the space separated list of elements of the non-decreasing sequence Alice thinks of. If there are several possible outputs you can output any of them.
Sample Input 0
3
1 3
3
2 2
12 34 56
3 2
2 3 4 4 5 6
Sample Output 0
1
6 28
1 2 3
Explanation 0
Sample case #00: When N = 1 and K = 3 the only K-sum is
S[1] = 3 * A[1]. Hence A[1] = S[1] / 3 = 3 / 3 = 1.
Sample case #01: Since 6 + 6 = 12, 6 + 28 = 34, 28 + 28 =
56, then Alice indeed could think of the sequence {6, 28}.
Sample case #02: It corresponds to the example in the problem
statement. | from itertools import combinations_with_replacement
def print_results(res_set):
output = " ".join([str(e) for e in res_set])
print(output)
def is_set_for_index(aSet, index):
for e in aSet:
if e != index:
return False
return True
T = int(input())
for num_tests in range(T):
input_line = input()
n, k = [int(x) for x in input_line.strip().split(" ")]
input_line = input()
ksums = [int(x.strip()) for x in input_line.strip().split(" ") if x != ""]
res_set = []
if k == 1:
res_set = ksums
print_results(res_set)
continue
if n == 1:
res_set.append(int(ksums[0] / k))
print_results(res_set)
continue
xList = [x for x in range(n)]
seq_set = list(combinations_with_replacement(xList, k))
curr_index = len(res_set)
curr_set = seq_set[0]
if is_set_for_index(curr_set, curr_index):
res_set.append(ksums[0] // k)
ksums.remove(ksums[0])
seq_set.remove(curr_set)
while n - len(res_set) > 0:
curr_index = len(res_set)
curr_set = seq_set[0]
if sum(curr_set) == curr_index:
curr_sum = ksums[0]
curr_val = curr_sum - res_set[0] * (k - 1)
res_set.append(curr_val)
if n - len(res_set) == 1:
res_set.append(ksums[-1] // k)
continue
for i, t in enumerate(seq_set):
sums = 0
if t[-1] <= curr_index:
for e in t:
sums += res_set[e]
ksums.remove(sums)
seq_set.pop(i)
print_results(res_set) | FUNC_DEF ASSIGN VAR FUNC_CALL STRING FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR FUNC_DEF FOR VAR VAR IF VAR VAR RETURN NUMBER RETURN NUMBER ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR ASSIGN VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL VAR STRING ASSIGN VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR STRING VAR STRING ASSIGN VAR LIST IF VAR NUMBER ASSIGN VAR VAR EXPR FUNC_CALL VAR VAR IF VAR NUMBER EXPR FUNC_CALL VAR FUNC_CALL VAR BIN_OP VAR NUMBER VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR NUMBER IF FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR EXPR FUNC_CALL VAR VAR NUMBER EXPR FUNC_CALL VAR VAR WHILE BIN_OP VAR FUNC_CALL VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR NUMBER IF FUNC_CALL VAR VAR VAR ASSIGN VAR VAR NUMBER ASSIGN VAR BIN_OP VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR IF BIN_OP VAR FUNC_CALL VAR VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR FOR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER IF VAR NUMBER VAR FOR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR |
Alice thinks of a non-decreasing sequence of non-negative integers and wants Bob to guess it by providing him the set of all its K-sums with repetitions.
What is this? Let the sequence be {A[1], A[2], ..., A[N]} and K be some positive integer that both Alice and Bob know. Alice gives Bob the set of all possible values that can be genereated by this - A[i_{1}] + A[i_{2}] + ... + A[i_{K}], where 1 β€ i_{1} β€ i_{2} β€ ... β€ i_{K} β€ N. She can provide the values generated in any order she wishes to. Bob's task is to restore the initial sequence.
Consider an example. Let N = 3 and K = 2. The sequence is {A[1], A[2], A[3]}. The sequence of its 2-sums with repetitions is {A[1] + A[1], A[1] + A[2], A[1] + A[3], A[2] + A[2], A[2] + A[3], A[3] + A[3]}. But its elements could be provided in any order. For example any permutation of {2, 3, 4, 4, 5, 6} corresponds to the sequence {1, 2, 3}.
Input Format
The first line of the input contains an integer T denoting the number of test cases.
The description of T test cases follows.
The first line of each test case contains two space separated integers N and K.
The second line contains the sequence S_{i} of all K-sums with repetitions of the sequence Alice initially thought of.
Constraints
$1\leq T\leq10^5$
$1\leq N\leq10^5$
$1\leq K\leq10^9$
$2\leq S_i\leq10^{18}$
Note
The total number of elements in any input sequence does not exceed 10^{5}
Each element of each input sequence is non-negative integer not exceeding 10^{18}.
Each input sequence is a correct sequence of all K-sums with repetitions of some non-decreasing sequence of non-negative integers.
Output Format
For each test case, output a single line containing the space separated list of elements of the non-decreasing sequence Alice thinks of. If there are several possible outputs you can output any of them.
Sample Input 0
3
1 3
3
2 2
12 34 56
3 2
2 3 4 4 5 6
Sample Output 0
1
6 28
1 2 3
Explanation 0
Sample case #00: When N = 1 and K = 3 the only K-sum is
S[1] = 3 * A[1]. Hence A[1] = S[1] / 3 = 3 / 3 = 1.
Sample case #01: Since 6 + 6 = 12, 6 + 28 = 34, 28 + 28 =
56, then Alice indeed could think of the sequence {6, 28}.
Sample case #02: It corresponds to the example in the problem
statement. | import itertools as it
for _ in range(int(input())):
n, k = map(int, input().split())
ewan = sorted(map(int, input().split()))
ans = [ewan[0] // k]
vals = {}
for x in ewan[1:]:
if vals.setdefault(x, 0) > 0:
vals[x] -= 1
else:
vals[x] -= 1
new = x - ans[0] * (k - 1)
for y in range(k):
for z in map(
lambda idk: (k - y) * new + sum(idk),
it.combinations_with_replacement(ans, y),
):
vals[z] = vals.get(z, 0) + 1
ans.append(new)
print(" ".join(map(str, ans))) | IMPORT FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR LIST BIN_OP VAR NUMBER VAR ASSIGN VAR DICT FOR VAR VAR NUMBER IF FUNC_CALL VAR VAR NUMBER NUMBER VAR VAR NUMBER VAR VAR NUMBER ASSIGN VAR BIN_OP VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR BIN_OP BIN_OP BIN_OP VAR VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR BIN_OP FUNC_CALL VAR VAR NUMBER NUMBER EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR FUNC_CALL STRING FUNC_CALL VAR VAR VAR |
Alice thinks of a non-decreasing sequence of non-negative integers and wants Bob to guess it by providing him the set of all its K-sums with repetitions.
What is this? Let the sequence be {A[1], A[2], ..., A[N]} and K be some positive integer that both Alice and Bob know. Alice gives Bob the set of all possible values that can be genereated by this - A[i_{1}] + A[i_{2}] + ... + A[i_{K}], where 1 β€ i_{1} β€ i_{2} β€ ... β€ i_{K} β€ N. She can provide the values generated in any order she wishes to. Bob's task is to restore the initial sequence.
Consider an example. Let N = 3 and K = 2. The sequence is {A[1], A[2], A[3]}. The sequence of its 2-sums with repetitions is {A[1] + A[1], A[1] + A[2], A[1] + A[3], A[2] + A[2], A[2] + A[3], A[3] + A[3]}. But its elements could be provided in any order. For example any permutation of {2, 3, 4, 4, 5, 6} corresponds to the sequence {1, 2, 3}.
Input Format
The first line of the input contains an integer T denoting the number of test cases.
The description of T test cases follows.
The first line of each test case contains two space separated integers N and K.
The second line contains the sequence S_{i} of all K-sums with repetitions of the sequence Alice initially thought of.
Constraints
$1\leq T\leq10^5$
$1\leq N\leq10^5$
$1\leq K\leq10^9$
$2\leq S_i\leq10^{18}$
Note
The total number of elements in any input sequence does not exceed 10^{5}
Each element of each input sequence is non-negative integer not exceeding 10^{18}.
Each input sequence is a correct sequence of all K-sums with repetitions of some non-decreasing sequence of non-negative integers.
Output Format
For each test case, output a single line containing the space separated list of elements of the non-decreasing sequence Alice thinks of. If there are several possible outputs you can output any of them.
Sample Input 0
3
1 3
3
2 2
12 34 56
3 2
2 3 4 4 5 6
Sample Output 0
1
6 28
1 2 3
Explanation 0
Sample case #00: When N = 1 and K = 3 the only K-sum is
S[1] = 3 * A[1]. Hence A[1] = S[1] / 3 = 3 / 3 = 1.
Sample case #01: Since 6 + 6 = 12, 6 + 28 = 34, 28 + 28 =
56, then Alice indeed could think of the sequence {6, 28}.
Sample case #02: It corresponds to the example in the problem
statement. | def comb(n, k):
S = 1
for i in range(k):
S *= n - i
S //= i + 1
return S
def Ksums(w, K):
if K == 1:
return w
elif len(w) == 1:
return [(K * w[0][0], comb(K + w[0][1] - 1, w[0][1] - 1))]
elif len(w) == 2:
return [
(
j * w[0][0] + (K - j) * w[1][0],
comb(j + w[0][1] - 1, w[0][1] - 1)
* comb(K - j + w[1][1] - 1, w[1][1] - 1),
)
for j in range(K + 1)
]
else:
W = dict()
for j in range(K + 1):
L = Ksums(w[:-1], K - j)
for x in L:
if x[0] + j * w[-1][0] in W:
W[x[0] + j * w[-1][0]] += (
comb(j + w[-1][1] - 1, w[-1][1] - 1) * x[1]
)
else:
W[x[0] + j * w[-1][0]] = comb(j + w[-1][1] - 1, w[-1][1] - 1) * x[1]
return list(W.items())
def solve(N, K, l):
w = dict()
i = 0
x = l[0]
w[x] = 0
L = [x // K]
S = {(x // K): 1}
while len(L) < N:
i += 1
x = l[i]
if not x in w or w[x] == 0:
y = x - (K - 1) * L[0]
L.append(y)
if y in S:
for t in Ksums(list(S.items()), K):
w[t[0]] -= t[1]
S[y] += 1
for t in Ksums(list(S.items()), K):
w[t[0]] += t[1]
else:
for t in Ksums(list(S.items()), K):
w[t[0]] -= t[1]
S[y] = 1
for z in Ksums(list(S.items()), K):
if z[0] in w:
w[z[0]] += z[1]
else:
w[z[0]] = z[1]
w[x] -= 1
return L
t = int(input())
for _ in range(t):
N, K = map(int, input().split())
l = map(int, input().split())
l = sorted(l)
print(*solve(N, K, l), sep=" ") | FUNC_DEF ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR VAR BIN_OP VAR VAR VAR BIN_OP VAR NUMBER RETURN VAR FUNC_DEF IF VAR NUMBER RETURN VAR IF FUNC_CALL VAR VAR NUMBER RETURN LIST BIN_OP VAR VAR NUMBER NUMBER FUNC_CALL VAR BIN_OP BIN_OP VAR VAR NUMBER NUMBER NUMBER BIN_OP VAR NUMBER NUMBER NUMBER IF FUNC_CALL VAR VAR NUMBER RETURN BIN_OP BIN_OP VAR VAR NUMBER NUMBER BIN_OP BIN_OP VAR VAR VAR NUMBER NUMBER BIN_OP FUNC_CALL VAR BIN_OP BIN_OP VAR VAR NUMBER NUMBER NUMBER BIN_OP VAR NUMBER NUMBER NUMBER FUNC_CALL VAR BIN_OP BIN_OP BIN_OP VAR VAR VAR NUMBER NUMBER NUMBER BIN_OP VAR NUMBER NUMBER NUMBER VAR FUNC_CALL VAR BIN_OP VAR NUMBER ASSIGN VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR NUMBER BIN_OP VAR VAR FOR VAR VAR IF BIN_OP VAR NUMBER BIN_OP VAR VAR NUMBER NUMBER VAR VAR BIN_OP VAR NUMBER BIN_OP VAR VAR NUMBER NUMBER BIN_OP FUNC_CALL VAR BIN_OP BIN_OP VAR VAR NUMBER NUMBER NUMBER BIN_OP VAR NUMBER NUMBER NUMBER VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER BIN_OP VAR VAR NUMBER NUMBER BIN_OP FUNC_CALL VAR BIN_OP BIN_OP VAR VAR NUMBER NUMBER NUMBER BIN_OP VAR NUMBER NUMBER NUMBER VAR NUMBER RETURN FUNC_CALL VAR FUNC_CALL VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR ASSIGN VAR NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR LIST BIN_OP VAR VAR ASSIGN VAR DICT BIN_OP VAR VAR NUMBER WHILE FUNC_CALL VAR VAR VAR VAR NUMBER ASSIGN VAR VAR VAR IF VAR VAR VAR VAR NUMBER ASSIGN VAR BIN_OP VAR BIN_OP BIN_OP VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR VAR IF VAR VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR VAR NUMBER VAR NUMBER VAR VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR VAR NUMBER VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR VAR NUMBER VAR NUMBER ASSIGN VAR VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR IF VAR NUMBER VAR VAR VAR NUMBER VAR NUMBER ASSIGN VAR VAR NUMBER VAR NUMBER VAR VAR NUMBER RETURN VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR VAR VAR VAR STRING |
Alice thinks of a non-decreasing sequence of non-negative integers and wants Bob to guess it by providing him the set of all its K-sums with repetitions.
What is this? Let the sequence be {A[1], A[2], ..., A[N]} and K be some positive integer that both Alice and Bob know. Alice gives Bob the set of all possible values that can be genereated by this - A[i_{1}] + A[i_{2}] + ... + A[i_{K}], where 1 β€ i_{1} β€ i_{2} β€ ... β€ i_{K} β€ N. She can provide the values generated in any order she wishes to. Bob's task is to restore the initial sequence.
Consider an example. Let N = 3 and K = 2. The sequence is {A[1], A[2], A[3]}. The sequence of its 2-sums with repetitions is {A[1] + A[1], A[1] + A[2], A[1] + A[3], A[2] + A[2], A[2] + A[3], A[3] + A[3]}. But its elements could be provided in any order. For example any permutation of {2, 3, 4, 4, 5, 6} corresponds to the sequence {1, 2, 3}.
Input Format
The first line of the input contains an integer T denoting the number of test cases.
The description of T test cases follows.
The first line of each test case contains two space separated integers N and K.
The second line contains the sequence S_{i} of all K-sums with repetitions of the sequence Alice initially thought of.
Constraints
$1\leq T\leq10^5$
$1\leq N\leq10^5$
$1\leq K\leq10^9$
$2\leq S_i\leq10^{18}$
Note
The total number of elements in any input sequence does not exceed 10^{5}
Each element of each input sequence is non-negative integer not exceeding 10^{18}.
Each input sequence is a correct sequence of all K-sums with repetitions of some non-decreasing sequence of non-negative integers.
Output Format
For each test case, output a single line containing the space separated list of elements of the non-decreasing sequence Alice thinks of. If there are several possible outputs you can output any of them.
Sample Input 0
3
1 3
3
2 2
12 34 56
3 2
2 3 4 4 5 6
Sample Output 0
1
6 28
1 2 3
Explanation 0
Sample case #00: When N = 1 and K = 3 the only K-sum is
S[1] = 3 * A[1]. Hence A[1] = S[1] / 3 = 3 / 3 = 1.
Sample case #01: Since 6 + 6 = 12, 6 + 28 = 34, 28 + 28 =
56, then Alice indeed could think of the sequence {6, 28}.
Sample case #02: It corresponds to the example in the problem
statement. | cache = dict()
def permutation(data, k):
key = tuple([k] + data)
if key in cache:
return cache[key]
ret = [data[-1] * k]
if len(data) == 1:
return ret
for i in range(k):
for x in permutation(data[:-1], k - i):
ret.append(data[-1] * i + x)
cache[key] = sorted(ret)
return cache[key]
def solve(n, k, sums):
if n == 0:
return []
x = int(sums[0] / k)
known = [x]
sums.remove(x * k)
sums = sorted(sums)
while True:
if len(sums) == 0:
break
tmp = x * (k - 1)
y = sums[0] - tmp
known.append(y)
p = permutation(known, k - 1)
i = 0
for t in p:
while True:
if sums[i] == t + y:
del sums[i]
break
i += 1
return known
_t = int(input().strip())
for _ in range(_t):
_n, _k = list(map(int, input().strip().split(" ")))
_data = list(map(int, input().strip().split(" ")))
print(" ".join([str(x) for x in solve(_n, _k, _data)])) | ASSIGN VAR FUNC_CALL VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR BIN_OP LIST VAR VAR IF VAR VAR RETURN VAR VAR ASSIGN VAR LIST BIN_OP VAR NUMBER VAR IF FUNC_CALL VAR VAR NUMBER RETURN VAR FOR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR NUMBER BIN_OP VAR VAR EXPR FUNC_CALL VAR BIN_OP BIN_OP VAR NUMBER VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR RETURN VAR VAR FUNC_DEF IF VAR NUMBER RETURN LIST ASSIGN VAR FUNC_CALL VAR BIN_OP VAR NUMBER VAR ASSIGN VAR LIST VAR EXPR FUNC_CALL VAR BIN_OP VAR VAR ASSIGN VAR FUNC_CALL VAR VAR WHILE NUMBER IF FUNC_CALL VAR VAR NUMBER ASSIGN VAR BIN_OP VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR WHILE NUMBER IF VAR VAR BIN_OP VAR VAR VAR VAR VAR NUMBER RETURN VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL FUNC_CALL VAR STRING ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL FUNC_CALL VAR STRING EXPR FUNC_CALL VAR FUNC_CALL STRING FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR VAR |
Alice thinks of a non-decreasing sequence of non-negative integers and wants Bob to guess it by providing him the set of all its K-sums with repetitions.
What is this? Let the sequence be {A[1], A[2], ..., A[N]} and K be some positive integer that both Alice and Bob know. Alice gives Bob the set of all possible values that can be genereated by this - A[i_{1}] + A[i_{2}] + ... + A[i_{K}], where 1 β€ i_{1} β€ i_{2} β€ ... β€ i_{K} β€ N. She can provide the values generated in any order she wishes to. Bob's task is to restore the initial sequence.
Consider an example. Let N = 3 and K = 2. The sequence is {A[1], A[2], A[3]}. The sequence of its 2-sums with repetitions is {A[1] + A[1], A[1] + A[2], A[1] + A[3], A[2] + A[2], A[2] + A[3], A[3] + A[3]}. But its elements could be provided in any order. For example any permutation of {2, 3, 4, 4, 5, 6} corresponds to the sequence {1, 2, 3}.
Input Format
The first line of the input contains an integer T denoting the number of test cases.
The description of T test cases follows.
The first line of each test case contains two space separated integers N and K.
The second line contains the sequence S_{i} of all K-sums with repetitions of the sequence Alice initially thought of.
Constraints
$1\leq T\leq10^5$
$1\leq N\leq10^5$
$1\leq K\leq10^9$
$2\leq S_i\leq10^{18}$
Note
The total number of elements in any input sequence does not exceed 10^{5}
Each element of each input sequence is non-negative integer not exceeding 10^{18}.
Each input sequence is a correct sequence of all K-sums with repetitions of some non-decreasing sequence of non-negative integers.
Output Format
For each test case, output a single line containing the space separated list of elements of the non-decreasing sequence Alice thinks of. If there are several possible outputs you can output any of them.
Sample Input 0
3
1 3
3
2 2
12 34 56
3 2
2 3 4 4 5 6
Sample Output 0
1
6 28
1 2 3
Explanation 0
Sample case #00: When N = 1 and K = 3 the only K-sum is
S[1] = 3 * A[1]. Hence A[1] = S[1] / 3 = 3 / 3 = 1.
Sample case #01: Since 6 + 6 = 12, 6 + 28 = 34, 28 + 28 =
56, then Alice indeed could think of the sequence {6, 28}.
Sample case #02: It corresponds to the example in the problem
statement. | def partial_sums(K, start, A):
if start == len(A) - 1:
yield K * A[-1]
else:
for k in range(K):
p = k * A[start]
for s in partial_sums(K - k, start + 1, A):
yield p + s
yield K * A[start]
for case in range(int(input().strip())):
N, K = input().split()
N, K = int(N), int(K)
Ksum = list(map(int, input().split()))
Ksum.sort()
if N == 1:
print(Ksum[0] // K)
continue
if N % 2 == 0:
Nmin = Nmax = N // 2
else:
Nmin = N // 2 + 1
Nmax = N // 2
Amin = [Ksum.pop(0) // K]
for i in range(1, Nmin - 1):
Amin.append(Ksum[0] - (K - 1) * Amin[0])
for s in partial_sums(K - 1, 0, Amin):
Ksum.remove(Amin[-1] + s)
if Nmin > 1:
Amin.append(Ksum[0] - (K - 1) * Amin[0])
Ksum.reverse()
Amax = [Ksum.pop(0) // K]
for i in range(1, Nmax - 1):
Amax.append(Ksum[0] - (K - 1) * Amax[0])
for s in partial_sums(K - 1, 0, Amax):
Ksum.remove(Amax[-1] + s)
if Nmax > 1:
Amax.append(Ksum[0] - (K - 1) * Amax[0])
Amin.extend(reversed(Amax))
print(" ".join(map(str, Amin))) | FUNC_DEF IF VAR BIN_OP FUNC_CALL VAR VAR NUMBER EXPR BIN_OP VAR VAR NUMBER FOR VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR VAR VAR FOR VAR FUNC_CALL VAR BIN_OP VAR VAR BIN_OP VAR NUMBER VAR EXPR BIN_OP VAR VAR EXPR BIN_OP VAR VAR VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR EXPR FUNC_CALL VAR IF VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR IF BIN_OP VAR NUMBER NUMBER ASSIGN VAR VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR LIST BIN_OP FUNC_CALL VAR NUMBER VAR FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP BIN_OP VAR NUMBER VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER NUMBER VAR EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR IF VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP BIN_OP VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR ASSIGN VAR LIST BIN_OP FUNC_CALL VAR NUMBER VAR FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP BIN_OP VAR NUMBER VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER NUMBER VAR EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR IF VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP BIN_OP VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR FUNC_CALL STRING FUNC_CALL VAR VAR VAR |
Alice thinks of a non-decreasing sequence of non-negative integers and wants Bob to guess it by providing him the set of all its K-sums with repetitions.
What is this? Let the sequence be {A[1], A[2], ..., A[N]} and K be some positive integer that both Alice and Bob know. Alice gives Bob the set of all possible values that can be genereated by this - A[i_{1}] + A[i_{2}] + ... + A[i_{K}], where 1 β€ i_{1} β€ i_{2} β€ ... β€ i_{K} β€ N. She can provide the values generated in any order she wishes to. Bob's task is to restore the initial sequence.
Consider an example. Let N = 3 and K = 2. The sequence is {A[1], A[2], A[3]}. The sequence of its 2-sums with repetitions is {A[1] + A[1], A[1] + A[2], A[1] + A[3], A[2] + A[2], A[2] + A[3], A[3] + A[3]}. But its elements could be provided in any order. For example any permutation of {2, 3, 4, 4, 5, 6} corresponds to the sequence {1, 2, 3}.
Input Format
The first line of the input contains an integer T denoting the number of test cases.
The description of T test cases follows.
The first line of each test case contains two space separated integers N and K.
The second line contains the sequence S_{i} of all K-sums with repetitions of the sequence Alice initially thought of.
Constraints
$1\leq T\leq10^5$
$1\leq N\leq10^5$
$1\leq K\leq10^9$
$2\leq S_i\leq10^{18}$
Note
The total number of elements in any input sequence does not exceed 10^{5}
Each element of each input sequence is non-negative integer not exceeding 10^{18}.
Each input sequence is a correct sequence of all K-sums with repetitions of some non-decreasing sequence of non-negative integers.
Output Format
For each test case, output a single line containing the space separated list of elements of the non-decreasing sequence Alice thinks of. If there are several possible outputs you can output any of them.
Sample Input 0
3
1 3
3
2 2
12 34 56
3 2
2 3 4 4 5 6
Sample Output 0
1
6 28
1 2 3
Explanation 0
Sample case #00: When N = 1 and K = 3 the only K-sum is
S[1] = 3 * A[1]. Hence A[1] = S[1] / 3 = 3 / 3 = 1.
Sample case #01: Since 6 + 6 = 12, 6 + 28 = 34, 28 + 28 =
56, then Alice indeed could think of the sequence {6, 28}.
Sample case #02: It corresponds to the example in the problem
statement. | inf = 10 ^ 18 + 1000
def merge(a, b):
if len(a) == 0:
return b[:]
if len(b) == 0:
return a[:]
tmp = []
i = 0
j = 0
while i < len(a) or j < len(b):
if i < len(a):
ai = a[i]
else:
ai = inf
if j < len(b):
bj = b[j]
else:
bj = inf
if ai < bj:
tmp.append(ai)
i += 1
else:
tmp.append(bj)
j += 1
return tmp
q = int(input())
for ii in range(q):
n, K = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
a.sort()
if n == 1:
print(a[0] // K)
continue
if n == 2:
print(a[0] // K, a[len(a) - 1] // K)
continue
if n == 3:
print(a[0] // K, a[1] - a[0] // K * (K - 1), a[len(a) - 1] // K)
continue
if n == 4:
ans0 = a[0] // K
ans1 = a[1] - ans0 * (K - 1)
ans3 = a[len(a) - 1] // K
ans2 = a[len(a) - 2] - (K - 1) * ans3
print(ans0, ans1, ans2, ans3)
continue
ans = [a[0] // K]
sums = []
for k in range(K + 1):
sums.append([k * ans[0]])
for m in range(1, n):
i = 0
while i < len(sums[K]) and a[i] == sums[K][i]:
i += 1
ans.append(a[i] - (K - 1) * ans[0])
new_sums = []
new_sums.append([0])
for k in range(1, K + 1):
tmp_sums = sums[: k + 1]
for l in range(1, k + 1):
tmp_sums[k - l] = [
(x + y)
for x, y in zip(sums[k - l], [ans[m] * l] * len(sums[k - l]))
]
tmp = []
for l in range(0, k + 1):
tmp.extend(tmp_sums[l])
new_sums.append(sorted(tmp))
sums = new_sums[:]
print(*ans, sep=" ") | ASSIGN VAR BIN_OP NUMBER BIN_OP NUMBER NUMBER FUNC_DEF IF FUNC_CALL VAR VAR NUMBER RETURN VAR IF FUNC_CALL VAR VAR NUMBER RETURN VAR ASSIGN VAR LIST ASSIGN VAR NUMBER ASSIGN VAR NUMBER WHILE VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR IF VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR IF VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR IF VAR VAR EXPR FUNC_CALL VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR NUMBER RETURN VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL VAR EXPR FUNC_CALL VAR IF VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR IF VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR BIN_OP VAR BIN_OP FUNC_CALL VAR VAR NUMBER VAR IF VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER BIN_OP BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER BIN_OP VAR BIN_OP FUNC_CALL VAR VAR NUMBER VAR IF VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER VAR ASSIGN VAR BIN_OP VAR NUMBER BIN_OP VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR BIN_OP FUNC_CALL VAR VAR NUMBER VAR ASSIGN VAR BIN_OP VAR BIN_OP FUNC_CALL VAR VAR NUMBER BIN_OP BIN_OP VAR NUMBER VAR EXPR FUNC_CALL VAR VAR VAR VAR VAR ASSIGN VAR LIST BIN_OP VAR NUMBER VAR ASSIGN VAR LIST FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR LIST BIN_OP VAR VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR ASSIGN VAR NUMBER WHILE VAR FUNC_CALL VAR VAR VAR VAR VAR VAR VAR VAR VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR VAR BIN_OP BIN_OP VAR NUMBER VAR NUMBER ASSIGN VAR LIST EXPR FUNC_CALL VAR LIST NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER ASSIGN VAR VAR BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR VAR BIN_OP VAR VAR VAR VAR FUNC_CALL VAR VAR BIN_OP VAR VAR BIN_OP LIST BIN_OP VAR VAR VAR FUNC_CALL VAR VAR BIN_OP VAR VAR ASSIGN VAR LIST FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR VAR EXPR FUNC_CALL VAR VAR STRING |
Alice thinks of a non-decreasing sequence of non-negative integers and wants Bob to guess it by providing him the set of all its K-sums with repetitions.
What is this? Let the sequence be {A[1], A[2], ..., A[N]} and K be some positive integer that both Alice and Bob know. Alice gives Bob the set of all possible values that can be genereated by this - A[i_{1}] + A[i_{2}] + ... + A[i_{K}], where 1 β€ i_{1} β€ i_{2} β€ ... β€ i_{K} β€ N. She can provide the values generated in any order she wishes to. Bob's task is to restore the initial sequence.
Consider an example. Let N = 3 and K = 2. The sequence is {A[1], A[2], A[3]}. The sequence of its 2-sums with repetitions is {A[1] + A[1], A[1] + A[2], A[1] + A[3], A[2] + A[2], A[2] + A[3], A[3] + A[3]}. But its elements could be provided in any order. For example any permutation of {2, 3, 4, 4, 5, 6} corresponds to the sequence {1, 2, 3}.
Input Format
The first line of the input contains an integer T denoting the number of test cases.
The description of T test cases follows.
The first line of each test case contains two space separated integers N and K.
The second line contains the sequence S_{i} of all K-sums with repetitions of the sequence Alice initially thought of.
Constraints
$1\leq T\leq10^5$
$1\leq N\leq10^5$
$1\leq K\leq10^9$
$2\leq S_i\leq10^{18}$
Note
The total number of elements in any input sequence does not exceed 10^{5}
Each element of each input sequence is non-negative integer not exceeding 10^{18}.
Each input sequence is a correct sequence of all K-sums with repetitions of some non-decreasing sequence of non-negative integers.
Output Format
For each test case, output a single line containing the space separated list of elements of the non-decreasing sequence Alice thinks of. If there are several possible outputs you can output any of them.
Sample Input 0
3
1 3
3
2 2
12 34 56
3 2
2 3 4 4 5 6
Sample Output 0
1
6 28
1 2 3
Explanation 0
Sample case #00: When N = 1 and K = 3 the only K-sum is
S[1] = 3 * A[1]. Hence A[1] = S[1] / 3 = 3 / 3 = 1.
Sample case #01: Since 6 + 6 = 12, 6 + 28 = 34, 28 + 28 =
56, then Alice indeed could think of the sequence {6, 28}.
Sample case #02: It corresponds to the example in the problem
statement. | t = int(input())
for _ in range(t):
n, k = [int(x) for x in input().split(" ")]
s = [int(x) for x in input().split(" ")]
s.sort()
a = [s[0] // k]
sac = [[a[0] * i] for i in range(k + 1)]
p = 0
while len(a) < n:
while p < len(sac[k]) and s[p] == sac[k][p]:
p += 1
ai = s[p] - (k - 1) * a[0]
a.append(ai)
if len(a) == n:
break
for i in range(k, 0, -1):
for j in range(i):
sac[i].extend((i - j) * ai + sacj for sacj in sac[j])
sac[k].sort()
print(" ".join(str(ai) for ai in a)) | ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL VAR STRING ASSIGN VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL VAR STRING EXPR FUNC_CALL VAR ASSIGN VAR LIST BIN_OP VAR NUMBER VAR ASSIGN VAR LIST BIN_OP VAR NUMBER VAR VAR FUNC_CALL VAR BIN_OP VAR NUMBER ASSIGN VAR NUMBER WHILE FUNC_CALL VAR VAR VAR WHILE VAR FUNC_CALL VAR VAR VAR VAR VAR VAR VAR VAR VAR NUMBER ASSIGN VAR BIN_OP VAR VAR BIN_OP BIN_OP VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR VAR IF FUNC_CALL VAR VAR VAR FOR VAR FUNC_CALL VAR VAR NUMBER NUMBER FOR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR BIN_OP BIN_OP BIN_OP VAR VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR FUNC_CALL STRING FUNC_CALL VAR VAR VAR VAR |
Alice thinks of a non-decreasing sequence of non-negative integers and wants Bob to guess it by providing him the set of all its K-sums with repetitions.
What is this? Let the sequence be {A[1], A[2], ..., A[N]} and K be some positive integer that both Alice and Bob know. Alice gives Bob the set of all possible values that can be genereated by this - A[i_{1}] + A[i_{2}] + ... + A[i_{K}], where 1 β€ i_{1} β€ i_{2} β€ ... β€ i_{K} β€ N. She can provide the values generated in any order she wishes to. Bob's task is to restore the initial sequence.
Consider an example. Let N = 3 and K = 2. The sequence is {A[1], A[2], A[3]}. The sequence of its 2-sums with repetitions is {A[1] + A[1], A[1] + A[2], A[1] + A[3], A[2] + A[2], A[2] + A[3], A[3] + A[3]}. But its elements could be provided in any order. For example any permutation of {2, 3, 4, 4, 5, 6} corresponds to the sequence {1, 2, 3}.
Input Format
The first line of the input contains an integer T denoting the number of test cases.
The description of T test cases follows.
The first line of each test case contains two space separated integers N and K.
The second line contains the sequence S_{i} of all K-sums with repetitions of the sequence Alice initially thought of.
Constraints
$1\leq T\leq10^5$
$1\leq N\leq10^5$
$1\leq K\leq10^9$
$2\leq S_i\leq10^{18}$
Note
The total number of elements in any input sequence does not exceed 10^{5}
Each element of each input sequence is non-negative integer not exceeding 10^{18}.
Each input sequence is a correct sequence of all K-sums with repetitions of some non-decreasing sequence of non-negative integers.
Output Format
For each test case, output a single line containing the space separated list of elements of the non-decreasing sequence Alice thinks of. If there are several possible outputs you can output any of them.
Sample Input 0
3
1 3
3
2 2
12 34 56
3 2
2 3 4 4 5 6
Sample Output 0
1
6 28
1 2 3
Explanation 0
Sample case #00: When N = 1 and K = 3 the only K-sum is
S[1] = 3 * A[1]. Hence A[1] = S[1] / 3 = 3 / 3 = 1.
Sample case #01: Since 6 + 6 = 12, 6 + 28 = 34, 28 + 28 =
56, then Alice indeed could think of the sequence {6, 28}.
Sample case #02: It corresponds to the example in the problem
statement. | import itertools
import sys
def combinations(factors, k):
return itertools.combinations_with_replacement(factors, k)
def cartesian_factors(seq, n, k):
def _backsolve(seq, n, k, factors=[]):
if len(seq) == 0:
return factors
if len(factors) == n:
return factors
a_0 = factors[0]
s_n = seq[0]
a_n = s_n - (k - 1) * a_0
coefs = combinations(factors + [a_n], k - 1)
for coef in coefs:
seq.remove(sum(coef) + a_n)
return _backsolve(seq, n, k, factors + [a_n])
a_0 = seq[0] // k
factors = [a_0]
seq = seq[1:]
return _backsolve(seq, n, k, factors)
def k_sums(seq, n, k):
a = sorted(list(map(int, seq)))
cwr = itertools.combinations_with_replacement
values = [a[0] // k]
combinations = {}
for i in a[1:]:
if combinations.setdefault(i, 0) > 0:
combinations[i] -= 1
else:
combinations[i] -= 1
new_val = i - values[0] * (k - 1)
for j in range(k):
for new_comb in map(
lambda x: (k - j) * new_val + sum(x), cwr(values, j)
):
combinations[new_comb] = combinations.get(new_comb, 0) + 1
values.append(new_val)
return values
def print_array(arr):
items = [str(item) for item in arr]
print(" ".join(items))
def print_solve(seq, n, k):
print_array(k_sums(seq, n, k))
n_test_cases = input()
for _ in range(int(n_test_cases)):
line_value = input().strip()
_n, _k = line_value.split(" ")
n = int(_n)
k = int(_k)
k_sum = [int(item) for item in input().strip().split(" ")]
print_solve(k_sum, n, k) | IMPORT IMPORT FUNC_DEF RETURN FUNC_CALL VAR VAR VAR FUNC_DEF FUNC_DEF LIST IF FUNC_CALL VAR VAR NUMBER RETURN VAR IF FUNC_CALL VAR VAR VAR RETURN VAR ASSIGN VAR VAR NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR BIN_OP VAR BIN_OP BIN_OP VAR NUMBER VAR ASSIGN VAR FUNC_CALL VAR BIN_OP VAR LIST VAR BIN_OP VAR NUMBER FOR VAR VAR EXPR FUNC_CALL VAR BIN_OP FUNC_CALL VAR VAR VAR RETURN FUNC_CALL VAR VAR VAR VAR BIN_OP VAR LIST VAR ASSIGN VAR BIN_OP VAR NUMBER VAR ASSIGN VAR LIST VAR ASSIGN VAR VAR NUMBER RETURN FUNC_CALL VAR VAR VAR VAR VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR LIST BIN_OP VAR NUMBER VAR ASSIGN VAR DICT FOR VAR VAR NUMBER IF FUNC_CALL VAR VAR NUMBER NUMBER VAR VAR NUMBER VAR VAR NUMBER ASSIGN VAR BIN_OP VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR BIN_OP BIN_OP BIN_OP VAR VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR BIN_OP FUNC_CALL VAR VAR NUMBER NUMBER EXPR FUNC_CALL VAR VAR RETURN VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR FUNC_CALL STRING VAR FUNC_DEF EXPR FUNC_CALL VAR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR VAR FUNC_CALL VAR STRING ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL FUNC_CALL VAR STRING EXPR FUNC_CALL VAR VAR VAR VAR |
Alice thinks of a non-decreasing sequence of non-negative integers and wants Bob to guess it by providing him the set of all its K-sums with repetitions.
What is this? Let the sequence be {A[1], A[2], ..., A[N]} and K be some positive integer that both Alice and Bob know. Alice gives Bob the set of all possible values that can be genereated by this - A[i_{1}] + A[i_{2}] + ... + A[i_{K}], where 1 β€ i_{1} β€ i_{2} β€ ... β€ i_{K} β€ N. She can provide the values generated in any order she wishes to. Bob's task is to restore the initial sequence.
Consider an example. Let N = 3 and K = 2. The sequence is {A[1], A[2], A[3]}. The sequence of its 2-sums with repetitions is {A[1] + A[1], A[1] + A[2], A[1] + A[3], A[2] + A[2], A[2] + A[3], A[3] + A[3]}. But its elements could be provided in any order. For example any permutation of {2, 3, 4, 4, 5, 6} corresponds to the sequence {1, 2, 3}.
Input Format
The first line of the input contains an integer T denoting the number of test cases.
The description of T test cases follows.
The first line of each test case contains two space separated integers N and K.
The second line contains the sequence S_{i} of all K-sums with repetitions of the sequence Alice initially thought of.
Constraints
$1\leq T\leq10^5$
$1\leq N\leq10^5$
$1\leq K\leq10^9$
$2\leq S_i\leq10^{18}$
Note
The total number of elements in any input sequence does not exceed 10^{5}
Each element of each input sequence is non-negative integer not exceeding 10^{18}.
Each input sequence is a correct sequence of all K-sums with repetitions of some non-decreasing sequence of non-negative integers.
Output Format
For each test case, output a single line containing the space separated list of elements of the non-decreasing sequence Alice thinks of. If there are several possible outputs you can output any of them.
Sample Input 0
3
1 3
3
2 2
12 34 56
3 2
2 3 4 4 5 6
Sample Output 0
1
6 28
1 2 3
Explanation 0
Sample case #00: When N = 1 and K = 3 the only K-sum is
S[1] = 3 * A[1]. Hence A[1] = S[1] / 3 = 3 / 3 = 1.
Sample case #01: Since 6 + 6 = 12, 6 + 28 = 34, 28 + 28 =
56, then Alice indeed could think of the sequence {6, 28}.
Sample case #02: It corresponds to the example in the problem
statement. | from itertools import combinations_with_replacement as cwr
for _ in range(int(input())):
n, k = list(map(int, input().rstrip().split()))
a = sorted(list(map(int, input().rstrip().split())))
values = []
used = {}
for i in a:
if not values:
values.append(i // k)
continue
elif used.setdefault(i, 0) > 0:
used[i] -= 1
else:
used[i] -= 1
new_num = i - values[0] * (k - 1)
for j in range(k):
for u in map(lambda x: (k - j) * new_num + sum(x), cwr(values, j)):
used[u] = used.get(u, 0) + 1
values.append(new_num)
print(*values) | FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL FUNC_CALL VAR ASSIGN VAR LIST ASSIGN VAR DICT FOR VAR VAR IF VAR EXPR FUNC_CALL VAR BIN_OP VAR VAR IF FUNC_CALL VAR VAR NUMBER NUMBER VAR VAR NUMBER VAR VAR NUMBER ASSIGN VAR BIN_OP VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR BIN_OP BIN_OP BIN_OP VAR VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR BIN_OP FUNC_CALL VAR VAR NUMBER NUMBER EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR |
Alice thinks of a non-decreasing sequence of non-negative integers and wants Bob to guess it by providing him the set of all its K-sums with repetitions.
What is this? Let the sequence be {A[1], A[2], ..., A[N]} and K be some positive integer that both Alice and Bob know. Alice gives Bob the set of all possible values that can be genereated by this - A[i_{1}] + A[i_{2}] + ... + A[i_{K}], where 1 β€ i_{1} β€ i_{2} β€ ... β€ i_{K} β€ N. She can provide the values generated in any order she wishes to. Bob's task is to restore the initial sequence.
Consider an example. Let N = 3 and K = 2. The sequence is {A[1], A[2], A[3]}. The sequence of its 2-sums with repetitions is {A[1] + A[1], A[1] + A[2], A[1] + A[3], A[2] + A[2], A[2] + A[3], A[3] + A[3]}. But its elements could be provided in any order. For example any permutation of {2, 3, 4, 4, 5, 6} corresponds to the sequence {1, 2, 3}.
Input Format
The first line of the input contains an integer T denoting the number of test cases.
The description of T test cases follows.
The first line of each test case contains two space separated integers N and K.
The second line contains the sequence S_{i} of all K-sums with repetitions of the sequence Alice initially thought of.
Constraints
$1\leq T\leq10^5$
$1\leq N\leq10^5$
$1\leq K\leq10^9$
$2\leq S_i\leq10^{18}$
Note
The total number of elements in any input sequence does not exceed 10^{5}
Each element of each input sequence is non-negative integer not exceeding 10^{18}.
Each input sequence is a correct sequence of all K-sums with repetitions of some non-decreasing sequence of non-negative integers.
Output Format
For each test case, output a single line containing the space separated list of elements of the non-decreasing sequence Alice thinks of. If there are several possible outputs you can output any of them.
Sample Input 0
3
1 3
3
2 2
12 34 56
3 2
2 3 4 4 5 6
Sample Output 0
1
6 28
1 2 3
Explanation 0
Sample case #00: When N = 1 and K = 3 the only K-sum is
S[1] = 3 * A[1]. Hence A[1] = S[1] / 3 = 3 / 3 = 1.
Sample case #01: Since 6 + 6 = 12, 6 + 28 = 34, 28 + 28 =
56, then Alice indeed could think of the sequence {6, 28}.
Sample case #02: It corresponds to the example in the problem
statement. | import sys
sys.setrecursionlimit(2000)
num_cases = int(input().strip())
test_cases = []
while num_cases > 0:
n, k = list(map(int, input().strip().split(" ")))
ksum = list(map(int, input().strip().split(" ")))
test_cases.append((n, k, ksum))
num_cases -= 1
class Solution:
def solver(self, n, k, ksum):
self.res = []
self.perm_dic = {}
self.index_dic = {}
self.removed = set()
ksum.sort()
for i in range(len(ksum)):
if ksum[i] in self.index_dic:
self.index_dic[ksum[i]].append(i)
else:
self.index_dic[ksum[i]] = [i]
self.res = [ksum[-1] // k]
i = len(ksum) - 1
self.index_dic[ksum[i]].pop()
if self.index_dic[ksum[i]] == []:
del self.index_dic[ksum[i]]
self.removed.add(i)
index = i - 1
self.helper(n, k, ksum, index)
return self.res
def helper(self, n, k, ksum, index):
if index < 0:
return
if ksum == []:
return
self.res_temp = [ksum[index] - self.res[-1] * (k - 1)]
self.res = self.res_temp + self.res
self.removed.add(index)
if len(self.res) == n:
return
res_per = self.permutation(self.res, k)
res_pre = self.permutation(self.res[1:], k)
res_diff = res_per[: -len(res_pre)]
res_per_sum = [sum(per) for per in res_diff]
for s in res_per_sum:
i = self.index_dic[s].pop()
if len(self.index_dic[s]) == 0:
del self.index_dic[s]
self.removed.add(i)
while index in self.removed:
index -= 1
self.helper(n, k, ksum, index)
def permutation(self, l, n):
if (tuple(l), n) in self.perm_dic:
return self.perm_dic[tuple(l), n]
if l == []:
return []
if n == 0:
return [[]]
self.perm_dic[tuple(l), n] = [
([l[0]] + p) for p in self.permutation(l, n - 1)
] + self.permutation(l[1:], n)
return self.perm_dic[tuple(l), n]
sol = Solution()
for cases in test_cases:
n, k, ksum = cases
res = sol.solver(n, k, ksum)
print(" ".join(list(map(str, res)))) | IMPORT EXPR FUNC_CALL VAR NUMBER ASSIGN VAR FUNC_CALL VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR LIST WHILE VAR NUMBER ASSIGN VAR VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL FUNC_CALL VAR STRING ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL FUNC_CALL VAR STRING EXPR FUNC_CALL VAR VAR VAR VAR VAR NUMBER CLASS_DEF FUNC_DEF ASSIGN VAR LIST ASSIGN VAR DICT ASSIGN VAR DICT ASSIGN VAR FUNC_CALL VAR EXPR FUNC_CALL VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR IF VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR VAR VAR LIST VAR ASSIGN VAR LIST BIN_OP VAR NUMBER VAR ASSIGN VAR BIN_OP FUNC_CALL VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR IF VAR VAR VAR LIST VAR VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR VAR VAR VAR RETURN VAR FUNC_DEF IF VAR NUMBER RETURN IF VAR LIST RETURN ASSIGN VAR LIST BIN_OP VAR VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR VAR EXPR FUNC_CALL VAR VAR IF FUNC_CALL VAR VAR VAR RETURN ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR NUMBER VAR ASSIGN VAR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR FOR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF FUNC_CALL VAR VAR VAR NUMBER VAR VAR EXPR FUNC_CALL VAR VAR WHILE VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR VAR VAR FUNC_DEF IF FUNC_CALL VAR VAR VAR VAR RETURN VAR FUNC_CALL VAR VAR VAR IF VAR LIST RETURN LIST IF VAR NUMBER RETURN LIST LIST ASSIGN VAR FUNC_CALL VAR VAR VAR BIN_OP BIN_OP LIST VAR NUMBER VAR VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER FUNC_CALL VAR VAR NUMBER VAR RETURN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR FOR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR FUNC_CALL STRING FUNC_CALL VAR FUNC_CALL VAR VAR VAR |
Alice thinks of a non-decreasing sequence of non-negative integers and wants Bob to guess it by providing him the set of all its K-sums with repetitions.
What is this? Let the sequence be {A[1], A[2], ..., A[N]} and K be some positive integer that both Alice and Bob know. Alice gives Bob the set of all possible values that can be genereated by this - A[i_{1}] + A[i_{2}] + ... + A[i_{K}], where 1 β€ i_{1} β€ i_{2} β€ ... β€ i_{K} β€ N. She can provide the values generated in any order she wishes to. Bob's task is to restore the initial sequence.
Consider an example. Let N = 3 and K = 2. The sequence is {A[1], A[2], A[3]}. The sequence of its 2-sums with repetitions is {A[1] + A[1], A[1] + A[2], A[1] + A[3], A[2] + A[2], A[2] + A[3], A[3] + A[3]}. But its elements could be provided in any order. For example any permutation of {2, 3, 4, 4, 5, 6} corresponds to the sequence {1, 2, 3}.
Input Format
The first line of the input contains an integer T denoting the number of test cases.
The description of T test cases follows.
The first line of each test case contains two space separated integers N and K.
The second line contains the sequence S_{i} of all K-sums with repetitions of the sequence Alice initially thought of.
Constraints
$1\leq T\leq10^5$
$1\leq N\leq10^5$
$1\leq K\leq10^9$
$2\leq S_i\leq10^{18}$
Note
The total number of elements in any input sequence does not exceed 10^{5}
Each element of each input sequence is non-negative integer not exceeding 10^{18}.
Each input sequence is a correct sequence of all K-sums with repetitions of some non-decreasing sequence of non-negative integers.
Output Format
For each test case, output a single line containing the space separated list of elements of the non-decreasing sequence Alice thinks of. If there are several possible outputs you can output any of them.
Sample Input 0
3
1 3
3
2 2
12 34 56
3 2
2 3 4 4 5 6
Sample Output 0
1
6 28
1 2 3
Explanation 0
Sample case #00: When N = 1 and K = 3 the only K-sum is
S[1] = 3 * A[1]. Hence A[1] = S[1] / 3 = 3 / 3 = 1.
Sample case #01: Since 6 + 6 = 12, 6 + 28 = 34, 28 + 28 =
56, then Alice indeed could think of the sequence {6, 28}.
Sample case #02: It corresponds to the example in the problem
statement. | import sys
class SumConstructor:
def __init__(self, k, s_0, in_list, a_0, in_floor):
self.steps = [k - 1]
self.values = [s_0]
self.newSums = {s_0: 1}
self.read = 0
self.next = 1
self.floor = s_0 - a_0
self.input = in_list
self.output = [a_0]
def addSum(self, vsum):
if self.newSums.setdefault(vsum, 0) == 0:
self.newSums[vsum] += 1
else:
self.newSums[vsum] += 1
def remSum(self, vsum):
occ_nb = self.newSums.get(vsum, -1)
if occ_nb == -1:
return False
elif occ_nb == 1:
del self.newSums[vsum]
return True
else:
self.newSums[vsum] -= 1
return True
def write(self, diff):
i = 0
wr_value = self.values[self.read] + diff
while i <= self.steps[self.read]:
self.steps.append(i)
self.values.append(wr_value)
self.addSum(wr_value)
wr_value += diff
self.next += 1
i += 1
self.read += 1
def createSums(self, diff):
self.newSums = dict()
for index in range(self.read, self.next):
self.write(diff)
def clearList(self):
i = 0
while self.newSums != {}:
if self.remSum(self.input[i]) == True:
del self.input[i]
else:
i += 1
def completeOut(self):
prev = self.output[-1]
new = self.input[0] - self.floor
self.output.append(new)
return new - prev
def solve(n, k, l):
l = sorted(l)
s_0 = l[0]
a_0 = s_0 // k
floor = s_0 - a_0
constructor = SumConstructor(k, s_0, l, a_0, floor)
for index in range(0, n - 1):
constructor.clearList()
delta = constructor.completeOut()
constructor.createSums(delta)
return constructor.output
def main():
nb_case = int(input())
for index in range(0, nb_case):
n, k = map(int, input().split(" "))
l = map(int, input().split(" "))
sys.stdout.write(" ".join(map(str, solve(n, k, l))))
if index != nb_case:
sys.stdout.write("\n")
main() | IMPORT CLASS_DEF FUNC_DEF ASSIGN VAR LIST BIN_OP VAR NUMBER ASSIGN VAR LIST VAR ASSIGN VAR DICT VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR BIN_OP VAR VAR ASSIGN VAR VAR ASSIGN VAR LIST VAR FUNC_DEF IF FUNC_CALL VAR VAR NUMBER NUMBER VAR VAR NUMBER VAR VAR NUMBER FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR NUMBER IF VAR NUMBER RETURN NUMBER IF VAR NUMBER VAR VAR RETURN NUMBER VAR VAR NUMBER RETURN NUMBER FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR BIN_OP VAR VAR VAR WHILE VAR VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR VAR NUMBER VAR NUMBER VAR NUMBER FUNC_DEF ASSIGN VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR FUNC_DEF ASSIGN VAR NUMBER WHILE VAR DICT IF FUNC_CALL VAR VAR VAR NUMBER VAR VAR VAR NUMBER FUNC_DEF ASSIGN VAR VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER VAR EXPR FUNC_CALL VAR VAR RETURN BIN_OP VAR VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR NUMBER ASSIGN VAR BIN_OP VAR VAR ASSIGN VAR BIN_OP VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR VAR VAR FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER EXPR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR EXPR FUNC_CALL VAR VAR RETURN VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR NUMBER VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR STRING ASSIGN VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR STRING EXPR FUNC_CALL VAR FUNC_CALL STRING FUNC_CALL VAR VAR FUNC_CALL VAR VAR VAR VAR IF VAR VAR EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR |
Alice thinks of a non-decreasing sequence of non-negative integers and wants Bob to guess it by providing him the set of all its K-sums with repetitions.
What is this? Let the sequence be {A[1], A[2], ..., A[N]} and K be some positive integer that both Alice and Bob know. Alice gives Bob the set of all possible values that can be genereated by this - A[i_{1}] + A[i_{2}] + ... + A[i_{K}], where 1 β€ i_{1} β€ i_{2} β€ ... β€ i_{K} β€ N. She can provide the values generated in any order she wishes to. Bob's task is to restore the initial sequence.
Consider an example. Let N = 3 and K = 2. The sequence is {A[1], A[2], A[3]}. The sequence of its 2-sums with repetitions is {A[1] + A[1], A[1] + A[2], A[1] + A[3], A[2] + A[2], A[2] + A[3], A[3] + A[3]}. But its elements could be provided in any order. For example any permutation of {2, 3, 4, 4, 5, 6} corresponds to the sequence {1, 2, 3}.
Input Format
The first line of the input contains an integer T denoting the number of test cases.
The description of T test cases follows.
The first line of each test case contains two space separated integers N and K.
The second line contains the sequence S_{i} of all K-sums with repetitions of the sequence Alice initially thought of.
Constraints
$1\leq T\leq10^5$
$1\leq N\leq10^5$
$1\leq K\leq10^9$
$2\leq S_i\leq10^{18}$
Note
The total number of elements in any input sequence does not exceed 10^{5}
Each element of each input sequence is non-negative integer not exceeding 10^{18}.
Each input sequence is a correct sequence of all K-sums with repetitions of some non-decreasing sequence of non-negative integers.
Output Format
For each test case, output a single line containing the space separated list of elements of the non-decreasing sequence Alice thinks of. If there are several possible outputs you can output any of them.
Sample Input 0
3
1 3
3
2 2
12 34 56
3 2
2 3 4 4 5 6
Sample Output 0
1
6 28
1 2 3
Explanation 0
Sample case #00: When N = 1 and K = 3 the only K-sum is
S[1] = 3 * A[1]. Hence A[1] = S[1] / 3 = 3 / 3 = 1.
Sample case #01: Since 6 + 6 = 12, 6 + 28 = 34, 28 + 28 =
56, then Alice indeed could think of the sequence {6, 28}.
Sample case #02: It corresponds to the example in the problem
statement. | def allcomb(seq, k):
if k == 0:
return [0]
lst = list()
seqbis = list(seq)
for a in seq:
for b in allcomb(seqbis, k - 1):
lst.append(a + b)
seqbis.remove(a)
return lst
def addSum(already, seq, nxt, k):
for p in range(1, k + 1):
for l in allcomb(seq, k - p):
already.append(l + nxt * p)
def getSequence(n, k, ksum):
seq = list()
ksum = sorted(ksum)
seq.append(int(ksum[0] / k))
already = list()
offset = 0
for i in range(1, n):
while ksum[i + offset] in already:
already.remove(ksum[i + offset])
offset += 1
nxt = ksum[i + offset] - seq[0] * (k - 1)
addSum(already, seq, nxt, k)
seq.append(nxt)
already.remove(ksum[i + offset])
return seq
t = int(input())
for case in range(t):
dim = [int(x) for x in input().split(" ")]
n = dim[0]
k = dim[1]
ksum = [int(x) for x in input().split(" ")]
res = getSequence(n, k, ksum)
print(" ".join([str(x) for x in res])) | FUNC_DEF IF VAR NUMBER RETURN LIST NUMBER ASSIGN VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR FOR VAR VAR FOR VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR VAR EXPR FUNC_CALL VAR VAR RETURN VAR FUNC_DEF FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR VAR BIN_OP VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR BIN_OP VAR VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR BIN_OP VAR NUMBER VAR ASSIGN VAR FUNC_CALL VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR WHILE VAR BIN_OP VAR VAR VAR EXPR FUNC_CALL VAR VAR BIN_OP VAR VAR VAR NUMBER ASSIGN VAR BIN_OP VAR BIN_OP VAR VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR BIN_OP VAR VAR RETURN VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL VAR STRING ASSIGN VAR VAR NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL VAR STRING ASSIGN VAR FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR FUNC_CALL STRING FUNC_CALL VAR VAR VAR VAR |
Alice thinks of a non-decreasing sequence of non-negative integers and wants Bob to guess it by providing him the set of all its K-sums with repetitions.
What is this? Let the sequence be {A[1], A[2], ..., A[N]} and K be some positive integer that both Alice and Bob know. Alice gives Bob the set of all possible values that can be genereated by this - A[i_{1}] + A[i_{2}] + ... + A[i_{K}], where 1 β€ i_{1} β€ i_{2} β€ ... β€ i_{K} β€ N. She can provide the values generated in any order she wishes to. Bob's task is to restore the initial sequence.
Consider an example. Let N = 3 and K = 2. The sequence is {A[1], A[2], A[3]}. The sequence of its 2-sums with repetitions is {A[1] + A[1], A[1] + A[2], A[1] + A[3], A[2] + A[2], A[2] + A[3], A[3] + A[3]}. But its elements could be provided in any order. For example any permutation of {2, 3, 4, 4, 5, 6} corresponds to the sequence {1, 2, 3}.
Input Format
The first line of the input contains an integer T denoting the number of test cases.
The description of T test cases follows.
The first line of each test case contains two space separated integers N and K.
The second line contains the sequence S_{i} of all K-sums with repetitions of the sequence Alice initially thought of.
Constraints
$1\leq T\leq10^5$
$1\leq N\leq10^5$
$1\leq K\leq10^9$
$2\leq S_i\leq10^{18}$
Note
The total number of elements in any input sequence does not exceed 10^{5}
Each element of each input sequence is non-negative integer not exceeding 10^{18}.
Each input sequence is a correct sequence of all K-sums with repetitions of some non-decreasing sequence of non-negative integers.
Output Format
For each test case, output a single line containing the space separated list of elements of the non-decreasing sequence Alice thinks of. If there are several possible outputs you can output any of them.
Sample Input 0
3
1 3
3
2 2
12 34 56
3 2
2 3 4 4 5 6
Sample Output 0
1
6 28
1 2 3
Explanation 0
Sample case #00: When N = 1 and K = 3 the only K-sum is
S[1] = 3 * A[1]. Hence A[1] = S[1] / 3 = 3 / 3 = 1.
Sample case #01: Since 6 + 6 = 12, 6 + 28 = 34, 28 + 28 =
56, then Alice indeed could think of the sequence {6, 28}.
Sample case #02: It corresponds to the example in the problem
statement. | def insertion_sort(a):
for i in range(0, len(a) - 1):
j = i
while a[j] > a[j + 1] and j >= 0:
temp = a[j]
a[j] = a[j + 1]
a[j + 1] = temp
j -= 1
return a
def merge_lists(a, b):
final_list = []
pos_a = 0
pos_b = 0
while pos_a + pos_b < len(a) + len(b):
if pos_a < len(a) and pos_b < len(b) and a[pos_a] <= b[pos_b]:
final_list.append(a[pos_a])
pos_a += 1
elif pos_a < len(a) and pos_b < len(b) and a[pos_a] > b[pos_b]:
final_list.append(b[pos_b])
pos_b += 1
elif pos_a == len(a) and pos_b < len(b):
final_list.append(b[pos_b])
pos_b += 1
elif pos_a < len(a) and pos_b == len(b):
final_list.append(a[pos_a])
pos_a += 1
else:
print("error")
return final_list
def merge_sort(a):
if len(a) < 10:
return insertion_sort(a)
else:
return merge_lists(
merge_sort(a[0 : len(a) // 2]), merge_sort(a[len(a) // 2 : len(a)])
)
def generate_all_k_sums(L, K, current_sum=0, start_index=0):
ret_list = []
if K == 0 and start_index < len(L):
return [current_sum]
elif start_index == len(L) - 1 and K >= 0:
return [current_sum + K * L[start_index]]
else:
for i in range(0, K + 1):
if K - i >= 0:
ret_list += generate_all_k_sums(
L, K - i, current_sum + i * L[start_index], start_index + 1
)
return ret_list
def reverse_k_sums(A, n, k):
current_list = [A[0] // k]
while len(current_list) < n:
k_sums = merge_sort(generate_all_k_sums(current_list, k))
i = 0
found = False
while i < len(k_sums) and not found:
if A[i] != k_sums[i]:
current_list.append(A[i] - current_list[0] * (k - 1))
found = True
i += 1
if not found and i == len(k_sums):
current_list.append(A[i] - current_list[0] * (k - 1))
return current_list
def repksum():
test_cases = int(input())
for q in range(0, test_cases):
N, K = [int(a) for a in input().split()]
rks = merge_sort([int(a) for a in input().split()])
if K > 1:
original_list = [str(a) for a in reverse_k_sums(rks, N, K)]
elif K == 1:
original_list = [str(a) for a in rks]
print(" ".join([str(a) for a in original_list]))
repksum() | FUNC_DEF FOR VAR FUNC_CALL VAR NUMBER BIN_OP FUNC_CALL VAR VAR NUMBER ASSIGN VAR VAR WHILE VAR VAR VAR BIN_OP VAR NUMBER VAR NUMBER ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER VAR VAR NUMBER RETURN VAR FUNC_DEF ASSIGN VAR LIST ASSIGN VAR NUMBER ASSIGN VAR NUMBER WHILE BIN_OP VAR VAR BIN_OP FUNC_CALL VAR VAR FUNC_CALL VAR VAR IF VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR NUMBER IF VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR NUMBER IF VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR NUMBER IF VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR NUMBER EXPR FUNC_CALL VAR STRING RETURN VAR FUNC_DEF IF FUNC_CALL VAR VAR NUMBER RETURN FUNC_CALL VAR VAR RETURN FUNC_CALL VAR FUNC_CALL VAR VAR NUMBER BIN_OP FUNC_CALL VAR VAR NUMBER FUNC_CALL VAR VAR BIN_OP FUNC_CALL VAR VAR NUMBER FUNC_CALL VAR VAR FUNC_DEF NUMBER NUMBER ASSIGN VAR LIST IF VAR NUMBER VAR FUNC_CALL VAR VAR RETURN LIST VAR IF VAR BIN_OP FUNC_CALL VAR VAR NUMBER VAR NUMBER RETURN LIST BIN_OP VAR BIN_OP VAR VAR VAR FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER IF BIN_OP VAR VAR NUMBER VAR FUNC_CALL VAR VAR BIN_OP VAR VAR BIN_OP VAR BIN_OP VAR VAR VAR BIN_OP VAR NUMBER RETURN VAR FUNC_DEF ASSIGN VAR LIST BIN_OP VAR NUMBER VAR WHILE FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR ASSIGN VAR NUMBER ASSIGN VAR NUMBER WHILE VAR FUNC_CALL VAR VAR VAR IF VAR VAR VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER ASSIGN VAR NUMBER VAR NUMBER IF VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER RETURN VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR NUMBER VAR ASSIGN VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL VAR IF VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR VAR IF VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR FUNC_CALL STRING FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR |
A rectangle with sides $A$ and $B$ is cut into rectangles with cuts parallel to its sides. For example, if $p$ horizontal and $q$ vertical cuts were made, $(p + 1) \cdot (q + 1)$ rectangles were left after the cutting. After the cutting, rectangles were of $n$ different types. Two rectangles are different if at least one side of one rectangle isn't equal to the corresponding side of the other. Note that the rectangle can't be rotated, this means that rectangles $a \times b$ and $b \times a$ are considered different if $a \neq b$.
For each type of rectangles, lengths of the sides of rectangles are given along with the amount of the rectangles of this type that were left after cutting the initial rectangle.
Calculate the amount of pairs $(A; B)$ such as the given rectangles could be created by cutting the rectangle with sides of lengths $A$ and $B$. Note that pairs $(A; B)$ and $(B; A)$ are considered different when $A \neq B$.
-----Input-----
The first line consists of a single integer $n$ ($1 \leq n \leq 2 \cdot 10^{5}$)Β β amount of different types of rectangles left after cutting the initial rectangle.
The next $n$ lines each consist of three integers $w_{i}, h_{i}, c_{i}$ $(1 \leq w_{i}, h_{i}, c_{i} \leq 10^{12})$Β β the lengths of the sides of the rectangles of this type and the amount of the rectangles of this type.
It is guaranteed that the rectangles of the different types are different.
-----Output-----
Output one integerΒ β the answer to the problem.
-----Examples-----
Input
1
1 1 9
Output
3
Input
2
2 3 20
2 4 40
Output
6
Input
2
1 2 5
2 3 5
Output
0
-----Note-----
In the first sample there are three suitable pairs: $(1; 9)$, $(3; 3)$ and $(9; 1)$.
In the second sample case there are 6 suitable pairs: $(2; 220)$, $(4; 110)$, $(8; 55)$, $(10; 44)$, $(20; 22)$ and $(40; 11)$.
Here the sample of cut for $(20; 22)$.
[Image]
The third sample has no suitable pairs. | n = int(input())
w = []
h = []
c = []
cntw = {}
cnth = {}
multMayotC = 0
cntC = 0
def insert1(a, b, c):
if not a in b:
b[a] = c
else:
b[a] = b[a] + c
def multMayot(a, b):
if a % b == 0:
return b
else:
return multMayot(b, a % b)
for i in range(0, n):
a, b, d = map(int, input().split())
w.append(a)
h.append(b)
c.append(d)
insert1(a, cntw, d)
insert1(b, cnth, d)
cntC += d
if multMayotC == 0:
multMayotC = d
else:
multMayotC = multMayot(multMayotC, d)
for i in range(0, n):
if cntw[w[i]] * cnth[h[i]] != cntC * c[i]:
print(0)
return
result = 0
i = 1
while i * i <= multMayotC:
if multMayotC % i == 0:
result += 1
if i * i != multMayotC:
result += 1
i += 1
print(result) | ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR LIST ASSIGN VAR LIST ASSIGN VAR LIST ASSIGN VAR DICT ASSIGN VAR DICT ASSIGN VAR NUMBER ASSIGN VAR NUMBER FUNC_DEF IF VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR BIN_OP VAR VAR VAR FUNC_DEF IF BIN_OP VAR VAR NUMBER RETURN VAR RETURN FUNC_CALL VAR VAR BIN_OP VAR VAR FOR VAR FUNC_CALL VAR NUMBER VAR ASSIGN VAR VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR VAR VAR IF VAR NUMBER ASSIGN VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR FOR VAR FUNC_CALL VAR NUMBER VAR IF BIN_OP VAR VAR VAR VAR VAR VAR BIN_OP VAR VAR VAR EXPR FUNC_CALL VAR NUMBER RETURN ASSIGN VAR NUMBER ASSIGN VAR NUMBER WHILE BIN_OP VAR VAR VAR IF BIN_OP VAR VAR NUMBER VAR NUMBER IF BIN_OP VAR VAR VAR VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR VAR |
The aim of this kata is to determine the number of sub-function calls made by an unknown function.
You have to write a function named `count_calls` which:
* takes as parameter a function and its arguments (args, kwargs)
* calls the function
* returns a tuple containing:
* the number of function calls made inside it and inside all the sub-called functions recursively
* the function return value.
NB: The call to the function itself is not counted.
HINT: The sys module may come in handy. | import sys
def count_calls(f, *args, **kwargs):
total = 0
def count(frame, event, arg):
nonlocal total
if event == "call":
total += 1
sys.settrace(count)
ret = f(*args, **kwargs)
return total - 1, ret | IMPORT FUNC_DEF ASSIGN VAR NUMBER FUNC_DEF IF VAR STRING VAR NUMBER EXPR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN BIN_OP VAR NUMBER VAR |
The aim of this kata is to determine the number of sub-function calls made by an unknown function.
You have to write a function named `count_calls` which:
* takes as parameter a function and its arguments (args, kwargs)
* calls the function
* returns a tuple containing:
* the number of function calls made inside it and inside all the sub-called functions recursively
* the function return value.
NB: The call to the function itself is not counted.
HINT: The sys module may come in handy. | import sys
calls = 0
orig_func = ""
def profiler(frame, event, arg):
nonlocal calls
if event == "call":
if frame.f_code.co_name != orig_func:
calls += 1
return profiler
def count_calls(func, *args, **kwargs):
nonlocal orig_func
nonlocal calls
sys.settrace(profiler)
orig_func = func
rv = func(*args, **kwargs)
count = calls - 1
sys.settrace(None)
calls = 0
orig_func = ""
return count, rv | IMPORT ASSIGN VAR NUMBER ASSIGN VAR STRING FUNC_DEF IF VAR STRING IF VAR VAR VAR NUMBER RETURN VAR FUNC_DEF EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR NONE ASSIGN VAR NUMBER ASSIGN VAR STRING RETURN VAR VAR |
The aim of this kata is to determine the number of sub-function calls made by an unknown function.
You have to write a function named `count_calls` which:
* takes as parameter a function and its arguments (args, kwargs)
* calls the function
* returns a tuple containing:
* the number of function calls made inside it and inside all the sub-called functions recursively
* the function return value.
NB: The call to the function itself is not counted.
HINT: The sys module may come in handy. | import sys
def count_calls(func, *args, **kwargs):
def tracefunc(frame, event, arg):
nonlocal calls
if event == "call":
calls += 1
return tracefunc
calls = -1
sys.settrace(tracefunc)
rv = func(*args, **kwargs)
return calls, rv | IMPORT FUNC_DEF FUNC_DEF IF VAR STRING VAR NUMBER RETURN VAR ASSIGN VAR NUMBER EXPR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN VAR VAR |
The aim of this kata is to determine the number of sub-function calls made by an unknown function.
You have to write a function named `count_calls` which:
* takes as parameter a function and its arguments (args, kwargs)
* calls the function
* returns a tuple containing:
* the number of function calls made inside it and inside all the sub-called functions recursively
* the function return value.
NB: The call to the function itself is not counted.
HINT: The sys module may come in handy. | import sys
calls = 0
def trace(frame, event, arg):
nonlocal calls
if event == "call":
calls += 1
sys.settrace(trace)
def count_calls(func, *args, **kwargs):
nonlocal calls
calls = -1
result = func(*args, **kwargs)
return calls, result | IMPORT ASSIGN VAR NUMBER FUNC_DEF IF VAR STRING VAR NUMBER EXPR FUNC_CALL VAR VAR FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN VAR VAR |
The aim of this kata is to determine the number of sub-function calls made by an unknown function.
You have to write a function named `count_calls` which:
* takes as parameter a function and its arguments (args, kwargs)
* calls the function
* returns a tuple containing:
* the number of function calls made inside it and inside all the sub-called functions recursively
* the function return value.
NB: The call to the function itself is not counted.
HINT: The sys module may come in handy. | import sys
def count_calls(func, *args, **kwargs):
tracer = Tracer()
sys.settrace(tracer.my_tracer)
rv = func(*args, **kwargs)
return tracer.count, rv
class Tracer:
count: int = -1
def my_tracer(self, frame, event, arg=None):
if event == "call":
self.count += 1
return self.my_tracer | IMPORT FUNC_DEF ASSIGN VAR FUNC_CALL VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN VAR VAR CLASS_DEF VAR VAR NUMBER FUNC_DEF NONE IF VAR STRING VAR NUMBER RETURN VAR |
The aim of this kata is to determine the number of sub-function calls made by an unknown function.
You have to write a function named `count_calls` which:
* takes as parameter a function and its arguments (args, kwargs)
* calls the function
* returns a tuple containing:
* the number of function calls made inside it and inside all the sub-called functions recursively
* the function return value.
NB: The call to the function itself is not counted.
HINT: The sys module may come in handy. | import sys
def count_calls(func, *args, **kwargs):
tracer = Tracer(func)
sys.settrace(tracer.my_tracer)
rv = func(*args, **kwargs)
return tracer.count, rv
class Tracer:
count: int = 0
func_name: str
recursive: bool = False
def __init__(self, func: callable):
self.func_name = func.__name__
def my_tracer(self, frame, event, arg=None):
func_name = frame.f_code.co_name
if event == "call" and (self.recursive or func_name != self.func_name):
self.count += 1
elif func_name == self.func_name and not self.recursive:
self.recursive = True
return self.my_tracer | IMPORT FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN VAR VAR CLASS_DEF VAR VAR NUMBER VAR VAR VAR VAR NUMBER FUNC_DEF VAR ASSIGN VAR VAR FUNC_DEF NONE ASSIGN VAR VAR IF VAR STRING VAR VAR VAR VAR NUMBER IF VAR VAR VAR ASSIGN VAR NUMBER RETURN VAR |
The aim of this kata is to determine the number of sub-function calls made by an unknown function.
You have to write a function named `count_calls` which:
* takes as parameter a function and its arguments (args, kwargs)
* calls the function
* returns a tuple containing:
* the number of function calls made inside it and inside all the sub-called functions recursively
* the function return value.
NB: The call to the function itself is not counted.
HINT: The sys module may come in handy. | import sys
def count_calls(func, *args, **kwargs):
def handler(_, line, k):
handler.count += int(line == "call")
handler.__dict__["count"] = 0
sys.settrace(handler)
rv = func(*args, **kwargs)
return handler.count - 1, rv | IMPORT FUNC_DEF FUNC_DEF VAR FUNC_CALL VAR VAR STRING ASSIGN VAR STRING NUMBER EXPR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN BIN_OP VAR NUMBER VAR |
You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d.
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. The binary tree is such a tree that no vertex has more than 2 children.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 1000) β the number of test cases.
The only line of each test case contains two integers n and d (2 β€ n, d β€ 5000) β the number of vertices in the tree and the required sum of depths of all vertices.
It is guaranteed that the sum of n and the sum of d both does not exceed 5000 (β n β€ 5000, β d β€ 5000).
Output
For each test case, print the answer.
If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n-1 integers p_2, p_3, ..., p_n in the second line, where p_i is the parent of the vertex i. Note that the sequence of parents you print should describe some binary tree.
Example
Input
3
5 7
10 19
10 18
Output
YES
1 2 1 3
YES
1 2 3 3 9 9 2 1 6
NO
Note
Pictures corresponding to the first and the second test cases of the example:
<image>
<image> | import sys
sys.setrecursionlimit(10**6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II():
return int(sys.stdin.readline())
def MI():
return map(int, sys.stdin.readline().split())
def LI():
return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number):
return [LI() for _ in range(rows_number)]
def SI():
return sys.stdin.readline()[:-1]
def main():
t = II()
for _ in range(t):
n, d = MI()
s = n * (n - 1) // 2
diff = s - d
if d > s:
print("NO")
continue
aa = [1] * n
l = 1
for r in range(n - 1, -1, -1):
if l >= r:
break
if diff == 0:
break
to = max(r - diff, l)
aa[r] = 0
aa[to] += 1
diff -= r - to
if aa[l] == 1 << l:
l += 1
if diff:
print("NO")
continue
ans = []
pa = 1
st = 1
for a in aa[1:]:
for i in range(a):
ans.append(st + i % pa)
st += pa
pa = a
print("YES")
print(*ans)
main() | IMPORT EXPR FUNC_CALL VAR BIN_OP NUMBER NUMBER ASSIGN VAR BIN_OP FUNC_CALL VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR STRING FUNC_DEF RETURN FUNC_CALL VAR FUNC_CALL VAR FUNC_DEF RETURN FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR FUNC_DEF RETURN FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR FUNC_DEF RETURN FUNC_CALL VAR VAR FUNC_CALL VAR VAR FUNC_DEF RETURN FUNC_CALL VAR NUMBER FUNC_DEF ASSIGN VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR ASSIGN VAR BIN_OP BIN_OP VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR BIN_OP VAR VAR IF VAR VAR EXPR FUNC_CALL VAR STRING ASSIGN VAR BIN_OP LIST NUMBER VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER NUMBER NUMBER IF VAR VAR IF VAR NUMBER ASSIGN VAR FUNC_CALL VAR BIN_OP VAR VAR VAR ASSIGN VAR VAR NUMBER VAR VAR NUMBER VAR BIN_OP VAR VAR IF VAR VAR BIN_OP NUMBER VAR VAR NUMBER IF VAR EXPR FUNC_CALL VAR STRING ASSIGN VAR LIST ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR NUMBER FOR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR BIN_OP VAR VAR VAR VAR ASSIGN VAR VAR EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR |
You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d.
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. The binary tree is such a tree that no vertex has more than 2 children.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 1000) β the number of test cases.
The only line of each test case contains two integers n and d (2 β€ n, d β€ 5000) β the number of vertices in the tree and the required sum of depths of all vertices.
It is guaranteed that the sum of n and the sum of d both does not exceed 5000 (β n β€ 5000, β d β€ 5000).
Output
For each test case, print the answer.
If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n-1 integers p_2, p_3, ..., p_n in the second line, where p_i is the parent of the vertex i. Note that the sequence of parents you print should describe some binary tree.
Example
Input
3
5 7
10 19
10 18
Output
YES
1 2 1 3
YES
1 2 3 3 9 9 2 1 6
NO
Note
Pictures corresponding to the first and the second test cases of the example:
<image>
<image> | for tests in range(int(input())):
n, d = map(int, input().split())
upper_bound, lower_bound, lv = n * (n - 1) // 2, 0, 0
for i in range(1, n + 1):
if not i & i - 1:
lv += 1
lower_bound += lv - 1
if not d in range(lower_bound, upper_bound + 1):
print("NO")
else:
bad = [False] * n
depth = list(range(n))
count_child = [1] * n
count_child[n - 1] = 0
current_depth = upper_bound
parent = list(range(-1, n - 1))
while current_depth > d:
v = -1
for i in range(n):
if (
not bad[i]
and count_child[i] == 0
and (v == -1 or depth[i] < depth[v])
):
v = i
if v == -1:
break
p = -1
for i in range(n):
if (
count_child[i] < 2
and depth[i] == depth[v] - 2
and (p == -1 or depth[i] > depth[p])
):
p = i
if p == -1:
bad[v] = True
continue
count_child[parent[v]] -= 1
depth[v] -= 1
count_child[p] += 1
parent[v] = p
current_depth -= 1
if current_depth == d:
print("YES")
for i in range(1, n):
print(parent[i] + 1, end=" ")
print()
else:
print("NO") | FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR VAR VAR BIN_OP BIN_OP VAR BIN_OP VAR NUMBER NUMBER NUMBER NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER IF BIN_OP VAR BIN_OP VAR NUMBER VAR NUMBER VAR BIN_OP VAR NUMBER IF VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR STRING ASSIGN VAR BIN_OP LIST NUMBER VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST NUMBER VAR ASSIGN VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER WHILE VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR NUMBER VAR NUMBER VAR VAR VAR VAR ASSIGN VAR VAR IF VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR NUMBER VAR VAR BIN_OP VAR VAR NUMBER VAR NUMBER VAR VAR VAR VAR ASSIGN VAR VAR IF VAR NUMBER ASSIGN VAR VAR NUMBER VAR VAR VAR NUMBER VAR VAR NUMBER VAR VAR NUMBER ASSIGN VAR VAR VAR VAR NUMBER IF VAR VAR EXPR FUNC_CALL VAR STRING FOR VAR FUNC_CALL VAR NUMBER VAR EXPR FUNC_CALL VAR BIN_OP VAR VAR NUMBER STRING EXPR FUNC_CALL VAR EXPR FUNC_CALL VAR STRING |
You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d.
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. The binary tree is such a tree that no vertex has more than 2 children.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 1000) β the number of test cases.
The only line of each test case contains two integers n and d (2 β€ n, d β€ 5000) β the number of vertices in the tree and the required sum of depths of all vertices.
It is guaranteed that the sum of n and the sum of d both does not exceed 5000 (β n β€ 5000, β d β€ 5000).
Output
For each test case, print the answer.
If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n-1 integers p_2, p_3, ..., p_n in the second line, where p_i is the parent of the vertex i. Note that the sequence of parents you print should describe some binary tree.
Example
Input
3
5 7
10 19
10 18
Output
YES
1 2 1 3
YES
1 2 3 3 9 9 2 1 6
NO
Note
Pictures corresponding to the first and the second test cases of the example:
<image>
<image> | import sys
input = sys.stdin.readline
t = int(input())
for tests in range(t):
n, d = map(int, input().split())
MIN = sum([(i.bit_length() - 1) for i in range(1, n + 1)])
MAX = (n - 1) * n // 2
if MIN <= d <= MAX:
print("YES")
else:
print("NO")
continue
TREE = [(i // 2) for i in range(n + 1)]
STEM = [(1 << i) for i in range(n.bit_length())]
SETSTEM = set(STEM)
rest = d - MIN
for x in range(n, -1, -1):
if x in SETSTEM:
continue
if rest == 0:
break
now_height = x.bit_length() - 1
max_height = len(STEM)
if rest > max_height - now_height:
rest -= max_height - now_height
TREE[x] = STEM[-1]
STEM.append(x)
else:
TREE[x] = STEM[now_height + rest - 1]
break
print(*TREE[2:]) | IMPORT ASSIGN VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR BIN_OP FUNC_CALL VAR NUMBER VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER ASSIGN VAR BIN_OP BIN_OP BIN_OP VAR NUMBER VAR NUMBER IF VAR VAR VAR EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING ASSIGN VAR BIN_OP VAR NUMBER VAR FUNC_CALL VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP NUMBER VAR VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR VAR FOR VAR FUNC_CALL VAR VAR NUMBER NUMBER IF VAR VAR IF VAR NUMBER ASSIGN VAR BIN_OP FUNC_CALL VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR IF VAR BIN_OP VAR VAR VAR BIN_OP VAR VAR ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR BIN_OP BIN_OP VAR VAR NUMBER EXPR FUNC_CALL VAR VAR NUMBER |
You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d.
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. The binary tree is such a tree that no vertex has more than 2 children.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 1000) β the number of test cases.
The only line of each test case contains two integers n and d (2 β€ n, d β€ 5000) β the number of vertices in the tree and the required sum of depths of all vertices.
It is guaranteed that the sum of n and the sum of d both does not exceed 5000 (β n β€ 5000, β d β€ 5000).
Output
For each test case, print the answer.
If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n-1 integers p_2, p_3, ..., p_n in the second line, where p_i is the parent of the vertex i. Note that the sequence of parents you print should describe some binary tree.
Example
Input
3
5 7
10 19
10 18
Output
YES
1 2 1 3
YES
1 2 3 3 9 9 2 1 6
NO
Note
Pictures corresponding to the first and the second test cases of the example:
<image>
<image> | t = int(input())
for loop in range(t):
n, d = map(int, input().split())
lis = [1] * n
nsum = 0
for i in range(n):
nsum += i
sub = nsum - d
if d > nsum:
print("NO")
continue
ableind = 1
pickind = n - 1
while pickind > ableind:
if sub > pickind - ableind:
lis[pickind] -= 1
lis[ableind] += 1
sub -= pickind - ableind
else:
lis[pickind] -= 1
lis[pickind - sub] += 1
sub = 0
break
if lis[ableind] == 2**ableind:
ableind += 1
if lis[pickind] == 0:
pickind -= 1
if sub > 0:
print("NO")
else:
print("YES")
ans = []
for i in range(n):
if i == 0:
ans.append([1])
ind = 2
else:
nlis = []
for j in range(lis[i]):
nlis.append(ind)
ind += 1
ans.append(nlis)
pl = []
for i in range(1, n):
for j in range(lis[i]):
pl.append(ans[i - 1][j // 2])
print(" ".join(map(str, pl))) | ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR BIN_OP LIST NUMBER VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR BIN_OP VAR VAR IF VAR VAR EXPR FUNC_CALL VAR STRING ASSIGN VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER WHILE VAR VAR IF VAR BIN_OP VAR VAR VAR VAR NUMBER VAR VAR NUMBER VAR BIN_OP VAR VAR VAR VAR NUMBER VAR BIN_OP VAR VAR NUMBER ASSIGN VAR NUMBER IF VAR VAR BIN_OP NUMBER VAR VAR NUMBER IF VAR VAR NUMBER VAR NUMBER IF VAR NUMBER EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR IF VAR NUMBER EXPR FUNC_CALL VAR LIST NUMBER ASSIGN VAR NUMBER ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR ASSIGN VAR LIST FOR VAR FUNC_CALL VAR NUMBER VAR FOR VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER EXPR FUNC_CALL VAR FUNC_CALL STRING FUNC_CALL VAR VAR VAR |
You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d.
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. The binary tree is such a tree that no vertex has more than 2 children.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 1000) β the number of test cases.
The only line of each test case contains two integers n and d (2 β€ n, d β€ 5000) β the number of vertices in the tree and the required sum of depths of all vertices.
It is guaranteed that the sum of n and the sum of d both does not exceed 5000 (β n β€ 5000, β d β€ 5000).
Output
For each test case, print the answer.
If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n-1 integers p_2, p_3, ..., p_n in the second line, where p_i is the parent of the vertex i. Note that the sequence of parents you print should describe some binary tree.
Example
Input
3
5 7
10 19
10 18
Output
YES
1 2 1 3
YES
1 2 3 3 9 9 2 1 6
NO
Note
Pictures corresponding to the first and the second test cases of the example:
<image>
<image> | t = int(input())
for _ in range(t):
n, d = map(int, input().split())
dsum = n * (n - 1) // 2
if d > dsum:
print("NO")
continue
tree = [[i] for i in range(n)]
lmin = 1
while dsum > d:
l = len(tree) - 1
while dsum > d and l > lmin:
l -= 1
dsum -= 1
if l == len(tree) - 1:
break
node = tree[-1][-1]
tree[-1].pop()
if not tree[-1]:
tree.pop()
tree[l].append(node)
if len(tree[l]) == 2**l:
lmin += 1
if dsum > d:
print("NO")
continue
print("YES")
parent = [0] * (n - 1)
for j in range(1, len(tree)):
layer = tree[j]
for i in range(len(layer)):
node = layer[i]
parent[node - 1] = tree[j - 1][i // 2] + 1
print(*parent) | ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR BIN_OP BIN_OP VAR BIN_OP VAR NUMBER NUMBER IF VAR VAR EXPR FUNC_CALL VAR STRING ASSIGN VAR LIST VAR VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER WHILE VAR VAR ASSIGN VAR BIN_OP FUNC_CALL VAR VAR NUMBER WHILE VAR VAR VAR VAR VAR NUMBER VAR NUMBER IF VAR BIN_OP FUNC_CALL VAR VAR NUMBER ASSIGN VAR VAR NUMBER NUMBER EXPR FUNC_CALL VAR NUMBER IF VAR NUMBER EXPR FUNC_CALL VAR EXPR FUNC_CALL VAR VAR VAR IF FUNC_CALL VAR VAR VAR BIN_OP NUMBER VAR VAR NUMBER IF VAR VAR EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING ASSIGN VAR BIN_OP LIST NUMBER BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER FUNC_CALL VAR VAR ASSIGN VAR VAR VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER BIN_OP VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER NUMBER EXPR FUNC_CALL VAR VAR |
You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d.
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. The binary tree is such a tree that no vertex has more than 2 children.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 1000) β the number of test cases.
The only line of each test case contains two integers n and d (2 β€ n, d β€ 5000) β the number of vertices in the tree and the required sum of depths of all vertices.
It is guaranteed that the sum of n and the sum of d both does not exceed 5000 (β n β€ 5000, β d β€ 5000).
Output
For each test case, print the answer.
If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n-1 integers p_2, p_3, ..., p_n in the second line, where p_i is the parent of the vertex i. Note that the sequence of parents you print should describe some binary tree.
Example
Input
3
5 7
10 19
10 18
Output
YES
1 2 1 3
YES
1 2 3 3 9 9 2 1 6
NO
Note
Pictures corresponding to the first and the second test cases of the example:
<image>
<image> | t = int(input())
pows = [(2**i) for i in range(21)]
for _ in range(t):
n, d = map(int, input().split())
mins = 0
for k in range(20):
if pows[k + 1] <= n:
mins += k * pows[k]
else:
mins += k * (n - (pows[k] - 1))
break
maxs = n * (n - 1) // 2
if d < mins or d > maxs:
print("NO")
else:
print("YES")
ans = [i for i in range(n)]
cnt = 1
base = 1
for i in range(n - 1, -1, -1):
if maxs - (ans[i] - base) > d:
maxs -= ans[i] - base
ans[i] = base
cnt += 1
if cnt == pows[base]:
base += 1
cnt = 1
else:
ans[i] -= maxs - d
break
ans = sorted(ans)
arr = [[] for _ in range(n + 1)]
for i in range(n):
arr[ans[i]].append(i + 1)
ret = []
for i in range(1, n + 1):
pos = 0
cnt = 0
for j in range(len(arr[i])):
ret.append(arr[i - 1][pos])
cnt += 1
if cnt == 2:
pos += 1
cnt = 0
print(*ret) | ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR BIN_OP NUMBER VAR VAR FUNC_CALL VAR NUMBER FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER IF VAR BIN_OP VAR NUMBER VAR VAR BIN_OP VAR VAR VAR VAR BIN_OP VAR BIN_OP VAR BIN_OP VAR VAR NUMBER ASSIGN VAR BIN_OP BIN_OP VAR BIN_OP VAR NUMBER NUMBER IF VAR VAR VAR VAR EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING ASSIGN VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER NUMBER NUMBER IF BIN_OP VAR BIN_OP VAR VAR VAR VAR VAR BIN_OP VAR VAR VAR ASSIGN VAR VAR VAR VAR NUMBER IF VAR VAR VAR VAR NUMBER ASSIGN VAR NUMBER VAR VAR BIN_OP VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR LIST VAR FUNC_CALL VAR BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER ASSIGN VAR LIST FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR NUMBER IF VAR NUMBER VAR NUMBER ASSIGN VAR NUMBER EXPR FUNC_CALL VAR VAR |
You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d.
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. The binary tree is such a tree that no vertex has more than 2 children.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 1000) β the number of test cases.
The only line of each test case contains two integers n and d (2 β€ n, d β€ 5000) β the number of vertices in the tree and the required sum of depths of all vertices.
It is guaranteed that the sum of n and the sum of d both does not exceed 5000 (β n β€ 5000, β d β€ 5000).
Output
For each test case, print the answer.
If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n-1 integers p_2, p_3, ..., p_n in the second line, where p_i is the parent of the vertex i. Note that the sequence of parents you print should describe some binary tree.
Example
Input
3
5 7
10 19
10 18
Output
YES
1 2 1 3
YES
1 2 3 3 9 9 2 1 6
NO
Note
Pictures corresponding to the first and the second test cases of the example:
<image>
<image> | t = int(input())
for T in range(t):
n, d = map(int, input().strip().split())
u = (n - 1) * n // 2
if d > u:
print("NO")
continue
l = t = 0
for i in range(1, 1 + n):
l += t
if not i & i + 1:
t += 1
if d < l:
print("NO")
continue
p = [1] * n
l = [(1 << i) for i in range(n)]
o = n - 1
while u > d:
m = o
while u > d and m and p[m - 1] < l[m - 1]:
m -= 1
u -= 1
p[o] -= 1
p[m] += 1
o -= 1
r = [0] * n
c = [1, 1]
t = []
v = 1
for i in range(1, n):
if not p[i]:
break
for j in range(p[i]):
r[v] = c.pop()
v += 1
t.append(v)
t.append(v)
c = t
t = []
print("YES")
print(*(r[i] for i in range(1, n))) | ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL FUNC_CALL VAR ASSIGN VAR BIN_OP BIN_OP BIN_OP VAR NUMBER VAR NUMBER IF VAR VAR EXPR FUNC_CALL VAR STRING ASSIGN VAR VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP NUMBER VAR VAR VAR IF BIN_OP VAR BIN_OP VAR NUMBER VAR NUMBER IF VAR VAR EXPR FUNC_CALL VAR STRING ASSIGN VAR BIN_OP LIST NUMBER VAR ASSIGN VAR BIN_OP NUMBER VAR VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR NUMBER WHILE VAR VAR ASSIGN VAR VAR WHILE VAR VAR VAR VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER VAR NUMBER VAR VAR NUMBER VAR VAR NUMBER VAR NUMBER ASSIGN VAR BIN_OP LIST NUMBER VAR ASSIGN VAR LIST NUMBER NUMBER ASSIGN VAR LIST ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR IF VAR VAR FOR VAR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR NUMBER EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR ASSIGN VAR LIST EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR VAR VAR VAR FUNC_CALL VAR NUMBER VAR |
You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d.
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. The binary tree is such a tree that no vertex has more than 2 children.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 1000) β the number of test cases.
The only line of each test case contains two integers n and d (2 β€ n, d β€ 5000) β the number of vertices in the tree and the required sum of depths of all vertices.
It is guaranteed that the sum of n and the sum of d both does not exceed 5000 (β n β€ 5000, β d β€ 5000).
Output
For each test case, print the answer.
If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n-1 integers p_2, p_3, ..., p_n in the second line, where p_i is the parent of the vertex i. Note that the sequence of parents you print should describe some binary tree.
Example
Input
3
5 7
10 19
10 18
Output
YES
1 2 1 3
YES
1 2 3 3 9 9 2 1 6
NO
Note
Pictures corresponding to the first and the second test cases of the example:
<image>
<image> | def solve(n, d):
arr = [[x] for x in range(1, n + 1)]
S = sum(range(1, n))
cur = 1
while S > d and cur != len(arr):
need = S - d
can = len(arr) - 1 - cur
if can < need:
S -= can
arr[cur] += arr[-1]
arr.pop()
else:
S -= need
arr[len(arr) - 1 - need] += arr[-1]
arr.pop()
if cur == len(arr):
break
elif len(arr[cur]) == 2**cur:
cur += 1
if S != d:
print("NO")
else:
print("YES")
ans = [0] * (n - 1)
for i, a in enumerate(arr):
if i == 0:
continue
for j, v in enumerate(a):
ans[v - 2] = str(arr[i - 1][j // 2])
print(" ".join(ans))
for _ in range(int(input())):
n, d = map(int, input().split())
solve(n, d) | FUNC_DEF ASSIGN VAR LIST VAR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR NUMBER VAR ASSIGN VAR NUMBER WHILE VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR VAR ASSIGN VAR BIN_OP BIN_OP FUNC_CALL VAR VAR NUMBER VAR IF VAR VAR VAR VAR VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR VAR BIN_OP BIN_OP FUNC_CALL VAR VAR NUMBER VAR VAR NUMBER EXPR FUNC_CALL VAR IF VAR FUNC_CALL VAR VAR IF FUNC_CALL VAR VAR VAR BIN_OP NUMBER VAR VAR NUMBER IF VAR VAR EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING ASSIGN VAR BIN_OP LIST NUMBER BIN_OP VAR NUMBER FOR VAR VAR FUNC_CALL VAR VAR IF VAR NUMBER FOR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR NUMBER FUNC_CALL VAR VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER EXPR FUNC_CALL VAR FUNC_CALL STRING VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR EXPR FUNC_CALL VAR VAR VAR |
You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d.
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. The binary tree is such a tree that no vertex has more than 2 children.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 1000) β the number of test cases.
The only line of each test case contains two integers n and d (2 β€ n, d β€ 5000) β the number of vertices in the tree and the required sum of depths of all vertices.
It is guaranteed that the sum of n and the sum of d both does not exceed 5000 (β n β€ 5000, β d β€ 5000).
Output
For each test case, print the answer.
If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n-1 integers p_2, p_3, ..., p_n in the second line, where p_i is the parent of the vertex i. Note that the sequence of parents you print should describe some binary tree.
Example
Input
3
5 7
10 19
10 18
Output
YES
1 2 1 3
YES
1 2 3 3 9 9 2 1 6
NO
Note
Pictures corresponding to the first and the second test cases of the example:
<image>
<image> | for _ in range(int(input())):
n, d = map(int, input().split())
ld, rd = 0, n * (n - 1) // 2
tn = n
cd = 0
mvl = 1
while tn:
vl = min(tn, mvl)
ld += cd * vl
cd += 1
tn -= vl
mvl *= 2
if not ld <= d <= rd:
print("NO")
continue
parent = [(i - 1) for i in range(n)]
bad = [False] * n
deep = [i for i in range(n)]
child = [1] * n
child[-1] = 0
cur = rd
while cur > d:
v = None
for i in range(n):
if not bad[i] and not child[i] and (v is None or deep[i] < deep[v]):
v = i
p = None
for i in range(n):
if (
child[i] < 2
and deep[i] == deep[v] - 2
and (p is None or deep[i] > deep[p])
):
p = i
if p is None:
bad[v] = True
else:
child[parent[v]] -= 1
deep[v] -= 1
child[p] += 1
parent[v] = p
cur -= 1
print("YES")
print(*map(lambda x: x + 1, parent[1:])) | FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR VAR NUMBER BIN_OP BIN_OP VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR VAR ASSIGN VAR NUMBER ASSIGN VAR NUMBER WHILE VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR BIN_OP VAR VAR VAR NUMBER VAR VAR VAR NUMBER IF VAR VAR VAR EXPR FUNC_CALL VAR STRING ASSIGN VAR BIN_OP VAR NUMBER VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST NUMBER VAR ASSIGN VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST NUMBER VAR ASSIGN VAR NUMBER NUMBER ASSIGN VAR VAR WHILE VAR VAR ASSIGN VAR NONE FOR VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR VAR NONE VAR VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR NONE FOR VAR FUNC_CALL VAR VAR IF VAR VAR NUMBER VAR VAR BIN_OP VAR VAR NUMBER VAR NONE VAR VAR VAR VAR ASSIGN VAR VAR IF VAR NONE ASSIGN VAR VAR NUMBER VAR VAR VAR NUMBER VAR VAR NUMBER VAR VAR NUMBER ASSIGN VAR VAR VAR VAR NUMBER EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR FUNC_CALL VAR BIN_OP VAR NUMBER VAR NUMBER |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
def findPath(self, m, n):
ans = ""
ds = []
dI = [+1, 0, 0, -1]
dJ = [0, -1, +1, 0]
def path(i, j, ans, vis):
if i == n - 1 and j == n - 1:
ds.append(ans)
return
dir = "DLRU"
for k in range(4):
nexti = i + dI[k]
nextj = j + dJ[k]
if (
nexti >= 0
and nextj >= 0
and nexti < n
and nextj < n
and not vis[nexti][nextj]
and m[nexti][nextj] == 1
):
vis[i][j] = 1
path(nexti, nextj, ans + dir[k], vis)
vis[i][j] = 0
vis = [[(0) for _ in range(n)] for _ in range(n)]
if m[0][0] == 1:
path(0, 0, ans, vis)
return ds | CLASS_DEF FUNC_DEF ASSIGN VAR STRING ASSIGN VAR LIST ASSIGN VAR LIST NUMBER NUMBER NUMBER NUMBER ASSIGN VAR LIST NUMBER NUMBER NUMBER NUMBER FUNC_DEF IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN ASSIGN VAR STRING FOR VAR FUNC_CALL VAR NUMBER ASSIGN VAR BIN_OP VAR VAR VAR ASSIGN VAR BIN_OP VAR VAR VAR IF VAR NUMBER VAR NUMBER VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR BIN_OP VAR VAR VAR VAR ASSIGN VAR VAR VAR NUMBER ASSIGN VAR NUMBER VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR IF VAR NUMBER NUMBER NUMBER EXPR FUNC_CALL VAR NUMBER NUMBER VAR VAR RETURN VAR |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
@staticmethod
def findAllPaths(m, n, i, j, ans, path):
if i < 0 or j < 0 or i >= n or j >= n or not m[i][j]:
return ans
if i == n - 1 and j == n - 1:
ans.append(path)
return
m[i][j] = 0
Solution.findAllPaths(m, n, i + 1, j, ans, path + "D")
Solution.findAllPaths(m, n, i, j + 1, ans, path + "R")
Solution.findAllPaths(m, n, i - 1, j, ans, path + "U")
Solution.findAllPaths(m, n, i, j - 1, ans, path + "L")
m[i][j] = 1
return ans
def findPath(self, m, n):
paths = Solution.findAllPaths(m, n, 0, 0, [], "")
return paths | CLASS_DEF FUNC_DEF IF VAR NUMBER VAR NUMBER VAR VAR VAR VAR VAR VAR VAR RETURN VAR IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER VAR VAR BIN_OP VAR STRING EXPR FUNC_CALL VAR VAR VAR VAR BIN_OP VAR NUMBER VAR BIN_OP VAR STRING EXPR FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER VAR VAR BIN_OP VAR STRING EXPR FUNC_CALL VAR VAR VAR VAR BIN_OP VAR NUMBER VAR BIN_OP VAR STRING ASSIGN VAR VAR VAR NUMBER RETURN VAR VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR VAR NUMBER NUMBER LIST STRING RETURN VAR |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | import sys
class Solution:
def findPath(self, m, n):
if m[0][0] == 0:
return [-1]
import sys
sys.setrecursionlimit(10**9)
visited = [[(False) for j in range(n)] for i in range(n)]
dx = [1, 0, 0, -1]
dy = [0, -1, 1, 0]
d = ["D", "L", "R", "U"]
result = []
temp = []
visited[0][0] = True
self.solve(0, 0, m, n, visited, dx, dy, d, result, temp)
return result
def solve(self, i, j, m, n, visited, dx, dy, d, result, temp):
if i == n - 1 and j == n - 1:
st = "".join(temp)
result.append(st)
return
for r in range(4):
x = i + dx[r]
y = j + dy[r]
if (
x >= 0
and x < n
and y >= 0
and y < n
and m[x][y] == 1
and not visited[x][y]
):
visited[x][y] = True
temp.append(d[r])
self.solve(x, y, m, n, visited, dx, dy, d, result, temp)
visited[x][y] = False
temp.pop() | IMPORT CLASS_DEF FUNC_DEF IF VAR NUMBER NUMBER NUMBER RETURN LIST NUMBER IMPORT EXPR FUNC_CALL VAR BIN_OP NUMBER NUMBER ASSIGN VAR NUMBER VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR LIST NUMBER NUMBER NUMBER NUMBER ASSIGN VAR LIST NUMBER NUMBER NUMBER NUMBER ASSIGN VAR LIST STRING STRING STRING STRING ASSIGN VAR LIST ASSIGN VAR LIST ASSIGN VAR NUMBER NUMBER NUMBER EXPR FUNC_CALL VAR NUMBER NUMBER VAR VAR VAR VAR VAR VAR VAR VAR RETURN VAR FUNC_DEF IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER ASSIGN VAR FUNC_CALL STRING VAR EXPR FUNC_CALL VAR VAR RETURN FOR VAR FUNC_CALL VAR NUMBER ASSIGN VAR BIN_OP VAR VAR VAR ASSIGN VAR BIN_OP VAR VAR VAR IF VAR NUMBER VAR VAR VAR NUMBER VAR VAR VAR VAR VAR NUMBER VAR VAR VAR ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
def __init__(self):
self.ans = []
def findPath(self, m, n):
self.util(n, m, 0, 0, [])
return self.ans
def util(self, n, m, x, y, path):
if x == n - 1 and y == n - 1 and m[x][y] == 1:
self.ans.append("".join(path))
return
if not 0 <= x < n or not 0 <= y < n or m[x][y] == 0:
return
else:
m[x][y] = 0
self.util(n, m, x + 1, y, [*path, "D"])
self.util(n, m, x - 1, y, [*path, "U"])
self.util(n, m, x, y + 1, [*path, "R"])
self.util(n, m, x, y - 1, [*path, "L"])
m[x][y] = 1
return | CLASS_DEF FUNC_DEF ASSIGN VAR LIST FUNC_DEF EXPR FUNC_CALL VAR VAR VAR NUMBER NUMBER LIST RETURN VAR FUNC_DEF IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER VAR VAR VAR NUMBER EXPR FUNC_CALL VAR FUNC_CALL STRING VAR RETURN IF NUMBER VAR VAR NUMBER VAR VAR VAR VAR VAR NUMBER RETURN ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER VAR LIST VAR STRING EXPR FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER VAR LIST VAR STRING EXPR FUNC_CALL VAR VAR VAR VAR BIN_OP VAR NUMBER LIST VAR STRING EXPR FUNC_CALL VAR VAR VAR VAR BIN_OP VAR NUMBER LIST VAR STRING ASSIGN VAR VAR VAR NUMBER RETURN |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
def getAns(self, m, n, i, j, res, ans):
if i == n - 1 and j == n - 1:
res.append(ans)
return
if i < 0 or j < 0 or j >= n or i >= n or m[i][j] == 0:
return
c = m[i][j]
m[i][j] = 0
top = self.getAns(m, n, i - 1, j, res, ans + "U")
left = self.getAns(m, n, i, j - 1, res, ans + "L")
right = self.getAns(m, n, i, j + 1, res, ans + "R")
bot = self.getAns(m, n, i + 1, j, res, ans + "D")
m[i][j] = c
def findPath(self, m, n):
if m[n - 1][n - 1] == 0 or m[0][0] == 0:
return [-1]
res = []
self.getAns(m, n, 0, 0, res, "")
if len(res) > 0:
return res
else:
return [-1] | CLASS_DEF FUNC_DEF IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN IF VAR NUMBER VAR NUMBER VAR VAR VAR VAR VAR VAR VAR NUMBER RETURN ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER VAR VAR BIN_OP VAR STRING ASSIGN VAR FUNC_CALL VAR VAR VAR VAR BIN_OP VAR NUMBER VAR BIN_OP VAR STRING ASSIGN VAR FUNC_CALL VAR VAR VAR VAR BIN_OP VAR NUMBER VAR BIN_OP VAR STRING ASSIGN VAR FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER VAR VAR BIN_OP VAR STRING ASSIGN VAR VAR VAR VAR FUNC_DEF IF VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER NUMBER VAR NUMBER NUMBER NUMBER RETURN LIST NUMBER ASSIGN VAR LIST EXPR FUNC_CALL VAR VAR VAR NUMBER NUMBER VAR STRING IF FUNC_CALL VAR VAR NUMBER RETURN VAR RETURN LIST NUMBER |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
def findPath(self, m, n):
if n == 0 or m[0][0] == 0 or m[n - 1][n - 1] == 0:
return [-1]
moves = [(-1, 0, "U"), (1, 0, "D"), (0, -1, "L"), (0, 1, "R")]
result = []
def dfs(r, c, slate):
if r < 0 or r >= n or c < 0 or c >= n or m[r][c] != 1:
return
if r == n - 1 and c == n - 1:
result.append(slate)
for i, j, Dir in moves:
m[r][c] = 2
dfs(r + i, c + j, slate + Dir)
m[r][c] = 1
dfs(0, 0, "")
if result:
return result
else:
return [-1] | CLASS_DEF FUNC_DEF IF VAR NUMBER VAR NUMBER NUMBER NUMBER VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER NUMBER RETURN LIST NUMBER ASSIGN VAR LIST NUMBER NUMBER STRING NUMBER NUMBER STRING NUMBER NUMBER STRING NUMBER NUMBER STRING ASSIGN VAR LIST FUNC_DEF IF VAR NUMBER VAR VAR VAR NUMBER VAR VAR VAR VAR VAR NUMBER RETURN IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR FOR VAR VAR VAR VAR ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR VAR BIN_OP VAR VAR BIN_OP VAR VAR ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR NUMBER NUMBER STRING IF VAR RETURN VAR RETURN LIST NUMBER |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
def findPath(self, m, n):
res = []
visited = [[(0) for i in range(n)] for j in range(n)]
i = j = 0
if m[i][j] == 1:
self.func(m, n, i, j, "", res, visited)
return res
def func(self, m, n, i, j, sub, res, visited):
if i == n - 1 and j == n - 1:
res.append(sub)
return
if i + 1 < n and not visited[i + 1][j] and m[i + 1][j] == 1:
visited[i][j] = 1
self.func(m, n, i + 1, j, sub + "D", res, visited)
visited[i][j] = 0
if j - 1 >= 0 and not visited[i][j - 1] and m[i][j - 1] == 1:
visited[i][j] = 1
self.func(m, n, i, j - 1, sub + "L", res, visited)
visited[i][j] = 0
if j + 1 < n and not visited[i][j + 1] and m[i][j + 1] == 1:
visited[i][j] = 1
self.func(m, n, i, j + 1, sub + "R", res, visited)
visited[i][j] = 0
if i - 1 >= 0 and not visited[i - 1][j] and m[i - 1][j] == 1:
visited[i][j] = 1
self.func(m, n, i - 1, j, sub + "U", res, visited)
visited[i][j] = 0 | CLASS_DEF FUNC_DEF ASSIGN VAR LIST ASSIGN VAR NUMBER VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR NUMBER IF VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR VAR VAR STRING VAR VAR RETURN VAR FUNC_DEF IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN IF BIN_OP VAR NUMBER VAR VAR BIN_OP VAR NUMBER VAR VAR BIN_OP VAR NUMBER VAR NUMBER ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER VAR BIN_OP VAR STRING VAR VAR ASSIGN VAR VAR VAR NUMBER IF BIN_OP VAR NUMBER NUMBER VAR VAR BIN_OP VAR NUMBER VAR VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR VAR BIN_OP VAR NUMBER BIN_OP VAR STRING VAR VAR ASSIGN VAR VAR VAR NUMBER IF BIN_OP VAR NUMBER VAR VAR VAR BIN_OP VAR NUMBER VAR VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR VAR BIN_OP VAR NUMBER BIN_OP VAR STRING VAR VAR ASSIGN VAR VAR VAR NUMBER IF BIN_OP VAR NUMBER NUMBER VAR BIN_OP VAR NUMBER VAR VAR BIN_OP VAR NUMBER VAR NUMBER ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER VAR BIN_OP VAR STRING VAR VAR ASSIGN VAR VAR VAR NUMBER |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
def findPath(self, m, n):
if m[n - 1][n - 1] == 0 or m[0][0] == 0:
return []
lst = []
visited = [[(0) for i in range(n)] for j in range(n)]
self.dfs(0, 0, m, visited, lst, "", n)
return lst
def dfs(self, i, j, m, visited, lst, ans, n):
if i == n - 1 and j == n - 1:
lst.append(ans)
return
if i > 0 and m[i - 1][j] == 1 and visited[i - 1][j] == 0:
visited[i][j] = 1
self.dfs(i - 1, j, m, visited, lst, ans + "U", n)
visited[i][j] = 0
if i < n - 1 and m[i + 1][j] == 1 and visited[i + 1][j] == 0:
visited[i][j] = 1
self.dfs(i + 1, j, m, visited, lst, ans + "D", n)
visited[i][j] = 0
if j > 0 and m[i][j - 1] == 1 and visited[i][j - 1] == 0:
visited[i][j] = 1
self.dfs(i, j - 1, m, visited, lst, ans + "L", n)
visited[i][j] = 0
if j < n - 1 and m[i][j + 1] == 1 and visited[i][j + 1] == 0:
visited[i][j] = 1
self.dfs(i, j + 1, m, visited, lst, ans + "R", n)
visited[i][j] = 0 | CLASS_DEF FUNC_DEF IF VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER NUMBER VAR NUMBER NUMBER NUMBER RETURN LIST ASSIGN VAR LIST ASSIGN VAR NUMBER VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR NUMBER NUMBER VAR VAR VAR STRING VAR RETURN VAR FUNC_DEF IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN IF VAR NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR VAR VAR BIN_OP VAR STRING VAR ASSIGN VAR VAR VAR NUMBER IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR VAR VAR BIN_OP VAR STRING VAR ASSIGN VAR VAR VAR NUMBER IF VAR NUMBER VAR VAR BIN_OP VAR NUMBER NUMBER VAR VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR VAR BIN_OP VAR STRING VAR ASSIGN VAR VAR VAR NUMBER IF VAR BIN_OP VAR NUMBER VAR VAR BIN_OP VAR NUMBER NUMBER VAR VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR VAR BIN_OP VAR STRING VAR ASSIGN VAR VAR VAR NUMBER |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
def f(self, i, j, mat, n, ans, vis, s):
if i == n - 1 and j == n - 1:
ans.append("".join(s))
return
if i < n - 1:
if mat[i + 1][j] == 1 and vis[i + 1][j] == 0:
s.append("D")
vis[i + 1][j] = 1
self.f(i + 1, j, mat, n, ans, vis, s)
s.pop()
vis[i + 1][j] = 0
if j > 0:
if mat[i][j - 1] == 1 and vis[i][j - 1] == 0:
s.append("L")
vis[i][j - 1] = 1
self.f(i, j - 1, mat, n, ans, vis, s)
s.pop()
vis[i][j - 1] = 0
if j < n - 1:
if mat[i][j + 1] == 1 and vis[i][j + 1] == 0:
s.append("R")
vis[i][j + 1] = 1
self.f(i, j + 1, mat, n, ans, vis, s)
s.pop()
vis[i][j + 1] = 0
if i > 0:
if mat[i - 1][j] == 1 and vis[i - 1][j] == 0:
s.append("U")
vis[i - 1][j] = 1
self.f(i - 1, j, mat, n, ans, vis, s)
s.pop()
vis[i - 1][j] = 0
def findPath(self, m, n):
ans = []
if m[0][0] == 0 or m[n - 1][n - 1] == 0:
return ans
vis = []
for i in range(n):
a = []
for j in range(n):
a.append(0)
vis.append(a)
vis[0][0] = 1
self.f(0, 0, m, n, ans, vis, [])
return ans | CLASS_DEF FUNC_DEF IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR FUNC_CALL STRING VAR RETURN IF VAR BIN_OP VAR NUMBER IF VAR BIN_OP VAR NUMBER VAR NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR STRING ASSIGN VAR BIN_OP VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR BIN_OP VAR NUMBER VAR NUMBER IF VAR NUMBER IF VAR VAR BIN_OP VAR NUMBER NUMBER VAR VAR BIN_OP VAR NUMBER NUMBER EXPR FUNC_CALL VAR STRING ASSIGN VAR VAR BIN_OP VAR NUMBER NUMBER EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR VAR BIN_OP VAR NUMBER NUMBER IF VAR BIN_OP VAR NUMBER IF VAR VAR BIN_OP VAR NUMBER NUMBER VAR VAR BIN_OP VAR NUMBER NUMBER EXPR FUNC_CALL VAR STRING ASSIGN VAR VAR BIN_OP VAR NUMBER NUMBER EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR VAR BIN_OP VAR NUMBER NUMBER IF VAR NUMBER IF VAR BIN_OP VAR NUMBER VAR NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR STRING ASSIGN VAR BIN_OP VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR BIN_OP VAR NUMBER VAR NUMBER FUNC_DEF ASSIGN VAR LIST IF VAR NUMBER NUMBER NUMBER VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER NUMBER RETURN VAR ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR NUMBER EXPR FUNC_CALL VAR VAR ASSIGN VAR NUMBER NUMBER NUMBER EXPR FUNC_CALL VAR NUMBER NUMBER VAR VAR VAR VAR LIST RETURN VAR |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
ans = []
arr = []
def gen(self, grid, n, i, j, visited):
if i == n - 1 and j == n - 1:
g = self.arr.copy()
self.ans.append("".join(g))
return
visited[i][j] = 1
if i - 1 >= 0 and visited[i - 1][j] == 0 and grid[i - 1][j] == 1:
visited[i - 1][j] = 1
self.arr.append("U")
self.gen(grid, n, i - 1, j, visited)
self.arr.pop()
visited[i - 1][j] = 0
if j - 1 >= 0 and visited[i][j - 1] == 0 and grid[i][j - 1] == 1:
visited[i][j - 1] = 1
self.arr.append("L")
self.gen(grid, n, i, j - 1, visited)
self.arr.pop()
visited[i][j - 1] = 0
if i + 1 < n and visited[i + 1][j] == 0 and grid[i + 1][j] == 1:
visited[i + 1][j] = 1
self.arr.append("D")
self.gen(grid, n, i + 1, j, visited)
self.arr.pop()
visited[i + 1][j] = 0
if j + 1 < n and visited[i][j + 1] == 0 and grid[i][j + 1] == 1:
visited[i][j + 1] = 1
self.arr.append("R")
self.gen(grid, n, i, j + 1, visited)
self.arr.pop()
visited[i][j + 1] = 0
visited[i][j] = 0
def findPath(self, m, n):
self.ans = []
self.arr = []
visited = []
for i in range(n):
a = []
for j in range(n):
a.append(0)
visited.append(a)
if m[0][0] == 1:
self.gen(m, n, 0, 0, visited)
if len(self.ans) == 0:
return [-1]
return self.ans | CLASS_DEF ASSIGN VAR LIST ASSIGN VAR LIST FUNC_DEF IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER ASSIGN VAR FUNC_CALL VAR EXPR FUNC_CALL VAR FUNC_CALL STRING VAR RETURN ASSIGN VAR VAR VAR NUMBER IF BIN_OP VAR NUMBER NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR BIN_OP VAR NUMBER VAR NUMBER IF BIN_OP VAR NUMBER NUMBER VAR VAR BIN_OP VAR NUMBER NUMBER VAR VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR VAR BIN_OP VAR NUMBER NUMBER EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR VAR VAR VAR BIN_OP VAR NUMBER VAR EXPR FUNC_CALL VAR ASSIGN VAR VAR BIN_OP VAR NUMBER NUMBER IF BIN_OP VAR NUMBER VAR VAR BIN_OP VAR NUMBER VAR NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR BIN_OP VAR NUMBER VAR NUMBER IF BIN_OP VAR NUMBER VAR VAR VAR BIN_OP VAR NUMBER NUMBER VAR VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR VAR BIN_OP VAR NUMBER NUMBER EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR VAR VAR VAR BIN_OP VAR NUMBER VAR EXPR FUNC_CALL VAR ASSIGN VAR VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR VAR VAR NUMBER FUNC_DEF ASSIGN VAR LIST ASSIGN VAR LIST ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR NUMBER EXPR FUNC_CALL VAR VAR IF VAR NUMBER NUMBER NUMBER EXPR FUNC_CALL VAR VAR VAR NUMBER NUMBER VAR IF FUNC_CALL VAR VAR NUMBER RETURN LIST NUMBER RETURN VAR |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
def findPath(self, m, n):
result = []
getPaths(m, n, result, "", 0, 0)
return result
def getPaths(m, n, result, temp, r, c):
if m[r][c] != 1:
return
m[r][c] = 2
if r == n - 1 and c == n - 1:
result.append(temp)
nbrs = getNeighbours(m, r, c)
for row, col, dir in nbrs:
getPaths(m, n, result, temp + dir, row, col)
m[r][c] = 1
def getNeighbours(m, r, c):
nbrs = []
if r > 0:
nbrs.append((r - 1, c, "U"))
if r < len(m) - 1:
nbrs.append((r + 1, c, "D"))
if c > 0:
nbrs.append((r, c - 1, "L"))
if c < len(m[0]) - 1:
nbrs.append((r, c + 1, "R"))
return nbrs | CLASS_DEF FUNC_DEF ASSIGN VAR LIST EXPR FUNC_CALL VAR VAR VAR VAR STRING NUMBER NUMBER RETURN VAR FUNC_DEF IF VAR VAR VAR NUMBER RETURN ASSIGN VAR VAR VAR NUMBER IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR FOR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR BIN_OP VAR VAR VAR VAR ASSIGN VAR VAR VAR NUMBER FUNC_DEF ASSIGN VAR LIST IF VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR STRING IF VAR BIN_OP FUNC_CALL VAR VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR STRING IF VAR NUMBER EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER STRING IF VAR BIN_OP FUNC_CALL VAR VAR NUMBER NUMBER EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER STRING RETURN VAR |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
def solve(self, m, n, x, y, visited, path, answer):
if x == n - 1 and y == n - 1 and m[x][y] != 0:
answer.append(path)
return
if -1 < x < n and -1 < y < n and not visited[x][y] and m[x][y] != 0:
visited[x][y] = 1
self.solve(m, n, x + 1, y, visited, path + "D", answer)
self.solve(m, n, x - 1, y, visited, path + "U", answer)
self.solve(m, n, x, y + 1, visited, path + "R", answer)
self.solve(m, n, x, y - 1, visited, path + "L", answer)
visited[x][y] = 0
def findPath(self, m, n):
visited = []
for i in range(n):
visited.append([0] * n)
answer = []
self.solve(m, n, 0, 0, visited, "", answer)
return answer if answer else [] | CLASS_DEF FUNC_DEF IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN IF NUMBER VAR VAR NUMBER VAR VAR VAR VAR VAR VAR VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER VAR VAR BIN_OP VAR STRING VAR EXPR FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER VAR VAR BIN_OP VAR STRING VAR EXPR FUNC_CALL VAR VAR VAR VAR BIN_OP VAR NUMBER VAR BIN_OP VAR STRING VAR EXPR FUNC_CALL VAR VAR VAR VAR BIN_OP VAR NUMBER VAR BIN_OP VAR STRING VAR ASSIGN VAR VAR VAR NUMBER FUNC_DEF ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR BIN_OP LIST NUMBER VAR ASSIGN VAR LIST EXPR FUNC_CALL VAR VAR VAR NUMBER NUMBER VAR STRING VAR RETURN VAR VAR LIST |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
def isValid(self, x, y, m, n):
if x < 0 or y < 0 or x >= n or y >= n:
return False
if m[x][y] == 0:
return False
return True
def sol(self, x, y, m, n, path, visited, dest):
if x == n - 1 and y == n - 1:
dest.append(path)
return True
if visited[x][y] == 1:
return False
visited[x][y] = 1
if Solution.isValid(self, x + 1, y, m, n):
Solution.sol(self, x + 1, y, m, n, path + "D", visited, dest)
if Solution.isValid(self, x - 1, y, m, n):
Solution.sol(self, x - 1, y, m, n, path + "U", visited, dest)
if Solution.isValid(self, x, y + 1, m, n):
Solution.sol(self, x, y + 1, m, n, path + "R", visited, dest)
if Solution.isValid(self, x, y - 1, m, n):
Solution.sol(self, x, y - 1, m, n, path + "L", visited, dest)
visited[x][y] = 0
def findPath(self, m, n):
dest = []
visited = [([0] * n) for _ in range(n)]
if m[0][0] == 0 or m[n - 1][n - 1] == 0:
return [-1]
Solution().sol(0, 0, m, n, "", visited, dest)
return [-1] if len(dest) == 0 else dest | CLASS_DEF FUNC_DEF IF VAR NUMBER VAR NUMBER VAR VAR VAR VAR RETURN NUMBER IF VAR VAR VAR NUMBER RETURN NUMBER RETURN NUMBER FUNC_DEF IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN NUMBER IF VAR VAR VAR NUMBER RETURN NUMBER ASSIGN VAR VAR VAR NUMBER IF FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR VAR EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR VAR BIN_OP VAR STRING VAR VAR IF FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR VAR EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR VAR BIN_OP VAR STRING VAR VAR IF FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER VAR VAR EXPR FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER VAR VAR BIN_OP VAR STRING VAR VAR IF FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER VAR VAR EXPR FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER VAR VAR BIN_OP VAR STRING VAR VAR ASSIGN VAR VAR VAR NUMBER FUNC_DEF ASSIGN VAR LIST ASSIGN VAR BIN_OP LIST NUMBER VAR VAR FUNC_CALL VAR VAR IF VAR NUMBER NUMBER NUMBER VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER NUMBER RETURN LIST NUMBER EXPR FUNC_CALL FUNC_CALL VAR NUMBER NUMBER VAR VAR STRING VAR VAR RETURN FUNC_CALL VAR VAR NUMBER LIST NUMBER VAR |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
def findPath(self, m, n):
vis = [[(0) for i in range(n)] for j in range(n)]
if m[0][0] == 0:
return []
return self.func(m, n, "", [], 0, 0, vis)
def func(self, m, n, str1, paths, i, j, vis):
if i == n - 1 and j == n - 1 and m[i][j] == 1:
paths.append(str1)
return paths
vis[i][j] = 1
if j + 1 < n and vis[i][j + 1] == 0 and m[i][j + 1] == 1:
paths = self.func(m, n, str1 + "R", paths, i, j + 1, vis)
vis[i][j + 1] = 0
if i - 1 >= 0 and vis[i - 1][j] == 0 and m[i - 1][j] == 1:
paths = self.func(m, n, str1 + "U", paths, i - 1, j, vis)
vis[i - 1][j] = 0
if i + 1 < n and vis[i + 1][j] == 0 and m[i + 1][j] == 1:
paths = self.func(m, n, str1 + "D", paths, i + 1, j, vis)
vis[i + 1][j] = 0
if j - 1 >= 0 and vis[i][j - 1] == 0 and m[i][j - 1] == 1:
paths = self.func(m, n, str1 + "L", paths, i, j - 1, vis)
vis[i][j - 1] = 0
return paths | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR IF VAR NUMBER NUMBER NUMBER RETURN LIST RETURN FUNC_CALL VAR VAR VAR STRING LIST NUMBER NUMBER VAR FUNC_DEF IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN VAR ASSIGN VAR VAR VAR NUMBER IF BIN_OP VAR NUMBER VAR VAR VAR BIN_OP VAR NUMBER NUMBER VAR VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR BIN_OP VAR STRING VAR VAR BIN_OP VAR NUMBER VAR ASSIGN VAR VAR BIN_OP VAR NUMBER NUMBER IF BIN_OP VAR NUMBER NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR BIN_OP VAR STRING VAR BIN_OP VAR NUMBER VAR VAR ASSIGN VAR BIN_OP VAR NUMBER VAR NUMBER IF BIN_OP VAR NUMBER VAR VAR BIN_OP VAR NUMBER VAR NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR BIN_OP VAR STRING VAR BIN_OP VAR NUMBER VAR VAR ASSIGN VAR BIN_OP VAR NUMBER VAR NUMBER IF BIN_OP VAR NUMBER NUMBER VAR VAR BIN_OP VAR NUMBER NUMBER VAR VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR BIN_OP VAR STRING VAR VAR BIN_OP VAR NUMBER VAR ASSIGN VAR VAR BIN_OP VAR NUMBER NUMBER RETURN VAR |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
def findPath(self, a, n):
vis = [[(0) for i in range(n)] for j in range(n)]
drow = [-1, 0, 1, 0]
dcol = [0, 1, 0, -1]
ans = []
def solve(row, col, s):
if row == n - 1 and col == n - 1:
ans.append(s)
return
dis = "URDL"
for i in range(4):
nr = row + drow[i]
nc = col + dcol[i]
if (
nc >= 0
and nr >= 0
and nc < n
and nr < n
and a[nr][nc] == 1
and vis[nr][nc] == 0
):
vis[row][col] = 1
solve(nr, nc, s + dis[i])
vis[row][col] = 0
if a[0][0] == 1:
solve(0, 0, "")
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR LIST NUMBER NUMBER NUMBER NUMBER ASSIGN VAR LIST NUMBER NUMBER NUMBER NUMBER ASSIGN VAR LIST FUNC_DEF IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN ASSIGN VAR STRING FOR VAR FUNC_CALL VAR NUMBER ASSIGN VAR BIN_OP VAR VAR VAR ASSIGN VAR BIN_OP VAR VAR VAR IF VAR NUMBER VAR NUMBER VAR VAR VAR VAR VAR VAR VAR NUMBER VAR VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR BIN_OP VAR VAR VAR ASSIGN VAR VAR VAR NUMBER IF VAR NUMBER NUMBER NUMBER EXPR FUNC_CALL VAR NUMBER NUMBER STRING RETURN VAR |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
def findPath(self, m, n):
def dfs(x, y, path, res, visited):
if x < 0 or x >= n or y < 0 or y >= n or m[x][y] == 0:
return
if x == n - 1 and y == n - 1:
res.append(path)
return
if (x, y) in visited:
return
dfs(x + 1, y, path + "D", res, visited + [(x, y)])
dfs(x - 1, y, path + "U", res, visited + [(x, y)])
dfs(x, y - 1, path + "L", res, visited + [(x, y)])
dfs(x, y + 1, path + "R", res, visited + [(x, y)])
paths = []
dfs(0, 0, "", paths, [])
return paths | CLASS_DEF FUNC_DEF FUNC_DEF IF VAR NUMBER VAR VAR VAR NUMBER VAR VAR VAR VAR VAR NUMBER RETURN IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN IF VAR VAR VAR RETURN EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR BIN_OP VAR STRING VAR BIN_OP VAR LIST VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR BIN_OP VAR STRING VAR BIN_OP VAR LIST VAR VAR EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER BIN_OP VAR STRING VAR BIN_OP VAR LIST VAR VAR EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER BIN_OP VAR STRING VAR BIN_OP VAR LIST VAR VAR ASSIGN VAR LIST EXPR FUNC_CALL VAR NUMBER NUMBER STRING VAR LIST RETURN VAR |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
def findPath(self, m, n):
ans = []
def path_helper(i, j, m, n, vis, direction):
if i == n - 1 and j == n - 1:
vis[i][j] = 1
ans.append(direction)
vis[i][j] = 0
return
if i < 0 or j < 0 or i >= n or j >= n or m[i][j] == 0 or vis[i][j] == 1:
return
vis[i][j] = 1
path_helper(i + 1, j, m, n, vis, direction + "D")
path_helper(i - 1, j, m, n, vis, direction + "U")
path_helper(i, j + 1, m, n, vis, direction + "R")
path_helper(i, j - 1, m, n, vis, direction + "L")
vis[i][j] = 0
return
vis = [[(0) for j in range(n)] for i in range(n)]
if m[0][0] == 1 and m[n - 1][n - 1] == 1:
path_helper(0, 0, m, n, vis, "")
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR LIST FUNC_DEF IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR NUMBER RETURN IF VAR NUMBER VAR NUMBER VAR VAR VAR VAR VAR VAR VAR NUMBER VAR VAR VAR NUMBER RETURN ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR VAR VAR BIN_OP VAR STRING EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR VAR VAR BIN_OP VAR STRING EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR VAR BIN_OP VAR STRING EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR VAR BIN_OP VAR STRING ASSIGN VAR VAR VAR NUMBER RETURN ASSIGN VAR NUMBER VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR IF VAR NUMBER NUMBER NUMBER VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER NUMBER EXPR FUNC_CALL VAR NUMBER NUMBER VAR VAR VAR STRING RETURN VAR |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
def findPath(self, m, n):
dir_ = [(-1, 0, "U"), (0, 1, "R"), (1, 0, "D"), (0, -1, "L")]
ans = []
pathVisited = set()
def isValid(x, y):
return -1 < x <= n - 1 and -1 < y <= n - 1 and m[x][y] != 0
def rec(i, j, path):
if (i, j) == (n - 1, n - 1):
if m[i][j] == 1:
ans.append(path)
return
if isValid(i, j):
pathVisited.add((i, j))
for d in dir_:
x, y, letter = i + d[0], j + d[1], d[2]
if (x, y) not in pathVisited:
rec(x, y, path + letter)
pathVisited.remove((i, j))
rec(0, 0, "")
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR LIST NUMBER NUMBER STRING NUMBER NUMBER STRING NUMBER NUMBER STRING NUMBER NUMBER STRING ASSIGN VAR LIST ASSIGN VAR FUNC_CALL VAR FUNC_DEF RETURN NUMBER VAR BIN_OP VAR NUMBER NUMBER VAR BIN_OP VAR NUMBER VAR VAR VAR NUMBER FUNC_DEF IF VAR VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER IF VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN IF FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR FOR VAR VAR ASSIGN VAR VAR VAR BIN_OP VAR VAR NUMBER BIN_OP VAR VAR NUMBER VAR NUMBER IF VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR BIN_OP VAR VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR NUMBER NUMBER STRING RETURN VAR |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
def findPath(self, m, n):
ans = []
def isSafe(m, visited, n, scrx, scry):
if (
scrx >= 0
and scry >= 0
and scrx < n
and scry < n
and m[scrx][scry] == 1
and visited[scrx][scry] != 1
):
return True
else:
return False
def helper(m, visited, temp, n, scrx, scry):
if scrx == n - 1 and scry == n - 1:
ans.append(temp)
return
visited[scrx][scry] = 1
if isSafe(m, visited, n, scrx + 1, scry):
helper(m, visited, temp + "D", n, scrx + 1, scry)
if isSafe(m, visited, n, scrx, scry - 1):
helper(m, visited, temp + "L", n, scrx, scry - 1)
if isSafe(m, visited, n, scrx, scry + 1):
helper(m, visited, temp + "R", n, scrx, scry + 1)
if isSafe(m, visited, n, scrx - 1, scry):
helper(m, visited, temp + "U", n, scrx - 1, scry)
visited[scrx][scry] = 0
if m[0][0] == 0:
return []
visited = []
for i in range(n):
col = []
for j in range(n):
col.append(0)
visited.append(col)
helper(m, visited, "", n, 0, 0)
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR LIST FUNC_DEF IF VAR NUMBER VAR NUMBER VAR VAR VAR VAR VAR VAR VAR NUMBER VAR VAR VAR NUMBER RETURN NUMBER RETURN NUMBER FUNC_DEF IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN ASSIGN VAR VAR VAR NUMBER IF FUNC_CALL VAR VAR VAR VAR BIN_OP VAR NUMBER VAR EXPR FUNC_CALL VAR VAR VAR BIN_OP VAR STRING VAR BIN_OP VAR NUMBER VAR IF FUNC_CALL VAR VAR VAR VAR VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR VAR BIN_OP VAR STRING VAR VAR BIN_OP VAR NUMBER IF FUNC_CALL VAR VAR VAR VAR VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR VAR BIN_OP VAR STRING VAR VAR BIN_OP VAR NUMBER IF FUNC_CALL VAR VAR VAR VAR BIN_OP VAR NUMBER VAR EXPR FUNC_CALL VAR VAR VAR BIN_OP VAR STRING VAR BIN_OP VAR NUMBER VAR ASSIGN VAR VAR VAR NUMBER IF VAR NUMBER NUMBER NUMBER RETURN LIST ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR NUMBER EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR STRING VAR NUMBER NUMBER RETURN VAR |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
def findPath(self, m, n):
def ax(vis, i, j, s):
if i < 0 or j < 0 or j >= n or i >= n:
return False
if m[i][j] == 0 or vis[i][j] == 1:
return False
if i == n - 1 and j == n - 1:
r.append(s)
return
vis[i][j] = 1
ax(vis, i - 1, j, s + "U")
ax(vis, i + 1, j, s + "D")
ax(vis, i, j - 1, s + "L")
ax(vis, i, j + 1, s + "R")
vis[i][j] = 0
r = []
vis = [([0] * n) for _ in range(n)]
ax(vis, 0, 0, "")
return r | CLASS_DEF FUNC_DEF FUNC_DEF IF VAR NUMBER VAR NUMBER VAR VAR VAR VAR RETURN NUMBER IF VAR VAR VAR NUMBER VAR VAR VAR NUMBER RETURN NUMBER IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR BIN_OP VAR STRING EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR BIN_OP VAR STRING EXPR FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER BIN_OP VAR STRING EXPR FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER BIN_OP VAR STRING ASSIGN VAR VAR VAR NUMBER ASSIGN VAR LIST ASSIGN VAR BIN_OP LIST NUMBER VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR NUMBER NUMBER STRING RETURN VAR |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
def solve(self, i, j, ans, res, mat, visited, n):
if i == n - 1 and j == n - 1:
res.append(ans)
return
if i < n - 1 and mat[i + 1][j] == 1 and visited[i + 1][j] != "v":
visited[i][j] = "v"
self.solve(i + 1, j, ans + "D", res, mat, visited, n)
visited[i][j] = "."
if j > 0 and mat[i][j - 1] == 1 and visited[i][j - 1] != "v":
visited[i][j] = "v"
self.solve(i, j - 1, ans + "L", res, mat, visited, n)
visited[i][j] = "."
if j < n - 1 and mat[i][j + 1] == 1 and visited[i][j + 1] != "v":
visited[i][j] = "v"
self.solve(i, j + 1, ans + "R", res, mat, visited, n)
visited[i][j] = "."
if i > 0 and mat[i - 1][j] == 1 and visited[i - 1][j] != "v":
visited[i][j] = "v"
self.solve(i - 1, j, ans + "U", res, mat, visited, n)
visited[i][j] = "."
def findPath(self, m, n):
if m[n - 1][n - 1] == 0 or m[0][0] == 0:
return []
res = []
visited = [["." for _ in range(n)] for _ in range(n)]
self.solve(0, 0, "", res, m, visited, n)
return res | CLASS_DEF FUNC_DEF IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER VAR BIN_OP VAR NUMBER VAR STRING ASSIGN VAR VAR VAR STRING EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR BIN_OP VAR STRING VAR VAR VAR VAR ASSIGN VAR VAR VAR STRING IF VAR NUMBER VAR VAR BIN_OP VAR NUMBER NUMBER VAR VAR BIN_OP VAR NUMBER STRING ASSIGN VAR VAR VAR STRING EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER BIN_OP VAR STRING VAR VAR VAR VAR ASSIGN VAR VAR VAR STRING IF VAR BIN_OP VAR NUMBER VAR VAR BIN_OP VAR NUMBER NUMBER VAR VAR BIN_OP VAR NUMBER STRING ASSIGN VAR VAR VAR STRING EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER BIN_OP VAR STRING VAR VAR VAR VAR ASSIGN VAR VAR VAR STRING IF VAR NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER VAR BIN_OP VAR NUMBER VAR STRING ASSIGN VAR VAR VAR STRING EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR BIN_OP VAR STRING VAR VAR VAR VAR ASSIGN VAR VAR VAR STRING FUNC_DEF IF VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER NUMBER VAR NUMBER NUMBER NUMBER RETURN LIST ASSIGN VAR LIST ASSIGN VAR STRING VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR NUMBER NUMBER STRING VAR VAR VAR VAR RETURN VAR |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
dirs = list()
visited = list()
def findPath(self, m, n):
result = list()
self.visited = [([0] * n) for i in range(n)]
self.dirs = [[0, 1], [1, 0], [-1, 0], [0, -1]]
if m[0][0] == 1:
self.helper(m, n, result, 0, 0, list())
return result
def helper(self, m, n, result, row, col, path):
if row == n - 1 and col == n - 1:
result.append("".join(path))
return
nav = "RDUL"
for i in range(len(self.dirs)):
d = self.dirs[i]
nr = row + d[0]
nc = col + d[1]
if (
nr >= 0
and nr < n
and nc < n
and nc >= 0
and self.visited[nr][nc] == 0
and m[nr][nc] == 1
):
self.visited[row][col] = 1
path.append(nav[i])
self.helper(m, n, result, nr, nc, path)
path.pop()
self.visited[row][col] = 0 | CLASS_DEF ASSIGN VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR ASSIGN VAR BIN_OP LIST NUMBER VAR VAR FUNC_CALL VAR VAR ASSIGN VAR LIST LIST NUMBER NUMBER LIST NUMBER NUMBER LIST NUMBER NUMBER LIST NUMBER NUMBER IF VAR NUMBER NUMBER NUMBER EXPR FUNC_CALL VAR VAR VAR VAR NUMBER NUMBER FUNC_CALL VAR RETURN VAR FUNC_DEF IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR FUNC_CALL STRING VAR RETURN ASSIGN VAR STRING FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR BIN_OP VAR VAR NUMBER ASSIGN VAR BIN_OP VAR VAR NUMBER IF VAR NUMBER VAR VAR VAR VAR VAR NUMBER VAR VAR VAR NUMBER VAR VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR VAR VAR NUMBER |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
def findPath(self, m, n):
ans = []
visited = [[(0) for _ in range(n)] for _ in range(n)]
path = ""
if m[0][0] == 0 or m[n - 1][n - 1] == 0:
return [-1]
self.solve(0, 0, m, n, ans, visited, path)
return ans
def isSafe(self, n, x, y, vis, maze):
if (
(x >= 0 and x < n)
and (y >= 0 and y < n)
and vis[x][y] == 0
and maze[x][y] == 1
):
return True
else:
return False
def solve(self, x, y, maze, n, ans, vis, path):
if x == n - 1 and y == n - 1:
ans.append(path)
return
vis[x][y] = 1
if self.isSafe(n, x + 1, y, vis, maze):
self.solve(x + 1, y, maze, n, ans, vis, path + "D")
if self.isSafe(n, x, y - 1, vis, maze):
self.solve(x, y - 1, maze, n, ans, vis, path + "L")
if self.isSafe(n, x, y + 1, vis, maze):
self.solve(x, y + 1, maze, n, ans, vis, path + "R")
if self.isSafe(n, x - 1, y, vis, maze):
self.solve(x - 1, y, maze, n, ans, vis, path + "U")
vis[x][y] = 0 | CLASS_DEF FUNC_DEF ASSIGN VAR LIST ASSIGN VAR NUMBER VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR STRING IF VAR NUMBER NUMBER NUMBER VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER NUMBER RETURN LIST NUMBER EXPR FUNC_CALL VAR NUMBER NUMBER VAR VAR VAR VAR VAR RETURN VAR FUNC_DEF IF VAR NUMBER VAR VAR VAR NUMBER VAR VAR VAR VAR VAR NUMBER VAR VAR VAR NUMBER RETURN NUMBER RETURN NUMBER FUNC_DEF IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN ASSIGN VAR VAR VAR NUMBER IF FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR VAR VAR VAR BIN_OP VAR STRING IF FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER VAR VAR EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR VAR VAR BIN_OP VAR STRING IF FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER VAR VAR EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR VAR VAR BIN_OP VAR STRING IF FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR VAR VAR VAR BIN_OP VAR STRING ASSIGN VAR VAR VAR NUMBER |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
def findPath(self, matrix, n):
ans = list()
def util(i, j, coveredCoord, path):
if (i, j) in coveredCoord or i < 0 or i >= n or j < 0 or j >= n:
return
if matrix[i][j] == 0:
return
if i == j == n - 1:
ans.append(path)
return
coveredCoord.add((i, j))
util(i - 1, j, coveredCoord.copy(), path + "U")
util(i, j - 1, coveredCoord.copy(), path + "L")
util(i + 1, j, coveredCoord.copy(), path + "D")
util(i, j + 1, coveredCoord.copy(), path + "R")
util(0, 0, set(), "")
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR FUNC_DEF IF VAR VAR VAR VAR NUMBER VAR VAR VAR NUMBER VAR VAR RETURN IF VAR VAR VAR NUMBER RETURN IF VAR VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR FUNC_CALL VAR BIN_OP VAR STRING EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER FUNC_CALL VAR BIN_OP VAR STRING EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR FUNC_CALL VAR BIN_OP VAR STRING EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER FUNC_CALL VAR BIN_OP VAR STRING EXPR FUNC_CALL VAR NUMBER NUMBER FUNC_CALL VAR STRING RETURN VAR |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | fans = []
moves = [[0, 1, "R"], [0, -1, "L"], [1, 0, "D"], [-1, 0, "U"]]
def valid(i, j, vis, arr):
if (
i < 0
or j < 0
or i >= len(arr)
or j >= len(arr[0])
or (i, j) in vis
or arr[i][j] == 0
):
return False
return True
def mgc(arr, i, j, vis, ans):
global fans, moves
if i == j and i == len(arr) - 1:
fans.append(ans)
return
vis.add((i, j))
for k in moves:
if valid(k[0] + i, k[1] + j, vis, arr):
mgc(arr, i + k[0], j + k[1], vis, ans + k[2])
vis.remove((i, j))
class Solution:
def findPath(self, m, n):
global fans
fans = []
if m[0][0] == 0 or m[n - 1][n - 1] == 0:
return []
mgc(m, 0, 0, set(), "")
return fans | ASSIGN VAR LIST ASSIGN VAR LIST LIST NUMBER NUMBER STRING LIST NUMBER NUMBER STRING LIST NUMBER NUMBER STRING LIST NUMBER NUMBER STRING FUNC_DEF IF VAR NUMBER VAR NUMBER VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR NUMBER VAR VAR VAR VAR VAR VAR NUMBER RETURN NUMBER RETURN NUMBER FUNC_DEF IF VAR VAR VAR BIN_OP FUNC_CALL VAR VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN EXPR FUNC_CALL VAR VAR VAR FOR VAR VAR IF FUNC_CALL VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER VAR VAR VAR EXPR FUNC_CALL VAR VAR BIN_OP VAR VAR NUMBER BIN_OP VAR VAR NUMBER VAR BIN_OP VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR CLASS_DEF FUNC_DEF ASSIGN VAR LIST IF VAR NUMBER NUMBER NUMBER VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER NUMBER RETURN LIST EXPR FUNC_CALL VAR VAR NUMBER NUMBER FUNC_CALL VAR STRING RETURN VAR |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
def findPath(self, m, n):
def solve(i, j, move):
if i == n - 1 and j == n - 1:
ans.append(move)
return
d = "DLRU"
for k in range(4):
ni = i + di[k]
nj = j + dj[k]
if (
ni >= 0
and nj >= 0
and ni < n
and nj < n
and vis[ni][nj] == 0
and m[ni][nj] == 1
):
vis[i][j] = 1
solve(ni, nj, move + d[k])
vis[i][j] = 0
ans = []
vis = [[(0) for i in range(n)] for j in range(n)]
di = [+1, 0, 0, -1]
dj = [0, -1, 1, 0]
if m[0][0] == 1:
solve(0, 0, "")
return ans | CLASS_DEF FUNC_DEF FUNC_DEF IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN ASSIGN VAR STRING FOR VAR FUNC_CALL VAR NUMBER ASSIGN VAR BIN_OP VAR VAR VAR ASSIGN VAR BIN_OP VAR VAR VAR IF VAR NUMBER VAR NUMBER VAR VAR VAR VAR VAR VAR VAR NUMBER VAR VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR BIN_OP VAR VAR VAR ASSIGN VAR VAR VAR NUMBER ASSIGN VAR LIST ASSIGN VAR NUMBER VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR LIST NUMBER NUMBER NUMBER NUMBER ASSIGN VAR LIST NUMBER NUMBER NUMBER NUMBER IF VAR NUMBER NUMBER NUMBER EXPR FUNC_CALL VAR NUMBER NUMBER STRING RETURN VAR |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution(object):
def findPath(self, board, n):
def backtracking(row, col, combination):
if not (0 <= row < n and 0 <= col < n):
return
if board[row][col] == "V" or board[row][col] == 0:
return
if row == col == n - 1:
result.append("".join(combination))
return
for rval, cval, direction in directions:
board[row][col] = "V"
combination.append(direction)
backtracking(row + rval, col + cval, combination)
combination.pop()
board[row][col] = 1
result = []
if board[0][0] == 0 or board[n - 1][n - 1] == 0:
return result
directions = [(1, 0, "D"), (0, -1, "L"), (0, 1, "R"), (-1, 0, "U")]
backtracking(0, 0, [])
return result | CLASS_DEF VAR FUNC_DEF FUNC_DEF IF NUMBER VAR VAR NUMBER VAR VAR RETURN IF VAR VAR VAR STRING VAR VAR VAR NUMBER RETURN IF VAR VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR FUNC_CALL STRING VAR RETURN FOR VAR VAR VAR VAR ASSIGN VAR VAR VAR STRING EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR VAR BIN_OP VAR VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR VAR VAR NUMBER ASSIGN VAR LIST IF VAR NUMBER NUMBER NUMBER VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER NUMBER RETURN VAR ASSIGN VAR LIST NUMBER NUMBER STRING NUMBER NUMBER STRING NUMBER NUMBER STRING NUMBER NUMBER STRING EXPR FUNC_CALL VAR NUMBER NUMBER LIST RETURN VAR |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | def sol(row, col, n, mat, path, ans, dRow, dCol):
if col == n - 1 and row == n - 1:
ans.append(path)
return ans
d = "DLRU"
for i in range(4):
nextRow = row + dRow[i]
nextCol = col + dCol[i]
if (
nextRow < n
and nextCol < n
and nextRow >= 0
and nextCol >= 0
and mat[nextRow][nextCol] != 0
):
mat[row][col] = 0
ans = sol(nextRow, nextCol, n, mat, path + d[i], ans, dRow, dCol)
mat[row][col] = 1
return ans
class Solution:
def findPath(self, m, n):
if m[0][0] == 0:
return [-1]
ans = []
dRow = [1, 0, 0, -1]
dCol = [0, -1, 1, 0]
return sol(0, 0, n, m, "", ans, dRow, dCol) | FUNC_DEF IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN VAR ASSIGN VAR STRING FOR VAR FUNC_CALL VAR NUMBER ASSIGN VAR BIN_OP VAR VAR VAR ASSIGN VAR BIN_OP VAR VAR VAR IF VAR VAR VAR VAR VAR NUMBER VAR NUMBER VAR VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR VAR VAR BIN_OP VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR NUMBER RETURN VAR CLASS_DEF FUNC_DEF IF VAR NUMBER NUMBER NUMBER RETURN LIST NUMBER ASSIGN VAR LIST ASSIGN VAR LIST NUMBER NUMBER NUMBER NUMBER ASSIGN VAR LIST NUMBER NUMBER NUMBER NUMBER RETURN FUNC_CALL VAR NUMBER NUMBER VAR VAR STRING VAR VAR VAR |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
def findPath(self, m, n):
matrix = m
if matrix[0][0] == 0 or matrix[n - 1][n - 1] == 0:
return [-1]
visited_vals = [(0, 0)]
solutions = []
def helper(i, j, direction, path):
path += direction
if i >= n - 1 and j >= n - 1:
solutions.append(path)
return
if (
i < 0
or j < 0
or i >= n
or j >= n
or matrix[i][j] == 0
or (i, j) in visited_vals
):
return
visited_vals.append((i, j))
for new_direction in ["L", "D", "R", "U"]:
if new_direction == "L":
helper(i, j - 1, new_direction, path)
elif new_direction == "D":
helper(i + 1, j, new_direction, path)
elif new_direction == "R":
helper(i, j + 1, new_direction, path)
else:
helper(i - 1, j, new_direction, path)
visited_vals.pop()
helper(0, 1, "R", "")
helper(1, 0, "D", "")
if not solutions:
return [-1]
return solutions | CLASS_DEF FUNC_DEF ASSIGN VAR VAR IF VAR NUMBER NUMBER NUMBER VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER NUMBER RETURN LIST NUMBER ASSIGN VAR LIST NUMBER NUMBER ASSIGN VAR LIST FUNC_DEF VAR VAR IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN IF VAR NUMBER VAR NUMBER VAR VAR VAR VAR VAR VAR VAR NUMBER VAR VAR VAR RETURN EXPR FUNC_CALL VAR VAR VAR FOR VAR LIST STRING STRING STRING STRING IF VAR STRING EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR IF VAR STRING EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR VAR IF VAR STRING EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR VAR EXPR FUNC_CALL VAR EXPR FUNC_CALL VAR NUMBER NUMBER STRING STRING EXPR FUNC_CALL VAR NUMBER NUMBER STRING STRING IF VAR RETURN LIST NUMBER RETURN VAR |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
def findPathHelper(self, i, j, a, n, ans, move, vis):
if i == n - 1 and j == n - 1:
ans.append(move)
return
if i + 1 < n and not vis[i + 1][j] and a[i + 1][j] == 1:
vis[i][j] = 1
self.findPathHelper(i + 1, j, a, n, ans, move + "D", vis)
vis[i][j] = 0
if j - 1 >= 0 and not vis[i][j - 1] and a[i][j - 1] == 1:
vis[i][j] = 1
self.findPathHelper(i, j - 1, a, n, ans, move + "L", vis)
vis[i][j] = 0
if j + 1 < n and not vis[i][j + 1] and a[i][j + 1] == 1:
vis[i][j] = 1
self.findPathHelper(i, j + 1, a, n, ans, move + "R", vis)
vis[i][j] = 0
if i - 1 >= 0 and not vis[i - 1][j] and a[i - 1][j] == 1:
vis[i][j] = 1
self.findPathHelper(i - 1, j, a, n, ans, move + "U", vis)
vis[i][j] = 0
def findPath(self, m, n):
ans = []
vis = [[(0) for _ in range(n)] for _ in range(n)]
if m[0][0] == 1:
self.findPathHelper(0, 0, m, n, ans, "", vis)
return ans | CLASS_DEF FUNC_DEF IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN IF BIN_OP VAR NUMBER VAR VAR BIN_OP VAR NUMBER VAR VAR BIN_OP VAR NUMBER VAR NUMBER ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR VAR VAR BIN_OP VAR STRING VAR ASSIGN VAR VAR VAR NUMBER IF BIN_OP VAR NUMBER NUMBER VAR VAR BIN_OP VAR NUMBER VAR VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR VAR BIN_OP VAR STRING VAR ASSIGN VAR VAR VAR NUMBER IF BIN_OP VAR NUMBER VAR VAR VAR BIN_OP VAR NUMBER VAR VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR VAR BIN_OP VAR STRING VAR ASSIGN VAR VAR VAR NUMBER IF BIN_OP VAR NUMBER NUMBER VAR BIN_OP VAR NUMBER VAR VAR BIN_OP VAR NUMBER VAR NUMBER ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR VAR VAR BIN_OP VAR STRING VAR ASSIGN VAR VAR VAR NUMBER FUNC_DEF ASSIGN VAR LIST ASSIGN VAR NUMBER VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR IF VAR NUMBER NUMBER NUMBER EXPR FUNC_CALL VAR NUMBER NUMBER VAR VAR VAR STRING VAR RETURN VAR |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | def isValid(i, j, m, n, curr_ans, vis, fin_ans):
return i >= 0 and j >= 0 and i < n and j < n and m[i][j] == 1 and vis[i][j] == False
def findPathUtil(i, j, m, n, ans, vis, fin_ans):
vis[i][j] = True
if i == n - 1 and j == n - 1:
fin_ans.append(ans)
if isValid(i + 1, j, m, n, ans, vis, fin_ans):
curr_ans = ans
curr_ans += "D"
findPathUtil(i + 1, j, m, n, curr_ans, vis, fin_ans)
if isValid(i - 1, j, m, n, ans, vis, fin_ans):
curr_ans = ans
curr_ans += "U"
findPathUtil(i - 1, j, m, n, curr_ans, vis, fin_ans)
if isValid(i, j + 1, m, n, ans, vis, fin_ans):
curr_ans = ans
curr_ans += "R"
findPathUtil(i, j + 1, m, n, curr_ans, vis, fin_ans)
if isValid(i, j - 1, m, n, ans, vis, fin_ans):
curr_ans = ans
curr_ans += "L"
findPathUtil(i, j - 1, m, n, curr_ans, vis, fin_ans)
vis[i][j] = False
class Solution:
def findPath(self, m, n):
ans = ""
if m[0][0] == 0:
return [-1]
vis = [[(False) for i in range(n)] for i in range(n)]
fin_ans = []
findPathUtil(0, 0, m, n, ans, vis, fin_ans)
return fin_ans | FUNC_DEF RETURN VAR NUMBER VAR NUMBER VAR VAR VAR VAR VAR VAR VAR NUMBER VAR VAR VAR NUMBER FUNC_DEF ASSIGN VAR VAR VAR NUMBER IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR IF FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR STRING EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR VAR VAR VAR VAR IF FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR STRING EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR VAR VAR VAR VAR IF FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR STRING EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR VAR VAR VAR IF FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR STRING EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR NUMBER CLASS_DEF FUNC_DEF ASSIGN VAR STRING IF VAR NUMBER NUMBER NUMBER RETURN LIST NUMBER ASSIGN VAR NUMBER VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR LIST EXPR FUNC_CALL VAR NUMBER NUMBER VAR VAR VAR VAR VAR RETURN VAR |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
def findpaths(self, matrix, n, i, j, seq):
if i == n - 1 and j == n - 1:
self.res.append(seq)
return
if i < 0 or j < 0 or i == n or j == n:
return
if matrix[i][j] == 0:
return
matrix[i][j] = 0
for direction, (movi, movj) in self.directions.items():
self.findpaths(matrix, n, i + movi, j + movj, seq + direction)
matrix[i][j] = 1
def findPath(self, matrix, n):
if matrix[0][0] == 0 or matrix[-1][-1] == 0:
return []
self.res = []
self.directions = {"R": (0, 1), "L": (0, -1), "D": (1, 0), "U": (-1, 0)}
self.findpaths(matrix, n, 0, 0, "")
return self.res | CLASS_DEF FUNC_DEF IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN IF VAR NUMBER VAR NUMBER VAR VAR VAR VAR RETURN IF VAR VAR VAR NUMBER RETURN ASSIGN VAR VAR VAR NUMBER FOR VAR VAR VAR FUNC_CALL VAR EXPR FUNC_CALL VAR VAR VAR BIN_OP VAR VAR BIN_OP VAR VAR BIN_OP VAR VAR ASSIGN VAR VAR VAR NUMBER FUNC_DEF IF VAR NUMBER NUMBER NUMBER VAR NUMBER NUMBER NUMBER RETURN LIST ASSIGN VAR LIST ASSIGN VAR DICT STRING STRING STRING STRING NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER EXPR FUNC_CALL VAR VAR VAR NUMBER NUMBER STRING RETURN VAR |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
def findPath(self, m, n):
visited = set()
ans = []
def solve(r, c, st):
if r < 0 or c < 0 or r >= n or c >= n or m[r][c] == 0 or (r, c) in visited:
return
if r == n - 1 and c == n - 1:
ans.append(st)
return
visited.add((r, c))
solve(r + 1, c, st + "D")
solve(r, c - 1, st + "L")
solve(r, c + 1, st + "R")
solve(r - 1, c, st + "U")
visited.remove((r, c))
if m[0][0] == 0:
return ans
solve(0, 0, "")
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR ASSIGN VAR LIST FUNC_DEF IF VAR NUMBER VAR NUMBER VAR VAR VAR VAR VAR VAR VAR NUMBER VAR VAR VAR RETURN IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR BIN_OP VAR STRING EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER BIN_OP VAR STRING EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER BIN_OP VAR STRING EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR BIN_OP VAR STRING EXPR FUNC_CALL VAR VAR VAR IF VAR NUMBER NUMBER NUMBER RETURN VAR EXPR FUNC_CALL VAR NUMBER NUMBER STRING RETURN VAR |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
def findPath(self, m, n):
row = 0
col = 0
arr = []
p = ""
if m[n - 1][n - 1] == 0:
return []
def dfs(p, row, col, arr):
if row == n - 1 and col == n - 1:
arr.append(p)
return
if row < 0 or row >= n or col < 0 or col >= n:
return
if m[row][col] != 1:
return
m[row][col] = -1
dfs(p + "D", row + 1, col, arr)
dfs(p + "R", row, col + 1, arr)
dfs(p + "U", row - 1, col, arr)
dfs(p + "L", row, col - 1, arr)
m[row][col] = 1
dfs(p, row, col, arr)
return arr | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR LIST ASSIGN VAR STRING IF VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER NUMBER RETURN LIST FUNC_DEF IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN IF VAR NUMBER VAR VAR VAR NUMBER VAR VAR RETURN IF VAR VAR VAR NUMBER RETURN ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR STRING BIN_OP VAR NUMBER VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR STRING VAR BIN_OP VAR NUMBER VAR EXPR FUNC_CALL VAR BIN_OP VAR STRING BIN_OP VAR NUMBER VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR STRING VAR BIN_OP VAR NUMBER VAR ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR VAR VAR RETURN VAR |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | def rat_in_maze_rec(m, i, j, res, path, n, vis, di, dj):
if i == n - 1 and j == n - 1:
res.append("".join(path[:]))
return
dir = "DLRU"
for idx in range(4):
nexti = i + di[idx]
nextj = j + dj[idx]
if (
0 <= nexti < n
and 0 <= nextj < n
and not vis[nexti][nextj] == 1
and m[nexti][nextj] == 1
):
vis[i][j] = 1
path.append(dir[idx])
rat_in_maze_rec(m, nexti, nextj, res, path, n, vis, di, dj)
path.pop()
vis[i][j] = 0
class Solution:
def findPath(self, m, n):
if m[0][0] == 0 or m[n - 1][n - 1] == 0:
return []
res = []
path = []
vis = [[(0) for _ in range(n)] for _ in range(n)]
di = [+1, 0, 0, -1]
dj = [0, -1, 1, 0]
rat_in_maze_rec(m, 0, 0, res, path, n, vis, di, dj)
return res | FUNC_DEF IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR FUNC_CALL STRING VAR RETURN ASSIGN VAR STRING FOR VAR FUNC_CALL VAR NUMBER ASSIGN VAR BIN_OP VAR VAR VAR ASSIGN VAR BIN_OP VAR VAR VAR IF NUMBER VAR VAR NUMBER VAR VAR VAR VAR VAR NUMBER VAR VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR VAR VAR NUMBER CLASS_DEF FUNC_DEF IF VAR NUMBER NUMBER NUMBER VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER NUMBER RETURN LIST ASSIGN VAR LIST ASSIGN VAR LIST ASSIGN VAR NUMBER VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR LIST NUMBER NUMBER NUMBER NUMBER ASSIGN VAR LIST NUMBER NUMBER NUMBER NUMBER EXPR FUNC_CALL VAR VAR NUMBER NUMBER VAR VAR VAR VAR VAR VAR RETURN VAR |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
def safe(self, x, y, n, v, m):
if (x >= 0 and x < n) and (y >= 0 and y < n) and v[x][y] == 0 and m[x][y] == 1:
return 1
else:
return 0
def sol(self, x, y, m, n, path, ans, v):
if x == n - 1 and y == n - 1:
ans.append(path)
return
v[x][y] = 1
if self.safe(x, y + 1, n, v, m):
self.sol(x, y + 1, m, n, path + "R", ans, v)
if self.safe(x + 1, y, n, v, m):
self.sol(x + 1, y, m, n, path + "D", ans, v)
if self.safe(x, y - 1, n, v, m):
self.sol(x, y - 1, m, n, path + "L", ans, v)
if self.safe(x - 1, y, n, v, m):
self.sol(x - 1, y, m, n, path + "U", ans, v)
v[x][y] = 0
def findPath(self, m, n):
x = y = 0
ans = []
k = [0] * n
v = []
for i in range(n):
v.append(k[:])
if m[0][0] == 0:
return ans
self.sol(x, y, m, n, "", ans, v)
return ans | CLASS_DEF FUNC_DEF IF VAR NUMBER VAR VAR VAR NUMBER VAR VAR VAR VAR VAR NUMBER VAR VAR VAR NUMBER RETURN NUMBER RETURN NUMBER FUNC_DEF IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN ASSIGN VAR VAR VAR NUMBER IF FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR VAR EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR BIN_OP VAR STRING VAR VAR IF FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR VAR BIN_OP VAR STRING VAR VAR IF FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR VAR EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR BIN_OP VAR STRING VAR VAR IF FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR VAR BIN_OP VAR STRING VAR VAR ASSIGN VAR VAR VAR NUMBER FUNC_DEF ASSIGN VAR VAR NUMBER ASSIGN VAR LIST ASSIGN VAR BIN_OP LIST NUMBER VAR ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR IF VAR NUMBER NUMBER NUMBER RETURN VAR EXPR FUNC_CALL VAR VAR VAR VAR VAR STRING VAR VAR RETURN VAR |
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Example 2:
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3^{N}^{^2})).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 β€ N β€ 5
0 β€ m[i][j] β€ 1 | class Solution:
def findPath(self, m, n):
visited = [[(0) for _ in range(n)] for _ in range(n)]
results = []
def path(cur_path, i, j):
if i == n - 1 and j == n - 1:
results.append("".join(cur_path))
return
if m[i][j] == 0:
return
if i + 1 < n and m[i + 1][j] == 1 and visited[i + 1][j] == 0:
cur_path.append("D")
visited[i + 1][j] = 1
path(cur_path, i + 1, j)
cur_path.pop()
visited[i + 1][j] = 0
if j - 1 > -1 and m[i][j - 1] == 1 and visited[i][j - 1] == 0:
cur_path.append("L")
visited[i][j - 1] = 1
path(cur_path, i, j - 1)
cur_path.pop()
visited[i][j - 1] = 0
if j + 1 < n and m[i][j + 1] == 1 and visited[i][j + 1] == 0:
cur_path.append("R")
visited[i][j + 1] = 1
path(cur_path, i, j + 1)
cur_path.pop()
visited[i][j + 1] = 0
if i - 1 > -1 and m[i - 1][j] == 1 and visited[i - 1][j] == 0:
cur_path.append("U")
visited[i - 1][j] = 1
path(cur_path, i - 1, j)
cur_path.pop()
visited[i - 1][j] = 0
return
visited[0][0] = 1
path([], 0, 0)
return results | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR LIST FUNC_DEF IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR FUNC_CALL STRING VAR RETURN IF VAR VAR VAR NUMBER RETURN IF BIN_OP VAR NUMBER VAR VAR BIN_OP VAR NUMBER VAR NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR STRING ASSIGN VAR BIN_OP VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR EXPR FUNC_CALL VAR ASSIGN VAR BIN_OP VAR NUMBER VAR NUMBER IF BIN_OP VAR NUMBER NUMBER VAR VAR BIN_OP VAR NUMBER NUMBER VAR VAR BIN_OP VAR NUMBER NUMBER EXPR FUNC_CALL VAR STRING ASSIGN VAR VAR BIN_OP VAR NUMBER NUMBER EXPR FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR ASSIGN VAR VAR BIN_OP VAR NUMBER NUMBER IF BIN_OP VAR NUMBER VAR VAR VAR BIN_OP VAR NUMBER NUMBER VAR VAR BIN_OP VAR NUMBER NUMBER EXPR FUNC_CALL VAR STRING ASSIGN VAR VAR BIN_OP VAR NUMBER NUMBER EXPR FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR ASSIGN VAR VAR BIN_OP VAR NUMBER NUMBER IF BIN_OP VAR NUMBER NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR STRING ASSIGN VAR BIN_OP VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR EXPR FUNC_CALL VAR ASSIGN VAR BIN_OP VAR NUMBER VAR NUMBER RETURN ASSIGN VAR NUMBER NUMBER NUMBER EXPR FUNC_CALL VAR LIST NUMBER NUMBER RETURN VAR |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.