description stringlengths 171 4k | code stringlengths 94 3.98k | normalized_code stringlengths 57 4.99k |
|---|---|---|
We define f (X, Y) as number of different corresponding bits in binary representation of X and Y. For example, f (2, 7) = 2, since binary representation of 2 and 7 are 010 and 111, respectively. The first and the third bit differ, so f (2, 7) = 2.
You are given an array A of N integers, A_{1}, A_{2} ,…, A_{N}. Find sum of f(A_{i}, A_{j}) for all ordered pairs (i, j) such that 1 ≤ i, j ≤ N. Return the answer modulo 10^{9}+7.
Example 1:
Input: N = 2
A = {2, 4}
Output: 4
Explaintion: We return
f(2, 2) + f(2, 4) +
f(4, 2) + f(4, 4) =
0 + 2 +
2 + 0 = 4.
Example 2:
Input: N = 3
A = {1, 3, 5}
Output: 8
Explaination: We return
f(1, 1) + f(1, 3) + f(1, 5) +
f(3, 1) + f(3, 3) + f(3, 5) +
f(5, 1) + f(5, 3) + f(5, 5) =
0 + 1 + 1 +
1 + 0 + 2 +
1 + 2 + 0 = 8.
Your Task:
You do not need to read input or print anything. Your task is to complete the function countBits() which takes the value N and the array A as input parameters and returns the desired count modulo 10^{9}+7.
Expected Time Complexity: O(N * log_{2}(Max(A_{i})))
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 10^{5}
2^{0} ≤ A[i] < 2^{31} | class Solution:
def countBits(self, N, A):
ans = 0
mod = 10**9 + 7
for i in range(32):
mask = 1 << i
ones = 0
zeros = 0
for val in A:
if val & mask > 0:
ones += 1
else:
zeros += 1
total = ones * zeros % mod
total = (total + total) % mod
ans = (ans + total) % mod
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR BIN_OP BIN_OP NUMBER NUMBER NUMBER FOR VAR FUNC_CALL VAR NUMBER ASSIGN VAR BIN_OP NUMBER VAR ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR IF BIN_OP VAR VAR NUMBER VAR NUMBER VAR NUMBER ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR RETURN VAR |
We define f (X, Y) as number of different corresponding bits in binary representation of X and Y. For example, f (2, 7) = 2, since binary representation of 2 and 7 are 010 and 111, respectively. The first and the third bit differ, so f (2, 7) = 2.
You are given an array A of N integers, A_{1}, A_{2} ,…, A_{N}. Find sum of f(A_{i}, A_{j}) for all ordered pairs (i, j) such that 1 ≤ i, j ≤ N. Return the answer modulo 10^{9}+7.
Example 1:
Input: N = 2
A = {2, 4}
Output: 4
Explaintion: We return
f(2, 2) + f(2, 4) +
f(4, 2) + f(4, 4) =
0 + 2 +
2 + 0 = 4.
Example 2:
Input: N = 3
A = {1, 3, 5}
Output: 8
Explaination: We return
f(1, 1) + f(1, 3) + f(1, 5) +
f(3, 1) + f(3, 3) + f(3, 5) +
f(5, 1) + f(5, 3) + f(5, 5) =
0 + 1 + 1 +
1 + 0 + 2 +
1 + 2 + 0 = 8.
Your Task:
You do not need to read input or print anything. Your task is to complete the function countBits() which takes the value N and the array A as input parameters and returns the desired count modulo 10^{9}+7.
Expected Time Complexity: O(N * log_{2}(Max(A_{i})))
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 10^{5}
2^{0} ≤ A[i] < 2^{31} | class Solution:
def countBits(self, N, A):
num_ones = [0] * 31
for ele in A:
i = 0
while ele:
if ele & 1:
num_ones[i] += 1
i += 1
ele = ele >> 1
res = 0
for ele in num_ones:
res += ele * (N - ele) % (1000000000.0 + 7)
return int(res * 2 % (1000000000.0 + 7)) | CLASS_DEF FUNC_DEF ASSIGN VAR BIN_OP LIST NUMBER NUMBER FOR VAR VAR ASSIGN VAR NUMBER WHILE VAR IF BIN_OP VAR NUMBER VAR VAR NUMBER VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR VAR BIN_OP BIN_OP VAR BIN_OP VAR VAR BIN_OP NUMBER NUMBER RETURN FUNC_CALL VAR BIN_OP BIN_OP VAR NUMBER BIN_OP NUMBER NUMBER |
We define f (X, Y) as number of different corresponding bits in binary representation of X and Y. For example, f (2, 7) = 2, since binary representation of 2 and 7 are 010 and 111, respectively. The first and the third bit differ, so f (2, 7) = 2.
You are given an array A of N integers, A_{1}, A_{2} ,…, A_{N}. Find sum of f(A_{i}, A_{j}) for all ordered pairs (i, j) such that 1 ≤ i, j ≤ N. Return the answer modulo 10^{9}+7.
Example 1:
Input: N = 2
A = {2, 4}
Output: 4
Explaintion: We return
f(2, 2) + f(2, 4) +
f(4, 2) + f(4, 4) =
0 + 2 +
2 + 0 = 4.
Example 2:
Input: N = 3
A = {1, 3, 5}
Output: 8
Explaination: We return
f(1, 1) + f(1, 3) + f(1, 5) +
f(3, 1) + f(3, 3) + f(3, 5) +
f(5, 1) + f(5, 3) + f(5, 5) =
0 + 1 + 1 +
1 + 0 + 2 +
1 + 2 + 0 = 8.
Your Task:
You do not need to read input or print anything. Your task is to complete the function countBits() which takes the value N and the array A as input parameters and returns the desired count modulo 10^{9}+7.
Expected Time Complexity: O(N * log_{2}(Max(A_{i})))
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 10^{5}
2^{0} ≤ A[i] < 2^{31} | class Solution:
def countBits(self, N, A):
max_val = max(A)
bin_max = bin(max_val)[2:]
max_len = len(bin_max)
countOnesZerosEachBit = [[0, 0] for i in range(max_len)]
for num in A:
bin_num = bin(num)[2:].zfill(max_len)
for d in range(max_len):
if bin_num[max_len - d - 1] == "1":
countOnesZerosEachBit[max_len - d - 1][1] += 1
else:
countOnesZerosEachBit[max_len - d - 1][0] += 1
result = 0
for pair in countOnesZerosEachBit:
result += pair[0] * pair[1]
return result * 2 % (10**9 + 7) | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR LIST NUMBER NUMBER VAR FUNC_CALL VAR VAR FOR VAR VAR ASSIGN VAR FUNC_CALL FUNC_CALL VAR VAR NUMBER VAR FOR VAR FUNC_CALL VAR VAR IF VAR BIN_OP BIN_OP VAR VAR NUMBER STRING VAR BIN_OP BIN_OP VAR VAR NUMBER NUMBER NUMBER VAR BIN_OP BIN_OP VAR VAR NUMBER NUMBER NUMBER ASSIGN VAR NUMBER FOR VAR VAR VAR BIN_OP VAR NUMBER VAR NUMBER RETURN BIN_OP BIN_OP VAR NUMBER BIN_OP BIN_OP NUMBER NUMBER NUMBER |
We define f (X, Y) as number of different corresponding bits in binary representation of X and Y. For example, f (2, 7) = 2, since binary representation of 2 and 7 are 010 and 111, respectively. The first and the third bit differ, so f (2, 7) = 2.
You are given an array A of N integers, A_{1}, A_{2} ,…, A_{N}. Find sum of f(A_{i}, A_{j}) for all ordered pairs (i, j) such that 1 ≤ i, j ≤ N. Return the answer modulo 10^{9}+7.
Example 1:
Input: N = 2
A = {2, 4}
Output: 4
Explaintion: We return
f(2, 2) + f(2, 4) +
f(4, 2) + f(4, 4) =
0 + 2 +
2 + 0 = 4.
Example 2:
Input: N = 3
A = {1, 3, 5}
Output: 8
Explaination: We return
f(1, 1) + f(1, 3) + f(1, 5) +
f(3, 1) + f(3, 3) + f(3, 5) +
f(5, 1) + f(5, 3) + f(5, 5) =
0 + 1 + 1 +
1 + 0 + 2 +
1 + 2 + 0 = 8.
Your Task:
You do not need to read input or print anything. Your task is to complete the function countBits() which takes the value N and the array A as input parameters and returns the desired count modulo 10^{9}+7.
Expected Time Complexity: O(N * log_{2}(Max(A_{i})))
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 10^{5}
2^{0} ≤ A[i] < 2^{31} | class Solution:
def countBits(self, n, arr):
lis = [0] * 33
for num in arr:
i = num
j = 0
while i > 0:
if i & 1 == 1:
lis[j] += 1
i //= 2
j += 1
ans = 0
m = 10**9 + 7
for i in range(33):
ans += 2 * (lis[i] * (n - lis[i]))
ans %= m
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR BIN_OP LIST NUMBER NUMBER FOR VAR VAR ASSIGN VAR VAR ASSIGN VAR NUMBER WHILE VAR NUMBER IF BIN_OP VAR NUMBER NUMBER VAR VAR NUMBER VAR NUMBER VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR BIN_OP BIN_OP NUMBER NUMBER NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR BIN_OP NUMBER BIN_OP VAR VAR BIN_OP VAR VAR VAR VAR VAR RETURN VAR |
We define f (X, Y) as number of different corresponding bits in binary representation of X and Y. For example, f (2, 7) = 2, since binary representation of 2 and 7 are 010 and 111, respectively. The first and the third bit differ, so f (2, 7) = 2.
You are given an array A of N integers, A_{1}, A_{2} ,…, A_{N}. Find sum of f(A_{i}, A_{j}) for all ordered pairs (i, j) such that 1 ≤ i, j ≤ N. Return the answer modulo 10^{9}+7.
Example 1:
Input: N = 2
A = {2, 4}
Output: 4
Explaintion: We return
f(2, 2) + f(2, 4) +
f(4, 2) + f(4, 4) =
0 + 2 +
2 + 0 = 4.
Example 2:
Input: N = 3
A = {1, 3, 5}
Output: 8
Explaination: We return
f(1, 1) + f(1, 3) + f(1, 5) +
f(3, 1) + f(3, 3) + f(3, 5) +
f(5, 1) + f(5, 3) + f(5, 5) =
0 + 1 + 1 +
1 + 0 + 2 +
1 + 2 + 0 = 8.
Your Task:
You do not need to read input or print anything. Your task is to complete the function countBits() which takes the value N and the array A as input parameters and returns the desired count modulo 10^{9}+7.
Expected Time Complexity: O(N * log_{2}(Max(A_{i})))
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 10^{5}
2^{0} ≤ A[i] < 2^{31} | class Solution:
def countBits(self, n, arr):
l = [(0) for i in range(32)]
for val in arr:
for i in range(32):
if val & 1 << i:
l[i] += 1
ans = 0
for i in range(32):
ans += 2 * (n - l[i]) * l[i] % (10**9 + 7)
return ans % (10**9 + 7) | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER VAR FUNC_CALL VAR NUMBER FOR VAR VAR FOR VAR FUNC_CALL VAR NUMBER IF BIN_OP VAR BIN_OP NUMBER VAR VAR VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR BIN_OP BIN_OP BIN_OP NUMBER BIN_OP VAR VAR VAR VAR VAR BIN_OP BIN_OP NUMBER NUMBER NUMBER RETURN BIN_OP VAR BIN_OP BIN_OP NUMBER NUMBER NUMBER |
We define f (X, Y) as number of different corresponding bits in binary representation of X and Y. For example, f (2, 7) = 2, since binary representation of 2 and 7 are 010 and 111, respectively. The first and the third bit differ, so f (2, 7) = 2.
You are given an array A of N integers, A_{1}, A_{2} ,…, A_{N}. Find sum of f(A_{i}, A_{j}) for all ordered pairs (i, j) such that 1 ≤ i, j ≤ N. Return the answer modulo 10^{9}+7.
Example 1:
Input: N = 2
A = {2, 4}
Output: 4
Explaintion: We return
f(2, 2) + f(2, 4) +
f(4, 2) + f(4, 4) =
0 + 2 +
2 + 0 = 4.
Example 2:
Input: N = 3
A = {1, 3, 5}
Output: 8
Explaination: We return
f(1, 1) + f(1, 3) + f(1, 5) +
f(3, 1) + f(3, 3) + f(3, 5) +
f(5, 1) + f(5, 3) + f(5, 5) =
0 + 1 + 1 +
1 + 0 + 2 +
1 + 2 + 0 = 8.
Your Task:
You do not need to read input or print anything. Your task is to complete the function countBits() which takes the value N and the array A as input parameters and returns the desired count modulo 10^{9}+7.
Expected Time Complexity: O(N * log_{2}(Max(A_{i})))
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 10^{5}
2^{0} ≤ A[i] < 2^{31} | class Solution:
def countBits(self, N, A):
maxOfA = max(A)
ans = 0
while maxOfA > 0:
countOfZero = 0
countOfOne = 0
for i in range(N):
lastBit = A[i] & 1
if lastBit == 0:
countOfZero += 1
else:
countOfOne += 1
A[i] = A[i] >> 1
ans += countOfZero * countOfOne * 2
maxOfA = maxOfA >> 1
return ans % 1000000007 | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER WHILE VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR VAR NUMBER IF VAR NUMBER VAR NUMBER VAR NUMBER ASSIGN VAR VAR BIN_OP VAR VAR NUMBER VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER RETURN BIN_OP VAR NUMBER |
We define f (X, Y) as number of different corresponding bits in binary representation of X and Y. For example, f (2, 7) = 2, since binary representation of 2 and 7 are 010 and 111, respectively. The first and the third bit differ, so f (2, 7) = 2.
You are given an array A of N integers, A_{1}, A_{2} ,…, A_{N}. Find sum of f(A_{i}, A_{j}) for all ordered pairs (i, j) such that 1 ≤ i, j ≤ N. Return the answer modulo 10^{9}+7.
Example 1:
Input: N = 2
A = {2, 4}
Output: 4
Explaintion: We return
f(2, 2) + f(2, 4) +
f(4, 2) + f(4, 4) =
0 + 2 +
2 + 0 = 4.
Example 2:
Input: N = 3
A = {1, 3, 5}
Output: 8
Explaination: We return
f(1, 1) + f(1, 3) + f(1, 5) +
f(3, 1) + f(3, 3) + f(3, 5) +
f(5, 1) + f(5, 3) + f(5, 5) =
0 + 1 + 1 +
1 + 0 + 2 +
1 + 2 + 0 = 8.
Your Task:
You do not need to read input or print anything. Your task is to complete the function countBits() which takes the value N and the array A as input parameters and returns the desired count modulo 10^{9}+7.
Expected Time Complexity: O(N * log_{2}(Max(A_{i})))
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 10^{5}
2^{0} ≤ A[i] < 2^{31} | class Solution:
def countBits(self, N, A):
ma = len(bin(max(A))) - 2
ar0 = [(0) for x in range(ma)]
ar1 = [(0) for x in range(ma)]
for x in A:
for y in range(ma):
bit = x & 1
if bit == 1:
ar1[y] += 1
else:
ar0[y] += 1
x = x >> 1
c = 0
for x in range(ma):
c += ar0[x] * ar1[x]
return c * 2 % (10**9 + 7) | CLASS_DEF FUNC_DEF ASSIGN VAR BIN_OP FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR NUMBER ASSIGN VAR NUMBER VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER VAR FUNC_CALL VAR VAR FOR VAR VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR NUMBER IF VAR NUMBER VAR VAR NUMBER VAR VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR VAR BIN_OP VAR VAR VAR VAR RETURN BIN_OP BIN_OP VAR NUMBER BIN_OP BIN_OP NUMBER NUMBER NUMBER |
We define f (X, Y) as number of different corresponding bits in binary representation of X and Y. For example, f (2, 7) = 2, since binary representation of 2 and 7 are 010 and 111, respectively. The first and the third bit differ, so f (2, 7) = 2.
You are given an array A of N integers, A_{1}, A_{2} ,…, A_{N}. Find sum of f(A_{i}, A_{j}) for all ordered pairs (i, j) such that 1 ≤ i, j ≤ N. Return the answer modulo 10^{9}+7.
Example 1:
Input: N = 2
A = {2, 4}
Output: 4
Explaintion: We return
f(2, 2) + f(2, 4) +
f(4, 2) + f(4, 4) =
0 + 2 +
2 + 0 = 4.
Example 2:
Input: N = 3
A = {1, 3, 5}
Output: 8
Explaination: We return
f(1, 1) + f(1, 3) + f(1, 5) +
f(3, 1) + f(3, 3) + f(3, 5) +
f(5, 1) + f(5, 3) + f(5, 5) =
0 + 1 + 1 +
1 + 0 + 2 +
1 + 2 + 0 = 8.
Your Task:
You do not need to read input or print anything. Your task is to complete the function countBits() which takes the value N and the array A as input parameters and returns the desired count modulo 10^{9}+7.
Expected Time Complexity: O(N * log_{2}(Max(A_{i})))
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 10^{5}
2^{0} ≤ A[i] < 2^{31} | class Solution:
def countBits(self, N, A):
t = 0.5
ans = 0
for i in range(32):
c1 = c2 = 0
t *= 2
for j in range(N):
if A[j] & 1 << i:
c1 += 1
else:
c2 += 1
ans += c1 * c2 * 2
return int(ans % 1000000007) | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER ASSIGN VAR VAR NUMBER VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF BIN_OP VAR VAR BIN_OP NUMBER VAR VAR NUMBER VAR NUMBER VAR BIN_OP BIN_OP VAR VAR NUMBER RETURN FUNC_CALL VAR BIN_OP VAR NUMBER |
We define f (X, Y) as number of different corresponding bits in binary representation of X and Y. For example, f (2, 7) = 2, since binary representation of 2 and 7 are 010 and 111, respectively. The first and the third bit differ, so f (2, 7) = 2.
You are given an array A of N integers, A_{1}, A_{2} ,…, A_{N}. Find sum of f(A_{i}, A_{j}) for all ordered pairs (i, j) such that 1 ≤ i, j ≤ N. Return the answer modulo 10^{9}+7.
Example 1:
Input: N = 2
A = {2, 4}
Output: 4
Explaintion: We return
f(2, 2) + f(2, 4) +
f(4, 2) + f(4, 4) =
0 + 2 +
2 + 0 = 4.
Example 2:
Input: N = 3
A = {1, 3, 5}
Output: 8
Explaination: We return
f(1, 1) + f(1, 3) + f(1, 5) +
f(3, 1) + f(3, 3) + f(3, 5) +
f(5, 1) + f(5, 3) + f(5, 5) =
0 + 1 + 1 +
1 + 0 + 2 +
1 + 2 + 0 = 8.
Your Task:
You do not need to read input or print anything. Your task is to complete the function countBits() which takes the value N and the array A as input parameters and returns the desired count modulo 10^{9}+7.
Expected Time Complexity: O(N * log_{2}(Max(A_{i})))
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 10^{5}
2^{0} ≤ A[i] < 2^{31} | class Solution:
def countBits(self, N, A):
has = {}
for i in range(31):
has[i] = 0
for j in range(N):
if A[j] > 0:
has[i] += A[j] % 2
A[j] //= 2
res = 0
for i in has:
res += has[i] * (N - has[i])
return 2 * res % (10**9 + 7) | CLASS_DEF FUNC_DEF ASSIGN VAR DICT FOR VAR FUNC_CALL VAR NUMBER ASSIGN VAR VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR NUMBER VAR VAR BIN_OP VAR VAR NUMBER VAR VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR VAR BIN_OP VAR VAR BIN_OP VAR VAR VAR RETURN BIN_OP BIN_OP NUMBER VAR BIN_OP BIN_OP NUMBER NUMBER NUMBER |
We define f (X, Y) as number of different corresponding bits in binary representation of X and Y. For example, f (2, 7) = 2, since binary representation of 2 and 7 are 010 and 111, respectively. The first and the third bit differ, so f (2, 7) = 2.
You are given an array A of N integers, A_{1}, A_{2} ,…, A_{N}. Find sum of f(A_{i}, A_{j}) for all ordered pairs (i, j) such that 1 ≤ i, j ≤ N. Return the answer modulo 10^{9}+7.
Example 1:
Input: N = 2
A = {2, 4}
Output: 4
Explaintion: We return
f(2, 2) + f(2, 4) +
f(4, 2) + f(4, 4) =
0 + 2 +
2 + 0 = 4.
Example 2:
Input: N = 3
A = {1, 3, 5}
Output: 8
Explaination: We return
f(1, 1) + f(1, 3) + f(1, 5) +
f(3, 1) + f(3, 3) + f(3, 5) +
f(5, 1) + f(5, 3) + f(5, 5) =
0 + 1 + 1 +
1 + 0 + 2 +
1 + 2 + 0 = 8.
Your Task:
You do not need to read input or print anything. Your task is to complete the function countBits() which takes the value N and the array A as input parameters and returns the desired count modulo 10^{9}+7.
Expected Time Complexity: O(N * log_{2}(Max(A_{i})))
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 10^{5}
2^{0} ≤ A[i] < 2^{31} | class Solution:
def countBits(self, N, A):
mx = max(A)
ans = 0
bits = len(bin(mx)[2:])
for x in range(0, bits + 2):
cnt = 0
for i in range(N):
if A[i] & 1 << x:
cnt += 1
ans += cnt * (N - cnt) * 2
return ans % 1000000007 | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF BIN_OP VAR VAR BIN_OP NUMBER VAR VAR NUMBER VAR BIN_OP BIN_OP VAR BIN_OP VAR VAR NUMBER RETURN BIN_OP VAR NUMBER |
We define f (X, Y) as number of different corresponding bits in binary representation of X and Y. For example, f (2, 7) = 2, since binary representation of 2 and 7 are 010 and 111, respectively. The first and the third bit differ, so f (2, 7) = 2.
You are given an array A of N integers, A_{1}, A_{2} ,…, A_{N}. Find sum of f(A_{i}, A_{j}) for all ordered pairs (i, j) such that 1 ≤ i, j ≤ N. Return the answer modulo 10^{9}+7.
Example 1:
Input: N = 2
A = {2, 4}
Output: 4
Explaintion: We return
f(2, 2) + f(2, 4) +
f(4, 2) + f(4, 4) =
0 + 2 +
2 + 0 = 4.
Example 2:
Input: N = 3
A = {1, 3, 5}
Output: 8
Explaination: We return
f(1, 1) + f(1, 3) + f(1, 5) +
f(3, 1) + f(3, 3) + f(3, 5) +
f(5, 1) + f(5, 3) + f(5, 5) =
0 + 1 + 1 +
1 + 0 + 2 +
1 + 2 + 0 = 8.
Your Task:
You do not need to read input or print anything. Your task is to complete the function countBits() which takes the value N and the array A as input parameters and returns the desired count modulo 10^{9}+7.
Expected Time Complexity: O(N * log_{2}(Max(A_{i})))
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 10^{5}
2^{0} ≤ A[i] < 2^{31} | class Solution:
def countBits(self, N, A):
ans = 0
m = 10**9 + 7
for i in range(0, 32):
z = 0
o = 0
for j in A:
if 1 << i & j == 0:
z += 1
else:
o += 1
ans += z * o
ans %= m
return ans * 2 % m | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR BIN_OP BIN_OP NUMBER NUMBER NUMBER FOR VAR FUNC_CALL VAR NUMBER NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR IF BIN_OP BIN_OP NUMBER VAR VAR NUMBER VAR NUMBER VAR NUMBER VAR BIN_OP VAR VAR VAR VAR RETURN BIN_OP BIN_OP VAR NUMBER VAR |
We define f (X, Y) as number of different corresponding bits in binary representation of X and Y. For example, f (2, 7) = 2, since binary representation of 2 and 7 are 010 and 111, respectively. The first and the third bit differ, so f (2, 7) = 2.
You are given an array A of N integers, A_{1}, A_{2} ,…, A_{N}. Find sum of f(A_{i}, A_{j}) for all ordered pairs (i, j) such that 1 ≤ i, j ≤ N. Return the answer modulo 10^{9}+7.
Example 1:
Input: N = 2
A = {2, 4}
Output: 4
Explaintion: We return
f(2, 2) + f(2, 4) +
f(4, 2) + f(4, 4) =
0 + 2 +
2 + 0 = 4.
Example 2:
Input: N = 3
A = {1, 3, 5}
Output: 8
Explaination: We return
f(1, 1) + f(1, 3) + f(1, 5) +
f(3, 1) + f(3, 3) + f(3, 5) +
f(5, 1) + f(5, 3) + f(5, 5) =
0 + 1 + 1 +
1 + 0 + 2 +
1 + 2 + 0 = 8.
Your Task:
You do not need to read input or print anything. Your task is to complete the function countBits() which takes the value N and the array A as input parameters and returns the desired count modulo 10^{9}+7.
Expected Time Complexity: O(N * log_{2}(Max(A_{i})))
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 10^{5}
2^{0} ≤ A[i] < 2^{31} | class Solution:
def countBits(self, N, A):
sum = 0
n = len(A)
x = 1000000007
for i in range(0, 32):
count = 0
for j in range(0, n):
if A[j] & 1 << i:
count += 1
sum += 2 * count * (n - count)
return sum % x | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR IF BIN_OP VAR VAR BIN_OP NUMBER VAR VAR NUMBER VAR BIN_OP BIN_OP NUMBER VAR BIN_OP VAR VAR RETURN BIN_OP VAR VAR |
We define f (X, Y) as number of different corresponding bits in binary representation of X and Y. For example, f (2, 7) = 2, since binary representation of 2 and 7 are 010 and 111, respectively. The first and the third bit differ, so f (2, 7) = 2.
You are given an array A of N integers, A_{1}, A_{2} ,…, A_{N}. Find sum of f(A_{i}, A_{j}) for all ordered pairs (i, j) such that 1 ≤ i, j ≤ N. Return the answer modulo 10^{9}+7.
Example 1:
Input: N = 2
A = {2, 4}
Output: 4
Explaintion: We return
f(2, 2) + f(2, 4) +
f(4, 2) + f(4, 4) =
0 + 2 +
2 + 0 = 4.
Example 2:
Input: N = 3
A = {1, 3, 5}
Output: 8
Explaination: We return
f(1, 1) + f(1, 3) + f(1, 5) +
f(3, 1) + f(3, 3) + f(3, 5) +
f(5, 1) + f(5, 3) + f(5, 5) =
0 + 1 + 1 +
1 + 0 + 2 +
1 + 2 + 0 = 8.
Your Task:
You do not need to read input or print anything. Your task is to complete the function countBits() which takes the value N and the array A as input parameters and returns the desired count modulo 10^{9}+7.
Expected Time Complexity: O(N * log_{2}(Max(A_{i})))
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 10^{5}
2^{0} ≤ A[i] < 2^{31} | from itertools import combinations
class Solution:
def bin_diffrence(self, pair):
bin_diff_bet_pair = 0
a = min(pair)
b = max(pair)
bin_a = bin(a)[2:]
bin_b = bin(b)[2:]
diff_bet_len = len(bin_b) - len(bin_a)
bin_a = "0" * diff_bet_len + bin_a
i = len(bin_a) - 1
for i in range(len(bin_b)):
if bin_a[i] != bin_b[i]:
bin_diff_bet_pair += 1
i -= 1
return bin_diff_bet_pair
def countBits(self, N, a):
modulo_number = 10**9 + 7
full_diff = 0
for i in range(32):
set_bits = 0
for elem in a:
if elem & 1 << i:
set_bits += 1
unset_bits = N - set_bits
full_diff += 2 * set_bits * unset_bits
return full_diff % modulo_number | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR NUMBER ASSIGN VAR BIN_OP FUNC_CALL VAR VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP BIN_OP STRING VAR VAR ASSIGN VAR BIN_OP FUNC_CALL VAR VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR VAR NUMBER VAR NUMBER RETURN VAR FUNC_DEF ASSIGN VAR BIN_OP BIN_OP NUMBER NUMBER NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR IF BIN_OP VAR BIN_OP NUMBER VAR VAR NUMBER ASSIGN VAR BIN_OP VAR VAR VAR BIN_OP BIN_OP NUMBER VAR VAR RETURN BIN_OP VAR VAR |
We define f (X, Y) as number of different corresponding bits in binary representation of X and Y. For example, f (2, 7) = 2, since binary representation of 2 and 7 are 010 and 111, respectively. The first and the third bit differ, so f (2, 7) = 2.
You are given an array A of N integers, A_{1}, A_{2} ,…, A_{N}. Find sum of f(A_{i}, A_{j}) for all ordered pairs (i, j) such that 1 ≤ i, j ≤ N. Return the answer modulo 10^{9}+7.
Example 1:
Input: N = 2
A = {2, 4}
Output: 4
Explaintion: We return
f(2, 2) + f(2, 4) +
f(4, 2) + f(4, 4) =
0 + 2 +
2 + 0 = 4.
Example 2:
Input: N = 3
A = {1, 3, 5}
Output: 8
Explaination: We return
f(1, 1) + f(1, 3) + f(1, 5) +
f(3, 1) + f(3, 3) + f(3, 5) +
f(5, 1) + f(5, 3) + f(5, 5) =
0 + 1 + 1 +
1 + 0 + 2 +
1 + 2 + 0 = 8.
Your Task:
You do not need to read input or print anything. Your task is to complete the function countBits() which takes the value N and the array A as input parameters and returns the desired count modulo 10^{9}+7.
Expected Time Complexity: O(N * log_{2}(Max(A_{i})))
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 10^{5}
2^{0} ≤ A[i] < 2^{31} | class Solution:
def countBits(self, N, A):
sum = 0
for i in range(32):
count1 = 0
for j in range(N):
if A[j] & 1 << i:
count1 += 1
count0 = N - count1
sum += 2 * count0 * count1
return sum % (10**9 + 7) | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF BIN_OP VAR VAR BIN_OP NUMBER VAR VAR NUMBER ASSIGN VAR BIN_OP VAR VAR VAR BIN_OP BIN_OP NUMBER VAR VAR RETURN BIN_OP VAR BIN_OP BIN_OP NUMBER NUMBER NUMBER |
Given an array A of strings, find any smallest string that contains each string in A as a substring.
We may assume that no string in A is substring of another string in A.
Example 1:
Input: ["alex","loves","leetcode"]
Output: "alexlovesleetcode"
Explanation: All permutations of "alex","loves","leetcode" would also be accepted.
Example 2:
Input: ["catg","ctaagt","gcta","ttca","atgcatc"]
Output: "gctaagttcatgcatc"
Note:
1 <= A.length <= 12
1 <= A[i].length <= 20 | INF = 1 << 60
class Solution:
def shortestSuperstring(self, A: List[str]) -> str:
n = len(A)
overlap = [([0] * n) for _ in range(n)]
for i, j in product(range(n), repeat=2):
l = min(len(A[i]), len(A[j]))
overlap[i][j] = max(
k for k in range(l + 1) if A[i][len(A[i]) - k :] == A[j][:k]
)
dp = [([INF] * n) for _ in range(1 << n)]
prev = [([(None, None)] * n) for _ in range(1 << n)]
for i, S in enumerate(A):
dp[1 << i][i] = len(S)
for U, i in product(range(1 << n), range(n)):
if not U >> i & 1:
continue
for ni in range(n):
if U >> ni & 1:
continue
if dp[U | 1 << ni][ni] > dp[U][i] + len(A[ni]) - overlap[i][ni]:
dp[U | 1 << ni][ni] = dp[U][i] + len(A[ni]) - overlap[i][ni]
prev[U | 1 << ni][ni] = U, i
U, i = (1 << n) - 1, min(range(n), key=lambda i: dp[-1][i])
res = []
while U is not None:
res.append(A[i])
U, i = prev[U][i]
res.reverse()
ans = ""
for S in res:
l = min(len(ans), len(S))
k = max(k for k in range(l + 1) if ans[len(ans) - k :] == S[:k])
ans += S[k:]
return ans | ASSIGN VAR BIN_OP NUMBER NUMBER CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST NUMBER VAR VAR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR FUNC_CALL VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR BIN_OP FUNC_CALL VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR BIN_OP LIST VAR VAR VAR FUNC_CALL VAR BIN_OP NUMBER VAR ASSIGN VAR BIN_OP LIST NONE NONE VAR VAR FUNC_CALL VAR BIN_OP NUMBER VAR FOR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP NUMBER VAR VAR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR FUNC_CALL VAR BIN_OP NUMBER VAR FUNC_CALL VAR VAR IF BIN_OP BIN_OP VAR VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF BIN_OP BIN_OP VAR VAR NUMBER IF VAR BIN_OP VAR BIN_OP NUMBER VAR VAR BIN_OP BIN_OP VAR VAR VAR FUNC_CALL VAR VAR VAR VAR VAR VAR ASSIGN VAR BIN_OP VAR BIN_OP NUMBER VAR VAR BIN_OP BIN_OP VAR VAR VAR FUNC_CALL VAR VAR VAR VAR VAR VAR ASSIGN VAR BIN_OP VAR BIN_OP NUMBER VAR VAR VAR VAR ASSIGN VAR VAR BIN_OP BIN_OP NUMBER VAR NUMBER FUNC_CALL VAR FUNC_CALL VAR VAR VAR NUMBER VAR ASSIGN VAR LIST WHILE VAR NONE EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR STRING FOR VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR BIN_OP VAR NUMBER VAR BIN_OP FUNC_CALL VAR VAR VAR VAR VAR VAR VAR VAR RETURN VAR VAR |
Given an array A of strings, find any smallest string that contains each string in A as a substring.
We may assume that no string in A is substring of another string in A.
Example 1:
Input: ["alex","loves","leetcode"]
Output: "alexlovesleetcode"
Explanation: All permutations of "alex","loves","leetcode" would also be accepted.
Example 2:
Input: ["catg","ctaagt","gcta","ttca","atgcatc"]
Output: "gctaagttcatgcatc"
Note:
1 <= A.length <= 12
1 <= A[i].length <= 20 | class Solution:
def shortestSuperstring(self, A: List[str]) -> str:
@lru_cache(None)
def dp(p, mask):
if mask == 0:
return 0, 0
result = 0
k = -1
for j in range(n):
if not mask >> j & 1:
continue
l = g[p].get(j, 0)
h, x = dp(j, mask & ~(1 << j))
h += l
if h >= result:
result = h
k = j
return result, k
A.insert(0, "*")
n = len(A)
g = collections.defaultdict(dict)
for i in range(n):
for j in range(n):
if i == j:
continue
h = min(len(A[i]), len(A[j]))
for l in range(h - 1, 0, -1):
if A[i][-l:] == A[j][:l]:
g[i][j] = l
break
mask = (1 << n) - 2
p = 0
result = ""
for i in range(1, n):
l, x = dp(p, mask)
result += A[x][g[p].get(x, 0) :]
p = x
mask = mask & ~(1 << x)
return result | CLASS_DEF FUNC_DEF VAR VAR FUNC_DEF IF VAR NUMBER RETURN NUMBER NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR NUMBER ASSIGN VAR VAR FUNC_CALL VAR VAR BIN_OP VAR BIN_OP NUMBER VAR VAR VAR IF VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR RETURN VAR VAR FUNC_CALL VAR NONE EXPR FUNC_CALL VAR NUMBER STRING ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR IF VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER NUMBER NUMBER IF VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR BIN_OP BIN_OP NUMBER VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR STRING FOR VAR FUNC_CALL VAR NUMBER VAR ASSIGN VAR VAR FUNC_CALL VAR VAR VAR VAR VAR VAR FUNC_CALL VAR VAR VAR NUMBER ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR BIN_OP NUMBER VAR RETURN VAR VAR |
Given an array A of strings, find any smallest string that contains each string in A as a substring.
We may assume that no string in A is substring of another string in A.
Example 1:
Input: ["alex","loves","leetcode"]
Output: "alexlovesleetcode"
Explanation: All permutations of "alex","loves","leetcode" would also be accepted.
Example 2:
Input: ["catg","ctaagt","gcta","ttca","atgcatc"]
Output: "gctaagttcatgcatc"
Note:
1 <= A.length <= 12
1 <= A[i].length <= 20 | class Solution:
def shortestSuperstring(self, A: List[str]) -> str:
n = len(A)
graph = [([0] * n) for _ in range(n)]
for i, word1 in enumerate(A):
for j, word2 in enumerate(A):
if i == j:
continue
for k in range(min(len(word1), len(word2)))[::-1]:
if word1[-k:] == word2[:k]:
graph[i][j] = k
break
memo = {}
def search(i, k):
if (i, k) in memo:
return memo[i, k]
if i == 1 << k:
return A[k]
memo[i, k] = ""
for j in range(n):
if j != k and i & 1 << j:
candidate = search(i ^ 1 << k, j) + A[k][graph[j][k] :]
if memo[i, k] == "" or len(candidate) < len(memo[i, k]):
memo[i, k] = candidate
return memo[i, k]
res = ""
for k in range(n):
candidate = search((1 << n) - 1, k)
if res == "" or len(candidate) < len(res):
res = candidate
return res | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST NUMBER VAR VAR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR VAR IF VAR VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR NUMBER IF VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR DICT FUNC_DEF IF VAR VAR VAR RETURN VAR VAR VAR IF VAR BIN_OP NUMBER VAR RETURN VAR VAR ASSIGN VAR VAR VAR STRING FOR VAR FUNC_CALL VAR VAR IF VAR VAR BIN_OP VAR BIN_OP NUMBER VAR ASSIGN VAR BIN_OP FUNC_CALL VAR BIN_OP VAR BIN_OP NUMBER VAR VAR VAR VAR VAR VAR VAR IF VAR VAR VAR STRING FUNC_CALL VAR VAR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR RETURN VAR VAR VAR ASSIGN VAR STRING FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR BIN_OP BIN_OP NUMBER VAR NUMBER VAR IF VAR STRING FUNC_CALL VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR RETURN VAR VAR |
Given an array A of strings, find any smallest string that contains each string in A as a substring.
We may assume that no string in A is substring of another string in A.
Example 1:
Input: ["alex","loves","leetcode"]
Output: "alexlovesleetcode"
Explanation: All permutations of "alex","loves","leetcode" would also be accepted.
Example 2:
Input: ["catg","ctaagt","gcta","ttca","atgcatc"]
Output: "gctaagttcatgcatc"
Note:
1 <= A.length <= 12
1 <= A[i].length <= 20 | class Solution:
def shortestSuperstring(self, A: List[str]) -> str:
N = len(A)
def Cost(x, y):
cost = len(y)
max_similarity = 0
for i in range(1, min(len(x), len(y))):
if x[-i:] == y[:i]:
max_similarity = i
return cost - max_similarity
g = [([float("inf")] * N) for _ in range(N)]
for i in range(N):
for j in range(N):
if i != j:
cost = Cost(A[i], A[j])
g[i][j] = cost
else:
g[i][j] = len(A[i])
dp = [([float("inf")] * N) for _ in range(1 << N)]
parent = [([-1] * N) for _ in range(1 << N)]
for i in range(N):
dp[1 << i][i] = len(A[i])
for s in range(1, 1 << N):
for i in range(N):
if s & 1 << i:
prev = s - (1 << i)
for j in range(N):
if j != i and prev & 1 << j:
cur_cost = dp[prev][j] + g[j][i]
if cur_cost < dp[s][i]:
dp[s][i] = cur_cost
parent[s][i] = j
min_cost = float("inf")
ind = -1
last_row = dp[2**N - 1]
for i in range(N):
if last_row[i] < min_cost:
min_cost = last_row[i]
ind = i
s = 2**N - 1
res = A[ind]
child_ind = ind
ind = parent[s][ind]
s = s - (1 << child_ind)
while s and ind >= 0:
cost = g[ind][child_ind]
pre_len = len(A[ind]) - len(A[child_ind]) + g[ind][child_ind]
res = A[ind][:pre_len] + res
child_ind = ind
ind = parent[s][ind]
s = s - (1 << child_ind)
return res | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR ASSIGN VAR VAR RETURN BIN_OP VAR VAR ASSIGN VAR BIN_OP LIST FUNC_CALL VAR STRING VAR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR IF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR FUNC_CALL VAR VAR VAR ASSIGN VAR BIN_OP LIST FUNC_CALL VAR STRING VAR VAR FUNC_CALL VAR BIN_OP NUMBER VAR ASSIGN VAR BIN_OP LIST NUMBER VAR VAR FUNC_CALL VAR BIN_OP NUMBER VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP NUMBER VAR VAR FUNC_CALL VAR VAR VAR FOR VAR FUNC_CALL VAR NUMBER BIN_OP NUMBER VAR FOR VAR FUNC_CALL VAR VAR IF BIN_OP VAR BIN_OP NUMBER VAR ASSIGN VAR BIN_OP VAR BIN_OP NUMBER VAR FOR VAR FUNC_CALL VAR VAR IF VAR VAR BIN_OP VAR BIN_OP NUMBER VAR ASSIGN VAR BIN_OP VAR VAR VAR VAR VAR VAR IF VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR STRING ASSIGN VAR NUMBER ASSIGN VAR VAR BIN_OP BIN_OP NUMBER VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP BIN_OP NUMBER VAR NUMBER ASSIGN VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR BIN_OP VAR BIN_OP NUMBER VAR WHILE VAR VAR NUMBER ASSIGN VAR VAR VAR VAR ASSIGN VAR BIN_OP BIN_OP FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR VAR VAR VAR ASSIGN VAR BIN_OP VAR VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR BIN_OP VAR BIN_OP NUMBER VAR RETURN VAR VAR |
Given an array A of strings, find any smallest string that contains each string in A as a substring.
We may assume that no string in A is substring of another string in A.
Example 1:
Input: ["alex","loves","leetcode"]
Output: "alexlovesleetcode"
Explanation: All permutations of "alex","loves","leetcode" would also be accepted.
Example 2:
Input: ["catg","ctaagt","gcta","ttca","atgcatc"]
Output: "gctaagttcatgcatc"
Note:
1 <= A.length <= 12
1 <= A[i].length <= 20 | class Solution:
def shortestSuperstring(self, A: List[str]) -> str:
def dist(s1, s2):
ans = 0
for k in range(min(len(s1), len(s2))):
if s1[len(s1) - k :] == s2[:k]:
ans = len(s2) - k
return ans
n = len(A)
g = [([0] * n) for _ in range(n)]
for i in range(n):
for j in range(i + 1, n):
g[i][j] = dist(A[i], A[j])
g[j][i] = dist(A[j], A[i])
parent = [([-1] * n) for _ in range(1 << n)]
dp = [([float("inf")] * n) for _ in range(1 << n)]
for i in range(n):
dp[1 << i][i] = len(A[i])
for s in range(1, 1 << n):
for i in range(n):
if not s & 1 << i:
continue
prev = s - (1 << i)
for j in range(n):
if dp[prev][j] + g[j][i] < dp[s][i]:
dp[s][i] = dp[prev][j] + g[j][i]
parent[s][i] = j
end = dp[-1].index(min(dp[-1]))
s = (1 << n) - 1
res = ""
while s:
prev = parent[s][end]
if prev < 0:
res = A[end] + res
else:
res = A[end][len(A[end]) - g[prev][end] :] + res
s &= ~(1 << end)
end = prev
return res | CLASS_DEF FUNC_DEF VAR VAR FUNC_DEF ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR IF VAR BIN_OP FUNC_CALL VAR VAR VAR VAR VAR ASSIGN VAR BIN_OP FUNC_CALL VAR VAR VAR RETURN VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST NUMBER VAR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER VAR ASSIGN VAR VAR VAR FUNC_CALL VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR FUNC_CALL VAR VAR VAR VAR VAR ASSIGN VAR BIN_OP LIST NUMBER VAR VAR FUNC_CALL VAR BIN_OP NUMBER VAR ASSIGN VAR BIN_OP LIST FUNC_CALL VAR STRING VAR VAR FUNC_CALL VAR BIN_OP NUMBER VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP NUMBER VAR VAR FUNC_CALL VAR VAR VAR FOR VAR FUNC_CALL VAR NUMBER BIN_OP NUMBER VAR FOR VAR FUNC_CALL VAR VAR IF BIN_OP VAR BIN_OP NUMBER VAR ASSIGN VAR BIN_OP VAR BIN_OP NUMBER VAR FOR VAR FUNC_CALL VAR VAR IF BIN_OP VAR VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR BIN_OP VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR NUMBER FUNC_CALL VAR VAR NUMBER ASSIGN VAR BIN_OP BIN_OP NUMBER VAR NUMBER ASSIGN VAR STRING WHILE VAR ASSIGN VAR VAR VAR VAR IF VAR NUMBER ASSIGN VAR BIN_OP VAR VAR VAR ASSIGN VAR BIN_OP VAR VAR BIN_OP FUNC_CALL VAR VAR VAR VAR VAR VAR VAR VAR BIN_OP NUMBER VAR ASSIGN VAR VAR RETURN VAR VAR |
Given an array A of strings, find any smallest string that contains each string in A as a substring.
We may assume that no string in A is substring of another string in A.
Example 1:
Input: ["alex","loves","leetcode"]
Output: "alexlovesleetcode"
Explanation: All permutations of "alex","loves","leetcode" would also be accepted.
Example 2:
Input: ["catg","ctaagt","gcta","ttca","atgcatc"]
Output: "gctaagttcatgcatc"
Note:
1 <= A.length <= 12
1 <= A[i].length <= 20 | class Solution:
def shortestSuperstring(self, A: List[str]) -> str:
n = len(A)
overlaps = [([0] * n) for _ in range(n)]
for i, x in enumerate(A):
for j, y in enumerate(A):
for ans in range(min(len(x), len(y)), -1, -1):
if x.endswith(y[:ans]):
overlaps[i][j] = ans
break
maxv = 20 * n + 1
dp = [([maxv] * n) for _ in range(1 << n)]
parent = [([-1] * n) for _ in range(1 << n)]
for i in range(n):
dp[1 << i][i] = len(A[i])
for s in range(1, 1 << n):
for i in range(n):
if not s & 1 << i:
continue
prev = s - (1 << i)
for j in range(n):
if dp[prev][j] + len(A[i]) - overlaps[j][i] < dp[s][i]:
dp[s][i] = dp[prev][j] + len(A[i]) - overlaps[j][i]
parent[s][i] = j
path = []
s, i = (1 << n) - 1, 0
for j in range(1, n):
if dp[s][j] < dp[s][i]:
i = j
path.append(i)
while len(path) < n:
j = parent[s][i]
path.append(j)
prev = s ^ 1 << i
s, i = prev, j
i = path[-1]
res = [A[i]]
for j in path[::-1][1:]:
res.append(A[j][overlaps[i][j] :])
i = j
return "".join(res) | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST NUMBER VAR VAR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR NUMBER NUMBER IF FUNC_CALL VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR BIN_OP BIN_OP NUMBER VAR NUMBER ASSIGN VAR BIN_OP LIST VAR VAR VAR FUNC_CALL VAR BIN_OP NUMBER VAR ASSIGN VAR BIN_OP LIST NUMBER VAR VAR FUNC_CALL VAR BIN_OP NUMBER VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP NUMBER VAR VAR FUNC_CALL VAR VAR VAR FOR VAR FUNC_CALL VAR NUMBER BIN_OP NUMBER VAR FOR VAR FUNC_CALL VAR VAR IF BIN_OP VAR BIN_OP NUMBER VAR ASSIGN VAR BIN_OP VAR BIN_OP NUMBER VAR FOR VAR FUNC_CALL VAR VAR IF BIN_OP BIN_OP VAR VAR VAR FUNC_CALL VAR VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR BIN_OP BIN_OP VAR VAR VAR FUNC_CALL VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR LIST ASSIGN VAR VAR BIN_OP BIN_OP NUMBER VAR NUMBER NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR IF VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR EXPR FUNC_CALL VAR VAR WHILE FUNC_CALL VAR VAR VAR ASSIGN VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR BIN_OP NUMBER VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR NUMBER ASSIGN VAR LIST VAR VAR FOR VAR VAR NUMBER NUMBER EXPR FUNC_CALL VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR RETURN FUNC_CALL STRING VAR VAR |
Given an array A of strings, find any smallest string that contains each string in A as a substring.
We may assume that no string in A is substring of another string in A.
Example 1:
Input: ["alex","loves","leetcode"]
Output: "alexlovesleetcode"
Explanation: All permutations of "alex","loves","leetcode" would also be accepted.
Example 2:
Input: ["catg","ctaagt","gcta","ttca","atgcatc"]
Output: "gctaagttcatgcatc"
Note:
1 <= A.length <= 12
1 <= A[i].length <= 20 | class Solution:
def shortestSuperstring(self, A: List[str]) -> str:
n = len(A)
common = {}
for i, s1 in enumerate(A):
for j in range(i):
s2 = A[j]
longest1, longest2 = 0, 0
for k in range(min(len(s1), len(s2)) + 1):
if s1.endswith(s2[:k]):
longest1 = k
if s2.endswith(s1[:k]):
longest2 = k
common[i, j] = longest1
common[j, i] = longest2
end = 1 << n
dp = [[(float("inf"), "") for i in range(n)] for m in range(end)]
le, res = float("inf"), ""
for used in range(end):
for i, s in enumerate(A):
if used >> i & 1 != 1:
continue
mask = 1 << i
if used ^ mask == 0:
dp[used][i] = len(A[i]), A[i]
else:
for j, last in enumerate(A):
if i == j or used >> j & 1 != 1:
continue
l, pref = dp[used ^ mask][j]
cand = pref + A[i][common[j, i] :]
if len(cand) < dp[used][i][0]:
dp[used][i] = len(cand), cand
if used == end - 1 and dp[used][i][0] < le:
le, res = dp[used][i]
return res | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR DICT FOR VAR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR NUMBER NUMBER FOR VAR FUNC_CALL VAR BIN_OP FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR NUMBER IF FUNC_CALL VAR VAR VAR ASSIGN VAR VAR IF FUNC_CALL VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR BIN_OP NUMBER VAR ASSIGN VAR FUNC_CALL VAR STRING STRING VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR STRING STRING FOR VAR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR VAR IF BIN_OP BIN_OP VAR VAR NUMBER NUMBER ASSIGN VAR BIN_OP NUMBER VAR IF BIN_OP VAR VAR NUMBER ASSIGN VAR VAR VAR FUNC_CALL VAR VAR VAR VAR VAR FOR VAR VAR FUNC_CALL VAR VAR IF VAR VAR BIN_OP BIN_OP VAR VAR NUMBER NUMBER ASSIGN VAR VAR VAR BIN_OP VAR VAR VAR ASSIGN VAR BIN_OP VAR VAR VAR VAR VAR VAR IF FUNC_CALL VAR VAR VAR VAR VAR NUMBER ASSIGN VAR VAR VAR FUNC_CALL VAR VAR VAR IF VAR BIN_OP VAR NUMBER VAR VAR VAR NUMBER VAR ASSIGN VAR VAR VAR VAR VAR RETURN VAR VAR |
Given an array A of strings, find any smallest string that contains each string in A as a substring.
We may assume that no string in A is substring of another string in A.
Example 1:
Input: ["alex","loves","leetcode"]
Output: "alexlovesleetcode"
Explanation: All permutations of "alex","loves","leetcode" would also be accepted.
Example 2:
Input: ["catg","ctaagt","gcta","ttca","atgcatc"]
Output: "gctaagttcatgcatc"
Note:
1 <= A.length <= 12
1 <= A[i].length <= 20 | class Solution:
def shortestSuperstring(self, A: List[str]) -> str:
n = len(A)
overlaps = [([0] * n) for x in range(n)]
for i, x in enumerate(A):
for j, y in enumerate(A):
if i != j:
for l in range(min(len(x), len(y)), -1, -1):
if x.endswith(y[:l]):
overlaps[i][j] = l
break
dp = [([-1] * n) for x in range(1 << n)]
parent = [([None] * n) for x in range(1 << n)]
for mask in range(1, 1 << n):
for bit in range(n):
if mask >> bit & 1:
pmask = mask ^ 1 << bit
if pmask == 0:
dp[mask][bit] = 0
continue
for i in range(n):
if pmask >> i & 1:
value = dp[pmask][i] + overlaps[i][bit]
if value > dp[mask][bit]:
dp[mask][bit] = value
parent[mask][bit] = i
print(dp)
perm = []
mask = (1 << n) - 1
i = 0
for j, val in enumerate(dp[-1]):
if val > dp[-1][i]:
i = j
while i is not None:
perm.append(i)
mask, i = mask ^ 1 << i, parent[mask][i]
perm = perm[::-1]
ans = [A[perm[0]]]
for i in range(1, len(perm)):
overlap = overlaps[perm[i - 1]][perm[i]]
ans.append(A[perm[i]][overlap:])
return "".join(ans) | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST NUMBER VAR VAR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR VAR IF VAR VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR NUMBER NUMBER IF FUNC_CALL VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR BIN_OP LIST NUMBER VAR VAR FUNC_CALL VAR BIN_OP NUMBER VAR ASSIGN VAR BIN_OP LIST NONE VAR VAR FUNC_CALL VAR BIN_OP NUMBER VAR FOR VAR FUNC_CALL VAR NUMBER BIN_OP NUMBER VAR FOR VAR FUNC_CALL VAR VAR IF BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR BIN_OP VAR BIN_OP NUMBER VAR IF VAR NUMBER ASSIGN VAR VAR VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR BIN_OP VAR VAR VAR VAR VAR VAR IF VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR LIST ASSIGN VAR BIN_OP BIN_OP NUMBER VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR FUNC_CALL VAR VAR NUMBER IF VAR VAR NUMBER VAR ASSIGN VAR VAR WHILE VAR NONE EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR BIN_OP VAR BIN_OP NUMBER VAR VAR VAR VAR ASSIGN VAR VAR NUMBER ASSIGN VAR LIST VAR VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER FUNC_CALL VAR VAR ASSIGN VAR VAR VAR BIN_OP VAR NUMBER VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR VAR RETURN FUNC_CALL STRING VAR VAR |
Given an array A of strings, find any smallest string that contains each string in A as a substring.
We may assume that no string in A is substring of another string in A.
Example 1:
Input: ["alex","loves","leetcode"]
Output: "alexlovesleetcode"
Explanation: All permutations of "alex","loves","leetcode" would also be accepted.
Example 2:
Input: ["catg","ctaagt","gcta","ttca","atgcatc"]
Output: "gctaagttcatgcatc"
Note:
1 <= A.length <= 12
1 <= A[i].length <= 20 | class Solution:
def shortestSuperstring(self, A: List[str]) -> str:
N = len(A)
cost = [([0] * N) for _ in range(N)]
for i in range(N):
for j in range(N):
cost[i][j] = math.inf
for k in range(len(A[i])):
if A[j].startswith(A[i][k:]):
cost[i][j] = k + len(A[j]) - len(A[i])
break
if cost[i][j] == math.inf:
cost[i][j] = len(A[j])
dp = [[math.inf for _ in range(1 << N)] for i in range(N)]
for i in range(N):
dp[i][1 << i] = len(A[i])
backtrack = [([None] * (1 << N)) for _ in range(N)]
for i in range(N):
backtrack[i][1 << i] = i, 0
for i in range(1 << N):
for j in range(N):
if i & 1 << j:
for k in range(N):
if i & 1 << k and i != k:
if dp[j][i] > dp[k][i ^ 1 << j] + cost[k][j]:
dp[j][i] = dp[k][i ^ 1 << j] + cost[k][j]
backtrack[j][i] = k, i ^ 1 << j
min_cost = math.inf
min_index = -1
for i in range(N):
if min_cost > dp[i][(1 << N) - 1]:
min_cost = dp[i][(1 << N) - 1]
min_index = i
mask = (1 << N) - 1
order = []
while mask:
order.append(min_index)
min_index, mask = backtrack[min_index][mask]
order.reverse()
answer = []
last_i = -1
for i in order:
if len(answer) == 0:
answer.append(A[i])
else:
answer.append(A[i][-cost[last_i][i] :])
last_i = i
return "".join(answer) | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST NUMBER VAR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR IF FUNC_CALL VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR BIN_OP BIN_OP VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR IF VAR VAR VAR VAR ASSIGN VAR VAR VAR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR VAR FUNC_CALL VAR BIN_OP NUMBER VAR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR BIN_OP NUMBER VAR FUNC_CALL VAR VAR VAR ASSIGN VAR BIN_OP LIST NONE BIN_OP NUMBER VAR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR BIN_OP NUMBER VAR VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP NUMBER VAR FOR VAR FUNC_CALL VAR VAR IF BIN_OP VAR BIN_OP NUMBER VAR FOR VAR FUNC_CALL VAR VAR IF BIN_OP VAR BIN_OP NUMBER VAR VAR VAR IF VAR VAR VAR BIN_OP VAR VAR BIN_OP VAR BIN_OP NUMBER VAR VAR VAR VAR ASSIGN VAR VAR VAR BIN_OP VAR VAR BIN_OP VAR BIN_OP NUMBER VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR BIN_OP VAR BIN_OP NUMBER VAR ASSIGN VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR VAR BIN_OP BIN_OP NUMBER VAR NUMBER ASSIGN VAR VAR VAR BIN_OP BIN_OP NUMBER VAR NUMBER ASSIGN VAR VAR ASSIGN VAR BIN_OP BIN_OP NUMBER VAR NUMBER ASSIGN VAR LIST WHILE VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR LIST ASSIGN VAR NUMBER FOR VAR VAR IF FUNC_CALL VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR RETURN FUNC_CALL STRING VAR VAR |
Given an array A of strings, find any smallest string that contains each string in A as a substring.
We may assume that no string in A is substring of another string in A.
Example 1:
Input: ["alex","loves","leetcode"]
Output: "alexlovesleetcode"
Explanation: All permutations of "alex","loves","leetcode" would also be accepted.
Example 2:
Input: ["catg","ctaagt","gcta","ttca","atgcatc"]
Output: "gctaagttcatgcatc"
Note:
1 <= A.length <= 12
1 <= A[i].length <= 20 | class Solution:
def shortestSuperstring(self, A: List[str]) -> str:
def dist(a, b):
for i in range(min(len(a), len(b)), 0, -1):
if a[-i:] == b[:i]:
return len(b) - i
return len(b)
def build_graph():
graph = [([0] * n) for _ in range(n)]
for i in range(n):
for j in range(n):
graph[i][j] = dist(A[i], A[j])
return graph
def get_dp():
dp = [([sys.maxsize / 2] * n) for _ in range(1 << n)]
parent = [([-1] * n) for _ in range(1 << n)]
for i in range(n):
dp[1 << i][i] = len(A[i])
for s in range(1 << n):
for j in range(n):
if not s & 1 << j:
continue
ps = s & ~(1 << j)
for i in range(n):
if dp[ps][i] + g[i][j] < dp[s][j]:
dp[s][j] = dp[ps][i] + g[i][j]
parent[s][j] = i
return dp, parent
def recover_path():
ans = ""
j = dp[-1].index(min(dp[-1]))
s = (1 << n) - 1
while s:
i = parent[s][j]
if i < 0:
ans = A[j] + ans
else:
ans = A[j][-g[i][j] :] + ans
s &= ~(1 << j)
j = i
return ans
n = len(A)
g = build_graph()
dp, parent = get_dp()
ans = recover_path()
return ans | CLASS_DEF FUNC_DEF VAR VAR FUNC_DEF FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR NUMBER NUMBER IF VAR VAR VAR VAR RETURN BIN_OP FUNC_CALL VAR VAR VAR RETURN FUNC_CALL VAR VAR FUNC_DEF ASSIGN VAR BIN_OP LIST NUMBER VAR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR FUNC_CALL VAR VAR VAR VAR VAR RETURN VAR FUNC_DEF ASSIGN VAR BIN_OP LIST BIN_OP VAR NUMBER VAR VAR FUNC_CALL VAR BIN_OP NUMBER VAR ASSIGN VAR BIN_OP LIST NUMBER VAR VAR FUNC_CALL VAR BIN_OP NUMBER VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP NUMBER VAR VAR FUNC_CALL VAR VAR VAR FOR VAR FUNC_CALL VAR BIN_OP NUMBER VAR FOR VAR FUNC_CALL VAR VAR IF BIN_OP VAR BIN_OP NUMBER VAR ASSIGN VAR BIN_OP VAR BIN_OP NUMBER VAR FOR VAR FUNC_CALL VAR VAR IF BIN_OP VAR VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR BIN_OP VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR RETURN VAR VAR FUNC_DEF ASSIGN VAR STRING ASSIGN VAR FUNC_CALL VAR NUMBER FUNC_CALL VAR VAR NUMBER ASSIGN VAR BIN_OP BIN_OP NUMBER VAR NUMBER WHILE VAR ASSIGN VAR VAR VAR VAR IF VAR NUMBER ASSIGN VAR BIN_OP VAR VAR VAR ASSIGN VAR BIN_OP VAR VAR VAR VAR VAR VAR VAR BIN_OP NUMBER VAR ASSIGN VAR VAR RETURN VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR ASSIGN VAR VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR RETURN VAR VAR |
Given an array A of strings, find any smallest string that contains each string in A as a substring.
We may assume that no string in A is substring of another string in A.
Example 1:
Input: ["alex","loves","leetcode"]
Output: "alexlovesleetcode"
Explanation: All permutations of "alex","loves","leetcode" would also be accepted.
Example 2:
Input: ["catg","ctaagt","gcta","ttca","atgcatc"]
Output: "gctaagttcatgcatc"
Note:
1 <= A.length <= 12
1 <= A[i].length <= 20 | class Solution:
def shortestSuperstring(self, A: List[str]) -> str:
n = len(A)
w = [([0] * n) for _ in range(n)]
for i in range(n):
for j in range(n):
for k in range(min(len(A[i]), len(A[j])), 0, -1):
if A[j].startswith(A[i][-k:]):
w[i][j] = k
break
@lru_cache(None)
def dp(nodes):
if len(nodes) == 2:
return A[nodes[0]]
end = nodes[-1]
end_idx = nodes.index(end)
nodes_wo_end = nodes[:end_idx] + nodes[end_idx + 1 : -1]
return min(
(
dp(nodes_wo_end + (node,)) + A[end][w[node][end] :]
for node in nodes_wo_end
),
key=len,
)
return min((dp(tuple(range(n)) + (node,)) for node in range(n)), key=len) | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST NUMBER VAR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR NUMBER NUMBER IF FUNC_CALL VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR FUNC_DEF IF FUNC_CALL VAR VAR NUMBER RETURN VAR VAR NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR VAR VAR BIN_OP VAR NUMBER NUMBER RETURN FUNC_CALL VAR BIN_OP FUNC_CALL VAR BIN_OP VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR FUNC_CALL VAR NONE RETURN FUNC_CALL VAR FUNC_CALL VAR BIN_OP FUNC_CALL VAR FUNC_CALL VAR VAR VAR VAR FUNC_CALL VAR VAR VAR VAR |
Given an array A of strings, find any smallest string that contains each string in A as a substring.
We may assume that no string in A is substring of another string in A.
Example 1:
Input: ["alex","loves","leetcode"]
Output: "alexlovesleetcode"
Explanation: All permutations of "alex","loves","leetcode" would also be accepted.
Example 2:
Input: ["catg","ctaagt","gcta","ttca","atgcatc"]
Output: "gctaagttcatgcatc"
Note:
1 <= A.length <= 12
1 <= A[i].length <= 20 | class Solution:
def shortestSuperstring(self, A: List[str]) -> str:
A = [
a
for i, a in enumerate(A)
if all(a not in b for j, b in enumerate(A) if i != j)
]
def memo(f):
dic = {}
def f_alt(*args):
if args not in dic:
dic[args] = f(*args)
return dic[args]
return f_alt
def merge(w1, w2):
for k in range(len(w2), -1, -1):
if w1.endswith(w2[:k]):
return w1 + w2[k:]
@memo
def find_short(tup, last):
if len(tup) == 1:
return A[tup[0]]
mtup = tuple(t for t in tup if t != last)
return min((merge(find_short(mtup, t), A[last]) for t in mtup), key=len)
tup = tuple(range(len(A)))
return min((find_short(tup, i) for i in range(len(A))), key=len) | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR VAR VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR VAR VAR VAR FUNC_CALL VAR VAR VAR VAR FUNC_DEF ASSIGN VAR DICT FUNC_DEF IF VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR RETURN VAR VAR RETURN VAR FUNC_DEF FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR NUMBER NUMBER IF FUNC_CALL VAR VAR VAR RETURN BIN_OP VAR VAR VAR FUNC_DEF IF FUNC_CALL VAR VAR NUMBER RETURN VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR VAR VAR VAR RETURN FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR RETURN FUNC_CALL VAR FUNC_CALL VAR VAR VAR VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR VAR |
Given an array A of strings, find any smallest string that contains each string in A as a substring.
We may assume that no string in A is substring of another string in A.
Example 1:
Input: ["alex","loves","leetcode"]
Output: "alexlovesleetcode"
Explanation: All permutations of "alex","loves","leetcode" would also be accepted.
Example 2:
Input: ["catg","ctaagt","gcta","ttca","atgcatc"]
Output: "gctaagttcatgcatc"
Note:
1 <= A.length <= 12
1 <= A[i].length <= 20 | class Solution:
def shortestSuperstring(self, A: List[str]) -> str:
def cost(a, b):
alen, blen = len(a), len(b)
minlen = min(alen, blen)
for i in range(minlen - 1, 0, -1):
if a[alen - i :] == b[:i]:
return blen - i
return blen
n = len(A)
g = [([-1] * n) for _ in range(n)]
for i in range(n):
for j in range(n):
if j == i:
continue
g[i][j] = cost(A[i], A[j])
dp = [([float("inf")] * n) for _ in range(1 << n)]
parent = [([-1] * n) for _ in range(1 << n)]
anslen = float("inf")
cur = -1
ans = ""
for i in range(n):
dp[1 << i][i] = len(A[i])
for s in range(1, 1 << n):
for j in range(n):
if s & 1 << j == 0:
continue
ps = s & ~(1 << j)
for i in range(n):
if i == j:
continue
if dp[s][j] > dp[ps][i] + g[i][j]:
dp[s][j] = dp[ps][i] + g[i][j]
parent[s][j] = i
for i in range(n):
if anslen > dp[(1 << n) - 1][i]:
anslen = dp[(1 << n) - 1][i]
cur = i
s = (1 << n) - 1
while s > 0:
ps = s & ~(1 << cur)
parent_node = parent[s][cur]
if ps == 0:
ans = A[cur] + ans
else:
curstr = A[cur]
ans = curstr[len(curstr) - g[parent_node][cur] :] + ans
s = ps
cur = parent_node
return ans | CLASS_DEF FUNC_DEF VAR VAR FUNC_DEF ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER NUMBER NUMBER IF VAR BIN_OP VAR VAR VAR VAR RETURN BIN_OP VAR VAR RETURN VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST NUMBER VAR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR IF VAR VAR ASSIGN VAR VAR VAR FUNC_CALL VAR VAR VAR VAR VAR ASSIGN VAR BIN_OP LIST FUNC_CALL VAR STRING VAR VAR FUNC_CALL VAR BIN_OP NUMBER VAR ASSIGN VAR BIN_OP LIST NUMBER VAR VAR FUNC_CALL VAR BIN_OP NUMBER VAR ASSIGN VAR FUNC_CALL VAR STRING ASSIGN VAR NUMBER ASSIGN VAR STRING FOR VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP NUMBER VAR VAR FUNC_CALL VAR VAR VAR FOR VAR FUNC_CALL VAR NUMBER BIN_OP NUMBER VAR FOR VAR FUNC_CALL VAR VAR IF BIN_OP VAR BIN_OP NUMBER VAR NUMBER ASSIGN VAR BIN_OP VAR BIN_OP NUMBER VAR FOR VAR FUNC_CALL VAR VAR IF VAR VAR IF VAR VAR VAR BIN_OP VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR BIN_OP VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR FOR VAR FUNC_CALL VAR VAR IF VAR VAR BIN_OP BIN_OP NUMBER VAR NUMBER VAR ASSIGN VAR VAR BIN_OP BIN_OP NUMBER VAR NUMBER VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP BIN_OP NUMBER VAR NUMBER WHILE VAR NUMBER ASSIGN VAR BIN_OP VAR BIN_OP NUMBER VAR ASSIGN VAR VAR VAR VAR IF VAR NUMBER ASSIGN VAR BIN_OP VAR VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR BIN_OP VAR BIN_OP FUNC_CALL VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR RETURN VAR VAR |
Given an array A of strings, find any smallest string that contains each string in A as a substring.
We may assume that no string in A is substring of another string in A.
Example 1:
Input: ["alex","loves","leetcode"]
Output: "alexlovesleetcode"
Explanation: All permutations of "alex","loves","leetcode" would also be accepted.
Example 2:
Input: ["catg","ctaagt","gcta","ttca","atgcatc"]
Output: "gctaagttcatgcatc"
Note:
1 <= A.length <= 12
1 <= A[i].length <= 20 | class Solution:
def int2arr(self, x, n):
arr = []
x1 = x
for i in range(n):
arr.append(x1 % 2)
x1 = x1 // 2
return arr
def arr2int(self, arr):
x = 0
for i in range(len(arr)):
x += arr[i] * 2**i
return x
def shortestSuperstring(self, A: List[str]) -> str:
n = len(A)
overlap = {}
for i in range(n):
for j in range(n):
short = min(len(A[i]), len(A[j]))
for k in range(short, -1, -1):
if A[i][len(A[i]) - k : len(A[i])] == A[j][0:k]:
break
overlap[i, j] = k
state_order = []
for i in range(0, n + 2):
state_order.append([])
for i in range(0, 2**n):
arr = self.int2arr(i, n)
state_order[sum(arr)].append(i)
m = {}
conn = {}
for i in range(n):
x = 2**i
m[x, i] = len(A[i])
conn[x, i] = A[i]
for l in range(2, n + 1):
for x in state_order[l]:
arr = self.int2arr(x, n)
for end in range(n):
if arr[end] == 1:
m[x, end] = 100000
x_prev = x - 2**end
arr_prev = self.int2arr(x_prev, n)
for prev in range(n):
if (
arr_prev[prev] == 1
and m[x_prev, prev] + len(A[end]) - overlap[prev, end]
< m[x, end]
):
m[x, end] = (
m[x_prev, prev] + len(A[end]) - overlap[prev, end]
)
conn[x, end] = (
conn[x_prev, prev]
+ A[end][overlap[prev, end] : len(A[end])]
)
ans = 100000
for i in range(n):
if m[2**n - 1, i] < ans:
ans = m[2**n - 1, i]
ans_str = conn[2**n - 1, i]
return ans_str | CLASS_DEF FUNC_DEF ASSIGN VAR LIST ASSIGN VAR VAR FOR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR FUNC_DEF ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR BIN_OP VAR VAR BIN_OP NUMBER VAR RETURN VAR FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR DICT FOR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR FOR VAR FUNC_CALL VAR VAR NUMBER NUMBER IF VAR VAR BIN_OP FUNC_CALL VAR VAR VAR VAR FUNC_CALL VAR VAR VAR VAR VAR NUMBER VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR LIST FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER EXPR FUNC_CALL VAR LIST FOR VAR FUNC_CALL VAR NUMBER BIN_OP NUMBER VAR ASSIGN VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR VAR VAR ASSIGN VAR DICT ASSIGN VAR DICT FOR VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP NUMBER VAR ASSIGN VAR VAR VAR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER FOR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR FOR VAR FUNC_CALL VAR VAR IF VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER ASSIGN VAR BIN_OP VAR BIN_OP NUMBER VAR ASSIGN VAR FUNC_CALL VAR VAR VAR FOR VAR FUNC_CALL VAR VAR IF VAR VAR NUMBER BIN_OP BIN_OP VAR VAR VAR FUNC_CALL VAR VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR BIN_OP BIN_OP VAR VAR VAR FUNC_CALL VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR BIN_OP VAR VAR VAR VAR VAR VAR VAR VAR FUNC_CALL VAR VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR BIN_OP BIN_OP NUMBER VAR NUMBER VAR VAR ASSIGN VAR VAR BIN_OP BIN_OP NUMBER VAR NUMBER VAR ASSIGN VAR VAR BIN_OP BIN_OP NUMBER VAR NUMBER VAR RETURN VAR VAR |
Given an array A of strings, find any smallest string that contains each string in A as a substring.
We may assume that no string in A is substring of another string in A.
Example 1:
Input: ["alex","loves","leetcode"]
Output: "alexlovesleetcode"
Explanation: All permutations of "alex","loves","leetcode" would also be accepted.
Example 2:
Input: ["catg","ctaagt","gcta","ttca","atgcatc"]
Output: "gctaagttcatgcatc"
Note:
1 <= A.length <= 12
1 <= A[i].length <= 20 | class Solution:
def shortestSuperstring(self, A: List[str]) -> str:
def extra_to_append(w1, w2):
for i in range(len(w1)):
if w2.startswith(w1[i:]):
return w2[len(w1) - i :]
return w2
n = len(A)
extra = [([""] * n) for _ in range(n)]
for i, j in itertools.permutations(list(range(n)), 2):
extra[i][j] = extra_to_append(A[i], A[j])
dp = [([""] * n) for _ in range(1 << n)]
ret = ""
for mask in range(1, 1 << n):
for ci, cw in enumerate(A):
if not mask & 1 << ci:
continue
pre_mask = mask & ~(1 << ci)
if not pre_mask:
dp[mask][ci] = cw
else:
for pi, pw in enumerate(A):
if not pre_mask & 1 << pi:
continue
if not dp[mask][ci] or len(dp[mask][ci]) > len(
dp[pre_mask][pi]
) + len(extra[pi][ci]):
dp[mask][ci] = dp[pre_mask][pi] + extra[pi][ci]
if mask == (1 << n) - 1:
ret = (
dp[mask][ci] if not ret or len(ret) > len(dp[mask][ci]) else ret
)
return ret | CLASS_DEF FUNC_DEF VAR VAR FUNC_DEF FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR IF FUNC_CALL VAR VAR VAR RETURN VAR BIN_OP FUNC_CALL VAR VAR VAR RETURN VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST STRING VAR VAR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR NUMBER ASSIGN VAR VAR VAR FUNC_CALL VAR VAR VAR VAR VAR ASSIGN VAR BIN_OP LIST STRING VAR VAR FUNC_CALL VAR BIN_OP NUMBER VAR ASSIGN VAR STRING FOR VAR FUNC_CALL VAR NUMBER BIN_OP NUMBER VAR FOR VAR VAR FUNC_CALL VAR VAR IF BIN_OP VAR BIN_OP NUMBER VAR ASSIGN VAR BIN_OP VAR BIN_OP NUMBER VAR IF VAR ASSIGN VAR VAR VAR VAR FOR VAR VAR FUNC_CALL VAR VAR IF BIN_OP VAR BIN_OP NUMBER VAR IF VAR VAR VAR FUNC_CALL VAR VAR VAR VAR BIN_OP FUNC_CALL VAR VAR VAR VAR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR VAR VAR BIN_OP VAR VAR VAR VAR VAR VAR IF VAR BIN_OP BIN_OP NUMBER VAR NUMBER ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR VAR VAR VAR VAR VAR VAR RETURN VAR VAR |
Given an array A of strings, find any smallest string that contains each string in A as a substring.
We may assume that no string in A is substring of another string in A.
Example 1:
Input: ["alex","loves","leetcode"]
Output: "alexlovesleetcode"
Explanation: All permutations of "alex","loves","leetcode" would also be accepted.
Example 2:
Input: ["catg","ctaagt","gcta","ttca","atgcatc"]
Output: "gctaagttcatgcatc"
Note:
1 <= A.length <= 12
1 <= A[i].length <= 20 | class Solution:
def shortestSuperstring(self, A: List[str]) -> str:
n = len(A)
self.cost = [[(0) for j in range(n)] for i in range(n)]
for i in range(n):
for j in range(n):
w1 = A[i]
w2 = A[j]
k = min(len(w1), len(w2))
while k > 0:
if w1[-k:] == w2[:k]:
break
k -= 1
self.cost[i][j] = k
self.cache = {}
ans = ""
for i in range(n):
candidate = self.dfs(A, i, (1 << n) - 1)
if ans == "" or len(candidate) < len(ans):
ans = candidate
return ans
def dfs(self, A, index, cur):
if (index, cur) in self.cache:
return self.cache[index, cur]
if not 1 << index & cur:
return ""
if cur == 1 << index:
return A[index]
self.cache[index, cur] = ""
for i in range(len(A)):
if i == index or not 1 << i & cur:
continue
temp = self.dfs(A, i, cur - (1 << index)) + A[index][self.cost[i][index] :]
if self.cache[index, cur] == "" or len(temp) < len(self.cache[index, cur]):
self.cache[index, cur] = temp
return self.cache[index, cur] | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR WHILE VAR NUMBER IF VAR VAR VAR VAR VAR NUMBER ASSIGN VAR VAR VAR VAR ASSIGN VAR DICT ASSIGN VAR STRING FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR BIN_OP BIN_OP NUMBER VAR NUMBER IF VAR STRING FUNC_CALL VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR RETURN VAR VAR FUNC_DEF IF VAR VAR VAR RETURN VAR VAR VAR IF BIN_OP BIN_OP NUMBER VAR VAR RETURN STRING IF VAR BIN_OP NUMBER VAR RETURN VAR VAR ASSIGN VAR VAR VAR STRING FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR IF VAR VAR BIN_OP BIN_OP NUMBER VAR VAR ASSIGN VAR BIN_OP FUNC_CALL VAR VAR VAR BIN_OP VAR BIN_OP NUMBER VAR VAR VAR VAR VAR VAR IF VAR VAR VAR STRING FUNC_CALL VAR VAR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR RETURN VAR VAR VAR |
Given an array A of strings, find any smallest string that contains each string in A as a substring.
We may assume that no string in A is substring of another string in A.
Example 1:
Input: ["alex","loves","leetcode"]
Output: "alexlovesleetcode"
Explanation: All permutations of "alex","loves","leetcode" would also be accepted.
Example 2:
Input: ["catg","ctaagt","gcta","ttca","atgcatc"]
Output: "gctaagttcatgcatc"
Note:
1 <= A.length <= 12
1 <= A[i].length <= 20 | class Solution:
def shortestSuperstring(self, A: List[str]) -> str:
size = len(A)
costs = [([0] * size) for _ in range(size)]
for i in range(size):
for j in range(size):
if i == j:
costs[i][j] = 0
continue
wi, wj = A[i], A[j]
si, sj = len(wi), len(wj)
costs[i][j] = sj
for k in range(1, min(si, sj) + 1):
if wi[-k:] == wj[:k]:
costs[i][j] = sj - k
dp = [([20 * 12] * size) for _ in range(1 << size)]
parent = [([-1] * size) for _ in range(1 << size)]
for i in range(size):
dp[1 << i][i] = len(A[i])
for state in range(1, 1 << size):
for i in range(size):
if state & 1 << i == 0:
continue
prev = state - (1 << i)
for j in range(size):
if prev & 1 << j == 0:
continue
if dp[state][i] > dp[prev][j] + costs[j][i]:
dp[state][i] = dp[prev][j] + costs[j][i]
parent[state][i] = j
minCost = min(dp[-1])
index = dp[-1].index(minCost)
res = ""
state = (1 << size) - 1
while state:
prevIndex = parent[state][index]
if prevIndex < 0:
res = A[index] + res
else:
cost = costs[prevIndex][index]
res = A[index][-cost:] + res
state -= 1 << index
index = prevIndex
return res | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST NUMBER VAR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR IF VAR VAR ASSIGN VAR VAR VAR NUMBER ASSIGN VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR FOR VAR FUNC_CALL VAR NUMBER BIN_OP FUNC_CALL VAR VAR VAR NUMBER IF VAR VAR VAR VAR ASSIGN VAR VAR VAR BIN_OP VAR VAR ASSIGN VAR BIN_OP LIST BIN_OP NUMBER NUMBER VAR VAR FUNC_CALL VAR BIN_OP NUMBER VAR ASSIGN VAR BIN_OP LIST NUMBER VAR VAR FUNC_CALL VAR BIN_OP NUMBER VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP NUMBER VAR VAR FUNC_CALL VAR VAR VAR FOR VAR FUNC_CALL VAR NUMBER BIN_OP NUMBER VAR FOR VAR FUNC_CALL VAR VAR IF BIN_OP VAR BIN_OP NUMBER VAR NUMBER ASSIGN VAR BIN_OP VAR BIN_OP NUMBER VAR FOR VAR FUNC_CALL VAR VAR IF BIN_OP VAR BIN_OP NUMBER VAR NUMBER IF VAR VAR VAR BIN_OP VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR BIN_OP VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR NUMBER VAR ASSIGN VAR STRING ASSIGN VAR BIN_OP BIN_OP NUMBER VAR NUMBER WHILE VAR ASSIGN VAR VAR VAR VAR IF VAR NUMBER ASSIGN VAR BIN_OP VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR BIN_OP VAR VAR VAR VAR VAR BIN_OP NUMBER VAR ASSIGN VAR VAR RETURN VAR VAR |
Given an array A of strings, find any smallest string that contains each string in A as a substring.
We may assume that no string in A is substring of another string in A.
Example 1:
Input: ["alex","loves","leetcode"]
Output: "alexlovesleetcode"
Explanation: All permutations of "alex","loves","leetcode" would also be accepted.
Example 2:
Input: ["catg","ctaagt","gcta","ttca","atgcatc"]
Output: "gctaagttcatgcatc"
Note:
1 <= A.length <= 12
1 <= A[i].length <= 20 | class Solution:
def shortestSuperstring(self, A: List[str]) -> str:
n, N = len(A), 1 << len(A)
w = [([0] * n) for _ in range(n)]
for i in range(n):
for j in range(n):
for k in range(min(len(A[i]), len(A[j])), 0, -1):
if A[j].startswith(A[i][-k:]):
w[i][j] = k
break
f = [([None] * n) for _ in range(N)]
for i in range(N):
for k in filter(lambda x: 1 << x & i, range(n)):
i1 = i ^ 1 << k
f[i][k] = min(
[
(f[i1][j] + A[k][w[j][k] :])
for j in filter(lambda x: 1 << x & i1, range(n))
],
key=len,
default=A[k],
)
return min(filter(None, f[-1]), key=len) | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR BIN_OP NUMBER FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST NUMBER VAR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR NUMBER NUMBER IF FUNC_CALL VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR BIN_OP LIST NONE VAR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR BIN_OP BIN_OP NUMBER VAR VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR BIN_OP NUMBER VAR ASSIGN VAR VAR VAR FUNC_CALL VAR BIN_OP VAR VAR VAR VAR VAR VAR VAR VAR VAR FUNC_CALL VAR BIN_OP BIN_OP NUMBER VAR VAR FUNC_CALL VAR VAR VAR VAR VAR RETURN FUNC_CALL VAR FUNC_CALL VAR NONE VAR NUMBER VAR VAR |
Given an array arr of N integers and an integer K, find the number of subsets of arr having XOR of elements as K.
Example 1:
Input:
N = 4
k = 6
arr: 6 9 4 2
Output:
2
Explanation:
The subsets are
{4,2} and {6}
Example 2:
Input:
N = 5
K = 4
arr: 1 2 3 4 5
Output:
4
Explanation:
The subsets are {1, 5},
{4}, {1, 2, 3, 4},
and {2, 3, 5}
Your Task:
You don't need to read input or print anything. Your task is to complete the function subsetXOR() which takes the array arr[], its size N, and an integer K as input parameters and returns the number of subsets having xor as K
Expected Time Complexity: O(N*M)
Expected Space Complexity: O(N*M)
Note: M = maximum value any XOR subset will acquire
Constraints:
1<=N<=20
1<=K<=100
0<=arr[i]<=100 | class Solution:
def subsetXOR(self, arr, N, K):
ht = {(0): 1}
cnt = 0
for i in arr[:N]:
temp = i ^ K
if temp in ht:
cnt += ht[temp]
for k, v in list(ht.items()):
xor = i ^ k
ht[xor] = ht.get(xor, 0) + v
return cnt | CLASS_DEF FUNC_DEF ASSIGN VAR DICT NUMBER NUMBER ASSIGN VAR NUMBER FOR VAR VAR VAR ASSIGN VAR BIN_OP VAR VAR IF VAR VAR VAR VAR VAR FOR VAR VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR BIN_OP VAR VAR ASSIGN VAR VAR BIN_OP FUNC_CALL VAR VAR NUMBER VAR RETURN VAR |
Given an array arr of N integers and an integer K, find the number of subsets of arr having XOR of elements as K.
Example 1:
Input:
N = 4
k = 6
arr: 6 9 4 2
Output:
2
Explanation:
The subsets are
{4,2} and {6}
Example 2:
Input:
N = 5
K = 4
arr: 1 2 3 4 5
Output:
4
Explanation:
The subsets are {1, 5},
{4}, {1, 2, 3, 4},
and {2, 3, 5}
Your Task:
You don't need to read input or print anything. Your task is to complete the function subsetXOR() which takes the array arr[], its size N, and an integer K as input parameters and returns the number of subsets having xor as K
Expected Time Complexity: O(N*M)
Expected Space Complexity: O(N*M)
Note: M = maximum value any XOR subset will acquire
Constraints:
1<=N<=20
1<=K<=100
0<=arr[i]<=100 | class Solution:
def solve(self, arr, n, k, i, xor):
if i == n:
return 1 if xor == k else 0
if dp[i][xor] != -1:
return dp[i][xor]
x = self.solve(arr, n, k, i + 1, arr[i] ^ xor)
y = self.solve(arr, n, k, i + 1, xor)
dp[i][xor] = x + y
return dp[i][xor]
def subsetXOR(self, arr, n, k):
global dp
dp = [[(-1) for i in range(200)] for j in range(25)]
return self.solve(arr, n, k, 0, 0) | CLASS_DEF FUNC_DEF IF VAR VAR RETURN VAR VAR NUMBER NUMBER IF VAR VAR VAR NUMBER RETURN VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR BIN_OP VAR NUMBER BIN_OP VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR BIN_OP VAR NUMBER VAR ASSIGN VAR VAR VAR BIN_OP VAR VAR RETURN VAR VAR VAR FUNC_DEF ASSIGN VAR NUMBER VAR FUNC_CALL VAR NUMBER VAR FUNC_CALL VAR NUMBER RETURN FUNC_CALL VAR VAR VAR VAR NUMBER NUMBER |
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000]. | class Solution:
def splitArraySameAverage(self, A: List[int]) -> bool:
ksums = [{0}]
maxk = len(A) // 2
for a in A:
ksums = [[0]] + [
(
(ksums[k] if k < len(ksums) else set())
| {(a + x) for x in ksums[k - 1]}
)
for k in range(1, min(len(ksums), maxk) + 1)
]
n = len(A)
S = sum(A)
for k in range(1, min(len(ksums), maxk) + 1):
if any(x * (n - k) == k * (S - x) for x in ksums[k]):
return True
return False | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR LIST NUMBER ASSIGN VAR BIN_OP FUNC_CALL VAR VAR NUMBER FOR VAR VAR ASSIGN VAR BIN_OP LIST LIST NUMBER BIN_OP VAR FUNC_CALL VAR VAR VAR VAR FUNC_CALL VAR BIN_OP VAR VAR VAR VAR BIN_OP VAR NUMBER VAR FUNC_CALL VAR NUMBER BIN_OP FUNC_CALL VAR FUNC_CALL VAR VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR NUMBER BIN_OP FUNC_CALL VAR FUNC_CALL VAR VAR VAR NUMBER IF FUNC_CALL VAR BIN_OP VAR BIN_OP VAR VAR BIN_OP VAR BIN_OP VAR VAR VAR VAR VAR RETURN NUMBER RETURN NUMBER VAR |
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000]. | class Solution:
def splitArraySameAverage(self, A: List[int]) -> bool:
N = len(A)
if N <= 1:
return False
max_sum = sum(A)
sums = [0] * (max_sum + 1)
for i in range(N):
num = A[i]
for s in range(max_sum, num - 1, -1):
if sums[s - num]:
sums[s] |= sums[s - num] << 1
sums[num] |= 1
for l in range(1, N):
if max_sum * l % N == 0:
s = int(max_sum * l / N)
if sums[s] >> l - 1 & 1:
return True
return False | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR NUMBER RETURN NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST NUMBER BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR FOR VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER NUMBER IF VAR BIN_OP VAR VAR VAR VAR BIN_OP VAR BIN_OP VAR VAR NUMBER VAR VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR IF BIN_OP BIN_OP VAR VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR BIN_OP BIN_OP VAR VAR VAR IF BIN_OP BIN_OP VAR VAR BIN_OP VAR NUMBER NUMBER RETURN NUMBER RETURN NUMBER VAR |
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000]. | class Solution:
def splitArraySameAverage(self, A: List[int]) -> bool:
dp = set([(0, 0)])
suma = sum(A)
N = len(A)
A.sort()
for num in A:
for k, v in list(dp):
if k >= N // 2:
continue
if num + v > suma * (k + 1) // N:
continue
if (
num + v == suma * (k + 1) // N
and suma * (k + 1) % N == 0
and k + 1 < N
):
return True
dp.add((k + 1, num + v))
return False | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR LIST NUMBER NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR FOR VAR VAR FOR VAR VAR FUNC_CALL VAR VAR IF VAR BIN_OP VAR NUMBER IF BIN_OP VAR VAR BIN_OP BIN_OP VAR BIN_OP VAR NUMBER VAR IF BIN_OP VAR VAR BIN_OP BIN_OP VAR BIN_OP VAR NUMBER VAR BIN_OP BIN_OP VAR BIN_OP VAR NUMBER VAR NUMBER BIN_OP VAR NUMBER VAR RETURN NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP VAR VAR RETURN NUMBER VAR |
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000]. | class Solution:
def splitArraySameAverage(self, A: List[int]) -> bool:
tot = sum(A)
n = len(A)
target = tot / n
visited = [False] * len(A)
m = n // 2
possible = False
for i in range(1, m + 1):
if tot * i % n == 0:
possible = True
break
if not possible:
return False
A.sort()
def helper(A, cursum, curcnt, pos):
if curcnt == 0:
return cursum == 0
for i in range(pos, len(A) - curcnt + 1):
if i > pos and A[i] == A[i - 1]:
continue
if helper(A, cursum - A[i], curcnt - 1, i + 1):
return True
return False
for i in range(1, m + 1):
if tot * i % n == 0 and helper(A, tot * i / n, i, 0):
return True
return False | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR VAR ASSIGN VAR BIN_OP LIST NUMBER FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER IF BIN_OP BIN_OP VAR VAR VAR NUMBER ASSIGN VAR NUMBER IF VAR RETURN NUMBER EXPR FUNC_CALL VAR FUNC_DEF IF VAR NUMBER RETURN VAR NUMBER FOR VAR FUNC_CALL VAR VAR BIN_OP BIN_OP FUNC_CALL VAR VAR VAR NUMBER IF VAR VAR VAR VAR VAR BIN_OP VAR NUMBER IF FUNC_CALL VAR VAR BIN_OP VAR VAR VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER RETURN NUMBER RETURN NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER IF BIN_OP BIN_OP VAR VAR VAR NUMBER FUNC_CALL VAR VAR BIN_OP BIN_OP VAR VAR VAR VAR NUMBER RETURN NUMBER RETURN NUMBER VAR |
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000]. | class Solution:
def splitArraySameAverage(self, A: List[int]) -> bool:
A.sort(reverse=True)
def helper(goal, cnt):
@lru_cache(None)
def dp(i, tot, left):
if tot == goal and left == 0:
return True
if tot > goal or left == 0 or i == len(A):
return False
return dp(i + 1, tot, left) or dp(i + 1, tot + A[i], left - 1)
return dp(0, 0, cnt)
tot = sum(A)
for i in range(1, len(A) // 2 + 1):
needed = tot * i / len(A)
if int(needed) != needed:
continue
needed = int(needed)
if helper(needed, i):
print(needed)
return True
return False | CLASS_DEF FUNC_DEF VAR VAR EXPR FUNC_CALL VAR NUMBER FUNC_DEF FUNC_DEF IF VAR VAR VAR NUMBER RETURN NUMBER IF VAR VAR VAR NUMBER VAR FUNC_CALL VAR VAR RETURN NUMBER RETURN FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP VAR VAR VAR BIN_OP VAR NUMBER FUNC_CALL VAR NONE RETURN FUNC_CALL VAR NUMBER NUMBER VAR ASSIGN VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR NUMBER BIN_OP BIN_OP FUNC_CALL VAR VAR NUMBER NUMBER ASSIGN VAR BIN_OP BIN_OP VAR VAR FUNC_CALL VAR VAR IF FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR RETURN NUMBER RETURN NUMBER VAR |
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000]. | class Solution:
def splitArraySameAverage(self, A: List[int]) -> bool:
S = sum(A)
L = len(A)
if L == 1:
return False
sizes = {(0, 0)}
for n in A:
for s, c in sizes.copy():
if c < L // 2:
sizes.add((s + n, c + 1))
sizes.remove((0, 0))
for s, c in sizes:
if s * (L - c) == (S - s) * c:
return True
return False | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR NUMBER RETURN NUMBER ASSIGN VAR NUMBER NUMBER FOR VAR VAR FOR VAR VAR FUNC_CALL VAR IF VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR NUMBER NUMBER FOR VAR VAR VAR IF BIN_OP VAR BIN_OP VAR VAR BIN_OP BIN_OP VAR VAR VAR RETURN NUMBER RETURN NUMBER VAR |
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000]. | class Solution:
def splitArraySameAverage(self, A: List[int]) -> bool:
la = len(A)
sa = sum(A)
memo = {}
def find(target, k, i):
if k == 0:
return target == 0
if k + i > la:
return False
if (target, k, i) in memo:
return memo[target, k, i]
memo[target, k, i] = find(target - A[i], k - 1, i + 1) or find(
target, k, i + 1
)
return memo[target, k, i]
return any(
find(j * sa // la, j, 0) for j in range(1, la // 2 + 1) if j * sa % la == 0
) | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR DICT FUNC_DEF IF VAR NUMBER RETURN VAR NUMBER IF BIN_OP VAR VAR VAR RETURN NUMBER IF VAR VAR VAR VAR RETURN VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR FUNC_CALL VAR BIN_OP VAR VAR VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER RETURN VAR VAR VAR VAR RETURN FUNC_CALL VAR FUNC_CALL VAR BIN_OP BIN_OP VAR VAR VAR VAR NUMBER VAR FUNC_CALL VAR NUMBER BIN_OP BIN_OP VAR NUMBER NUMBER BIN_OP BIN_OP VAR VAR VAR NUMBER VAR |
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000]. | class Solution:
def splitArraySameAverage(self, A: List[int]) -> bool:
memo = {}
def dfs(k, idx, total):
if k == 0:
return total == 0
if k + idx > len(A):
return False
if (k, idx, total) in memo:
return memo[k, idx, total]
pick = dfs(k - 1, idx + 1, total - A[idx])
not_pick = dfs(k, idx + 1, total)
memo[k - 1, idx + 1, total - A[idx]] = pick or not_pick
return pick or not_pick
n, s = len(A), sum(A)
for k in range(1, n // 2 + 1):
if k * s % n == 0 and dfs(k, 0, k * s // n):
return True
return False | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR DICT FUNC_DEF IF VAR NUMBER RETURN VAR NUMBER IF BIN_OP VAR VAR FUNC_CALL VAR VAR RETURN NUMBER IF VAR VAR VAR VAR RETURN VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER BIN_OP VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR ASSIGN VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER BIN_OP VAR VAR VAR VAR VAR RETURN VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR NUMBER BIN_OP BIN_OP VAR NUMBER NUMBER IF BIN_OP BIN_OP VAR VAR VAR NUMBER FUNC_CALL VAR VAR NUMBER BIN_OP BIN_OP VAR VAR VAR RETURN NUMBER RETURN NUMBER VAR |
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000]. | class Solution:
def splitArraySameAverage(self, A: List[int]) -> bool:
total = sum(A)
l = len(A)
dp = [0] * (total + 1)
dp[A[0]] = 2
for i in range(1, l):
for j in range(total - A[i], -1, -1):
dp[j + A[i]] |= dp[j] << 1
dp[A[i]] |= 2
for i in range(1, l):
if total * i % l == 0 and 1 << i & dp[total * i // l] > 0:
return True
return False | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST NUMBER BIN_OP VAR NUMBER ASSIGN VAR VAR NUMBER NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR FOR VAR FUNC_CALL VAR BIN_OP VAR VAR VAR NUMBER NUMBER VAR BIN_OP VAR VAR VAR BIN_OP VAR VAR NUMBER VAR VAR VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR IF BIN_OP BIN_OP VAR VAR VAR NUMBER BIN_OP BIN_OP NUMBER VAR VAR BIN_OP BIN_OP VAR VAR VAR NUMBER RETURN NUMBER RETURN NUMBER VAR |
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000]. | class Solution:
def splitArraySameAverage(self, A: List[int]) -> bool:
m = len(A)
total = sum(A)
target = total / m
A.sort()
@lru_cache(None)
def dfs(k, i, sum_b):
if k == 0:
return sum_b == 0
if i == len(A):
return False
return dfs(k - 1, i + 1, sum_b - A[i]) or dfs(k, i + 1, sum_b)
for k in range(1, m // 2 + 1):
if total * k % m == 0:
if dfs(k, 0, total * k // m):
return True
return False | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR VAR EXPR FUNC_CALL VAR FUNC_DEF IF VAR NUMBER RETURN VAR NUMBER IF VAR FUNC_CALL VAR VAR RETURN NUMBER RETURN FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER BIN_OP VAR VAR VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR FUNC_CALL VAR NONE FOR VAR FUNC_CALL VAR NUMBER BIN_OP BIN_OP VAR NUMBER NUMBER IF BIN_OP BIN_OP VAR VAR VAR NUMBER IF FUNC_CALL VAR VAR NUMBER BIN_OP BIN_OP VAR VAR VAR RETURN NUMBER RETURN NUMBER VAR |
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000]. | class Solution:
def splitArraySameAverage(self, A: List[int]) -> bool:
A_sum = float(sum(A))
max_sublen = len(A) // 2
targets = {}
last_valid_target = None
for i in range(1, max_sublen + 1):
target = A_sum * i / len(A)
if target % 1 == 0:
last_valid_target = int(target)
targets[last_valid_target] = i
if last_valid_target is None:
return False
dp = [set() for _ in range(last_valid_target + 1)]
dp[0].add(0)
for i in range(len(A)):
for sum_ in range(last_valid_target, A[i] - 1, -1):
set2 = dp[sum_ - A[i]]
if A[i] == 0:
set2 = dp[sum_ - A[i]].copy()
for n in set2:
dp[sum_].add(n + 1)
if sum_ in targets and targets[sum_] == n + 1:
return True
return False | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP FUNC_CALL VAR VAR NUMBER ASSIGN VAR DICT ASSIGN VAR NONE FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER ASSIGN VAR BIN_OP BIN_OP VAR VAR FUNC_CALL VAR VAR IF BIN_OP VAR NUMBER NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR IF VAR NONE RETURN NUMBER ASSIGN VAR FUNC_CALL VAR VAR FUNC_CALL VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR NUMBER NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR BIN_OP VAR VAR NUMBER NUMBER ASSIGN VAR VAR BIN_OP VAR VAR VAR IF VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR BIN_OP VAR VAR VAR FOR VAR VAR EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER IF VAR VAR VAR VAR BIN_OP VAR NUMBER RETURN NUMBER RETURN NUMBER VAR |
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000]. | class Solution:
def splitArraySameAverage(self, nums):
def find(target, k, i):
if (target, k) in d and d[target, k] <= i:
return False
if k == 0:
return target == 0
if k + i > len(nums):
return False
res = find(target - nums[i], k - 1, i + 1) or find(target, k, i + 1)
if not res:
d[target, k] = min(d.get((target, k), length), i)
return res
d, length, sum_nums = {}, len(nums), sum(nums)
return any(
find(sum_nums * i // length, i, 0)
for i in range(1, length // 2 + 1)
if sum_nums * i % length == 0
) | CLASS_DEF FUNC_DEF FUNC_DEF IF VAR VAR VAR VAR VAR VAR VAR RETURN NUMBER IF VAR NUMBER RETURN VAR NUMBER IF BIN_OP VAR VAR FUNC_CALL VAR VAR RETURN NUMBER ASSIGN VAR FUNC_CALL VAR BIN_OP VAR VAR VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER IF VAR ASSIGN VAR VAR VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR VAR VAR RETURN VAR ASSIGN VAR VAR VAR DICT FUNC_CALL VAR VAR FUNC_CALL VAR VAR RETURN FUNC_CALL VAR FUNC_CALL VAR BIN_OP BIN_OP VAR VAR VAR VAR NUMBER VAR FUNC_CALL VAR NUMBER BIN_OP BIN_OP VAR NUMBER NUMBER BIN_OP BIN_OP VAR VAR VAR NUMBER |
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000]. | class Solution:
def splitArraySameAverage(self, A: List[int]) -> bool:
if len(A) < 2:
return False
sumA, lenA = sum(A), len(A)
if sumA / lenA in A:
return True
if len(A) < 3:
return False
if not any(sumA * size % lenA == 0 for size in range(1, lenA // 2 + 1)):
return False
A = [(i * lenA - sumA) for i in A]
A.sort()
a = [i for i in A if i < 0]
b = [i for i in A if i > 0]
if len(a) > len(b):
a, b = b, a
d = set()
def r1(s, arr, n):
xx = None
while arr:
x = arr.pop()
if xx == x:
continue
xx = x
ss = s + x
d.add(-ss)
if n:
r1(ss, list(arr), n - 1)
r1(0, a, len(a) // 2)
def r2(s, arr, n):
xx = None
while arr:
x = arr.pop()
if xx == x:
continue
xx = x
ss = s + x
if ss in d:
return True
if n and r2(ss, list(arr), n - 1):
return True
return r2(0, b, len(b) // 2 - 1) | CLASS_DEF FUNC_DEF VAR VAR IF FUNC_CALL VAR VAR NUMBER RETURN NUMBER ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR IF BIN_OP VAR VAR VAR RETURN NUMBER IF FUNC_CALL VAR VAR NUMBER RETURN NUMBER IF FUNC_CALL VAR BIN_OP BIN_OP VAR VAR VAR NUMBER VAR FUNC_CALL VAR NUMBER BIN_OP BIN_OP VAR NUMBER NUMBER RETURN NUMBER ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR VAR VAR VAR VAR NUMBER ASSIGN VAR VAR VAR VAR VAR NUMBER IF FUNC_CALL VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_DEF ASSIGN VAR NONE WHILE VAR ASSIGN VAR FUNC_CALL VAR IF VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR VAR EXPR FUNC_CALL VAR VAR IF VAR EXPR FUNC_CALL VAR VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR NUMBER VAR BIN_OP FUNC_CALL VAR VAR NUMBER FUNC_DEF ASSIGN VAR NONE WHILE VAR ASSIGN VAR FUNC_CALL VAR IF VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR VAR IF VAR VAR RETURN NUMBER IF VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER RETURN NUMBER RETURN FUNC_CALL VAR NUMBER VAR BIN_OP BIN_OP FUNC_CALL VAR VAR NUMBER NUMBER VAR |
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000]. | class Solution:
def dp(self, A, index, sum_, size, aux, dp):
if index == len(A):
return False
if size == 0:
return sum_ == 0
key = str(index) + str(sum_) + str(size)
if key in dp:
return dp[key]
if A[index] <= sum_:
aux.append(A[index])
if self.dp(A, index + 1, sum_ - A[index], size - 1, aux, dp):
dp[key] = True
return dp[key]
aux.pop()
if self.dp(A, index + 1, sum_, size, aux, dp):
dp[key] = True
return dp[key]
dp[key] = False
return dp[key]
def splitArraySameAverage(self, A: List[int]) -> bool:
n = len(A)
sum_ = sum(A)
dp = {}
ans = []
tmp1 = A
for i in range(1, n):
if sum_ * i % n == 0:
s1 = sum_ * i
s1 //= n
aux = []
if self.dp(A, 0, s1, i, aux, dp):
return True
return False | CLASS_DEF FUNC_DEF IF VAR FUNC_CALL VAR VAR RETURN NUMBER IF VAR NUMBER RETURN VAR NUMBER ASSIGN VAR BIN_OP BIN_OP FUNC_CALL VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR IF VAR VAR RETURN VAR VAR IF VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR IF FUNC_CALL VAR VAR BIN_OP VAR NUMBER BIN_OP VAR VAR VAR BIN_OP VAR NUMBER VAR VAR ASSIGN VAR VAR NUMBER RETURN VAR VAR EXPR FUNC_CALL VAR IF FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR VAR VAR ASSIGN VAR VAR NUMBER RETURN VAR VAR ASSIGN VAR VAR NUMBER RETURN VAR VAR FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR DICT ASSIGN VAR LIST ASSIGN VAR VAR FOR VAR FUNC_CALL VAR NUMBER VAR IF BIN_OP BIN_OP VAR VAR VAR NUMBER ASSIGN VAR BIN_OP VAR VAR VAR VAR ASSIGN VAR LIST IF FUNC_CALL VAR VAR NUMBER VAR VAR VAR VAR RETURN NUMBER RETURN NUMBER VAR |
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000]. | class Solution:
def splitArraySameAverage(self, A: List[int]) -> bool:
total = sum(A)
sets = [{0}] + [set() for _ in A]
for num in A:
for j in reversed(list(range(len(A) - 1))):
for k in sets[j]:
s = k + num
if total * (j + 1) == s * len(A):
return True
sets[j + 1].add(k + num)
return False | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST NUMBER FUNC_CALL VAR VAR VAR FOR VAR VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR BIN_OP FUNC_CALL VAR VAR NUMBER FOR VAR VAR VAR ASSIGN VAR BIN_OP VAR VAR IF BIN_OP VAR BIN_OP VAR NUMBER BIN_OP VAR FUNC_CALL VAR VAR RETURN NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP VAR VAR RETURN NUMBER VAR |
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000]. | class Solution:
def splitArraySameAverage(self, A):
N, S = len(A), sum(A)
if N == 1:
return False
A = [(z * N - S) for z in A]
mid, left, right = N // 2, {A[0]}, {A[-1]}
if not any(S * size % N == 0 for size in range(1, mid + 1)):
return False
for i in range(1, mid):
left |= {(z + A[i]) for z in left} | {A[i]}
for i in range(mid, N - 1):
right |= {(z + A[i]) for z in right} | {A[i]}
if 0 in left | right:
return True
left -= {sum(A[:mid])}
return any(-ha in right for ha in left) | CLASS_DEF FUNC_DEF ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR IF VAR NUMBER RETURN NUMBER ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR BIN_OP VAR NUMBER VAR NUMBER VAR NUMBER IF FUNC_CALL VAR BIN_OP BIN_OP VAR VAR VAR NUMBER VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER RETURN NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR VAR BIN_OP BIN_OP VAR VAR VAR VAR VAR VAR VAR FOR VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR BIN_OP BIN_OP VAR VAR VAR VAR VAR VAR VAR IF NUMBER BIN_OP VAR VAR RETURN NUMBER VAR FUNC_CALL VAR VAR VAR RETURN FUNC_CALL VAR VAR VAR VAR VAR |
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000]. | class Solution:
def splitArraySameAverage(self, A: List[int]) -> bool:
memo = {}
def dfs(idx, k, total) -> bool:
if k == 0:
return total == 0
if k + idx > len(A):
return False
if (idx, k, total) in memo:
return memo[idx, k, total]
memo[idx + 1, k - 1, total - A[idx]] = dfs(
idx + 1, k - 1, total - A[idx]
) or dfs(idx + 1, k, total)
return memo[idx + 1, k - 1, total - A[idx]]
s, n = sum(A), len(A)
return any(
dfs(0, k, k * s // n) for k in range(1, n // 2 + 1) if k * s % n == 0
) | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR DICT FUNC_DEF IF VAR NUMBER RETURN VAR NUMBER IF BIN_OP VAR VAR FUNC_CALL VAR VAR RETURN NUMBER IF VAR VAR VAR VAR RETURN VAR VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER BIN_OP VAR VAR VAR FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER BIN_OP VAR VAR VAR FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR RETURN VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER BIN_OP VAR VAR VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR RETURN FUNC_CALL VAR FUNC_CALL VAR NUMBER VAR BIN_OP BIN_OP VAR VAR VAR VAR FUNC_CALL VAR NUMBER BIN_OP BIN_OP VAR NUMBER NUMBER BIN_OP BIN_OP VAR VAR VAR NUMBER VAR |
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000]. | class Solution:
def splitArraySameAverage(self, A: List[int]) -> bool:
A.sort()
DP = [set() for _ in range(len(A) // 2 + 1)]
all_sum = sum(A)
DP[0] = set([0])
for item in A:
for count in range(len(DP) - 2, -1, -1):
if len(DP[count]) > 0:
for a in DP[count]:
DP[count + 1].add(a + item)
for size in range(1, len(DP)):
if all_sum * size / len(A) in DP[size]:
return True
return False | CLASS_DEF FUNC_DEF VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR FUNC_CALL VAR BIN_OP BIN_OP FUNC_CALL VAR VAR NUMBER NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER FUNC_CALL VAR LIST NUMBER FOR VAR VAR FOR VAR FUNC_CALL VAR BIN_OP FUNC_CALL VAR VAR NUMBER NUMBER NUMBER IF FUNC_CALL VAR VAR VAR NUMBER FOR VAR VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP VAR VAR FOR VAR FUNC_CALL VAR NUMBER FUNC_CALL VAR VAR IF BIN_OP BIN_OP VAR VAR FUNC_CALL VAR VAR VAR VAR RETURN NUMBER RETURN NUMBER VAR |
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000]. | class Solution:
def splitArraySameAverage(self, A) -> bool:
if sum(A) == 0 and len(A) > 1:
return True
elif len(A) == 1:
return False
mem = {}
ss = sum(A)
n = len(A)
def rec(index, cur_sum, length):
if (
cur_sum * (n - length) == length * (ss - cur_sum)
and length > 0
and length < n
):
return True
elif index == n:
return False
elif (index, cur_sum) in mem:
return mem[index, cur_sum]
else:
mem[index, cur_sum] = rec(
index + 1, cur_sum + A[index], length + 1
) | rec(index + 1, cur_sum, length)
return mem[index, cur_sum]
return rec(0, 0, 0) | CLASS_DEF FUNC_DEF IF FUNC_CALL VAR VAR NUMBER FUNC_CALL VAR VAR NUMBER RETURN NUMBER IF FUNC_CALL VAR VAR NUMBER RETURN NUMBER ASSIGN VAR DICT ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR FUNC_DEF IF BIN_OP VAR BIN_OP VAR VAR BIN_OP VAR BIN_OP VAR VAR VAR NUMBER VAR VAR RETURN NUMBER IF VAR VAR RETURN NUMBER IF VAR VAR VAR RETURN VAR VAR VAR ASSIGN VAR VAR VAR BIN_OP FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP VAR VAR VAR BIN_OP VAR NUMBER FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR RETURN VAR VAR VAR RETURN FUNC_CALL VAR NUMBER NUMBER NUMBER VAR |
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000]. | class Solution:
def splitArraySameAverage(self, A: List[int]) -> bool:
def dp(idx, rem, cnt):
if cnt == 0 and rem == 0:
return True
if idx == N or cnt == 0 or rem == 0:
return False
if (idx, rem, cnt) in memo:
return memo[idx, rem, cnt]
res = False
for i in range(idx, N):
if A[i] > rem:
break
if dp(i + 1, rem - A[i], cnt - 1):
res = True
break
memo[idx, rem, cnt] = res
return res
suma = sum(A)
N = len(A)
memo = {}
A.sort()
for i in range(1, N // 2 + 1):
if suma * i % N == 0 and dp(0, suma * i / N, i):
return True
return False | CLASS_DEF FUNC_DEF VAR VAR FUNC_DEF IF VAR NUMBER VAR NUMBER RETURN NUMBER IF VAR VAR VAR NUMBER VAR NUMBER RETURN NUMBER IF VAR VAR VAR VAR RETURN VAR VAR VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR VAR IF VAR VAR VAR IF FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP VAR VAR VAR BIN_OP VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR VAR VAR VAR VAR RETURN VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR DICT EXPR FUNC_CALL VAR FOR VAR FUNC_CALL VAR NUMBER BIN_OP BIN_OP VAR NUMBER NUMBER IF BIN_OP BIN_OP VAR VAR VAR NUMBER FUNC_CALL VAR NUMBER BIN_OP BIN_OP VAR VAR VAR VAR RETURN NUMBER RETURN NUMBER VAR |
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000]. | class Solution:
def splitArraySameAverage(self, A: List[int]) -> bool:
def dp(idx, L, target):
if L == 0 and target == 0:
return True
if idx == N or L == 0 or target < 0:
return False
if (idx, L, target) in memo:
return memo[idx, L, target]
memo[idx, L, target] = (
A[idx] <= target
and dp(idx + 1, L - 1, target - A[idx])
or dp(idx + 1, L, target)
)
return memo[idx, L, target]
total = sum(A)
N = len(A)
for i in range(1, len(A) // 2 + 1):
sub_sum = total * i / N
memo = {}
if sub_sum == int(sub_sum) and dp(0, i, int(sub_sum)):
return True
return False | CLASS_DEF FUNC_DEF VAR VAR FUNC_DEF IF VAR NUMBER VAR NUMBER RETURN NUMBER IF VAR VAR VAR NUMBER VAR NUMBER RETURN NUMBER IF VAR VAR VAR VAR RETURN VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER BIN_OP VAR VAR VAR FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR RETURN VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR NUMBER BIN_OP BIN_OP FUNC_CALL VAR VAR NUMBER NUMBER ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR ASSIGN VAR DICT IF VAR FUNC_CALL VAR VAR FUNC_CALL VAR NUMBER VAR FUNC_CALL VAR VAR RETURN NUMBER RETURN NUMBER VAR |
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000]. | class Solution:
dp = []
def is_possible(self, l, actual_sum, index, curr_sum, curr_element_count):
if index >= len(l):
return False
if Solution.dp[curr_element_count][curr_sum] != None:
return Solution.dp[curr_element_count][curr_sum]
if (
curr_element_count != 0
and (actual_sum - curr_sum) / (len(l) - curr_element_count)
== curr_sum / curr_element_count
):
print(curr_sum / curr_element_count)
return True
Solution.dp[curr_element_count][curr_sum] = self.is_possible(
l, actual_sum, index + 1, curr_sum + l[index], curr_element_count + 1
) or self.is_possible(l, actual_sum, index + 1, curr_sum, curr_element_count)
return Solution.dp[curr_element_count][curr_sum]
def splitArraySameAverage(self, A: List[int]) -> bool:
if A == None or len(A) <= 1:
return False
Solution.dp = [([None] * (sum(A) + 10)) for _ in range(len(A) + 1)]
return self.is_possible(A, sum(A), 0, 0, 0) | CLASS_DEF ASSIGN VAR LIST FUNC_DEF IF VAR FUNC_CALL VAR VAR RETURN NUMBER IF VAR VAR VAR NONE RETURN VAR VAR VAR IF VAR NUMBER BIN_OP BIN_OP VAR VAR BIN_OP FUNC_CALL VAR VAR VAR BIN_OP VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR VAR RETURN NUMBER ASSIGN VAR VAR VAR FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER BIN_OP VAR VAR VAR BIN_OP VAR NUMBER FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER VAR VAR RETURN VAR VAR VAR FUNC_DEF VAR VAR IF VAR NONE FUNC_CALL VAR VAR NUMBER RETURN NUMBER ASSIGN VAR BIN_OP LIST NONE BIN_OP FUNC_CALL VAR VAR NUMBER VAR FUNC_CALL VAR BIN_OP FUNC_CALL VAR VAR NUMBER RETURN FUNC_CALL VAR VAR FUNC_CALL VAR VAR NUMBER NUMBER NUMBER VAR |
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000]. | class Solution:
def splitArraySameAverage(self, A: List[int]) -> bool:
total_sum = sum(A)
sum_dict = collections.defaultdict(set)
for val in A:
temp_list = [(1, val)]
for key, set_val in sorted(sum_dict.items()):
if key == len(A) // 2:
break
for sum_val in set_val:
temp_list.append((key + 1, val + sum_val))
for key_val, sum_val in temp_list:
sum_dict[key_val].add(sum_val)
for i in range(len(A) - 1):
if total_sum * (i + 1) / len(A) in sum_dict[i + 1]:
return True
return False | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR FOR VAR VAR ASSIGN VAR LIST NUMBER VAR FOR VAR VAR FUNC_CALL VAR FUNC_CALL VAR IF VAR BIN_OP FUNC_CALL VAR VAR NUMBER FOR VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP VAR VAR FOR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR FOR VAR FUNC_CALL VAR BIN_OP FUNC_CALL VAR VAR NUMBER IF BIN_OP BIN_OP VAR BIN_OP VAR NUMBER FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER RETURN NUMBER RETURN NUMBER VAR |
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000]. | class Solution:
def splitArraySameAverage(self, A: List[int]) -> bool:
if len(A) < 3:
return False
sumA, lenA = sum(A), len(A)
if sumA / lenA in A:
return True
A = [(i * lenA - sumA) for i in A]
A.sort()
a = [i for i in A if i < 0]
b = [i for i in A if i > 0]
if len(a) > len(b):
a, b = b, a
d = {(-i) for i in A}
def r(s, arr, n):
xx = None
while arr:
x = arr.pop()
if xx == x:
continue
xx = x
ss = s + x
if ss in d:
return True
d.add(-ss)
if n and r(ss, list(arr), n - 1):
return True
if r(0, a, len(a) - 1):
return True
if r(0, b, len(b) // 2 - 1):
return True
return False | CLASS_DEF FUNC_DEF VAR VAR IF FUNC_CALL VAR VAR NUMBER RETURN NUMBER ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR IF BIN_OP VAR VAR VAR RETURN NUMBER ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR VAR VAR VAR VAR NUMBER ASSIGN VAR VAR VAR VAR VAR NUMBER IF FUNC_CALL VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR FUNC_DEF ASSIGN VAR NONE WHILE VAR ASSIGN VAR FUNC_CALL VAR IF VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR VAR IF VAR VAR RETURN NUMBER EXPR FUNC_CALL VAR VAR IF VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER RETURN NUMBER IF FUNC_CALL VAR NUMBER VAR BIN_OP FUNC_CALL VAR VAR NUMBER RETURN NUMBER IF FUNC_CALL VAR NUMBER VAR BIN_OP BIN_OP FUNC_CALL VAR VAR NUMBER NUMBER RETURN NUMBER RETURN NUMBER VAR |
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000]. | class Solution:
def splitArraySameAverage(self, A: List[int]) -> bool:
su = sum(A)
ii = len(A) // 2 + 1
arr = [set() for _ in range(ii)]
arr[0].add(0)
for x in A:
for t in reversed(range(1, ii)):
arr[t] |= set(map(lambda s: s + x, arr[t - 1]))
for i in range(1, len(A) // 2 + 1):
if su * i % len(A) == 0:
if su * i // len(A) in arr[i]:
return True
return False | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP BIN_OP FUNC_CALL VAR VAR NUMBER NUMBER ASSIGN VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR NUMBER NUMBER FOR VAR VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR NUMBER VAR VAR VAR FUNC_CALL VAR FUNC_CALL VAR BIN_OP VAR VAR VAR BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP BIN_OP FUNC_CALL VAR VAR NUMBER NUMBER IF BIN_OP BIN_OP VAR VAR FUNC_CALL VAR VAR NUMBER IF BIN_OP BIN_OP VAR VAR FUNC_CALL VAR VAR VAR VAR RETURN NUMBER RETURN NUMBER VAR |
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000]. | class Solution:
def splitArraySameAverage(self, A: List[int]) -> bool:
n = len(A)
k = int(n / 2)
dp = [set() for i in range(k + 1)]
dp[0].add(0)
for i, v in enumerate(A):
for j in range(min(i + 1, k), 0, -1):
for m in dp[j - 1]:
dp[j].add(m + v)
total = sum(A)
for i in range(1, k + 1):
if total * i % n == 0:
if i * total / n in dp[i]:
return True
return False | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR BIN_OP VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR FUNC_CALL VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR NUMBER NUMBER FOR VAR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR BIN_OP VAR NUMBER VAR NUMBER NUMBER FOR VAR VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR BIN_OP VAR VAR ASSIGN VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER IF BIN_OP BIN_OP VAR VAR VAR NUMBER IF BIN_OP BIN_OP VAR VAR VAR VAR VAR RETURN NUMBER RETURN NUMBER VAR |
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000]. | class Solution:
def splitArraySameAverage(self, A: List[int]) -> bool:
avg, N = sum(A), len(A)
if N < 2:
return False
if N == 2:
return A[0] == A[1]
A = [(num * N - avg) for num in A]
dp = collections.defaultdict(set)
for i, n in enumerate(A[:-1]):
if n == 0:
return True
if i == 0:
dp[0].add(n)
continue
sums = set()
sums.add(n)
for j, s in dp.items():
for ps in s:
if ps + n == 0:
return True
sums.add(ps + n)
dp[i] = sums
return False | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR IF VAR NUMBER RETURN NUMBER IF VAR NUMBER RETURN VAR NUMBER VAR NUMBER ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR VAR NUMBER IF VAR NUMBER RETURN NUMBER IF VAR NUMBER EXPR FUNC_CALL VAR NUMBER VAR ASSIGN VAR FUNC_CALL VAR EXPR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR FOR VAR VAR IF BIN_OP VAR VAR NUMBER RETURN NUMBER EXPR FUNC_CALL VAR BIN_OP VAR VAR ASSIGN VAR VAR VAR RETURN NUMBER VAR |
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000]. | class Solution:
def splitArraySameAverage(self, A):
N, S, P = len(A), sum(A), [1]
for a in A:
P[1:] = [(p << a | q) for p, q in zip(P, P[1:] + [0])]
return any(S * n % N == 0 and P[n] & 1 << S * n // N for n in range(1, N)) | CLASS_DEF FUNC_DEF ASSIGN VAR VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR LIST NUMBER FOR VAR VAR ASSIGN VAR NUMBER BIN_OP BIN_OP VAR VAR VAR VAR VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER LIST NUMBER RETURN FUNC_CALL VAR BIN_OP BIN_OP VAR VAR VAR NUMBER BIN_OP VAR VAR BIN_OP NUMBER BIN_OP BIN_OP VAR VAR VAR VAR FUNC_CALL VAR NUMBER VAR |
Roy has N coin boxes numbered from 1 to N.
Every day he selects two indices [L,R] and adds 1 coin to each coin box starting from L to R (both inclusive).
He does this for M number of days.
After M days, Roy has a query: How many coin boxes have atleast X coins.
He has Q such queries.
Input:
First line contains N - number of coin boxes.
Second line contains M - number of days.
Each of the next M lines consists of two space separated integers L and R.
Followed by integer Q - number of queries.
Each of next Q lines contain a single integer X.
Output:
For each query output the result in a new line.
Constraints:
1 ≤ N ≤ 1000000
1 ≤ M ≤ 1000000
1 ≤ L ≤ R ≤ N
1 ≤ Q ≤ 1000000
1 ≤ X ≤ N
SAMPLE INPUT
7
4
1 3
2 5
1 2
5 6
4
1
7
4
2SAMPLE OUTPUT
6
0
0
4Explanation
Let's have a list of coin boxes.
Initially, as shown in the sample test case below we have 7 coin boxes, so let's have an array of 7 integers initialized to 0 (consider 1-based indexing).
arr = [0,0,0,0,0,0,0]
After Day 1, arr becomes:
arr = [1,1,1,0,0,0,0]
After Day 2, arr becomes:
arr = [1,2,2,1,1,0,0]
After Day 3, arr becomes:
arr = [2,3,2,1,1,0,0]
After Day 4, arr becomes:
arr = [2,3,2,1,2,1,0]
Now we have queries on this list:
Query 1: How many coin boxes have atleast 1 coin?
Ans 1: Coin boxes 1,2,3,4,5 and 6 have atleast 1 coin in them. Hence the output is 6.
Query 2: How many coin boxes have atleast 7 coins?
Ans 2: We can see that there are no coin boxes with atleast 7 coins. Hence the output is 0.
Query 3: Its similar to Query 2.
Query 4: For how many seconds atleast 2 machines were connected?
Ans 4: Coin boxes 1,2,3 and 5 have atleast 2 coins in them. Hence the output is 4. | def bs(i, j, key):
global final
if key > final[j]:
return j
if key < final[i]:
return -1
while j - i > 1:
mid = (i + j) / 2
if final[mid] < key:
i = mid
elif final[mid] >= key:
j = mid - 1
if final[j] < key:
return j
elif final[i] < key:
return i
n = eval(input())
m = eval(input())
dp = [0] * (n + 2)
for i in range(0, m):
l, r = (int(i) for i in input().split())
dp[l - 1] += 1
dp[r] -= 1
final = []
val = 0
for i in range(0, n):
val += dp[i]
final.append(val)
length = len(final)
final.sort()
q = eval(input())
for i in range(0, q):
k = eval(input())
print(length - bs(0, length - 1, k) - 1) | FUNC_DEF IF VAR VAR VAR RETURN VAR IF VAR VAR VAR RETURN NUMBER WHILE BIN_OP VAR VAR NUMBER ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER IF VAR VAR VAR ASSIGN VAR VAR IF VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER IF VAR VAR VAR RETURN VAR IF VAR VAR VAR RETURN VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR BIN_OP LIST NUMBER BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR ASSIGN VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL VAR VAR BIN_OP VAR NUMBER NUMBER VAR VAR NUMBER ASSIGN VAR LIST ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR NUMBER VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR EXPR FUNC_CALL VAR BIN_OP BIN_OP VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER VAR NUMBER |
Roy has N coin boxes numbered from 1 to N.
Every day he selects two indices [L,R] and adds 1 coin to each coin box starting from L to R (both inclusive).
He does this for M number of days.
After M days, Roy has a query: How many coin boxes have atleast X coins.
He has Q such queries.
Input:
First line contains N - number of coin boxes.
Second line contains M - number of days.
Each of the next M lines consists of two space separated integers L and R.
Followed by integer Q - number of queries.
Each of next Q lines contain a single integer X.
Output:
For each query output the result in a new line.
Constraints:
1 ≤ N ≤ 1000000
1 ≤ M ≤ 1000000
1 ≤ L ≤ R ≤ N
1 ≤ Q ≤ 1000000
1 ≤ X ≤ N
SAMPLE INPUT
7
4
1 3
2 5
1 2
5 6
4
1
7
4
2SAMPLE OUTPUT
6
0
0
4Explanation
Let's have a list of coin boxes.
Initially, as shown in the sample test case below we have 7 coin boxes, so let's have an array of 7 integers initialized to 0 (consider 1-based indexing).
arr = [0,0,0,0,0,0,0]
After Day 1, arr becomes:
arr = [1,1,1,0,0,0,0]
After Day 2, arr becomes:
arr = [1,2,2,1,1,0,0]
After Day 3, arr becomes:
arr = [2,3,2,1,1,0,0]
After Day 4, arr becomes:
arr = [2,3,2,1,2,1,0]
Now we have queries on this list:
Query 1: How many coin boxes have atleast 1 coin?
Ans 1: Coin boxes 1,2,3,4,5 and 6 have atleast 1 coin in them. Hence the output is 6.
Query 2: How many coin boxes have atleast 7 coins?
Ans 2: We can see that there are no coin boxes with atleast 7 coins. Hence the output is 0.
Query 3: Its similar to Query 2.
Query 4: For how many seconds atleast 2 machines were connected?
Ans 4: Coin boxes 1,2,3 and 5 have atleast 2 coins in them. Hence the output is 4. | num_box = int(input())
num_days = int(input())
boxes_arr = [0] * (num_box + 2)
boxcount_numcoin = [0] * (num_days + 1)
retval_list = [0] * (num_days + 1)
num_queries = 0
query = 0
for iterv in range(num_days):
LR_list = [int(elem) for elem in input().split(" ")]
boxes_arr[LR_list[0]] += 1
boxes_arr[LR_list[1] + 1] -= 1
for iterv in range(1, num_box + 2):
boxes_arr[iterv] += boxes_arr[iterv - 1]
boxcount_numcoin[boxes_arr[iterv]] += 1
retval_list[-1] = boxcount_numcoin[-1]
for iterv in range(num_days - 1, -1, -1):
retval_list[iterv] = boxcount_numcoin[iterv] + retval_list[iterv + 1]
num_queries = int(input())
for iterv in range(num_queries):
query = int(input())
if query > num_days:
print(0)
else:
print(retval_list[query]) | ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR BIN_OP LIST NUMBER BIN_OP VAR NUMBER ASSIGN VAR BIN_OP LIST NUMBER BIN_OP VAR NUMBER ASSIGN VAR BIN_OP LIST NUMBER BIN_OP VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL VAR STRING VAR VAR NUMBER NUMBER VAR BIN_OP VAR NUMBER NUMBER NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER VAR VAR VAR BIN_OP VAR NUMBER VAR VAR VAR NUMBER ASSIGN VAR NUMBER VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER NUMBER NUMBER ASSIGN VAR VAR BIN_OP VAR VAR VAR BIN_OP VAR NUMBER ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR IF VAR VAR EXPR FUNC_CALL VAR NUMBER EXPR FUNC_CALL VAR VAR VAR |
Given a string s containing 0's and 1's. You have to return the smallest positive integer C, such that the binary string can be cut into C pieces and each piece should be of the power of 5 with no leading zeros.
Note: The string s is a binary string. And if no such cuts are possible, then return -1.
Example 1:
Input:
s = "101101101"
Output:
3
Explanation:
We can split the given string into
three 101s, where 101 is the binary
representation of 5.
Example 2:
Input:
s = "00000"
Output:
-1
Explanation:
0 is not a power of 5.
Your Task:
Your task is to complete the function cuts() which take a single argument(string s). You need not take any input or print anything. Return an int C if the cut is possible else return -1.
Expected Time Complexity: O(|s|*|s|*|s|).
Expected Auxiliary Space: O(|s|).
Constraints:
1<= |s| <=50 | class Solution:
def check(self, string):
temp = int(string, 2)
while temp > 1:
if temp % 5 != 0:
return False
temp /= 5
return True
def cuts(self, s):
n = len(s)
if n == 0 or s[0] == "0":
return -1
if self.check(s):
return 1
min_cuts = float("inf")
for i in range(1, n):
left = s[:i]
right = s[i:]
if self.check(left):
cuts_right = self.cuts(right)
if cuts_right != -1:
min_cuts = min(min_cuts, cuts_right + 1)
if min_cuts != float("inf"):
return min_cuts
return -1 | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR NUMBER WHILE VAR NUMBER IF BIN_OP VAR NUMBER NUMBER RETURN NUMBER VAR NUMBER RETURN NUMBER FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR IF VAR NUMBER VAR NUMBER STRING RETURN NUMBER IF FUNC_CALL VAR VAR RETURN NUMBER ASSIGN VAR FUNC_CALL VAR STRING FOR VAR FUNC_CALL VAR NUMBER VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR IF FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER IF VAR FUNC_CALL VAR STRING RETURN VAR RETURN NUMBER |
Given a string s containing 0's and 1's. You have to return the smallest positive integer C, such that the binary string can be cut into C pieces and each piece should be of the power of 5 with no leading zeros.
Note: The string s is a binary string. And if no such cuts are possible, then return -1.
Example 1:
Input:
s = "101101101"
Output:
3
Explanation:
We can split the given string into
three 101s, where 101 is the binary
representation of 5.
Example 2:
Input:
s = "00000"
Output:
-1
Explanation:
0 is not a power of 5.
Your Task:
Your task is to complete the function cuts() which take a single argument(string s). You need not take any input or print anything. Return an int C if the cut is possible else return -1.
Expected Time Complexity: O(|s|*|s|*|s|).
Expected Auxiliary Space: O(|s|).
Constraints:
1<= |s| <=50 | import sys
class Solution:
def isPower(self, num, exp):
pwr = 1
pcnt = 0
while num > 1:
if num % exp == 0:
num //= exp
pwr += 1
else:
return 0
return pwr
def solve(self, s, start, count, mcount):
if start == len(s):
mcount[0] = min(mcount[0], count)
return
if start > len(s):
return
if s[start] == "0":
return
x = 0
j = 1
for i in range(start, len(s)):
if s[i] == "1":
x += j
if self.isPower(x, 5):
self.solve(s, i + 1, count + 1, mcount)
j *= 2
def cuts(self, s):
phase = 0
ans = 0
snum = 0
dv = int(s, 2)
if dv < 5:
if dv == 1:
return 1
return -1
if self.isPower(dv, 5):
return 1
rs = s[::-1]
mcnt = [sys.maxsize - 1]
self.solve(rs, 0, 0, mcnt)
if mcnt[0] == sys.maxsize - 1:
return -1
return mcnt[0]
def cuts_v1(self, s):
phase = 0
ans = 0
snum = 0
for i in range(len(s)):
snum <<= 1
if s[i] == "1":
snum += 1
if snum % 5 == 0:
ans += 1
snum = 0
return ans if ans > 0 else -1 | IMPORT CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER WHILE VAR NUMBER IF BIN_OP VAR VAR NUMBER VAR VAR VAR NUMBER RETURN NUMBER RETURN VAR FUNC_DEF IF VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER FUNC_CALL VAR VAR NUMBER VAR RETURN IF VAR FUNC_CALL VAR VAR RETURN IF VAR VAR STRING RETURN ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR IF VAR VAR STRING VAR VAR IF FUNC_CALL VAR VAR NUMBER EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER VAR VAR NUMBER FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR NUMBER IF VAR NUMBER IF VAR NUMBER RETURN NUMBER RETURN NUMBER IF FUNC_CALL VAR VAR NUMBER RETURN NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR LIST BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR NUMBER NUMBER VAR IF VAR NUMBER BIN_OP VAR NUMBER RETURN NUMBER RETURN VAR NUMBER FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR NUMBER IF VAR VAR STRING VAR NUMBER IF BIN_OP VAR NUMBER NUMBER VAR NUMBER ASSIGN VAR NUMBER RETURN VAR NUMBER VAR NUMBER |
Given a string s containing 0's and 1's. You have to return the smallest positive integer C, such that the binary string can be cut into C pieces and each piece should be of the power of 5 with no leading zeros.
Note: The string s is a binary string. And if no such cuts are possible, then return -1.
Example 1:
Input:
s = "101101101"
Output:
3
Explanation:
We can split the given string into
three 101s, where 101 is the binary
representation of 5.
Example 2:
Input:
s = "00000"
Output:
-1
Explanation:
0 is not a power of 5.
Your Task:
Your task is to complete the function cuts() which take a single argument(string s). You need not take any input or print anything. Return an int C if the cut is possible else return -1.
Expected Time Complexity: O(|s|*|s|*|s|).
Expected Auxiliary Space: O(|s|).
Constraints:
1<= |s| <=50 | class Solution:
def cuts(self, s):
def check(s, start, end):
num = 0
j = 1
for i in range(end, start - 1, -1):
if s[i] == "1":
num += j
j *= 2
while num > 1:
if num % 5 != 0:
return False
num //= 5
return True
def recur(s, start, end, dp):
if end < start:
return 0
if s[start] == "0":
return -1
if dp[start][end] != -1:
return dp[start][end]
if check(s, start, end):
return 1
ans = float("inf")
for i in range(start, end + 1):
if check(s, start, i):
second = recur(s, i + 1, end, dp)
if second != -1:
ans = min(ans, 1 + second)
dp[start][end] = -1 if ans == float("inf") else ans
return dp[start][end]
n = len(s)
dp = [([-1] * n) for _ in range(n)]
return recur(s, 0, n - 1, dp) | CLASS_DEF FUNC_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER NUMBER IF VAR VAR STRING VAR VAR VAR NUMBER WHILE VAR NUMBER IF BIN_OP VAR NUMBER NUMBER RETURN NUMBER VAR NUMBER RETURN NUMBER FUNC_DEF IF VAR VAR RETURN NUMBER IF VAR VAR STRING RETURN NUMBER IF VAR VAR VAR NUMBER RETURN VAR VAR VAR IF FUNC_CALL VAR VAR VAR VAR RETURN NUMBER ASSIGN VAR FUNC_CALL VAR STRING FOR VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER IF FUNC_CALL VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR IF VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR BIN_OP NUMBER VAR ASSIGN VAR VAR VAR VAR FUNC_CALL VAR STRING NUMBER VAR RETURN VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST NUMBER VAR VAR FUNC_CALL VAR VAR RETURN FUNC_CALL VAR VAR NUMBER BIN_OP VAR NUMBER VAR |
Given a string s containing 0's and 1's. You have to return the smallest positive integer C, such that the binary string can be cut into C pieces and each piece should be of the power of 5 with no leading zeros.
Note: The string s is a binary string. And if no such cuts are possible, then return -1.
Example 1:
Input:
s = "101101101"
Output:
3
Explanation:
We can split the given string into
three 101s, where 101 is the binary
representation of 5.
Example 2:
Input:
s = "00000"
Output:
-1
Explanation:
0 is not a power of 5.
Your Task:
Your task is to complete the function cuts() which take a single argument(string s). You need not take any input or print anything. Return an int C if the cut is possible else return -1.
Expected Time Complexity: O(|s|*|s|*|s|).
Expected Auxiliary Space: O(|s|).
Constraints:
1<= |s| <=50 | class Solution:
def p(self, n):
if n == 1:
return True
while n >= 5:
if n % 5 != 0:
return False
n /= 5
return n == 1
def cuts(self, s):
m = 0
j = 0
while len(s) - 1 >= 0:
c = 0
i = len(s)
while True:
if s[0] == "0":
return -1
if self.p(int(s[:i], 2)):
s = s[i:]
c += 1
break
elif i == 1:
return -1
i -= 1
m += c
if s != "":
return -1
return m | CLASS_DEF FUNC_DEF IF VAR NUMBER RETURN NUMBER WHILE VAR NUMBER IF BIN_OP VAR NUMBER NUMBER RETURN NUMBER VAR NUMBER RETURN VAR NUMBER FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER WHILE BIN_OP FUNC_CALL VAR VAR NUMBER NUMBER ASSIGN VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR WHILE NUMBER IF VAR NUMBER STRING RETURN NUMBER IF FUNC_CALL VAR FUNC_CALL VAR VAR VAR NUMBER ASSIGN VAR VAR VAR VAR NUMBER IF VAR NUMBER RETURN NUMBER VAR NUMBER VAR VAR IF VAR STRING RETURN NUMBER RETURN VAR |
Given a string s containing 0's and 1's. You have to return the smallest positive integer C, such that the binary string can be cut into C pieces and each piece should be of the power of 5 with no leading zeros.
Note: The string s is a binary string. And if no such cuts are possible, then return -1.
Example 1:
Input:
s = "101101101"
Output:
3
Explanation:
We can split the given string into
three 101s, where 101 is the binary
representation of 5.
Example 2:
Input:
s = "00000"
Output:
-1
Explanation:
0 is not a power of 5.
Your Task:
Your task is to complete the function cuts() which take a single argument(string s). You need not take any input or print anything. Return an int C if the cut is possible else return -1.
Expected Time Complexity: O(|s|*|s|*|s|).
Expected Auxiliary Space: O(|s|).
Constraints:
1<= |s| <=50 | class Solution:
def cuts(self, s):
n = len(s)
power = [1, 5, 25, 125, 625]
binary = ["1", "101", "11001", "1111101", "1001110001"]
dp = [float("inf")] * (n + 1)
dp[0] = 0
for i in range(1, n + 1):
for j in range(5):
l = len(binary[j])
if i >= l and s[i - l : i] == binary[j]:
dp[i] = min(dp[i], dp[i - l] + 1)
return dp[n] if dp[n] != float("inf") else -1 | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR LIST NUMBER NUMBER NUMBER NUMBER NUMBER ASSIGN VAR LIST STRING STRING STRING STRING STRING ASSIGN VAR BIN_OP LIST FUNC_CALL VAR STRING BIN_OP VAR NUMBER ASSIGN VAR NUMBER NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR IF VAR VAR VAR BIN_OP VAR VAR VAR VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR VAR BIN_OP VAR BIN_OP VAR VAR NUMBER RETURN VAR VAR FUNC_CALL VAR STRING VAR VAR NUMBER |
Given a string s containing 0's and 1's. You have to return the smallest positive integer C, such that the binary string can be cut into C pieces and each piece should be of the power of 5 with no leading zeros.
Note: The string s is a binary string. And if no such cuts are possible, then return -1.
Example 1:
Input:
s = "101101101"
Output:
3
Explanation:
We can split the given string into
three 101s, where 101 is the binary
representation of 5.
Example 2:
Input:
s = "00000"
Output:
-1
Explanation:
0 is not a power of 5.
Your Task:
Your task is to complete the function cuts() which take a single argument(string s). You need not take any input or print anything. Return an int C if the cut is possible else return -1.
Expected Time Complexity: O(|s|*|s|*|s|).
Expected Auxiliary Space: O(|s|).
Constraints:
1<= |s| <=50 | class Solution:
def is_power_of_5(self, n):
while n % 5 == 0:
n //= 5
return n == 1
def cuts(self, s):
n = len(s)
dp = [float("inf")] * (n + 1)
dp[0] = 0
for i in range(1, n + 1):
for j in range(i):
num = int(s[j:i], 2)
if s[j] == "0":
continue
if self.is_power_of_5(num):
dp[i] = min(dp[i], dp[j] + 1)
return dp[n] if dp[n] != float("inf") else -1 | CLASS_DEF FUNC_DEF WHILE BIN_OP VAR NUMBER NUMBER VAR NUMBER RETURN VAR NUMBER FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST FUNC_CALL VAR STRING BIN_OP VAR NUMBER ASSIGN VAR NUMBER NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR NUMBER IF VAR VAR STRING IF FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR VAR BIN_OP VAR VAR NUMBER RETURN VAR VAR FUNC_CALL VAR STRING VAR VAR NUMBER |
Given a string s containing 0's and 1's. You have to return the smallest positive integer C, such that the binary string can be cut into C pieces and each piece should be of the power of 5 with no leading zeros.
Note: The string s is a binary string. And if no such cuts are possible, then return -1.
Example 1:
Input:
s = "101101101"
Output:
3
Explanation:
We can split the given string into
three 101s, where 101 is the binary
representation of 5.
Example 2:
Input:
s = "00000"
Output:
-1
Explanation:
0 is not a power of 5.
Your Task:
Your task is to complete the function cuts() which take a single argument(string s). You need not take any input or print anything. Return an int C if the cut is possible else return -1.
Expected Time Complexity: O(|s|*|s|*|s|).
Expected Auxiliary Space: O(|s|).
Constraints:
1<= |s| <=50 | class Solution:
def cuts(self, s):
if not s:
return -1
if s[0] == "0":
return -1
pow5, local, out = 1, 0, 99
for i in range(len(s)):
local *= 2
if s[i] == "1":
local += 1
if local > pow5:
pow5 *= 5
if local == pow5:
if i == len(s) - 1:
return 1
deeper = self.cuts(s[slice(i + 1, len(s) + 1)])
if deeper != -1:
out = min(deeper + 1, out)
return out if out < 99 else -1 | CLASS_DEF FUNC_DEF IF VAR RETURN NUMBER IF VAR NUMBER STRING RETURN NUMBER ASSIGN VAR VAR VAR NUMBER NUMBER NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR NUMBER IF VAR VAR STRING VAR NUMBER IF VAR VAR VAR NUMBER IF VAR VAR IF VAR BIN_OP FUNC_CALL VAR VAR NUMBER RETURN NUMBER ASSIGN VAR FUNC_CALL VAR VAR FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP FUNC_CALL VAR VAR NUMBER IF VAR NUMBER ASSIGN VAR FUNC_CALL VAR BIN_OP VAR NUMBER VAR RETURN VAR NUMBER VAR NUMBER |
Given a string s containing 0's and 1's. You have to return the smallest positive integer C, such that the binary string can be cut into C pieces and each piece should be of the power of 5 with no leading zeros.
Note: The string s is a binary string. And if no such cuts are possible, then return -1.
Example 1:
Input:
s = "101101101"
Output:
3
Explanation:
We can split the given string into
three 101s, where 101 is the binary
representation of 5.
Example 2:
Input:
s = "00000"
Output:
-1
Explanation:
0 is not a power of 5.
Your Task:
Your task is to complete the function cuts() which take a single argument(string s). You need not take any input or print anything. Return an int C if the cut is possible else return -1.
Expected Time Complexity: O(|s|*|s|*|s|).
Expected Auxiliary Space: O(|s|).
Constraints:
1<= |s| <=50 | class Solution:
def cuts(self, s):
if s == "1":
return 1
c = 0
d = 0
l = [
"1",
"101",
"11001",
"1111101",
"1001110001",
"110000110101",
"11110100001001",
"10011000100101101",
"1011111010111100001",
"111011100110101100101",
"100101010000001011111001",
"10111010010000111011011101",
"1110100011010100101001010001",
"1001000110000100111001110010101",
"101101011110011000100000111101001",
"11100011010111111010100100110001101",
"10001110000110111100100110111111000001",
"1011000110100010101111000010111011000101",
"110111100000101101101011001110100111011001",
"100010101100011100100011000001001000100111101",
"10101101011110001110101111000101101011000110001",
]
l.reverse()
q = s
for i in l:
if i in s:
x = s.count(i)
s = s.replace(i, "")
d += x
c += x * len(i)
if c == len(q):
return d
return -1 | CLASS_DEF FUNC_DEF IF VAR STRING RETURN NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR LIST STRING STRING STRING STRING STRING STRING STRING STRING STRING STRING STRING STRING STRING STRING STRING STRING STRING STRING STRING STRING STRING EXPR FUNC_CALL VAR ASSIGN VAR VAR FOR VAR VAR IF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR STRING VAR VAR VAR BIN_OP VAR FUNC_CALL VAR VAR IF VAR FUNC_CALL VAR VAR RETURN VAR RETURN NUMBER |
Given a string s containing 0's and 1's. You have to return the smallest positive integer C, such that the binary string can be cut into C pieces and each piece should be of the power of 5 with no leading zeros.
Note: The string s is a binary string. And if no such cuts are possible, then return -1.
Example 1:
Input:
s = "101101101"
Output:
3
Explanation:
We can split the given string into
three 101s, where 101 is the binary
representation of 5.
Example 2:
Input:
s = "00000"
Output:
-1
Explanation:
0 is not a power of 5.
Your Task:
Your task is to complete the function cuts() which take a single argument(string s). You need not take any input or print anything. Return an int C if the cut is possible else return -1.
Expected Time Complexity: O(|s|*|s|*|s|).
Expected Auxiliary Space: O(|s|).
Constraints:
1<= |s| <=50 | def pow_5(n):
if n == 0:
return False
if n == 1:
return True
if n % 5 == 0:
return pow_5(n / 5)
return False
class Solution:
def cuts(self, s):
n = len(s)
dp = [0] * (n + 1)
for i in range(1, n + 1):
j = i - 1
if s[j] == "0":
dp[i] = -1
else:
dp[i] = -1
curr_ans = 1000000000
dec = 0
for k in range(i):
if s[j - k] == "1":
dec += 1 << k
if pow_5(dec) and dp[j - k] != -1:
curr_ans = min(1 + dp[j - k], curr_ans)
if curr_ans != 1000000000:
dp[i] = curr_ans
return dp[n] | FUNC_DEF IF VAR NUMBER RETURN NUMBER IF VAR NUMBER RETURN NUMBER IF BIN_OP VAR NUMBER NUMBER RETURN FUNC_CALL VAR BIN_OP VAR NUMBER RETURN NUMBER CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST NUMBER BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER IF VAR VAR STRING ASSIGN VAR VAR NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR BIN_OP VAR VAR STRING VAR BIN_OP NUMBER VAR IF FUNC_CALL VAR VAR VAR BIN_OP VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR BIN_OP NUMBER VAR BIN_OP VAR VAR VAR IF VAR NUMBER ASSIGN VAR VAR VAR RETURN VAR VAR |
Given a string s containing 0's and 1's. You have to return the smallest positive integer C, such that the binary string can be cut into C pieces and each piece should be of the power of 5 with no leading zeros.
Note: The string s is a binary string. And if no such cuts are possible, then return -1.
Example 1:
Input:
s = "101101101"
Output:
3
Explanation:
We can split the given string into
three 101s, where 101 is the binary
representation of 5.
Example 2:
Input:
s = "00000"
Output:
-1
Explanation:
0 is not a power of 5.
Your Task:
Your task is to complete the function cuts() which take a single argument(string s). You need not take any input or print anything. Return an int C if the cut is possible else return -1.
Expected Time Complexity: O(|s|*|s|*|s|).
Expected Auxiliary Space: O(|s|).
Constraints:
1<= |s| <=50 | class Solution:
def cuts(self, s):
def ok(ss):
n = int(ss, 2)
while n > 1 and n % 5 == 0:
n //= 5
return n == 1
n = len(s)
dp = [float("inf")] * (n + 1)
dp[0] = 0
for i in range(n):
for k in range(i, -1, -1):
if s[k] != "0" and ok(s[k : i + 1]):
dp[i + 1] = min(dp[i + 1], dp[k] + 1)
return dp[n] if dp[n] != float("inf") else -1 | CLASS_DEF FUNC_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR NUMBER WHILE VAR NUMBER BIN_OP VAR NUMBER NUMBER VAR NUMBER RETURN VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST FUNC_CALL VAR STRING BIN_OP VAR NUMBER ASSIGN VAR NUMBER NUMBER FOR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR NUMBER NUMBER IF VAR VAR STRING FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER FUNC_CALL VAR VAR BIN_OP VAR NUMBER BIN_OP VAR VAR NUMBER RETURN VAR VAR FUNC_CALL VAR STRING VAR VAR NUMBER |
Given a string s containing 0's and 1's. You have to return the smallest positive integer C, such that the binary string can be cut into C pieces and each piece should be of the power of 5 with no leading zeros.
Note: The string s is a binary string. And if no such cuts are possible, then return -1.
Example 1:
Input:
s = "101101101"
Output:
3
Explanation:
We can split the given string into
three 101s, where 101 is the binary
representation of 5.
Example 2:
Input:
s = "00000"
Output:
-1
Explanation:
0 is not a power of 5.
Your Task:
Your task is to complete the function cuts() which take a single argument(string s). You need not take any input or print anything. Return an int C if the cut is possible else return -1.
Expected Time Complexity: O(|s|*|s|*|s|).
Expected Auxiliary Space: O(|s|).
Constraints:
1<= |s| <=50 | class Solution:
def cuts(self, s):
c = list(s)
l = len(c)
dp = [0] * (l + 1)
dp[0] = 0
for i in range(1, l + 1):
index = i - 1
if c[index] == "0":
dp[i] = -1
else:
dp[i] = -1
t = 1000
count = 0
for j in range(i):
if c[index - j] == "1":
count += Solution.num(j)
if Solution.check(count) and dp[index - j] != -1:
w = 1 + dp[index - j]
t = min(w, t)
if t != 1000:
dp[i] = t
return dp[l]
def num(y):
if y == 0:
return 1
x = 2
for i in range(1, y):
x = x << 1
return x
@staticmethod
def check(n):
if n == 0:
return False
if n == 1:
return True
if n % 5 != 0:
return False
else:
return Solution.check(n // 5) | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST NUMBER BIN_OP VAR NUMBER ASSIGN VAR NUMBER NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER IF VAR VAR STRING ASSIGN VAR VAR NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR BIN_OP VAR VAR STRING VAR FUNC_CALL VAR VAR IF FUNC_CALL VAR VAR VAR BIN_OP VAR VAR NUMBER ASSIGN VAR BIN_OP NUMBER VAR BIN_OP VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR IF VAR NUMBER ASSIGN VAR VAR VAR RETURN VAR VAR FUNC_DEF IF VAR NUMBER RETURN NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR FUNC_DEF IF VAR NUMBER RETURN NUMBER IF VAR NUMBER RETURN NUMBER IF BIN_OP VAR NUMBER NUMBER RETURN NUMBER RETURN FUNC_CALL VAR BIN_OP VAR NUMBER VAR |
Given a string s containing 0's and 1's. You have to return the smallest positive integer C, such that the binary string can be cut into C pieces and each piece should be of the power of 5 with no leading zeros.
Note: The string s is a binary string. And if no such cuts are possible, then return -1.
Example 1:
Input:
s = "101101101"
Output:
3
Explanation:
We can split the given string into
three 101s, where 101 is the binary
representation of 5.
Example 2:
Input:
s = "00000"
Output:
-1
Explanation:
0 is not a power of 5.
Your Task:
Your task is to complete the function cuts() which take a single argument(string s). You need not take any input or print anything. Return an int C if the cut is possible else return -1.
Expected Time Complexity: O(|s|*|s|*|s|).
Expected Auxiliary Space: O(|s|).
Constraints:
1<= |s| <=50 | class Solution:
def check(self, s):
j = 1
num = 0
for i in range(len(s) - 1, -1, -1):
if s[i] == "1":
num = num + j
j *= 2
while num > 1:
if num % 5 != 0:
return False
num = num // 5
return True
def helper(self, ind, s):
if ind >= len(s):
return 1000000000.0
if s[ind] == "0":
return -1
if self.check(s[ind:]) == True:
return 1
ans = 1000000000.0
for i in range(ind, len(s)):
if self.check(s[ind : i + 1]) == True:
b = self.helper(i + 1, s)
if b != -1:
ans = min(ans, 1 + b)
return ans
def cuts(self, s):
res = self.helper(0, s)
if res == 1000000000.0:
return -1
return res | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP FUNC_CALL VAR VAR NUMBER NUMBER NUMBER IF VAR VAR STRING ASSIGN VAR BIN_OP VAR VAR VAR NUMBER WHILE VAR NUMBER IF BIN_OP VAR NUMBER NUMBER RETURN NUMBER ASSIGN VAR BIN_OP VAR NUMBER RETURN NUMBER FUNC_DEF IF VAR FUNC_CALL VAR VAR RETURN NUMBER IF VAR VAR STRING RETURN NUMBER IF FUNC_CALL VAR VAR VAR NUMBER RETURN NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR IF FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR FUNC_CALL VAR BIN_OP VAR NUMBER VAR IF VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR BIN_OP NUMBER VAR RETURN VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR NUMBER VAR IF VAR NUMBER RETURN NUMBER RETURN VAR |
Given a string s containing 0's and 1's. You have to return the smallest positive integer C, such that the binary string can be cut into C pieces and each piece should be of the power of 5 with no leading zeros.
Note: The string s is a binary string. And if no such cuts are possible, then return -1.
Example 1:
Input:
s = "101101101"
Output:
3
Explanation:
We can split the given string into
three 101s, where 101 is the binary
representation of 5.
Example 2:
Input:
s = "00000"
Output:
-1
Explanation:
0 is not a power of 5.
Your Task:
Your task is to complete the function cuts() which take a single argument(string s). You need not take any input or print anything. Return an int C if the cut is possible else return -1.
Expected Time Complexity: O(|s|*|s|*|s|).
Expected Auxiliary Space: O(|s|).
Constraints:
1<= |s| <=50 | class Solution:
st = set()
@staticmethod
def initialize():
p = 1
for i in range(1, 23):
Solution.st.add(bin(p)[2:])
p *= 5
@staticmethod
def helper(s, idx):
if idx >= len(s):
return 0
ans = float("inf")
for i in range(idx, len(s)):
substring = s[idx : i + 1]
if substring in Solution.st:
ans = min(ans, 1 + Solution.helper(s, i + 1))
return ans
@staticmethod
def cuts(s):
Solution.initialize()
ans = Solution.helper(s, 0)
return -1 if ans == float("inf") else ans | CLASS_DEF ASSIGN VAR FUNC_CALL VAR FUNC_DEF ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER NUMBER EXPR FUNC_CALL VAR FUNC_CALL VAR VAR NUMBER VAR NUMBER VAR FUNC_DEF IF VAR FUNC_CALL VAR VAR RETURN NUMBER ASSIGN VAR FUNC_CALL VAR STRING FOR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR BIN_OP VAR NUMBER IF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR BIN_OP NUMBER FUNC_CALL VAR VAR BIN_OP VAR NUMBER RETURN VAR VAR FUNC_DEF EXPR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR NUMBER RETURN VAR FUNC_CALL VAR STRING NUMBER VAR VAR |
Read problem statements in [Hindi], [Bengali], [Mandarin Chinese], [Russian], and [Vietnamese] as well.
Chef has $N$ vases in a row (numbered $1$ through $N$, initially from left to right). He wants to sort them in a particular order which he finds the most beautiful. You are given a permutation $p_{1}, p_{2}, \ldots, p_{N}$ of the integers $1$ through $N$; for each valid $i$, Chef wants the $i$-th vase to end up as the $p_{i}$-th vase from the left.
In order to achieve this, Chef can swap vases. Any two vases can be swapped in $1$ minute. Chef also has a very efficient, but limited, robot at his disposal. You are given $M$ pairs $(X_{1},Y_{1}), (X_{2},Y_{2}), \ldots, (X_{M},Y_{M})$. For each valid $i$, the robot can instantly swap two vases whenever one of them is at the position $X_{i}$ and the other at the position $Y_{i}$. Note that the initial positions of the vases are irrelevant to the robot.
Formally, Chef, at any moment, may choose to perform one of the following actions, until the vases are sorted in the desired order:
Choose two indices $i$ and $j$ ($1 ≤ i, j ≤ N$) and swap the vases that are currently at the positions $i$ and $j$. It takes $1$ minute to perform this action.
Choose an integer $k$ ($1 ≤ k ≤ M$) and order the robot to swap the vases that are currently at the positions $X_{k}$ and $Y_{k}$. It takes $0$ minutes to perform this action.
Chef cannot perform multiple operations at the same time ― if he chooses to perform some operation of the first type, he has to wait for $1$ minute before performing any further operations.
What is the minimum number of minutes that Chef needs to sort the vases?
------ Input ------
The first line of the input contains a single 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 $M$.
The second line contains $N$ space-separated integers $p_{1}, p_{2}, \ldots, p_{N}$.
$M$ lines follow. For each valid $i$, the $i$-th of these lines contains two space-separated integers $X_{i}$ and $Y_{i}$.
------ Output ------
For each test case, print a single line containing one integer ― the minimum number of minutes Chef needs to sort the vases.
------ Constraints ------
$1 ≤ T ≤ 100$
$1 ≤ N ≤ 18$
$0 ≤ M ≤ 18$
$1 ≤ p_{i} ≤ N$ for each valid $i$
$1 ≤ X_{i}, Y_{i} ≤ N$ for each valid $i$
$X_{i} \neq Y_{i}$ for each valid $i$
$N > 10$ holds in at most one test case
------ Subtasks ------
Subtask #1 (20 points): $M = 0$
Subtask #2 (20 points): $N ≤ 5$
Subtask #3 (60 points): original constraints
----- Sample Input 1 ------
3
3 1
2 3 1
2 3
5 10
2 4 5 1 3
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
4 1
3 1 4 2
1 2
----- Sample Output 1 ------
1
0
2
----- explanation 1 ------
Example case 1: Chef can ask the robot to swap the vases at the positions $2$ and $3$, and then he can swap the vases at the positions $1$ and $2$.
Example case 2: The robot can swap each pair of vases, so the answer is $0$.
Example case 3: Chef can swap the vases at the positions $1$ and $4$, then ask the robot to swap the vases at the positions $1$ and $2$, and then swap the vases at the positions $3$ and $4$, taking a total of two minutes. | import sys
Ri = lambda: [int(x) for x in sys.stdin.readline().split()]
ri = lambda: sys.stdin.readline().strip()
def deletearrele(arr, ele, no):
newarr = []
ite = 0
for i in range(len(arr)):
if arr[i] != ele:
newarr.append(arr[i])
elif ite < no:
ite += 1
else:
newarr.append(arr[i])
return newarr
for _ in range(int(ri())):
n, m = Ri()
a = Ri()
posicidt = {}
a = [0] + a
for i in range(1, n + 1):
posicidt[a[i]] = i
par = [i for i in range(n + 1)]
rank = [(1) for i in range(n + 1)]
def findpar(a):
if par[a] == a:
return a
else:
swaptemp = findpar(par[a])
par[a] = swaptemp
return swaptemp
def disunion(a, b):
ap = findpar(a)
bp = findpar(b)
if ap != bp:
par[bp] = ap
rank[ap] += rank[bp]
for i in range(m):
x, y = Ri()
xp = findpar(x)
yp = findpar(y)
if xp != yp:
disunion(x, y)
ccomp = []
cid = {}
ite = 0
for i in range(1, n + 1):
if rank[findpar(i)] >= 2:
if findpar(i) in cid:
ccomp[cid[findpar(i)]].append(i)
else:
cid[findpar(i)] = ite
ite += 1
ccomp.append([i])
ccomp.append([])
for i in range(1, n + 1):
if rank[findpar(i)] == 1:
ccomp[-1].append(i)
ans = 0
i = ccomp[-1]
for j in i:
if a[j] != j and findpar(j) == findpar(posicidt[j]):
disunionwant = a[j]
want = j
tochange = j
tobechanged = posicidt[j]
a[tochange], a[tobechanged] = a[tobechanged], a[tochange]
posicidt[disunionwant] = posicidt[j]
posicidt[j] = j
continue
if a[j] != j and findpar(j) != findpar(posicidt[j]):
ans += 1
disunionwant = a[j]
want = j
tochange = j
tobechanged = posicidt[j]
a[tochange], a[tobechanged] = a[tobechanged], a[tochange]
posicidt[disunionwant] = posicidt[j]
posicidt[j] = j
ccomp.pop()
ite = 0
dp = []
for i in ccomp:
swaptemp = []
for j in i:
if cid[findpar(a[j])] != ite:
swaptemp.append(cid[findpar(a[j])])
dp.append(swaptemp)
ite += 1
for i in range(len(dp)):
for j in range(i + 1, len(dp)):
val1 = dp[i].count(j)
val2 = dp[j].count(i)
minn = min(val1, val2)
dp[i] = deletearrele(dp[i], j, minn)
dp[j] = deletearrele(dp[j], i, minn)
ans += minn
while True:
firstele = -1
for i in range(len(dp)):
if len(dp[i]) != 0:
firstele = i
break
if firstele == -1:
break
cur = firstele
while True:
if len(dp[cur]) > 0:
swaptemp = dp[cur][-1]
dp[cur].pop()
cur = swaptemp
if cur == firstele:
break
ans += 1
else:
break
print(ans) | IMPORT ASSIGN VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL FUNC_CALL VAR FUNC_DEF ASSIGN VAR LIST ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR IF VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR IF VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR RETURN VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR ASSIGN VAR DICT ASSIGN VAR BIN_OP LIST NUMBER VAR FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR FUNC_CALL VAR BIN_OP VAR NUMBER ASSIGN VAR NUMBER VAR FUNC_CALL VAR BIN_OP VAR NUMBER FUNC_DEF IF VAR VAR VAR RETURN VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR VAR RETURN VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR LIST ASSIGN VAR DICT ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER IF VAR FUNC_CALL VAR VAR NUMBER IF FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR NUMBER EXPR FUNC_CALL VAR LIST VAR EXPR FUNC_CALL VAR LIST FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER IF VAR FUNC_CALL VAR VAR NUMBER EXPR FUNC_CALL VAR NUMBER VAR ASSIGN VAR NUMBER ASSIGN VAR VAR NUMBER FOR VAR VAR IF VAR VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR IF VAR VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR VAR VAR NUMBER ASSIGN VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR NUMBER ASSIGN VAR LIST FOR VAR VAR ASSIGN VAR LIST FOR VAR VAR IF VAR FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR VAR VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR VAR VAR VAR VAR VAR WHILE NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR IF FUNC_CALL VAR VAR VAR NUMBER ASSIGN VAR VAR IF VAR NUMBER ASSIGN VAR VAR WHILE NUMBER IF FUNC_CALL VAR VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR IF VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR |
Read problem statements in [Hindi], [Bengali], [Mandarin Chinese], [Russian], and [Vietnamese] as well.
Chef has $N$ vases in a row (numbered $1$ through $N$, initially from left to right). He wants to sort them in a particular order which he finds the most beautiful. You are given a permutation $p_{1}, p_{2}, \ldots, p_{N}$ of the integers $1$ through $N$; for each valid $i$, Chef wants the $i$-th vase to end up as the $p_{i}$-th vase from the left.
In order to achieve this, Chef can swap vases. Any two vases can be swapped in $1$ minute. Chef also has a very efficient, but limited, robot at his disposal. You are given $M$ pairs $(X_{1},Y_{1}), (X_{2},Y_{2}), \ldots, (X_{M},Y_{M})$. For each valid $i$, the robot can instantly swap two vases whenever one of them is at the position $X_{i}$ and the other at the position $Y_{i}$. Note that the initial positions of the vases are irrelevant to the robot.
Formally, Chef, at any moment, may choose to perform one of the following actions, until the vases are sorted in the desired order:
Choose two indices $i$ and $j$ ($1 ≤ i, j ≤ N$) and swap the vases that are currently at the positions $i$ and $j$. It takes $1$ minute to perform this action.
Choose an integer $k$ ($1 ≤ k ≤ M$) and order the robot to swap the vases that are currently at the positions $X_{k}$ and $Y_{k}$. It takes $0$ minutes to perform this action.
Chef cannot perform multiple operations at the same time ― if he chooses to perform some operation of the first type, he has to wait for $1$ minute before performing any further operations.
What is the minimum number of minutes that Chef needs to sort the vases?
------ Input ------
The first line of the input contains a single 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 $M$.
The second line contains $N$ space-separated integers $p_{1}, p_{2}, \ldots, p_{N}$.
$M$ lines follow. For each valid $i$, the $i$-th of these lines contains two space-separated integers $X_{i}$ and $Y_{i}$.
------ Output ------
For each test case, print a single line containing one integer ― the minimum number of minutes Chef needs to sort the vases.
------ Constraints ------
$1 ≤ T ≤ 100$
$1 ≤ N ≤ 18$
$0 ≤ M ≤ 18$
$1 ≤ p_{i} ≤ N$ for each valid $i$
$1 ≤ X_{i}, Y_{i} ≤ N$ for each valid $i$
$X_{i} \neq Y_{i}$ for each valid $i$
$N > 10$ holds in at most one test case
------ Subtasks ------
Subtask #1 (20 points): $M = 0$
Subtask #2 (20 points): $N ≤ 5$
Subtask #3 (60 points): original constraints
----- Sample Input 1 ------
3
3 1
2 3 1
2 3
5 10
2 4 5 1 3
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
4 1
3 1 4 2
1 2
----- Sample Output 1 ------
1
0
2
----- explanation 1 ------
Example case 1: Chef can ask the robot to swap the vases at the positions $2$ and $3$, and then he can swap the vases at the positions $1$ and $2$.
Example case 2: The robot can swap each pair of vases, so the answer is $0$.
Example case 3: Chef can swap the vases at the positions $1$ and $4$, then ask the robot to swap the vases at the positions $1$ and $2$, and then swap the vases at the positions $3$ and $4$, taking a total of two minutes. | rr = lambda: input().strip()
rrm = lambda: map(int, rr().split())
def solve(N, M, p):
group, count = [0] * N, 0
j = 1
for i in range(M):
x, y = rrm()
if group[x - 1] + group[y - 1] == 0:
group[x - 1] = group[y - 1] = j
j += 1
elif group[x - 1] == 0:
group[x - 1] = group[y - 1]
elif group[y - 1] == 0:
group[y - 1] = group[x - 1]
else:
a = min(group[x - 1], group[y - 1])
b = max(group[x - 1], group[y - 1])
for k in range(N):
if group[k] == b:
group[k] = a
cp = 0
while 1:
if cp == N:
break
dp = p[cp] - 1
if p[cp] == cp + 1 or group[cp] != 0 or group[dp] != 0:
cp += 1
continue
else:
p[dp], p[cp] = p[cp], p[dp]
count += 1
for cp in range(N):
dp = p[cp] - 1
if group[dp] != group[cp] and group[dp] == 0:
p[dp], p[cp] = p[cp], p[dp]
count += 1
cp = 0
while 1:
if cp == N:
break
dp = p[cp] - 1
if group[cp] == group[dp]:
cp += 1
continue
lis = []
for i in range(cp + 1, N):
if group[i] == group[dp]:
lis.append(i)
if group[cp] == group[p[i] - 1]:
p[i], p[cp] = p[cp], p[i]
count += 1
break
else:
for i in lis:
c = p[i] - 1
if group[i] != group[c]:
p[i], p[cp] = p[cp], p[i]
count += 1
break
return count
T = int(rr())
for _ in range(T):
N, M = rrm()
p = list(rrm())
ans = solve(N, M, p)
print(ans) | ASSIGN VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR FUNC_DEF ASSIGN VAR VAR BIN_OP LIST NUMBER VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR IF BIN_OP VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER VAR VAR NUMBER IF VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER IF VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR NUMBER WHILE NUMBER IF VAR VAR ASSIGN VAR BIN_OP VAR VAR NUMBER IF VAR VAR BIN_OP VAR NUMBER VAR VAR NUMBER VAR VAR NUMBER VAR NUMBER ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR VAR NUMBER FOR VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR VAR NUMBER IF VAR VAR VAR VAR VAR VAR NUMBER ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR VAR NUMBER ASSIGN VAR NUMBER WHILE NUMBER IF VAR VAR ASSIGN VAR BIN_OP VAR VAR NUMBER IF VAR VAR VAR VAR VAR NUMBER ASSIGN VAR LIST FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER VAR IF VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR IF VAR VAR VAR BIN_OP VAR VAR NUMBER ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR VAR NUMBER FOR VAR VAR ASSIGN VAR BIN_OP VAR VAR NUMBER IF VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR 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 ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR |
Read problem statements in [Hindi], [Bengali], [Mandarin Chinese], [Russian], and [Vietnamese] as well.
Chef has $N$ vases in a row (numbered $1$ through $N$, initially from left to right). He wants to sort them in a particular order which he finds the most beautiful. You are given a permutation $p_{1}, p_{2}, \ldots, p_{N}$ of the integers $1$ through $N$; for each valid $i$, Chef wants the $i$-th vase to end up as the $p_{i}$-th vase from the left.
In order to achieve this, Chef can swap vases. Any two vases can be swapped in $1$ minute. Chef also has a very efficient, but limited, robot at his disposal. You are given $M$ pairs $(X_{1},Y_{1}), (X_{2},Y_{2}), \ldots, (X_{M},Y_{M})$. For each valid $i$, the robot can instantly swap two vases whenever one of them is at the position $X_{i}$ and the other at the position $Y_{i}$. Note that the initial positions of the vases are irrelevant to the robot.
Formally, Chef, at any moment, may choose to perform one of the following actions, until the vases are sorted in the desired order:
Choose two indices $i$ and $j$ ($1 ≤ i, j ≤ N$) and swap the vases that are currently at the positions $i$ and $j$. It takes $1$ minute to perform this action.
Choose an integer $k$ ($1 ≤ k ≤ M$) and order the robot to swap the vases that are currently at the positions $X_{k}$ and $Y_{k}$. It takes $0$ minutes to perform this action.
Chef cannot perform multiple operations at the same time ― if he chooses to perform some operation of the first type, he has to wait for $1$ minute before performing any further operations.
What is the minimum number of minutes that Chef needs to sort the vases?
------ Input ------
The first line of the input contains a single 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 $M$.
The second line contains $N$ space-separated integers $p_{1}, p_{2}, \ldots, p_{N}$.
$M$ lines follow. For each valid $i$, the $i$-th of these lines contains two space-separated integers $X_{i}$ and $Y_{i}$.
------ Output ------
For each test case, print a single line containing one integer ― the minimum number of minutes Chef needs to sort the vases.
------ Constraints ------
$1 ≤ T ≤ 100$
$1 ≤ N ≤ 18$
$0 ≤ M ≤ 18$
$1 ≤ p_{i} ≤ N$ for each valid $i$
$1 ≤ X_{i}, Y_{i} ≤ N$ for each valid $i$
$X_{i} \neq Y_{i}$ for each valid $i$
$N > 10$ holds in at most one test case
------ Subtasks ------
Subtask #1 (20 points): $M = 0$
Subtask #2 (20 points): $N ≤ 5$
Subtask #3 (60 points): original constraints
----- Sample Input 1 ------
3
3 1
2 3 1
2 3
5 10
2 4 5 1 3
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
4 1
3 1 4 2
1 2
----- Sample Output 1 ------
1
0
2
----- explanation 1 ------
Example case 1: Chef can ask the robot to swap the vases at the positions $2$ and $3$, and then he can swap the vases at the positions $1$ and $2$.
Example case 2: The robot can swap each pair of vases, so the answer is $0$.
Example case 3: Chef can swap the vases at the positions $1$ and $4$, then ask the robot to swap the vases at the positions $1$ and $2$, and then swap the vases at the positions $3$ and $4$, taking a total of two minutes. | for _ in range(int(input())):
n, m = map(int, input().split())
p = [0] + list(map(int, input().split()))
cor, tree, res = (
[sorted(list(map(int, input().split()))) for i in range(m)],
[[] for i in p],
0,
)
for i, j in cor:
tree[i].append(j)
tree[j].append(i)
lis = sorted([p[i] for i in range(1, n + 1)])
vis, pic = [(0) for i in range(n)], []
for j in range(len(lis)):
if vis[j]:
continue
pack = [lis[j]]
for k in pack:
for l in tree[k]:
if l in lis and l not in pack:
pack.append(l)
vis[lis.index(l)] = 1
pic.append(pack)
PIC, lno = len(pic), [(-1) for i in p]
for j in range(PIC):
for k in pic[j]:
lno[k] = j
exc, tot = [[(0) for i in range(PIC)] for i in range(PIC)], 0
for j in range(PIC):
for k in pic[j]:
exc[j][lno[p[k]]] += 1
for j in range(PIC):
exc[j][j] = 0
for j in range(PIC):
for k in range(j + 1, PIC):
tot += exc[j][k] + exc[k][j]
while tot > 0:
J, K = -1, -1
for j in range(PIC):
for k in range(PIC):
if exc[j][k]:
J, K = j, k
break
if J != -1:
break
I, All, wor = J, [[J, K]], []
for j in All:
flag = 0
for k in range(PIC):
if exc[j[-1]][k]:
if k == I:
j.append(I)
wor, flag = j, 1
break
if k in j:
continue
news = [i for i in j]
news.append(k)
All.append(news)
if flag:
break
for i in range(len(wor) - 1):
exc[wor[i]][wor[i + 1]] -= 1
res += len(wor) - 2
tot -= len(wor) - 1
print(res) | 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 BIN_OP LIST NUMBER FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR VAR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR VAR FUNC_CALL VAR VAR LIST VAR VAR NUMBER FOR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER ASSIGN VAR VAR NUMBER VAR FUNC_CALL VAR VAR LIST FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR IF VAR VAR ASSIGN VAR LIST VAR VAR FOR VAR VAR FOR VAR VAR VAR IF VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR NUMBER EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR NUMBER VAR VAR FOR VAR FUNC_CALL VAR VAR FOR VAR VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR NUMBER VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR NUMBER FOR VAR FUNC_CALL VAR VAR FOR VAR VAR VAR VAR VAR VAR VAR VAR NUMBER FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR NUMBER FOR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR BIN_OP VAR VAR VAR VAR VAR VAR WHILE VAR NUMBER ASSIGN VAR VAR NUMBER NUMBER FOR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR IF VAR VAR VAR ASSIGN VAR VAR VAR VAR IF VAR NUMBER ASSIGN VAR VAR VAR VAR LIST LIST VAR VAR LIST FOR VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR NUMBER VAR IF VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR NUMBER IF VAR VAR ASSIGN VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR IF VAR FOR VAR FUNC_CALL VAR BIN_OP FUNC_CALL VAR VAR NUMBER VAR VAR VAR VAR BIN_OP VAR NUMBER NUMBER VAR BIN_OP FUNC_CALL VAR VAR NUMBER VAR BIN_OP FUNC_CALL VAR VAR NUMBER EXPR FUNC_CALL VAR VAR |
Read problem statements in [Hindi], [Bengali], [Mandarin Chinese], [Russian], and [Vietnamese] as well.
Chef has $N$ vases in a row (numbered $1$ through $N$, initially from left to right). He wants to sort them in a particular order which he finds the most beautiful. You are given a permutation $p_{1}, p_{2}, \ldots, p_{N}$ of the integers $1$ through $N$; for each valid $i$, Chef wants the $i$-th vase to end up as the $p_{i}$-th vase from the left.
In order to achieve this, Chef can swap vases. Any two vases can be swapped in $1$ minute. Chef also has a very efficient, but limited, robot at his disposal. You are given $M$ pairs $(X_{1},Y_{1}), (X_{2},Y_{2}), \ldots, (X_{M},Y_{M})$. For each valid $i$, the robot can instantly swap two vases whenever one of them is at the position $X_{i}$ and the other at the position $Y_{i}$. Note that the initial positions of the vases are irrelevant to the robot.
Formally, Chef, at any moment, may choose to perform one of the following actions, until the vases are sorted in the desired order:
Choose two indices $i$ and $j$ ($1 ≤ i, j ≤ N$) and swap the vases that are currently at the positions $i$ and $j$. It takes $1$ minute to perform this action.
Choose an integer $k$ ($1 ≤ k ≤ M$) and order the robot to swap the vases that are currently at the positions $X_{k}$ and $Y_{k}$. It takes $0$ minutes to perform this action.
Chef cannot perform multiple operations at the same time ― if he chooses to perform some operation of the first type, he has to wait for $1$ minute before performing any further operations.
What is the minimum number of minutes that Chef needs to sort the vases?
------ Input ------
The first line of the input contains a single 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 $M$.
The second line contains $N$ space-separated integers $p_{1}, p_{2}, \ldots, p_{N}$.
$M$ lines follow. For each valid $i$, the $i$-th of these lines contains two space-separated integers $X_{i}$ and $Y_{i}$.
------ Output ------
For each test case, print a single line containing one integer ― the minimum number of minutes Chef needs to sort the vases.
------ Constraints ------
$1 ≤ T ≤ 100$
$1 ≤ N ≤ 18$
$0 ≤ M ≤ 18$
$1 ≤ p_{i} ≤ N$ for each valid $i$
$1 ≤ X_{i}, Y_{i} ≤ N$ for each valid $i$
$X_{i} \neq Y_{i}$ for each valid $i$
$N > 10$ holds in at most one test case
------ Subtasks ------
Subtask #1 (20 points): $M = 0$
Subtask #2 (20 points): $N ≤ 5$
Subtask #3 (60 points): original constraints
----- Sample Input 1 ------
3
3 1
2 3 1
2 3
5 10
2 4 5 1 3
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
4 1
3 1 4 2
1 2
----- Sample Output 1 ------
1
0
2
----- explanation 1 ------
Example case 1: Chef can ask the robot to swap the vases at the positions $2$ and $3$, and then he can swap the vases at the positions $1$ and $2$.
Example case 2: The robot can swap each pair of vases, so the answer is $0$.
Example case 3: Chef can swap the vases at the positions $1$ and $4$, then ask the robot to swap the vases at the positions $1$ and $2$, and then swap the vases at the positions $3$ and $4$, taking a total of two minutes. | papa_array = []
cg = []
def spapa(kx):
if papa_array[kx] != kx:
sl = spapa(papa_array[kx])
papa_array[kx] = sl
return papa_array[kx]
def add_edge(kx, ky):
sx = spapa(kx)
sy = spapa(ky)
if sx != sy:
if cg[sx] == cg[sy]:
papa_array[sy] = sx
cg[sx] += 1
elif cg[sx] > cg[sy]:
papa_array[sy] = sx
else:
papa_array[sx] = sy
def check_empty(c):
cnt = 0
for i in c:
for j in i:
cnt += 1
if cnt > 0:
return False
else:
return True
for _ in range(int(input())):
n, m = [int(kx) for kx in input().split()]
arr = [int(kx) for kx in input().split()]
papa_array = []
cg = [0] * (n + 1)
for i in range(n + 1):
papa_array.append(i)
for _i in range(m):
u, v = [int(kx) for kx in input().split()]
add_edge(u, v)
c = []
r = []
for i in range(n):
c.append([])
r.append([])
for i in range(n):
r[spapa(i + 1) - 1].append(i + 1)
for i in range(n):
rem = []
for j in r[i]:
c[i].append(arr[j - 1])
for i in range(n):
rem = []
for kz1 in r[i]:
if kz1 in c[i]:
rem.append(kz1)
for kz1 in rem:
c[i].remove(kz1)
r[i].remove(kz1)
ans = 0
while check_empty(c) == False:
for i in range(n - 1):
j = i + 1
while j < n:
idx1 = idx2 = -1
for kz1 in r[i]:
if kz1 in c[j]:
idx1 = kz1
for kz1 in r[j]:
if kz1 in c[i]:
idx2 = kz1
if idx1 < 0 or idx2 < 0:
j += 1
continue
r[i].remove(idx1)
c[j].remove(idx1)
r[j].remove(idx2)
c[i].remove(idx2)
ans += 1
j -= 1
if check_empty(c) == False:
j = 0
ssz = 10000
for i in range(n):
for k in c[i]:
if ssz > len(c[i]):
j = i
ssz = len(c[i])
break
kz1 = r[j][0]
kz2 = c[j][0]
iiiii = 0
for i in range(n):
if i != j:
if kz1 in c[i]:
iiiii = i
r[j].remove(kz1)
c[j].remove(kz2)
c[iiiii].remove(kz1)
c[iiiii].append(kz2)
ans += 1
print(ans) | ASSIGN VAR LIST ASSIGN VAR LIST FUNC_DEF IF VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR VAR RETURN VAR VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR VAR IF VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR NUMBER IF VAR VAR VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR FUNC_DEF ASSIGN VAR NUMBER FOR VAR VAR FOR VAR VAR VAR NUMBER IF VAR NUMBER RETURN NUMBER RETURN NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL 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 ASSIGN VAR LIST ASSIGN VAR BIN_OP LIST NUMBER BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR LIST ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR LIST EXPR FUNC_CALL VAR LIST FOR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR BIN_OP FUNC_CALL VAR BIN_OP VAR NUMBER NUMBER BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR VAR ASSIGN VAR LIST FOR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR VAR ASSIGN VAR LIST FOR VAR VAR VAR IF VAR VAR VAR EXPR FUNC_CALL VAR VAR FOR VAR VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR NUMBER WHILE FUNC_CALL VAR VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER WHILE VAR VAR ASSIGN VAR VAR NUMBER FOR VAR VAR VAR IF VAR VAR VAR ASSIGN VAR VAR FOR VAR VAR VAR IF VAR VAR VAR ASSIGN VAR VAR IF VAR NUMBER VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR NUMBER VAR NUMBER IF FUNC_CALL VAR VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR FOR VAR VAR VAR IF VAR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR IF VAR VAR VAR ASSIGN VAR VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR |
Read problem statements in [Hindi], [Bengali], [Mandarin Chinese], [Russian], and [Vietnamese] as well.
Chef has $N$ vases in a row (numbered $1$ through $N$, initially from left to right). He wants to sort them in a particular order which he finds the most beautiful. You are given a permutation $p_{1}, p_{2}, \ldots, p_{N}$ of the integers $1$ through $N$; for each valid $i$, Chef wants the $i$-th vase to end up as the $p_{i}$-th vase from the left.
In order to achieve this, Chef can swap vases. Any two vases can be swapped in $1$ minute. Chef also has a very efficient, but limited, robot at his disposal. You are given $M$ pairs $(X_{1},Y_{1}), (X_{2},Y_{2}), \ldots, (X_{M},Y_{M})$. For each valid $i$, the robot can instantly swap two vases whenever one of them is at the position $X_{i}$ and the other at the position $Y_{i}$. Note that the initial positions of the vases are irrelevant to the robot.
Formally, Chef, at any moment, may choose to perform one of the following actions, until the vases are sorted in the desired order:
Choose two indices $i$ and $j$ ($1 ≤ i, j ≤ N$) and swap the vases that are currently at the positions $i$ and $j$. It takes $1$ minute to perform this action.
Choose an integer $k$ ($1 ≤ k ≤ M$) and order the robot to swap the vases that are currently at the positions $X_{k}$ and $Y_{k}$. It takes $0$ minutes to perform this action.
Chef cannot perform multiple operations at the same time ― if he chooses to perform some operation of the first type, he has to wait for $1$ minute before performing any further operations.
What is the minimum number of minutes that Chef needs to sort the vases?
------ Input ------
The first line of the input contains a single 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 $M$.
The second line contains $N$ space-separated integers $p_{1}, p_{2}, \ldots, p_{N}$.
$M$ lines follow. For each valid $i$, the $i$-th of these lines contains two space-separated integers $X_{i}$ and $Y_{i}$.
------ Output ------
For each test case, print a single line containing one integer ― the minimum number of minutes Chef needs to sort the vases.
------ Constraints ------
$1 ≤ T ≤ 100$
$1 ≤ N ≤ 18$
$0 ≤ M ≤ 18$
$1 ≤ p_{i} ≤ N$ for each valid $i$
$1 ≤ X_{i}, Y_{i} ≤ N$ for each valid $i$
$X_{i} \neq Y_{i}$ for each valid $i$
$N > 10$ holds in at most one test case
------ Subtasks ------
Subtask #1 (20 points): $M = 0$
Subtask #2 (20 points): $N ≤ 5$
Subtask #3 (60 points): original constraints
----- Sample Input 1 ------
3
3 1
2 3 1
2 3
5 10
2 4 5 1 3
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
4 1
3 1 4 2
1 2
----- Sample Output 1 ------
1
0
2
----- explanation 1 ------
Example case 1: Chef can ask the robot to swap the vases at the positions $2$ and $3$, and then he can swap the vases at the positions $1$ and $2$.
Example case 2: The robot can swap each pair of vases, so the answer is $0$.
Example case 3: Chef can swap the vases at the positions $1$ and $4$, then ask the robot to swap the vases at the positions $1$ and $2$, and then swap the vases at the positions $3$ and $4$, taking a total of two minutes. | for _ in range(int(input())):
N, M = list(map(int, input().split()))
P = [0]
P.extend(list(map(int, input().split())))
xy = []
for _ in range(M):
xy.append(list(map(int, input().split())))
Tree = [[] for _ in range(N + 1)]
for i, j in xy:
Tree[i].append(j)
Tree[j].append(i)
DjSets = []
Used = [True]
Used.extend([(False) for _ in range(N)])
for i in range(len(Tree)):
if Used[i]:
continue
pack = [i]
for j in pack:
for l in Tree[j]:
if l not in pack and not Used[l]:
pack.append(l)
Used[l] = True
DjSets.append(pack)
for i in range(len(DjSets)):
DjSets[i].sort()
table, Lno = [[(0) for _ in range(len(DjSets))] for _ in range(len(DjSets))], [
(-1) for _ in range(N + 1)
]
for i in range(1, N + 1):
for j in range(len(DjSets)):
if P[i] in DjSets[j]:
Lno[i] = j
break
for i in range(len(DjSets)):
for k in DjSets[i]:
if Lno[k] != i:
table[i][Lno[k]] += 1
res, tot = 0, sum([sum(i) for i in table])
while tot > 0:
J, K = -1, -1
for i in range(len(table)):
for j in range(len(table)):
if table[i][j]:
J, K = i, j
break
if J != -1:
break
if J == -1:
break
I, All, wor = J, [[J, K]], []
for i in All:
f = False
for j in range(len(table)):
if table[i[-1]][j]:
if j == I:
i.append(j)
wor, f = i, True
if j in i:
continue
news = [n for n in i]
news.append(j)
All.append(news)
if f:
break
for i in range(len(wor) - 1):
table[wor[i]][wor[i + 1]] -= 1
res += len(wor) - 2
tot -= len(wor) - 1
print(res) | 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 VAR ASSIGN VAR LIST NUMBER EXPR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR LIST VAR FUNC_CALL VAR BIN_OP VAR NUMBER FOR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR LIST ASSIGN VAR LIST NUMBER EXPR FUNC_CALL VAR NUMBER VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR IF VAR VAR ASSIGN VAR LIST VAR FOR VAR VAR FOR VAR VAR VAR IF VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR NUMBER EXPR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR NUMBER VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR FUNC_CALL VAR VAR NUMBER VAR FUNC_CALL VAR BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR ASSIGN VAR VAR VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR FOR VAR VAR VAR IF VAR VAR VAR VAR VAR VAR VAR NUMBER ASSIGN VAR VAR NUMBER FUNC_CALL VAR FUNC_CALL VAR VAR VAR VAR WHILE VAR NUMBER ASSIGN VAR VAR NUMBER NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR IF VAR VAR VAR ASSIGN VAR VAR VAR VAR IF VAR NUMBER IF VAR NUMBER ASSIGN VAR VAR VAR VAR LIST LIST VAR VAR LIST FOR VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR IF VAR VAR NUMBER VAR IF VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR NUMBER IF VAR VAR ASSIGN VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR IF VAR FOR VAR FUNC_CALL VAR BIN_OP FUNC_CALL VAR VAR NUMBER VAR VAR VAR VAR BIN_OP VAR NUMBER NUMBER VAR BIN_OP FUNC_CALL VAR VAR NUMBER VAR BIN_OP FUNC_CALL VAR VAR NUMBER EXPR FUNC_CALL VAR VAR |
Read problem statements in [Hindi], [Bengali], [Mandarin Chinese], [Russian], and [Vietnamese] as well.
Chef has $N$ vases in a row (numbered $1$ through $N$, initially from left to right). He wants to sort them in a particular order which he finds the most beautiful. You are given a permutation $p_{1}, p_{2}, \ldots, p_{N}$ of the integers $1$ through $N$; for each valid $i$, Chef wants the $i$-th vase to end up as the $p_{i}$-th vase from the left.
In order to achieve this, Chef can swap vases. Any two vases can be swapped in $1$ minute. Chef also has a very efficient, but limited, robot at his disposal. You are given $M$ pairs $(X_{1},Y_{1}), (X_{2},Y_{2}), \ldots, (X_{M},Y_{M})$. For each valid $i$, the robot can instantly swap two vases whenever one of them is at the position $X_{i}$ and the other at the position $Y_{i}$. Note that the initial positions of the vases are irrelevant to the robot.
Formally, Chef, at any moment, may choose to perform one of the following actions, until the vases are sorted in the desired order:
Choose two indices $i$ and $j$ ($1 ≤ i, j ≤ N$) and swap the vases that are currently at the positions $i$ and $j$. It takes $1$ minute to perform this action.
Choose an integer $k$ ($1 ≤ k ≤ M$) and order the robot to swap the vases that are currently at the positions $X_{k}$ and $Y_{k}$. It takes $0$ minutes to perform this action.
Chef cannot perform multiple operations at the same time ― if he chooses to perform some operation of the first type, he has to wait for $1$ minute before performing any further operations.
What is the minimum number of minutes that Chef needs to sort the vases?
------ Input ------
The first line of the input contains a single 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 $M$.
The second line contains $N$ space-separated integers $p_{1}, p_{2}, \ldots, p_{N}$.
$M$ lines follow. For each valid $i$, the $i$-th of these lines contains two space-separated integers $X_{i}$ and $Y_{i}$.
------ Output ------
For each test case, print a single line containing one integer ― the minimum number of minutes Chef needs to sort the vases.
------ Constraints ------
$1 ≤ T ≤ 100$
$1 ≤ N ≤ 18$
$0 ≤ M ≤ 18$
$1 ≤ p_{i} ≤ N$ for each valid $i$
$1 ≤ X_{i}, Y_{i} ≤ N$ for each valid $i$
$X_{i} \neq Y_{i}$ for each valid $i$
$N > 10$ holds in at most one test case
------ Subtasks ------
Subtask #1 (20 points): $M = 0$
Subtask #2 (20 points): $N ≤ 5$
Subtask #3 (60 points): original constraints
----- Sample Input 1 ------
3
3 1
2 3 1
2 3
5 10
2 4 5 1 3
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
4 1
3 1 4 2
1 2
----- Sample Output 1 ------
1
0
2
----- explanation 1 ------
Example case 1: Chef can ask the robot to swap the vases at the positions $2$ and $3$, and then he can swap the vases at the positions $1$ and $2$.
Example case 2: The robot can swap each pair of vases, so the answer is $0$.
Example case 3: Chef can swap the vases at the positions $1$ and $4$, then ask the robot to swap the vases at the positions $1$ and $2$, and then swap the vases at the positions $3$ and $4$, taking a total of two minutes. | def swap_items(l, swapped, ind):
for i in range(ind, n):
if swapIndex[l[i]] != swapIndex[i + 1]:
j = 0
while j < n:
if (
swapIndex[l[i]] == swapIndex[j + 1]
and swapIndex[l[j]] == swapIndex[i + 1]
):
break
j += 1
if j < n:
swapped += 1
l[i], l[j] = l[j], l[i]
else:
j = i + 1
while j < n:
if (
swapIndex[l[j]] == swapIndex[i + 1]
and swapIndex[l[j]] != swapIndex[j + 1]
):
l2 = l[:]
l2[i], l2[j] = l2[j], l2[i]
swap_items(l2, swapped + 1, i + 1)
j += 1
isSolved = True
for i in range(n):
if swapIndex[l[i]] != swapIndex[i + 1]:
isSolved = False
break
if isSolved:
swapped_all.append(swapped)
t = int(input())
for _ in range(t):
n, m = map(int, input().split())
l = list(map(int, input().split()))
swapped_all = []
swaps = []
for i in range(1, n + 1):
swaps.append(set([i]))
for _ in range(m):
s1, s2 = map(int, input().split())
s1i, s2i = -1, -1
i = 0
for swap in swaps:
if s1 in swap:
s1i = i
if s2 in swap:
s2i = i
i += 1
if s1i == s2i:
continue
swap1 = swaps.pop(s1i)
if s1i < s2i:
swap2 = swaps.pop(s2i - 1)
else:
swap2 = swaps.pop(s2i)
swaps.append(swap1 | swap2)
swapIndex = {}
i = 1
for swap in swaps:
for s in swap:
swapIndex[s] = i
i += 1
swap_items(l[:], 0, 0)
print(min(swapped_all)) | FUNC_DEF FOR VAR FUNC_CALL VAR VAR VAR IF VAR VAR VAR VAR BIN_OP VAR NUMBER ASSIGN VAR NUMBER WHILE VAR VAR IF VAR VAR VAR VAR BIN_OP VAR NUMBER VAR VAR VAR VAR BIN_OP VAR NUMBER VAR NUMBER IF VAR VAR VAR NUMBER ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER WHILE VAR VAR IF VAR VAR VAR VAR BIN_OP VAR NUMBER VAR VAR VAR VAR BIN_OP VAR NUMBER ASSIGN VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR BIN_OP VAR NUMBER ASSIGN VAR NUMBER IF VAR EXPR FUNC_CALL 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 FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR LIST ASSIGN VAR LIST FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER EXPR FUNC_CALL VAR FUNC_CALL VAR LIST VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR VAR NUMBER NUMBER ASSIGN VAR NUMBER FOR VAR VAR IF VAR VAR ASSIGN VAR VAR IF VAR VAR ASSIGN VAR VAR VAR NUMBER IF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR VAR ASSIGN VAR FUNC_CALL VAR BIN_OP VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR VAR ASSIGN VAR DICT ASSIGN VAR NUMBER FOR VAR VAR FOR VAR VAR ASSIGN VAR VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR NUMBER NUMBER EXPR FUNC_CALL VAR FUNC_CALL VAR VAR |
Read problem statements in [Hindi], [Bengali], [Mandarin Chinese], [Russian], and [Vietnamese] as well.
Chef has $N$ vases in a row (numbered $1$ through $N$, initially from left to right). He wants to sort them in a particular order which he finds the most beautiful. You are given a permutation $p_{1}, p_{2}, \ldots, p_{N}$ of the integers $1$ through $N$; for each valid $i$, Chef wants the $i$-th vase to end up as the $p_{i}$-th vase from the left.
In order to achieve this, Chef can swap vases. Any two vases can be swapped in $1$ minute. Chef also has a very efficient, but limited, robot at his disposal. You are given $M$ pairs $(X_{1},Y_{1}), (X_{2},Y_{2}), \ldots, (X_{M},Y_{M})$. For each valid $i$, the robot can instantly swap two vases whenever one of them is at the position $X_{i}$ and the other at the position $Y_{i}$. Note that the initial positions of the vases are irrelevant to the robot.
Formally, Chef, at any moment, may choose to perform one of the following actions, until the vases are sorted in the desired order:
Choose two indices $i$ and $j$ ($1 ≤ i, j ≤ N$) and swap the vases that are currently at the positions $i$ and $j$. It takes $1$ minute to perform this action.
Choose an integer $k$ ($1 ≤ k ≤ M$) and order the robot to swap the vases that are currently at the positions $X_{k}$ and $Y_{k}$. It takes $0$ minutes to perform this action.
Chef cannot perform multiple operations at the same time ― if he chooses to perform some operation of the first type, he has to wait for $1$ minute before performing any further operations.
What is the minimum number of minutes that Chef needs to sort the vases?
------ Input ------
The first line of the input contains a single 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 $M$.
The second line contains $N$ space-separated integers $p_{1}, p_{2}, \ldots, p_{N}$.
$M$ lines follow. For each valid $i$, the $i$-th of these lines contains two space-separated integers $X_{i}$ and $Y_{i}$.
------ Output ------
For each test case, print a single line containing one integer ― the minimum number of minutes Chef needs to sort the vases.
------ Constraints ------
$1 ≤ T ≤ 100$
$1 ≤ N ≤ 18$
$0 ≤ M ≤ 18$
$1 ≤ p_{i} ≤ N$ for each valid $i$
$1 ≤ X_{i}, Y_{i} ≤ N$ for each valid $i$
$X_{i} \neq Y_{i}$ for each valid $i$
$N > 10$ holds in at most one test case
------ Subtasks ------
Subtask #1 (20 points): $M = 0$
Subtask #2 (20 points): $N ≤ 5$
Subtask #3 (60 points): original constraints
----- Sample Input 1 ------
3
3 1
2 3 1
2 3
5 10
2 4 5 1 3
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
4 1
3 1 4 2
1 2
----- Sample Output 1 ------
1
0
2
----- explanation 1 ------
Example case 1: Chef can ask the robot to swap the vases at the positions $2$ and $3$, and then he can swap the vases at the positions $1$ and $2$.
Example case 2: The robot can swap each pair of vases, so the answer is $0$.
Example case 3: Chef can swap the vases at the positions $1$ and $4$, then ask the robot to swap the vases at the positions $1$ and $2$, and then swap the vases at the positions $3$ and $4$, taking a total of two minutes. | from sys import stdin
class UnionFind:
def __init__(self, n):
self.size = [(1) for _ in range(n)]
self.parent = [i for i in range(n)]
def find(self, i):
while self.parent[i] != self.parent[self.parent[i]]:
self.parent[i] = self.parent[self.parent[i]]
return self.parent[i]
def union(self, i, j):
rooti, rootj = self.find(i), self.find(j)
if rooti == rootj:
return
if self.size[rooti] > self.size[rootj]:
rooti, rootj = rootj, rooti
self.parent[rooti] = rootj
self.size[rootj] += self.size[rooti]
def solve(N, M, nums, pairs):
nums = [(n - 1) for n in nums]
pairs = [[x - 1, y - 1] for x, y in pairs]
uf = UnionFind(N)
for x, y in pairs:
uf.union(x, y)
group = [uf.find(i) for i in range(N)]
res = N * N
def valid(val, i):
return group[i] == group[val]
def swap(i, j):
nums[i], nums[j] = nums[j], nums[i]
def search(i, cnt):
nonlocal res
if i >= N - 1:
res = min(res, cnt)
return
if valid(nums[i], i):
search(i + 1, cnt)
return
for j in range(i + 1, N):
if valid(nums[j], i):
swap(i, j)
search(i + 1, cnt + 1)
swap(i, j)
search(0, 0)
return res
def main():
from sys import stdin
T = int(stdin.readline().strip())
for t in range(T):
N, M = list(map(int, stdin.readline().strip().split()))
nums = list(map(int, stdin.readline().strip().split()))
pairs = [list(map(int, stdin.readline().strip().split())) for _ in range(M)]
out = solve(N, M, nums, pairs)
print(out)
main() | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR FUNC_CALL VAR VAR FUNC_DEF WHILE VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR RETURN VAR VAR FUNC_DEF ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR IF VAR VAR RETURN IF VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR FUNC_DEF ASSIGN VAR BIN_OP VAR NUMBER VAR VAR ASSIGN VAR LIST BIN_OP VAR NUMBER BIN_OP VAR NUMBER VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR FOR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR VAR FUNC_DEF RETURN VAR VAR VAR VAR FUNC_DEF ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR FUNC_DEF IF VAR BIN_OP VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN IF FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR RETURN FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER VAR IF FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR NUMBER NUMBER RETURN VAR FUNC_DEF 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 ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL FUNC_CALL VAR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR |
Elena is the topper of the class. Once her teacher asked her a problem. He gave Elena an array of integers of length n. He calls a subset of array arr good if its product can be represented as a product of one or more distinct prime numbers. He asked her to find the number of different good subsets in arr modulo 10^{9} + 7.
As a good friend of Elena help her to solve the problem.
Example 1:
Input:
N: 4
arr: {1,2,3,4}
Output: 6
Explanation:
The good subsets are:
- [1,2]: product is 2, which is the product of distinct
prime 2.
- [1,2,3]: product is 6, which is the product of
distinct primes 2 and 3.
- [1,3]: product is 3, which is the product of distinct
prime 3.
- [2]: product is 2, which is the product of distinct
prime 2.
- [2,3]: product is 6, which is the product of distinct
primes 2 and 3.
- [3]: product is 3, which is the product of distinct
prime 3.
Example 2:
Input:
N : 3
arr : {2, 2, 3}
Output: 5
Explanantion:
The good subsets are : {2}, {2}, {2, 3}, {2, 3}, {3}
Your Task:
The task is to complete the function goodSubsets() which takes an integer n and an array arr as the input parameters and should return the number of different good subsets.
Expected Time Complexity: O(NlogN)
Expected Space Complexity: O(N)
Constraints:
1 <= N <= 10^{5}
1< = arr[i] <= 30 | mod = 10**9 + 7
mapper = [0] * 31
prime = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
for i in range(2, 31):
if 0 == i % 4 or 0 == i % 9 or 25 == i:
continue
mask = 0
for j in range(10):
if 0 == i % prime[j]:
mask |= 1 << j
mapper[i] = mask
class Solution:
def goodSubsets(self, n, arr):
one = 0
dp = [0] * 1024
cnt = [0] * 31
dp[0] = 1
for i in arr:
if i == 1:
one += 1
elif mapper[i] != 0:
cnt[i] += 1
for i in range(31):
if cnt[i] == 0:
continue
for j in range(1024):
if 0 != j & mapper[i]:
continue
dp[j | mapper[i]] = (dp[j | mapper[i]] + dp[j] * cnt[i]) % mod
res = 0
for i in dp:
res = (res + i) % mod
res -= 1
if one != 0:
res = res * pow(2, one, mod) % mod
return res | ASSIGN VAR BIN_OP BIN_OP NUMBER NUMBER NUMBER ASSIGN VAR BIN_OP LIST NUMBER NUMBER ASSIGN VAR LIST NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER FOR VAR FUNC_CALL VAR NUMBER NUMBER IF NUMBER BIN_OP VAR NUMBER NUMBER BIN_OP VAR NUMBER NUMBER VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER IF NUMBER BIN_OP VAR VAR VAR VAR BIN_OP NUMBER VAR ASSIGN VAR VAR VAR CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR BIN_OP LIST NUMBER NUMBER ASSIGN VAR BIN_OP LIST NUMBER NUMBER ASSIGN VAR NUMBER NUMBER FOR VAR VAR IF VAR NUMBER VAR NUMBER IF VAR VAR NUMBER VAR VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER IF VAR VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER IF NUMBER BIN_OP VAR VAR VAR ASSIGN VAR BIN_OP VAR VAR VAR BIN_OP BIN_OP VAR BIN_OP VAR VAR VAR BIN_OP VAR VAR VAR VAR VAR ASSIGN VAR NUMBER FOR VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR VAR NUMBER IF VAR NUMBER ASSIGN VAR BIN_OP BIN_OP VAR FUNC_CALL VAR NUMBER VAR VAR VAR RETURN VAR |
Read problems statements in Mandarin Chinese and Russian.
Alok-nath is man of equality. He needs your help to divide his “sanskars” evenly amongst all his followers. By doing this, Alok-nath can create equality amongst his followers and he'll be called a true “sanskari”.
Alok-nath has N sanskars, and K followers. Each sanskar is given a numerical value which shows its intensity.
Your task is to determine whether it is possible to allocate all the sanskars to followers in such a way that the sum of intensities of the sanskars allocated to each follower is equal. Note : A sanskar can be allocated to only one of the followers.
------ Input ------
The first line of the input contains an integer T, denoting the number of test cases. Then T test cases follow. The first line of each case contains two integers N and K, with N denoting the number of sanskars and K denoting the number of followers. In the next line are N space separated integers denoting the intensities of each sanskar.
------ Output ------
For each test case, output "yes" if it is possible to divide his sanskars equally amongst his followers; otherwise output "no" (without quotes).
------ Constraints ------
$1 ≤ T ≤ 10$
$1 ≤ N ≤ 21$
$1 ≤ K ≤ 8$
$Subtask #1 (20 points) : 0 ≤ intensity of sanskar ≤ 10^{5}$
$Subtask #2 (80 points) : 0 ≤ intensity of sanskar ≤ 10^{10}$
----- Sample Input 1 ------
2
5 3
1 2 4 5 6
5 3
1 2 4 5 7
----- Sample Output 1 ------
yes
no
----- explanation 1 ------
In the first case, sanskars can be allocated as follows, each follower receiving a total intensity of 6: {1,5}, {2,4}, {6}. | def divide(l, num, dn):
if dn == 0:
return True
if num == -1:
return False
if l[num] > dn or l[num] == 0:
return divide(l, num - 1, dn)
if divide(l, num - 1, dn - l[num]):
l[num] = 0
return True
return divide(l, num - 1, dn)
for _ in range(int(input())):
n, k = map(int, input().split())
l = sorted(list(map(int, input().split())))
if sum(l) % k != 0 or n < k:
print("no")
continue
dn = sum(l) // k
ans = False
if l[n - 1] <= dn:
ans = True
for i in range(k):
if not divide(l, n - 1, dn):
ans = False
break
print("yes") if ans == True else print("no") | FUNC_DEF IF VAR NUMBER RETURN NUMBER IF VAR NUMBER RETURN NUMBER IF VAR VAR VAR VAR VAR NUMBER RETURN FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR IF FUNC_CALL VAR VAR BIN_OP VAR NUMBER BIN_OP VAR VAR VAR ASSIGN VAR VAR NUMBER RETURN NUMBER RETURN FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR 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 FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR IF BIN_OP FUNC_CALL VAR VAR VAR NUMBER VAR VAR EXPR FUNC_CALL VAR STRING ASSIGN VAR BIN_OP FUNC_CALL VAR VAR VAR ASSIGN VAR NUMBER IF VAR BIN_OP VAR NUMBER VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR ASSIGN VAR NUMBER EXPR VAR NUMBER FUNC_CALL VAR STRING FUNC_CALL VAR STRING |
Read problems statements in Mandarin Chinese and Russian.
Alok-nath is man of equality. He needs your help to divide his “sanskars” evenly amongst all his followers. By doing this, Alok-nath can create equality amongst his followers and he'll be called a true “sanskari”.
Alok-nath has N sanskars, and K followers. Each sanskar is given a numerical value which shows its intensity.
Your task is to determine whether it is possible to allocate all the sanskars to followers in such a way that the sum of intensities of the sanskars allocated to each follower is equal. Note : A sanskar can be allocated to only one of the followers.
------ Input ------
The first line of the input contains an integer T, denoting the number of test cases. Then T test cases follow. The first line of each case contains two integers N and K, with N denoting the number of sanskars and K denoting the number of followers. In the next line are N space separated integers denoting the intensities of each sanskar.
------ Output ------
For each test case, output "yes" if it is possible to divide his sanskars equally amongst his followers; otherwise output "no" (without quotes).
------ Constraints ------
$1 ≤ T ≤ 10$
$1 ≤ N ≤ 21$
$1 ≤ K ≤ 8$
$Subtask #1 (20 points) : 0 ≤ intensity of sanskar ≤ 10^{5}$
$Subtask #2 (80 points) : 0 ≤ intensity of sanskar ≤ 10^{10}$
----- Sample Input 1 ------
2
5 3
1 2 4 5 6
5 3
1 2 4 5 7
----- Sample Output 1 ------
yes
no
----- explanation 1 ------
In the first case, sanskars can be allocated as follows, each follower receiving a total intensity of 6: {1,5}, {2,4}, {6}. | def ret_res(arr, vis_arr, ind, memo, val):
if (ind, val) in memo:
return memo[ind, val]
elif val < 0:
return None
elif val == 0:
return []
elif ind == -1:
return None
elif not vis_arr[ind]:
ret1 = ret_res(arr, vis_arr, ind - 1, memo, val - arr[ind])
if ret1 != None:
ret1.append(ind)
memo[ind, val] = ret1
return memo[ind, val]
ret2 = ret_res(arr, vis_arr, ind - 1, memo, val)
memo[ind, val] = ret2
return memo[ind, val]
else:
ret3 = ret_res(arr, vis_arr, ind - 1, memo, val)
memo[ind, val] = ret3
return memo[ind, val]
for i in range(int(input())):
n, k = map(int, input().split())
arr = sorted(list(map(int, input().split())))
tot = sum(arr)
if tot % k == 0 and k <= n:
val = tot // k
vis_arr = [(False) for _ in range(n)]
for i in range(k):
path = ret_res(arr, vis_arr, n - 1, {}, val)
if path == None:
print("no")
break
else:
for j in path:
vis_arr[j] = True
else:
print("yes")
else:
print("no") | FUNC_DEF IF VAR VAR VAR RETURN VAR VAR VAR IF VAR NUMBER RETURN NONE IF VAR NUMBER RETURN LIST IF VAR NUMBER RETURN NONE IF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER VAR BIN_OP VAR VAR VAR IF VAR NONE EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR RETURN VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER VAR VAR ASSIGN VAR VAR VAR VAR RETURN VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER VAR VAR ASSIGN VAR VAR VAR VAR RETURN VAR VAR VAR 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 FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR IF BIN_OP VAR VAR NUMBER VAR VAR ASSIGN VAR BIN_OP VAR VAR ASSIGN VAR NUMBER VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER DICT VAR IF VAR NONE EXPR FUNC_CALL VAR STRING FOR VAR VAR ASSIGN VAR VAR NUMBER EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING |
Read problems statements in Mandarin Chinese and Russian.
Alok-nath is man of equality. He needs your help to divide his “sanskars” evenly amongst all his followers. By doing this, Alok-nath can create equality amongst his followers and he'll be called a true “sanskari”.
Alok-nath has N sanskars, and K followers. Each sanskar is given a numerical value which shows its intensity.
Your task is to determine whether it is possible to allocate all the sanskars to followers in such a way that the sum of intensities of the sanskars allocated to each follower is equal. Note : A sanskar can be allocated to only one of the followers.
------ Input ------
The first line of the input contains an integer T, denoting the number of test cases. Then T test cases follow. The first line of each case contains two integers N and K, with N denoting the number of sanskars and K denoting the number of followers. In the next line are N space separated integers denoting the intensities of each sanskar.
------ Output ------
For each test case, output "yes" if it is possible to divide his sanskars equally amongst his followers; otherwise output "no" (without quotes).
------ Constraints ------
$1 ≤ T ≤ 10$
$1 ≤ N ≤ 21$
$1 ≤ K ≤ 8$
$Subtask #1 (20 points) : 0 ≤ intensity of sanskar ≤ 10^{5}$
$Subtask #2 (80 points) : 0 ≤ intensity of sanskar ≤ 10^{10}$
----- Sample Input 1 ------
2
5 3
1 2 4 5 6
5 3
1 2 4 5 7
----- Sample Output 1 ------
yes
no
----- explanation 1 ------
In the first case, sanskars can be allocated as follows, each follower receiving a total intensity of 6: {1,5}, {2,4}, {6}. | import sys
def is_partition(n, tot, count):
if tot == 0:
for v in range(count):
sk.remove(l[v])
return True
if tot < 0:
return False
if n < 0 and tot != 0:
return False
l[count] = sk[n]
return is_partition(n - 1, tot - sk[n], count + 1) or is_partition(
n - 1, tot, count
)
t = sys.stdin.readline()
t = int(t)
for j in range(t):
n, k = sys.stdin.readline().split()
n = int(n)
k = int(k)
tot = 0
sk = []
l = [None] * n
p = []
flag = False
count = 0
a = sys.stdin.readline().split()
if k > n:
print("no")
continue
for i in range(n):
a[i] = int(a[i])
sk.append(a[i])
tot += a[i]
indv = int(tot / k)
if tot % k != 0:
print("no")
continue
sk.sort()
else:
for i in range(k):
ans = is_partition(len(sk) - 1, indv, 0)
if ans == False:
flag = True
break
if flag == False:
print("yes")
else:
print("no") | IMPORT FUNC_DEF IF VAR NUMBER FOR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR RETURN NUMBER IF VAR NUMBER RETURN NUMBER IF VAR NUMBER VAR NUMBER RETURN NUMBER ASSIGN VAR VAR VAR VAR RETURN FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP VAR VAR VAR BIN_OP VAR NUMBER FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR ASSIGN VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER ASSIGN VAR LIST ASSIGN VAR BIN_OP LIST NONE VAR ASSIGN VAR LIST ASSIGN VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR FUNC_CALL FUNC_CALL VAR IF VAR VAR EXPR FUNC_CALL VAR STRING FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR BIN_OP VAR VAR IF BIN_OP VAR VAR NUMBER EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR BIN_OP FUNC_CALL VAR VAR NUMBER VAR NUMBER IF VAR NUMBER ASSIGN VAR NUMBER IF VAR NUMBER EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING |
Read problems statements in Mandarin Chinese and Russian.
Alok-nath is man of equality. He needs your help to divide his “sanskars” evenly amongst all his followers. By doing this, Alok-nath can create equality amongst his followers and he'll be called a true “sanskari”.
Alok-nath has N sanskars, and K followers. Each sanskar is given a numerical value which shows its intensity.
Your task is to determine whether it is possible to allocate all the sanskars to followers in such a way that the sum of intensities of the sanskars allocated to each follower is equal. Note : A sanskar can be allocated to only one of the followers.
------ Input ------
The first line of the input contains an integer T, denoting the number of test cases. Then T test cases follow. The first line of each case contains two integers N and K, with N denoting the number of sanskars and K denoting the number of followers. In the next line are N space separated integers denoting the intensities of each sanskar.
------ Output ------
For each test case, output "yes" if it is possible to divide his sanskars equally amongst his followers; otherwise output "no" (without quotes).
------ Constraints ------
$1 ≤ T ≤ 10$
$1 ≤ N ≤ 21$
$1 ≤ K ≤ 8$
$Subtask #1 (20 points) : 0 ≤ intensity of sanskar ≤ 10^{5}$
$Subtask #2 (80 points) : 0 ≤ intensity of sanskar ≤ 10^{10}$
----- Sample Input 1 ------
2
5 3
1 2 4 5 6
5 3
1 2 4 5 7
----- Sample Output 1 ------
yes
no
----- explanation 1 ------
In the first case, sanskars can be allocated as follows, each follower receiving a total intensity of 6: {1,5}, {2,4}, {6}. | import sys
tests = int(input())
for t in range(tests):
line = input().split()
sanskars = int(line[0])
followers = int(line[1])
intensities = list(map(int, input().split()))
ti = sum(intensities)
togive = ti / followers
go = 1
if followers > sanskars or round(togive) != togive or max(intensities) > togive:
print("no")
go = 0
if go == 1:
intensities.sort(reverse=True)
def give(intensities, runsum, pos):
if intensities == [] or intensities[0] == 0:
return 1
runsum = (runsum + intensities[pos]) % togive
intensities.pop(pos)
if runsum == 0:
return give(intensities, 0, 0)
p = pos
for i in intensities[pos:]:
if runsum + i <= togive:
topass = intensities[:]
if give(topass, runsum, p) == 1:
return 1
p += 1
return 0
print("yes") if give(intensities, 0, 0) == 1 else print("no") | IMPORT ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR VAR ASSIGN VAR NUMBER IF VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR STRING ASSIGN VAR NUMBER IF VAR NUMBER EXPR FUNC_CALL VAR NUMBER FUNC_DEF IF VAR LIST VAR NUMBER NUMBER RETURN NUMBER ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR IF VAR NUMBER RETURN FUNC_CALL VAR VAR NUMBER NUMBER ASSIGN VAR VAR FOR VAR VAR VAR IF BIN_OP VAR VAR VAR ASSIGN VAR VAR IF FUNC_CALL VAR VAR VAR VAR NUMBER RETURN NUMBER VAR NUMBER RETURN NUMBER EXPR FUNC_CALL VAR VAR NUMBER NUMBER NUMBER FUNC_CALL VAR STRING FUNC_CALL VAR STRING |
Read problems statements in Mandarin Chinese and Russian.
Alok-nath is man of equality. He needs your help to divide his “sanskars” evenly amongst all his followers. By doing this, Alok-nath can create equality amongst his followers and he'll be called a true “sanskari”.
Alok-nath has N sanskars, and K followers. Each sanskar is given a numerical value which shows its intensity.
Your task is to determine whether it is possible to allocate all the sanskars to followers in such a way that the sum of intensities of the sanskars allocated to each follower is equal. Note : A sanskar can be allocated to only one of the followers.
------ Input ------
The first line of the input contains an integer T, denoting the number of test cases. Then T test cases follow. The first line of each case contains two integers N and K, with N denoting the number of sanskars and K denoting the number of followers. In the next line are N space separated integers denoting the intensities of each sanskar.
------ Output ------
For each test case, output "yes" if it is possible to divide his sanskars equally amongst his followers; otherwise output "no" (without quotes).
------ Constraints ------
$1 ≤ T ≤ 10$
$1 ≤ N ≤ 21$
$1 ≤ K ≤ 8$
$Subtask #1 (20 points) : 0 ≤ intensity of sanskar ≤ 10^{5}$
$Subtask #2 (80 points) : 0 ≤ intensity of sanskar ≤ 10^{10}$
----- Sample Input 1 ------
2
5 3
1 2 4 5 6
5 3
1 2 4 5 7
----- Sample Output 1 ------
yes
no
----- explanation 1 ------
In the first case, sanskars can be allocated as follows, each follower receiving a total intensity of 6: {1,5}, {2,4}, {6}. | def getans(arr, k):
sm = sum(arr)
if sm % k != 0 or k > len(arr):
return "no"
if all(i == 0 for i in arr):
return "yes"
req = sm // k
visited = [False] * len(arr)
retval = compute(arr, 0, k, req, visited, req)
if retval:
return "yes"
return "no"
def compute(arr, idx, k, req, visited, sm):
if k == 0:
return all(visited)
if req == 0:
return compute(arr, 0, k - 1, sm, visited, sm)
state = False
for i in range(idx, len(arr)):
if not visited[i] and arr[i] <= req:
visited[i] = True
state = compute(arr, i + 1, k, req - arr[i], visited, sm)
if state:
return state
visited[i] = False
return state
for _ in range(int(input())):
n, k = list(map(int, input().split()))
arr = list(map(int, input().split()))
arr.sort()
print(getans(arr, k)) | FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR IF BIN_OP VAR VAR NUMBER VAR FUNC_CALL VAR VAR RETURN STRING IF FUNC_CALL VAR VAR NUMBER VAR VAR RETURN STRING ASSIGN VAR BIN_OP VAR VAR ASSIGN VAR BIN_OP LIST NUMBER FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR NUMBER VAR VAR VAR VAR IF VAR RETURN STRING RETURN STRING FUNC_DEF IF VAR NUMBER RETURN FUNC_CALL VAR VAR IF VAR NUMBER RETURN FUNC_CALL VAR VAR NUMBER BIN_OP VAR NUMBER VAR VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR VAR ASSIGN VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR BIN_OP VAR VAR VAR VAR VAR IF VAR RETURN VAR ASSIGN VAR VAR NUMBER RETURN VAR 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 VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR EXPR FUNC_CALL VAR EXPR FUNC_CALL VAR FUNC_CALL VAR VAR VAR |
Read problems statements in Mandarin Chinese and Russian.
Alok-nath is man of equality. He needs your help to divide his “sanskars” evenly amongst all his followers. By doing this, Alok-nath can create equality amongst his followers and he'll be called a true “sanskari”.
Alok-nath has N sanskars, and K followers. Each sanskar is given a numerical value which shows its intensity.
Your task is to determine whether it is possible to allocate all the sanskars to followers in such a way that the sum of intensities of the sanskars allocated to each follower is equal. Note : A sanskar can be allocated to only one of the followers.
------ Input ------
The first line of the input contains an integer T, denoting the number of test cases. Then T test cases follow. The first line of each case contains two integers N and K, with N denoting the number of sanskars and K denoting the number of followers. In the next line are N space separated integers denoting the intensities of each sanskar.
------ Output ------
For each test case, output "yes" if it is possible to divide his sanskars equally amongst his followers; otherwise output "no" (without quotes).
------ Constraints ------
$1 ≤ T ≤ 10$
$1 ≤ N ≤ 21$
$1 ≤ K ≤ 8$
$Subtask #1 (20 points) : 0 ≤ intensity of sanskar ≤ 10^{5}$
$Subtask #2 (80 points) : 0 ≤ intensity of sanskar ≤ 10^{10}$
----- Sample Input 1 ------
2
5 3
1 2 4 5 6
5 3
1 2 4 5 7
----- Sample Output 1 ------
yes
no
----- explanation 1 ------
In the first case, sanskars can be allocated as follows, each follower receiving a total intensity of 6: {1,5}, {2,4}, {6}. | __author__ = "Rakshak.R.Hegde"
target = 0
san = []
def recurse(i, sum):
if sum == target:
return True
if sum > target or i == len(san):
return False
if recurse(i + 1, sum + san[i]):
del san[i]
return True
return recurse(i + 1, sum)
t = int(input())
while t:
t -= 1
n, k = map(int, input().split())
san = sorted(map(int, input().split()), reverse=True)
target, rem = divmod(sum(san), k)
if rem == 0 and san[0] <= target:
if target == 0:
print("yes" if n >= k else "no")
continue
possible = True
for i in range(k):
if recurse(1, san[0]):
del san[0]
else:
possible = False
break
print("yes" if possible else "no")
else:
print("no") | ASSIGN VAR STRING ASSIGN VAR NUMBER ASSIGN VAR LIST FUNC_DEF IF VAR VAR RETURN NUMBER IF VAR VAR VAR FUNC_CALL VAR VAR RETURN NUMBER IF FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP VAR VAR VAR VAR VAR RETURN NUMBER RETURN FUNC_CALL VAR BIN_OP VAR NUMBER VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR WHILE VAR VAR NUMBER 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 NUMBER ASSIGN VAR VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR IF VAR NUMBER VAR NUMBER VAR IF VAR NUMBER EXPR FUNC_CALL VAR VAR VAR STRING STRING ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF FUNC_CALL VAR NUMBER VAR NUMBER VAR NUMBER ASSIGN VAR NUMBER EXPR FUNC_CALL VAR VAR STRING STRING EXPR FUNC_CALL VAR STRING |
Read problems statements in Mandarin Chinese and Russian.
Alok-nath is man of equality. He needs your help to divide his “sanskars” evenly amongst all his followers. By doing this, Alok-nath can create equality amongst his followers and he'll be called a true “sanskari”.
Alok-nath has N sanskars, and K followers. Each sanskar is given a numerical value which shows its intensity.
Your task is to determine whether it is possible to allocate all the sanskars to followers in such a way that the sum of intensities of the sanskars allocated to each follower is equal. Note : A sanskar can be allocated to only one of the followers.
------ Input ------
The first line of the input contains an integer T, denoting the number of test cases. Then T test cases follow. The first line of each case contains two integers N and K, with N denoting the number of sanskars and K denoting the number of followers. In the next line are N space separated integers denoting the intensities of each sanskar.
------ Output ------
For each test case, output "yes" if it is possible to divide his sanskars equally amongst his followers; otherwise output "no" (without quotes).
------ Constraints ------
$1 ≤ T ≤ 10$
$1 ≤ N ≤ 21$
$1 ≤ K ≤ 8$
$Subtask #1 (20 points) : 0 ≤ intensity of sanskar ≤ 10^{5}$
$Subtask #2 (80 points) : 0 ≤ intensity of sanskar ≤ 10^{10}$
----- Sample Input 1 ------
2
5 3
1 2 4 5 6
5 3
1 2 4 5 7
----- Sample Output 1 ------
yes
no
----- explanation 1 ------
In the first case, sanskars can be allocated as follows, each follower receiving a total intensity of 6: {1,5}, {2,4}, {6}. | def hasSubsetSum(A, V):
if V == 0:
return True, []
if len(A) == 0:
return False, []
if V < A[len(A) - 1]:
return hasSubsetSum(A[0 : len(A) - 1], V)
else:
L = [len(A) - 1]
TMP = hasSubsetSum(A[0 : len(A) - 1], V - A[len(A) - 1])
if TMP[0]:
TMP[1].append(len(A) - 1)
return True, TMP[1]
else:
return hasSubsetSum(A[0 : len(A) - 1], V)
def hasPartition(A, SSUM, K):
if K == 0:
return True
TMP = hasSubsetSum(A, SSUM)
if TMP[0]:
B = [A[j] for j in range(len(A)) if not j in TMP[1]]
return hasPartition(B, SSUM, K - 1)
else:
return False
T = int(input())
for _ in range(T):
N, K = map(int, input().split())
A = list(map(int, input().split()))
if K > N:
print("no")
continue
SUM = 0
for j in range(N):
SUM = SUM + A[j]
if SUM % K != 0:
print("no")
continue
SSUM = SUM // K
if hasPartition(A, SSUM, K):
print("yes")
else:
print("no") | FUNC_DEF IF VAR NUMBER RETURN NUMBER LIST IF FUNC_CALL VAR VAR NUMBER RETURN NUMBER LIST IF VAR VAR BIN_OP FUNC_CALL VAR VAR NUMBER RETURN FUNC_CALL VAR VAR NUMBER BIN_OP FUNC_CALL VAR VAR NUMBER VAR ASSIGN VAR LIST BIN_OP FUNC_CALL VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR NUMBER BIN_OP FUNC_CALL VAR VAR NUMBER BIN_OP VAR VAR BIN_OP FUNC_CALL VAR VAR NUMBER IF VAR NUMBER EXPR FUNC_CALL VAR NUMBER BIN_OP FUNC_CALL VAR VAR NUMBER RETURN NUMBER VAR NUMBER RETURN FUNC_CALL VAR VAR NUMBER BIN_OP FUNC_CALL VAR VAR NUMBER VAR FUNC_DEF IF VAR NUMBER RETURN NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR IF VAR NUMBER ASSIGN VAR VAR VAR VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR VAR NUMBER RETURN FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER RETURN NUMBER 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 FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR IF VAR VAR EXPR FUNC_CALL VAR STRING ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR VAR VAR IF BIN_OP VAR VAR NUMBER EXPR FUNC_CALL VAR STRING ASSIGN VAR BIN_OP VAR VAR IF FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING |
Read problems statements in Mandarin Chinese and Russian.
Alok-nath is man of equality. He needs your help to divide his “sanskars” evenly amongst all his followers. By doing this, Alok-nath can create equality amongst his followers and he'll be called a true “sanskari”.
Alok-nath has N sanskars, and K followers. Each sanskar is given a numerical value which shows its intensity.
Your task is to determine whether it is possible to allocate all the sanskars to followers in such a way that the sum of intensities of the sanskars allocated to each follower is equal. Note : A sanskar can be allocated to only one of the followers.
------ Input ------
The first line of the input contains an integer T, denoting the number of test cases. Then T test cases follow. The first line of each case contains two integers N and K, with N denoting the number of sanskars and K denoting the number of followers. In the next line are N space separated integers denoting the intensities of each sanskar.
------ Output ------
For each test case, output "yes" if it is possible to divide his sanskars equally amongst his followers; otherwise output "no" (without quotes).
------ Constraints ------
$1 ≤ T ≤ 10$
$1 ≤ N ≤ 21$
$1 ≤ K ≤ 8$
$Subtask #1 (20 points) : 0 ≤ intensity of sanskar ≤ 10^{5}$
$Subtask #2 (80 points) : 0 ≤ intensity of sanskar ≤ 10^{10}$
----- Sample Input 1 ------
2
5 3
1 2 4 5 6
5 3
1 2 4 5 7
----- Sample Output 1 ------
yes
no
----- explanation 1 ------
In the first case, sanskars can be allocated as follows, each follower receiving a total intensity of 6: {1,5}, {2,4}, {6}. | from itertools import chain, combinations
def list_powerset(lst, k):
result = [[]]
for x in lst:
result.extend([(subset + [x]) for subset in result if sum(subset) + x <= k])
return result
def powerset(iterable, k):
xs = iterable
return chain.from_iterable(combinations(xs, n) for n in range(len(xs) - k + 1 + 1))
def list_powerset2(lst):
return reduce(
lambda result, x: result + [(subset + [x]) for subset in result], lst, [[]]
)
T = int(input())
for t in range(T):
N, K = [int(i) for i in input().split()]
nums = [int(i) for i in input().split() if int(i) != 0]
d = {}
for i in nums:
try:
d[i] += 1
except KeyError:
d[i] = 1
reach = sum(nums)
if reach == 0:
if N >= K:
print("yes")
else:
print("no")
continue
if reach % K != 0:
print("no")
continue
reach = int(reach / K)
subsets = [i for i in list_powerset(nums, reach) if sum(i) == reach]
n_set = 0
for i in subsets:
flag = True
for j in i:
if d[j] < 1:
flag = False
break
if flag:
for j in i:
d[j] -= 1
n_set += 1
flag = True
for key in d.keys():
if d[key] > 0:
flag = False
break
if flag and n_set == K:
print("yes")
else:
print("no") | FUNC_DEF ASSIGN VAR LIST LIST FOR VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR LIST VAR VAR VAR BIN_OP FUNC_CALL VAR VAR VAR VAR RETURN VAR FUNC_DEF ASSIGN VAR VAR RETURN FUNC_CALL VAR FUNC_CALL VAR VAR VAR VAR FUNC_CALL VAR BIN_OP BIN_OP BIN_OP FUNC_CALL VAR VAR VAR NUMBER NUMBER FUNC_DEF RETURN FUNC_CALL VAR BIN_OP VAR BIN_OP VAR LIST VAR VAR VAR VAR LIST LIST 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 FUNC_CALL VAR VAR NUMBER ASSIGN VAR DICT FOR VAR VAR VAR VAR NUMBER VAR ASSIGN VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR IF VAR NUMBER IF VAR VAR EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING IF BIN_OP VAR VAR NUMBER EXPR FUNC_CALL VAR STRING ASSIGN VAR FUNC_CALL VAR BIN_OP VAR VAR ASSIGN VAR VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR ASSIGN VAR NUMBER FOR VAR VAR ASSIGN VAR NUMBER FOR VAR VAR IF VAR VAR NUMBER ASSIGN VAR NUMBER IF VAR FOR VAR VAR VAR VAR NUMBER VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR IF VAR VAR NUMBER ASSIGN VAR NUMBER IF VAR VAR VAR EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING |
Read problems statements in Mandarin Chinese and Russian.
Alok-nath is man of equality. He needs your help to divide his “sanskars” evenly amongst all his followers. By doing this, Alok-nath can create equality amongst his followers and he'll be called a true “sanskari”.
Alok-nath has N sanskars, and K followers. Each sanskar is given a numerical value which shows its intensity.
Your task is to determine whether it is possible to allocate all the sanskars to followers in such a way that the sum of intensities of the sanskars allocated to each follower is equal. Note : A sanskar can be allocated to only one of the followers.
------ Input ------
The first line of the input contains an integer T, denoting the number of test cases. Then T test cases follow. The first line of each case contains two integers N and K, with N denoting the number of sanskars and K denoting the number of followers. In the next line are N space separated integers denoting the intensities of each sanskar.
------ Output ------
For each test case, output "yes" if it is possible to divide his sanskars equally amongst his followers; otherwise output "no" (without quotes).
------ Constraints ------
$1 ≤ T ≤ 10$
$1 ≤ N ≤ 21$
$1 ≤ K ≤ 8$
$Subtask #1 (20 points) : 0 ≤ intensity of sanskar ≤ 10^{5}$
$Subtask #2 (80 points) : 0 ≤ intensity of sanskar ≤ 10^{10}$
----- Sample Input 1 ------
2
5 3
1 2 4 5 6
5 3
1 2 4 5 7
----- Sample Output 1 ------
yes
no
----- explanation 1 ------
In the first case, sanskars can be allocated as follows, each follower receiving a total intensity of 6: {1,5}, {2,4}, {6}. | import sys
sys.setrecursionlimit(10**6)
book = dict()
a = []
n = kk = rs0 = 0
def outc(k, j, v, rs):
if (k, j, tuple(v)) in book.keys() and rs == rs0:
return book[k, j, tuple(v)]
elif rs != 0 and j != n:
res = False
if not v[j]:
if a[j] <= rs:
w = v.copy()
w[j] = True
res = res or outc(k, j + 1, w, rs - a[j])
res = res or outc(k, j + 1, v, rs)
book[k, j, tuple(v)] = res
return res
elif rs != 0 and j == n:
return False
elif rs == 0 and k != kk - 1:
return outc(k + 1, 0, v, rs0)
else:
return True
T = int(input())
for _ in range(T):
N, K = map(int, input().split())
A = list(map(int, input().split()))
a = A
n, kk = N, K
mysum = sum(A)
if N < K or mysum % K != 0:
print("no")
else:
rs0 = mysum // K
if outc(0, 0, [False] * N, rs0):
print("yes")
else:
print("no")
book.clear() | IMPORT EXPR FUNC_CALL VAR BIN_OP NUMBER NUMBER ASSIGN VAR FUNC_CALL VAR ASSIGN VAR LIST ASSIGN VAR VAR VAR NUMBER FUNC_DEF IF VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR VAR RETURN VAR VAR VAR FUNC_CALL VAR VAR IF VAR NUMBER VAR VAR ASSIGN VAR NUMBER IF VAR VAR IF VAR VAR VAR ASSIGN VAR FUNC_CALL VAR ASSIGN VAR VAR NUMBER ASSIGN VAR VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR BIN_OP VAR VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR ASSIGN VAR VAR VAR FUNC_CALL VAR VAR VAR RETURN VAR IF VAR NUMBER VAR VAR RETURN NUMBER IF VAR NUMBER VAR BIN_OP VAR NUMBER RETURN FUNC_CALL VAR BIN_OP VAR NUMBER NUMBER VAR VAR RETURN NUMBER 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 FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR VAR BIN_OP VAR VAR NUMBER EXPR FUNC_CALL VAR STRING ASSIGN VAR BIN_OP VAR VAR IF FUNC_CALL VAR NUMBER NUMBER BIN_OP LIST NUMBER VAR VAR EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR |
We have an array A of non-negative integers.
For every (contiguous) subarray B = [A[i], A[i+1], ..., A[j]] (with i <= j), we take the bitwise OR of all the elements in B, obtaining a result A[i] | A[i+1] | ... | A[j].
Return the number of possible results. (Results that occur more than once are only counted once in the final answer.)
Example 1:
Input: [0]
Output: 1
Explanation:
There is only one possible result: 0.
Example 2:
Input: [1,1,2]
Output: 3
Explanation:
The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2].
These yield the results 1, 1, 2, 1, 3, 3.
There are 3 unique values, so the answer is 3.
Example 3:
Input: [1,2,4]
Output: 6
Explanation:
The possible results are 1, 2, 3, 4, 6, and 7.
Note:
1 <= A.length <= 50000
0 <= A[i] <= 10^9 | class Solution:
def subarrayBitwiseORs(self, A: List[int]) -> int:
res = set()
tot = set()
for a in A:
res = {(prev | a) for prev in res} | {a}
tot |= res
return len(tot) | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FOR VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR VAR VAR VAR VAR RETURN FUNC_CALL VAR VAR VAR |
We have an array A of non-negative integers.
For every (contiguous) subarray B = [A[i], A[i+1], ..., A[j]] (with i <= j), we take the bitwise OR of all the elements in B, obtaining a result A[i] | A[i+1] | ... | A[j].
Return the number of possible results. (Results that occur more than once are only counted once in the final answer.)
Example 1:
Input: [0]
Output: 1
Explanation:
There is only one possible result: 0.
Example 2:
Input: [1,1,2]
Output: 3
Explanation:
The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2].
These yield the results 1, 1, 2, 1, 3, 3.
There are 3 unique values, so the answer is 3.
Example 3:
Input: [1,2,4]
Output: 6
Explanation:
The possible results are 1, 2, 3, 4, 6, and 7.
Note:
1 <= A.length <= 50000
0 <= A[i] <= 10^9 | class Solution:
def subarrayBitwiseORs(self, A: List[int]) -> int:
ans = set(A)
prev = set([A[0]])
for i in A[1:]:
temp = set()
for p in prev:
temp.add(i | p)
ans.add(i | p)
prev = temp
prev.add(i)
return len(ans) | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR LIST VAR NUMBER FOR VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR FOR VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR VAR ASSIGN VAR VAR EXPR FUNC_CALL VAR VAR RETURN FUNC_CALL VAR VAR VAR |
We have an array A of non-negative integers.
For every (contiguous) subarray B = [A[i], A[i+1], ..., A[j]] (with i <= j), we take the bitwise OR of all the elements in B, obtaining a result A[i] | A[i+1] | ... | A[j].
Return the number of possible results. (Results that occur more than once are only counted once in the final answer.)
Example 1:
Input: [0]
Output: 1
Explanation:
There is only one possible result: 0.
Example 2:
Input: [1,1,2]
Output: 3
Explanation:
The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2].
These yield the results 1, 1, 2, 1, 3, 3.
There are 3 unique values, so the answer is 3.
Example 3:
Input: [1,2,4]
Output: 6
Explanation:
The possible results are 1, 2, 3, 4, 6, and 7.
Note:
1 <= A.length <= 50000
0 <= A[i] <= 10^9 | class Solution:
def subarrayBitwiseORs(self, A: List[int]) -> int:
s = set()
s1 = set()
for n in A:
s2 = set()
for e in s1:
s2.add(e | n)
s1 = s2
s1.add(n)
s |= s1
return len(s) | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FOR VAR VAR ASSIGN VAR FUNC_CALL VAR FOR VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR VAR ASSIGN VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR RETURN FUNC_CALL VAR VAR VAR |
We have an array A of non-negative integers.
For every (contiguous) subarray B = [A[i], A[i+1], ..., A[j]] (with i <= j), we take the bitwise OR of all the elements in B, obtaining a result A[i] | A[i+1] | ... | A[j].
Return the number of possible results. (Results that occur more than once are only counted once in the final answer.)
Example 1:
Input: [0]
Output: 1
Explanation:
There is only one possible result: 0.
Example 2:
Input: [1,1,2]
Output: 3
Explanation:
The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2].
These yield the results 1, 1, 2, 1, 3, 3.
There are 3 unique values, so the answer is 3.
Example 3:
Input: [1,2,4]
Output: 6
Explanation:
The possible results are 1, 2, 3, 4, 6, and 7.
Note:
1 <= A.length <= 50000
0 <= A[i] <= 10^9 | class Solution:
def subarrayBitwiseORs(self, arr: List[int]) -> int:
ans = set()
current = set()
current.add(0)
for i in range(len(arr)):
a = arr[i]
s = set()
s.add(a)
for y in current:
s.add(a | y)
current = s
ans |= s
return len(ans)
if not arr:
return 0
l, ans = len(arr), set()
for i in range(l):
res = arr[i]
ans.add(res)
for j in range(i + 1, l):
res |= arr[j]
ans.add(res)
return len(ans) | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR EXPR FUNC_CALL VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR FUNC_CALL VAR EXPR FUNC_CALL VAR VAR FOR VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR VAR ASSIGN VAR VAR VAR VAR RETURN FUNC_CALL VAR VAR IF VAR RETURN NUMBER ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR EXPR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR RETURN FUNC_CALL VAR VAR VAR |
We have an array A of non-negative integers.
For every (contiguous) subarray B = [A[i], A[i+1], ..., A[j]] (with i <= j), we take the bitwise OR of all the elements in B, obtaining a result A[i] | A[i+1] | ... | A[j].
Return the number of possible results. (Results that occur more than once are only counted once in the final answer.)
Example 1:
Input: [0]
Output: 1
Explanation:
There is only one possible result: 0.
Example 2:
Input: [1,1,2]
Output: 3
Explanation:
The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2].
These yield the results 1, 1, 2, 1, 3, 3.
There are 3 unique values, so the answer is 3.
Example 3:
Input: [1,2,4]
Output: 6
Explanation:
The possible results are 1, 2, 3, 4, 6, and 7.
Note:
1 <= A.length <= 50000
0 <= A[i] <= 10^9 | class Solution:
def subarrayBitwiseORs(self, A: List[int]) -> int:
ans, frontier = set(), set()
for n in A:
frontier = {(x | n) for x in frontier if x | n != -1}
frontier.add(n)
ans |= frontier
return len(ans) | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR VAR ASSIGN VAR BIN_OP VAR VAR VAR VAR BIN_OP VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR VAR RETURN FUNC_CALL VAR VAR VAR |
We have an array A of non-negative integers.
For every (contiguous) subarray B = [A[i], A[i+1], ..., A[j]] (with i <= j), we take the bitwise OR of all the elements in B, obtaining a result A[i] | A[i+1] | ... | A[j].
Return the number of possible results. (Results that occur more than once are only counted once in the final answer.)
Example 1:
Input: [0]
Output: 1
Explanation:
There is only one possible result: 0.
Example 2:
Input: [1,1,2]
Output: 3
Explanation:
The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2].
These yield the results 1, 1, 2, 1, 3, 3.
There are 3 unique values, so the answer is 3.
Example 3:
Input: [1,2,4]
Output: 6
Explanation:
The possible results are 1, 2, 3, 4, 6, and 7.
Note:
1 <= A.length <= 50000
0 <= A[i] <= 10^9 | class Solution:
def subarrayBitwiseORs(self, A: List[int]) -> int:
arr_len = len(A)
final_result_set = set()
pre_result_set = set()
pre_result_set.add(A[0])
final_result_set.add(A[0])
for i in range(1, arr_len):
cur_result_set = set()
for pre_result in pre_result_set:
one_cur_result = pre_result | A[i]
cur_result_set.add(one_cur_result)
final_result_set.add(one_cur_result)
cur_result_set.add(A[i])
final_result_set.add(A[i])
pre_result_set = cur_result_set
return len(final_result_set) | CLASS_DEF FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR EXPR FUNC_CALL VAR VAR NUMBER EXPR FUNC_CALL VAR VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR ASSIGN VAR FUNC_CALL VAR FOR VAR VAR ASSIGN VAR BIN_OP VAR VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR RETURN FUNC_CALL VAR VAR VAR |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.