text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
At the first holiday in spring, the town Shortriver traditionally conducts a flower festival. Townsfolk wear traditional wreaths during these festivals. Each wreath contains exactly k flowers.
The work material for the wreaths for all n citizens of Shortriver is cut from the longest flowered liana that grew in the town that year. Liana is a sequence a_1, a_2, ..., a_m, where a_i is an integer that denotes the type of flower at the position i. This year the liana is very long (m ≥ n ⋅ k), and that means every citizen will get a wreath.
Very soon the liana will be inserted into a special cutting machine in order to make work material for wreaths. The machine works in a simple manner: it cuts k flowers from the beginning of the liana, then another k flowers and so on. Each such piece of k flowers is called a workpiece. The machine works until there are less than k flowers on the liana.
Diana has found a weaving schematic for the most beautiful wreath imaginable. In order to weave it, k flowers must contain flowers of types b_1, b_2, ..., b_s, while other can be of any type. If a type appears in this sequence several times, there should be at least that many flowers of that type as the number of occurrences of this flower in the sequence. The order of the flowers in a workpiece does not matter.
Diana has a chance to remove some flowers from the liana before it is inserted into the cutting machine. She can remove flowers from any part of the liana without breaking liana into pieces. If Diana removes too many flowers, it may happen so that some of the citizens do not get a wreath. Could some flowers be removed from the liana so that at least one workpiece would conform to the schematic and machine would still be able to create at least n workpieces?
Input
The first line contains four integers m, k, n and s (1 ≤ n, k, m ≤ 5 ⋅ 10^5, k ⋅ n ≤ m, 1 ≤ s ≤ k): the number of flowers on the liana, the number of flowers in one wreath, the amount of citizens and the length of Diana's flower sequence respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 ≤ a_i ≤ 5 ⋅ 10^5) — types of flowers on the liana.
The third line contains s integers b_1, b_2, ..., b_s (1 ≤ b_i ≤ 5 ⋅ 10^5) — the sequence in Diana's schematic.
Output
If it's impossible to remove some of the flowers so that there would be at least n workpieces and at least one of them fullfills Diana's schematic requirements, output -1.
Otherwise in the first line output one integer d — the number of flowers to be removed by Diana.
In the next line output d different integers — the positions of the flowers to be removed.
If there are multiple answers, print any.
Examples
Input
7 3 2 2
1 2 3 3 2 1 2
2 2
Output
1
4
Input
13 4 3 3
3 2 6 4 1 4 4 7 1 3 3 2 4
4 3 4
Output
-1
Input
13 4 1 3
3 2 6 4 1 4 4 7 1 3 3 2 4
4 3 4
Output
9
1 2 3 4 5 9 11 12 13
Note
In the first example, if you don't remove any flowers, the machine would put out two workpieces with flower types [1, 2, 3] and [3, 2, 1]. Those workpieces don't fit Diana's schematic. But if you remove flower on 4-th place, the machine would output workpieces [1, 2, 3] and [2, 1, 2]. The second workpiece fits Diana's schematic.
In the second example there is no way to remove flowers so that every citizen gets a wreath and Diana gets a workpiece that fits here schematic.
In the third example Diana is the only citizen of the town and that means she can, for example, just remove all flowers except the ones she needs.
Tags: greedy, implementation, two pointers
Correct Solution:
```
from math import *
import os, sys
from decimal import Decimal as db
from bisect import *
from io import BytesIO
from queue import Queue
from heapq import *
#input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
m, k, n, s = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
d = {}
p = {}
kol = s
for c in b:
#kol += int(d.get(c, 0) == 0)
d[c] = d.get(c, 0) + 1
p[c] = d[c]
l = 0
r = -1
c = 0
while r < m:
if kol:
r += 1
if r == m:
break
if a[r] in d:
d[a[r]] -= 1
if d[a[r]] >= 0:
kol -= 1
else:
l += 1
if a[l - 1] in d:
d[a[l - 1]] += 1
if d[a[l - 1]] > 0:
kol += 1
tmp = l % k + r - l - k + 1
if not kol and n * k <= m - tmp:
print(max(0, tmp))
for i in range(l, r + 1):
if c == max(0, tmp):
exit(0)
if a[i] not in d or p[a[i]] == 0:
print(i + 1, end = ' ')
c += 1
else:
p[a[i]] -= 1
exit(0)
print(-1)
```
| 1,700 |
Provide tags and a correct Python 3 solution for this coding contest problem.
At the first holiday in spring, the town Shortriver traditionally conducts a flower festival. Townsfolk wear traditional wreaths during these festivals. Each wreath contains exactly k flowers.
The work material for the wreaths for all n citizens of Shortriver is cut from the longest flowered liana that grew in the town that year. Liana is a sequence a_1, a_2, ..., a_m, where a_i is an integer that denotes the type of flower at the position i. This year the liana is very long (m ≥ n ⋅ k), and that means every citizen will get a wreath.
Very soon the liana will be inserted into a special cutting machine in order to make work material for wreaths. The machine works in a simple manner: it cuts k flowers from the beginning of the liana, then another k flowers and so on. Each such piece of k flowers is called a workpiece. The machine works until there are less than k flowers on the liana.
Diana has found a weaving schematic for the most beautiful wreath imaginable. In order to weave it, k flowers must contain flowers of types b_1, b_2, ..., b_s, while other can be of any type. If a type appears in this sequence several times, there should be at least that many flowers of that type as the number of occurrences of this flower in the sequence. The order of the flowers in a workpiece does not matter.
Diana has a chance to remove some flowers from the liana before it is inserted into the cutting machine. She can remove flowers from any part of the liana without breaking liana into pieces. If Diana removes too many flowers, it may happen so that some of the citizens do not get a wreath. Could some flowers be removed from the liana so that at least one workpiece would conform to the schematic and machine would still be able to create at least n workpieces?
Input
The first line contains four integers m, k, n and s (1 ≤ n, k, m ≤ 5 ⋅ 10^5, k ⋅ n ≤ m, 1 ≤ s ≤ k): the number of flowers on the liana, the number of flowers in one wreath, the amount of citizens and the length of Diana's flower sequence respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 ≤ a_i ≤ 5 ⋅ 10^5) — types of flowers on the liana.
The third line contains s integers b_1, b_2, ..., b_s (1 ≤ b_i ≤ 5 ⋅ 10^5) — the sequence in Diana's schematic.
Output
If it's impossible to remove some of the flowers so that there would be at least n workpieces and at least one of them fullfills Diana's schematic requirements, output -1.
Otherwise in the first line output one integer d — the number of flowers to be removed by Diana.
In the next line output d different integers — the positions of the flowers to be removed.
If there are multiple answers, print any.
Examples
Input
7 3 2 2
1 2 3 3 2 1 2
2 2
Output
1
4
Input
13 4 3 3
3 2 6 4 1 4 4 7 1 3 3 2 4
4 3 4
Output
-1
Input
13 4 1 3
3 2 6 4 1 4 4 7 1 3 3 2 4
4 3 4
Output
9
1 2 3 4 5 9 11 12 13
Note
In the first example, if you don't remove any flowers, the machine would put out two workpieces with flower types [1, 2, 3] and [3, 2, 1]. Those workpieces don't fit Diana's schematic. But if you remove flower on 4-th place, the machine would output workpieces [1, 2, 3] and [2, 1, 2]. The second workpiece fits Diana's schematic.
In the second example there is no way to remove flowers so that every citizen gets a wreath and Diana gets a workpiece that fits here schematic.
In the third example Diana is the only citizen of the town and that means she can, for example, just remove all flowers except the ones she needs.
Tags: greedy, implementation, two pointers
Correct Solution:
```
m, k, n, s = map(int, input().split())
ls = list(map(int, input().split()))
seq = map(int, input().split())
dseq = {}
for se in seq:
if se not in dseq: dseq[se] = 0
dseq[se]+=1
maxwindowsize = m-k*n + k
dcurr = {}
nrusefull = 0
for i in range(maxwindowsize-k):
if ls[i] not in dcurr: dcurr[ls[i]] = 0
dcurr[ls[i]] +=1
if ls[i] in dseq and dseq[ls[i]] >= dcurr[ls[i]]: nrusefull+=1
# found it
for j in range(m):
# print(j%k, j+k)
if j % k == 0 and j+k<=m:
mini = maxwindowsize+j-k
# print(mini, mini+k)
for i in range(mini, min(mini+k, m)):
if ls[i] not in dcurr: dcurr[ls[i]] = 0
dcurr[ls[i]] +=1
if ls[i] in dseq and dseq[ls[i]] >= dcurr[ls[i]]: nrusefull+=1
if nrusefull == s:
printl = []
dlast = {x:0 for x in dcurr}
for x in range(j, j+maxwindowsize):
if len(printl) == maxwindowsize-k: break
dlast[ls[x]] +=1
if ls[x] not in dseq or dseq[ls[x]] < dlast[ls[x]]:
printl.append(str(x+1))
break
dcurr[ls[j]] -=1
if ls[j] in dseq and dcurr[ls[j]] < dseq[ls[j]]: nrusefull-=1
else:
print(-1)
raise SystemExit()
print(len(printl))
print(" ".join(printl))
```
| 1,701 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
At the first holiday in spring, the town Shortriver traditionally conducts a flower festival. Townsfolk wear traditional wreaths during these festivals. Each wreath contains exactly k flowers.
The work material for the wreaths for all n citizens of Shortriver is cut from the longest flowered liana that grew in the town that year. Liana is a sequence a_1, a_2, ..., a_m, where a_i is an integer that denotes the type of flower at the position i. This year the liana is very long (m ≥ n ⋅ k), and that means every citizen will get a wreath.
Very soon the liana will be inserted into a special cutting machine in order to make work material for wreaths. The machine works in a simple manner: it cuts k flowers from the beginning of the liana, then another k flowers and so on. Each such piece of k flowers is called a workpiece. The machine works until there are less than k flowers on the liana.
Diana has found a weaving schematic for the most beautiful wreath imaginable. In order to weave it, k flowers must contain flowers of types b_1, b_2, ..., b_s, while other can be of any type. If a type appears in this sequence several times, there should be at least that many flowers of that type as the number of occurrences of this flower in the sequence. The order of the flowers in a workpiece does not matter.
Diana has a chance to remove some flowers from the liana before it is inserted into the cutting machine. She can remove flowers from any part of the liana without breaking liana into pieces. If Diana removes too many flowers, it may happen so that some of the citizens do not get a wreath. Could some flowers be removed from the liana so that at least one workpiece would conform to the schematic and machine would still be able to create at least n workpieces?
Input
The first line contains four integers m, k, n and s (1 ≤ n, k, m ≤ 5 ⋅ 10^5, k ⋅ n ≤ m, 1 ≤ s ≤ k): the number of flowers on the liana, the number of flowers in one wreath, the amount of citizens and the length of Diana's flower sequence respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 ≤ a_i ≤ 5 ⋅ 10^5) — types of flowers on the liana.
The third line contains s integers b_1, b_2, ..., b_s (1 ≤ b_i ≤ 5 ⋅ 10^5) — the sequence in Diana's schematic.
Output
If it's impossible to remove some of the flowers so that there would be at least n workpieces and at least one of them fullfills Diana's schematic requirements, output -1.
Otherwise in the first line output one integer d — the number of flowers to be removed by Diana.
In the next line output d different integers — the positions of the flowers to be removed.
If there are multiple answers, print any.
Examples
Input
7 3 2 2
1 2 3 3 2 1 2
2 2
Output
1
4
Input
13 4 3 3
3 2 6 4 1 4 4 7 1 3 3 2 4
4 3 4
Output
-1
Input
13 4 1 3
3 2 6 4 1 4 4 7 1 3 3 2 4
4 3 4
Output
9
1 2 3 4 5 9 11 12 13
Note
In the first example, if you don't remove any flowers, the machine would put out two workpieces with flower types [1, 2, 3] and [3, 2, 1]. Those workpieces don't fit Diana's schematic. But if you remove flower on 4-th place, the machine would output workpieces [1, 2, 3] and [2, 1, 2]. The second workpiece fits Diana's schematic.
In the second example there is no way to remove flowers so that every citizen gets a wreath and Diana gets a workpiece that fits here schematic.
In the third example Diana is the only citizen of the town and that means she can, for example, just remove all flowers except the ones she needs.
Submitted Solution:
```
def main():
m, k, n, s = map(int, input().split())
a = list(map(int, input().split())) # prevbug: input in a line!
b = list(map(int, input().split())) # prevbug: convert to list
b_dict = {}
for x in b:
b_dict.setdefault(x, 0)
b_dict[x] += 1 # prevbug: b or b_dict
left = 0
right = 0
max_cut = m - n * k
condition_not_met = len(b_dict)
a_dict = {}
while right < m and condition_not_met > 0:
x = a[right]
a_dict.setdefault(x, 0)
a_dict[x] += 1
if x in b_dict and a_dict[x] == b_dict[x]:
condition_not_met -= 1
right += 1 # prevbug: ftl
if condition_not_met > 0:
print(-1)
return
def num_to_remove(lft, rgt):
lft = lft // k * k
num_in_seq = rgt - lft
return num_in_seq - k
def test_plan():
nonlocal left
if num_to_remove(left, right) <= max_cut:
tot = num_to_remove(left, right)
print(tot)
left = left // k * k
while tot > 0:
x = a[left]
if x in b_dict:
b_dict[x] -= 1
if b_dict[x] == 0:
del b_dict[x]
else:
print(left + 1, end=' ')
tot -= 1 # prevbug: ftl
left += 1
return True
return False
while True:
while left < right: # prevbug: should shift left before shifting right
x = a[left]
if x in b_dict and a_dict[x] - 1 < b_dict[x]:
break
else:
a_dict[x] -= 1
if a_dict[x] == 0:
del a_dict[x] # prevbug: ftl
left += 1
if test_plan():
return
if right < m:
a_dict.setdefault(a[right], 0)
a_dict[a[right]] += 1
right += 1
else:
break
print(-1)
if __name__ == '__main__':
main()
```
No
| 1,702 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
At the first holiday in spring, the town Shortriver traditionally conducts a flower festival. Townsfolk wear traditional wreaths during these festivals. Each wreath contains exactly k flowers.
The work material for the wreaths for all n citizens of Shortriver is cut from the longest flowered liana that grew in the town that year. Liana is a sequence a_1, a_2, ..., a_m, where a_i is an integer that denotes the type of flower at the position i. This year the liana is very long (m ≥ n ⋅ k), and that means every citizen will get a wreath.
Very soon the liana will be inserted into a special cutting machine in order to make work material for wreaths. The machine works in a simple manner: it cuts k flowers from the beginning of the liana, then another k flowers and so on. Each such piece of k flowers is called a workpiece. The machine works until there are less than k flowers on the liana.
Diana has found a weaving schematic for the most beautiful wreath imaginable. In order to weave it, k flowers must contain flowers of types b_1, b_2, ..., b_s, while other can be of any type. If a type appears in this sequence several times, there should be at least that many flowers of that type as the number of occurrences of this flower in the sequence. The order of the flowers in a workpiece does not matter.
Diana has a chance to remove some flowers from the liana before it is inserted into the cutting machine. She can remove flowers from any part of the liana without breaking liana into pieces. If Diana removes too many flowers, it may happen so that some of the citizens do not get a wreath. Could some flowers be removed from the liana so that at least one workpiece would conform to the schematic and machine would still be able to create at least n workpieces?
Input
The first line contains four integers m, k, n and s (1 ≤ n, k, m ≤ 5 ⋅ 10^5, k ⋅ n ≤ m, 1 ≤ s ≤ k): the number of flowers on the liana, the number of flowers in one wreath, the amount of citizens and the length of Diana's flower sequence respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 ≤ a_i ≤ 5 ⋅ 10^5) — types of flowers on the liana.
The third line contains s integers b_1, b_2, ..., b_s (1 ≤ b_i ≤ 5 ⋅ 10^5) — the sequence in Diana's schematic.
Output
If it's impossible to remove some of the flowers so that there would be at least n workpieces and at least one of them fullfills Diana's schematic requirements, output -1.
Otherwise in the first line output one integer d — the number of flowers to be removed by Diana.
In the next line output d different integers — the positions of the flowers to be removed.
If there are multiple answers, print any.
Examples
Input
7 3 2 2
1 2 3 3 2 1 2
2 2
Output
1
4
Input
13 4 3 3
3 2 6 4 1 4 4 7 1 3 3 2 4
4 3 4
Output
-1
Input
13 4 1 3
3 2 6 4 1 4 4 7 1 3 3 2 4
4 3 4
Output
9
1 2 3 4 5 9 11 12 13
Note
In the first example, if you don't remove any flowers, the machine would put out two workpieces with flower types [1, 2, 3] and [3, 2, 1]. Those workpieces don't fit Diana's schematic. But if you remove flower on 4-th place, the machine would output workpieces [1, 2, 3] and [2, 1, 2]. The second workpiece fits Diana's schematic.
In the second example there is no way to remove flowers so that every citizen gets a wreath and Diana gets a workpiece that fits here schematic.
In the third example Diana is the only citizen of the town and that means she can, for example, just remove all flowers except the ones she needs.
Submitted Solution:
```
m, k, n, s = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
d = dict()
counts = dict()
for i in b:
if i in counts:
counts[i] += 1
else:
counts[i] = 1
left, r = 0, k + m - n * k
for i in a:
d[i] = 0
for i in b:
d[i] = 0
ok = False
ans = []
while r <= m:
d.clear()
for i in range(left, r):
if a[i] in d:
d[a[i]] += 1
else:
d[a[i]] = 1
ok = True
for i in counts.keys():
if i not in d or d[i] < counts[i]:
ok = False
break
if ok:
break
left += k
r = min(r + k, m + 1)
if not ok:
print(-1)
exit()
cur = m - n * k
for i in range(left, r):
if cur == 0:
break
if a[i] not in counts or counts[a[i]] == 0:
ans.append(str(i + 1))
cur -= 1
print(len(ans))
print(' '.join(ans))
```
No
| 1,703 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
At the first holiday in spring, the town Shortriver traditionally conducts a flower festival. Townsfolk wear traditional wreaths during these festivals. Each wreath contains exactly k flowers.
The work material for the wreaths for all n citizens of Shortriver is cut from the longest flowered liana that grew in the town that year. Liana is a sequence a_1, a_2, ..., a_m, where a_i is an integer that denotes the type of flower at the position i. This year the liana is very long (m ≥ n ⋅ k), and that means every citizen will get a wreath.
Very soon the liana will be inserted into a special cutting machine in order to make work material for wreaths. The machine works in a simple manner: it cuts k flowers from the beginning of the liana, then another k flowers and so on. Each such piece of k flowers is called a workpiece. The machine works until there are less than k flowers on the liana.
Diana has found a weaving schematic for the most beautiful wreath imaginable. In order to weave it, k flowers must contain flowers of types b_1, b_2, ..., b_s, while other can be of any type. If a type appears in this sequence several times, there should be at least that many flowers of that type as the number of occurrences of this flower in the sequence. The order of the flowers in a workpiece does not matter.
Diana has a chance to remove some flowers from the liana before it is inserted into the cutting machine. She can remove flowers from any part of the liana without breaking liana into pieces. If Diana removes too many flowers, it may happen so that some of the citizens do not get a wreath. Could some flowers be removed from the liana so that at least one workpiece would conform to the schematic and machine would still be able to create at least n workpieces?
Input
The first line contains four integers m, k, n and s (1 ≤ n, k, m ≤ 5 ⋅ 10^5, k ⋅ n ≤ m, 1 ≤ s ≤ k): the number of flowers on the liana, the number of flowers in one wreath, the amount of citizens and the length of Diana's flower sequence respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 ≤ a_i ≤ 5 ⋅ 10^5) — types of flowers on the liana.
The third line contains s integers b_1, b_2, ..., b_s (1 ≤ b_i ≤ 5 ⋅ 10^5) — the sequence in Diana's schematic.
Output
If it's impossible to remove some of the flowers so that there would be at least n workpieces and at least one of them fullfills Diana's schematic requirements, output -1.
Otherwise in the first line output one integer d — the number of flowers to be removed by Diana.
In the next line output d different integers — the positions of the flowers to be removed.
If there are multiple answers, print any.
Examples
Input
7 3 2 2
1 2 3 3 2 1 2
2 2
Output
1
4
Input
13 4 3 3
3 2 6 4 1 4 4 7 1 3 3 2 4
4 3 4
Output
-1
Input
13 4 1 3
3 2 6 4 1 4 4 7 1 3 3 2 4
4 3 4
Output
9
1 2 3 4 5 9 11 12 13
Note
In the first example, if you don't remove any flowers, the machine would put out two workpieces with flower types [1, 2, 3] and [3, 2, 1]. Those workpieces don't fit Diana's schematic. But if you remove flower on 4-th place, the machine would output workpieces [1, 2, 3] and [2, 1, 2]. The second workpiece fits Diana's schematic.
In the second example there is no way to remove flowers so that every citizen gets a wreath and Diana gets a workpiece that fits here schematic.
In the third example Diana is the only citizen of the town and that means she can, for example, just remove all flowers except the ones she needs.
Submitted Solution:
```
def All(have, need):
res = True
for flower in need.keys():
if (flower not in have.keys()) or (have[flower] < need[flower]):
res = False
break
return res
m, k, n, s = map(int, input().split())
flower = list(map(int, input().split()))
need = {}
need_lst = list(map(int, input().split()))
for fl in need_lst:
if fl in need.keys():
need[fl] += 1
else:
need[fl] = 1
d = -1
have = {}
r = 0
for l in range(m):
while not All(have, need) and r < m:
if flower[r] in need.keys():
if flower[r] in have.keys():
have[flower[r]] += 1
else:
have[flower[r]] = 1
r += 1
r -= 1
#print(have, need, l, r, All(have, need))
if r == m:
break
if (l//k + (m-1-r)//k >= n-1) and (r-l+1 >= k) and (have != {}):
del_list = []
i = l
ln = r - l + 1
while ln > k and i <= r:
if flower[i] not in need.keys():
del_list.append(i+1)
ln -= 1
if (flower[i] in need.keys()) and (have[flower[i]] > need[flower[i]]):
have[flower[i]] -= 1
del_list.append(i+1)
ln -= 1
i += 1
i = 0
while l % k != 0: #and l <= (n-1)*k
del_list.append(i+1)
l -= 1
i += 1
d = len(del_list)
break
if l < m-1:
if flower[l] in have.keys():
have[flower[l]] -= 1
if have[flower[l]] == 0:
have.pop(flower[l])
print(d)
if d != 0 and d != -1:
print(' '.join(map(str, del_list)))
'''
13 4 1 3
3 3 3 3 3 4 3 7 1 3 3 2 4
4 3 4
'''
```
No
| 1,704 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
At the first holiday in spring, the town Shortriver traditionally conducts a flower festival. Townsfolk wear traditional wreaths during these festivals. Each wreath contains exactly k flowers.
The work material for the wreaths for all n citizens of Shortriver is cut from the longest flowered liana that grew in the town that year. Liana is a sequence a_1, a_2, ..., a_m, where a_i is an integer that denotes the type of flower at the position i. This year the liana is very long (m ≥ n ⋅ k), and that means every citizen will get a wreath.
Very soon the liana will be inserted into a special cutting machine in order to make work material for wreaths. The machine works in a simple manner: it cuts k flowers from the beginning of the liana, then another k flowers and so on. Each such piece of k flowers is called a workpiece. The machine works until there are less than k flowers on the liana.
Diana has found a weaving schematic for the most beautiful wreath imaginable. In order to weave it, k flowers must contain flowers of types b_1, b_2, ..., b_s, while other can be of any type. If a type appears in this sequence several times, there should be at least that many flowers of that type as the number of occurrences of this flower in the sequence. The order of the flowers in a workpiece does not matter.
Diana has a chance to remove some flowers from the liana before it is inserted into the cutting machine. She can remove flowers from any part of the liana without breaking liana into pieces. If Diana removes too many flowers, it may happen so that some of the citizens do not get a wreath. Could some flowers be removed from the liana so that at least one workpiece would conform to the schematic and machine would still be able to create at least n workpieces?
Input
The first line contains four integers m, k, n and s (1 ≤ n, k, m ≤ 5 ⋅ 10^5, k ⋅ n ≤ m, 1 ≤ s ≤ k): the number of flowers on the liana, the number of flowers in one wreath, the amount of citizens and the length of Diana's flower sequence respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 ≤ a_i ≤ 5 ⋅ 10^5) — types of flowers on the liana.
The third line contains s integers b_1, b_2, ..., b_s (1 ≤ b_i ≤ 5 ⋅ 10^5) — the sequence in Diana's schematic.
Output
If it's impossible to remove some of the flowers so that there would be at least n workpieces and at least one of them fullfills Diana's schematic requirements, output -1.
Otherwise in the first line output one integer d — the number of flowers to be removed by Diana.
In the next line output d different integers — the positions of the flowers to be removed.
If there are multiple answers, print any.
Examples
Input
7 3 2 2
1 2 3 3 2 1 2
2 2
Output
1
4
Input
13 4 3 3
3 2 6 4 1 4 4 7 1 3 3 2 4
4 3 4
Output
-1
Input
13 4 1 3
3 2 6 4 1 4 4 7 1 3 3 2 4
4 3 4
Output
9
1 2 3 4 5 9 11 12 13
Note
In the first example, if you don't remove any flowers, the machine would put out two workpieces with flower types [1, 2, 3] and [3, 2, 1]. Those workpieces don't fit Diana's schematic. But if you remove flower on 4-th place, the machine would output workpieces [1, 2, 3] and [2, 1, 2]. The second workpiece fits Diana's schematic.
In the second example there is no way to remove flowers so that every citizen gets a wreath and Diana gets a workpiece that fits here schematic.
In the third example Diana is the only citizen of the town and that means she can, for example, just remove all flowers except the ones she needs.
Submitted Solution:
```
x=list(map(int,input('').split()))
y=list(map(int,input('').split()))
z=list(map(int,input('').split()))
sss=set(z)
di={i:0 for i in sss}
for qwer in z:
di[qwer]+=1
m,k,n,s=x[0],x[1],x[2],x[3] # цветов, в цикле
ost=m-n*k
q=[y[i*k:(i+1)*k+ost] for i in range(m)]
ttt=-1
ans1=0
ans2=[]
for i in range(len(q)):
count=0
if len(q[i])<k:
continue
dis={j:0 for j in (q[i]+list(sss))}
for j in q[i]:
dis[j]+=1
for j in sss:
if di[j]>dis[j]:
count=-1
if count==-1:
continue
else:
ttt=0
count1=k+ost
while len(q[i])!=k:
count1-=1
if not q[i][count1] in sss:
print(q[i][count1])
q[i]=q[i][0:count1]+q[i][count1+1:]
ans1+=1
ans2.append(i*k+count1)
elif dis[q[i][count1]]>di[q[i][count1]]:
print(q[i][count1])
dis[q[i][count1]]-=1
q[i]=q[i][0:count1]+q[i][count1+1:]
ans1+=1
ans2.append(i*k+count1)
break
if ttt==-1:
print(-1)
else:
print(ans1)
ans2=[go+1 for go in ans2]
print(' '.join(list(map(str,ans2))))
```
No
| 1,705 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n objects. Each object has two integer properties: val_i — its price — and mask_i. It is guaranteed that the sum of all prices is initially non-zero.
You want to select a positive integer s. All objects will be modified after that. The i-th object will be modified using the following procedure:
* Consider mask_i and s in binary notation,
* Compute the [bitwise AND](https://en.wikipedia.org/wiki/Bitwise_operation#AND) of s and mask_i (s \& mask_i),
* If (s \& mask_i) contains an odd number of ones, replace the val_i with -val_i. Otherwise do nothing with the i-th object.
You need to find such an integer s that when the modification above is done the sum of all prices changes sign (if it was negative, it should become positive, and vice-versa; it is not allowed for it to become zero). The absolute value of the sum can be arbitrary.
Input
The first line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of objects.
The i-th of next n lines contains integers val_i and mask_i (-10^9 ≤ val_i ≤ 10^9, 1 ≤ mask_i ≤ 2^{62} - 1) — the price of the object and its mask.
It is guaranteed that the sum of val_i is initially non-zero.
Output
Print an integer s (1 ≤ s ≤ 2^{62} - 1), such that if we modify the objects as described above, the sign of the sum of val_i changes its sign.
If there are multiple such s, print any of them. One can show that there is always at least one valid s.
Examples
Input
5
17 206
-6 117
-2 151
9 93
6 117
Output
64
Input
1
1 1
Output
1
Note
In the first test sample all objects will change their prices except for the object with mask 151.
So their total sum will change its sign: initially 24, after modifications — -28.
In the second test sample the only object will change its price. So the total sum will change its sign.
Submitted Solution:
```
n=int(input())
valList = list()
maskList = list()
count=0
for i in range(n):
a,b = map(int,input().split())
valList.append(a)
maskList.append(b)
for i in range(n):
if maskList[i] & 1 == 1:
count+=1
if count >= n/2:
print(1)
```
No
| 1,706 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n objects. Each object has two integer properties: val_i — its price — and mask_i. It is guaranteed that the sum of all prices is initially non-zero.
You want to select a positive integer s. All objects will be modified after that. The i-th object will be modified using the following procedure:
* Consider mask_i and s in binary notation,
* Compute the [bitwise AND](https://en.wikipedia.org/wiki/Bitwise_operation#AND) of s and mask_i (s \& mask_i),
* If (s \& mask_i) contains an odd number of ones, replace the val_i with -val_i. Otherwise do nothing with the i-th object.
You need to find such an integer s that when the modification above is done the sum of all prices changes sign (if it was negative, it should become positive, and vice-versa; it is not allowed for it to become zero). The absolute value of the sum can be arbitrary.
Input
The first line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of objects.
The i-th of next n lines contains integers val_i and mask_i (-10^9 ≤ val_i ≤ 10^9, 1 ≤ mask_i ≤ 2^{62} - 1) — the price of the object and its mask.
It is guaranteed that the sum of val_i is initially non-zero.
Output
Print an integer s (1 ≤ s ≤ 2^{62} - 1), such that if we modify the objects as described above, the sign of the sum of val_i changes its sign.
If there are multiple such s, print any of them. One can show that there is always at least one valid s.
Examples
Input
5
17 206
-6 117
-2 151
9 93
6 117
Output
64
Input
1
1 1
Output
1
Note
In the first test sample all objects will change their prices except for the object with mask 151.
So their total sum will change its sign: initially 24, after modifications — -28.
In the second test sample the only object will change its price. So the total sum will change its sign.
Submitted Solution:
```
n=int(input())
l=[]
for i in range(n):
l.append([*map(int,input().split())])
rf=l[:]
def f(l):
if sum([h[0] for h in l])>0:
return 0
return 1
s=0
t=f(l)
while f(l)==t:
l=rf[:]
s+=1
for z in l:
if bin(s&z[1])[2:].count('1')%2==1:
z[0]=-z[0]
print(s)
```
No
| 1,707 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n objects. Each object has two integer properties: val_i — its price — and mask_i. It is guaranteed that the sum of all prices is initially non-zero.
You want to select a positive integer s. All objects will be modified after that. The i-th object will be modified using the following procedure:
* Consider mask_i and s in binary notation,
* Compute the [bitwise AND](https://en.wikipedia.org/wiki/Bitwise_operation#AND) of s and mask_i (s \& mask_i),
* If (s \& mask_i) contains an odd number of ones, replace the val_i with -val_i. Otherwise do nothing with the i-th object.
You need to find such an integer s that when the modification above is done the sum of all prices changes sign (if it was negative, it should become positive, and vice-versa; it is not allowed for it to become zero). The absolute value of the sum can be arbitrary.
Input
The first line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of objects.
The i-th of next n lines contains integers val_i and mask_i (-10^9 ≤ val_i ≤ 10^9, 1 ≤ mask_i ≤ 2^{62} - 1) — the price of the object and its mask.
It is guaranteed that the sum of val_i is initially non-zero.
Output
Print an integer s (1 ≤ s ≤ 2^{62} - 1), such that if we modify the objects as described above, the sign of the sum of val_i changes its sign.
If there are multiple such s, print any of them. One can show that there is always at least one valid s.
Examples
Input
5
17 206
-6 117
-2 151
9 93
6 117
Output
64
Input
1
1 1
Output
1
Note
In the first test sample all objects will change their prices except for the object with mask 151.
So their total sum will change its sign: initially 24, after modifications — -28.
In the second test sample the only object will change its price. So the total sum will change its sign.
Submitted Solution:
```
n=int(input())
l=[]
for i in range(n):
l.append([*map(int,input().split())])
rf=l[:]
def f(l):
if sum([h[0] for h in l])>0:
return 0
return 1
s=0
t=f(l)
while f(l)==t:
l=rf
s+=1
for z in l:
if bin(s&z[1])[2:].count('1')%2==1:
z[0]=-z[0]
print(s)
```
No
| 1,708 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n objects. Each object has two integer properties: val_i — its price — and mask_i. It is guaranteed that the sum of all prices is initially non-zero.
You want to select a positive integer s. All objects will be modified after that. The i-th object will be modified using the following procedure:
* Consider mask_i and s in binary notation,
* Compute the [bitwise AND](https://en.wikipedia.org/wiki/Bitwise_operation#AND) of s and mask_i (s \& mask_i),
* If (s \& mask_i) contains an odd number of ones, replace the val_i with -val_i. Otherwise do nothing with the i-th object.
You need to find such an integer s that when the modification above is done the sum of all prices changes sign (if it was negative, it should become positive, and vice-versa; it is not allowed for it to become zero). The absolute value of the sum can be arbitrary.
Input
The first line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of objects.
The i-th of next n lines contains integers val_i and mask_i (-10^9 ≤ val_i ≤ 10^9, 1 ≤ mask_i ≤ 2^{62} - 1) — the price of the object and its mask.
It is guaranteed that the sum of val_i is initially non-zero.
Output
Print an integer s (1 ≤ s ≤ 2^{62} - 1), such that if we modify the objects as described above, the sign of the sum of val_i changes its sign.
If there are multiple such s, print any of them. One can show that there is always at least one valid s.
Examples
Input
5
17 206
-6 117
-2 151
9 93
6 117
Output
64
Input
1
1 1
Output
1
Note
In the first test sample all objects will change their prices except for the object with mask 151.
So their total sum will change its sign: initially 24, after modifications — -28.
In the second test sample the only object will change its price. So the total sum will change its sign.
Submitted Solution:
```
n=int(input())
l=[]
for i in range(n):
l.append([*map(int,input().split())])
def f(l):
if sum([h[0] for h in l])>0:
return 0
return 1
s=1
t=f(l)
while f(l)==t:
for z in l:
if bin(s&z[1])[2:].count('1')%2==1:
z[0]=-z[0]
s+=1
print(s-1)
```
No
| 1,709 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true:
* Employee A is the immediate manager of employee B
* Employee B has an immediate manager employee C such that employee A is the superior of employee C.
The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.
Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.
What is the minimum number of groups that must be formed?
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees.
The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager.
It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
Output
Print a single integer denoting the minimum number of groups that will be formed in the party.
Examples
Input
5
-1
1
2
1
-1
Output
3
Note
For the first example, three groups are sufficient, for example:
* Employee 1
* Employees 2 and 4
* Employees 3 and 5
Tags: dfs and similar, graphs, trees
Correct Solution:
```
n = int(input())
l = [int(input())-1 for i in range(n)]
cc = 0
for i in range(n):
c = 0
while i != -2:
i = l[i]
c += 1
cc = max(c,cc)
print(cc)
```
| 1,710 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true:
* Employee A is the immediate manager of employee B
* Employee B has an immediate manager employee C such that employee A is the superior of employee C.
The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.
Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.
What is the minimum number of groups that must be formed?
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees.
The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager.
It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
Output
Print a single integer denoting the minimum number of groups that will be formed in the party.
Examples
Input
5
-1
1
2
1
-1
Output
3
Note
For the first example, three groups are sufficient, for example:
* Employee 1
* Employees 2 and 4
* Employees 3 and 5
Tags: dfs and similar, graphs, trees
Correct Solution:
```
n=int(input())
a=[]
for i in range(n):
a.append(int(input())-1)
ans=0
for i in range(len(a)):
L=0
while i>-2:
i=a[i]
L+=1
ans=max(ans,L)
print(ans)
```
| 1,711 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true:
* Employee A is the immediate manager of employee B
* Employee B has an immediate manager employee C such that employee A is the superior of employee C.
The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.
Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.
What is the minimum number of groups that must be formed?
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees.
The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager.
It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
Output
Print a single integer denoting the minimum number of groups that will be formed in the party.
Examples
Input
5
-1
1
2
1
-1
Output
3
Note
For the first example, three groups are sufficient, for example:
* Employee 1
* Employees 2 and 4
* Employees 3 and 5
Tags: dfs and similar, graphs, trees
Correct Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
n = I()
p = [I() for _ in range(n)]
fm = {}
fm[-1] = 0
def f(i):
if i in fm:
return fm[i]
t = f(p[i-1]) + 1
fm[i] = t
return t
r = 0
for i in range(1,n+1):
t = f(i)
if r < t:
r = t
return r
print(main())
```
| 1,712 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true:
* Employee A is the immediate manager of employee B
* Employee B has an immediate manager employee C such that employee A is the superior of employee C.
The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.
Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.
What is the minimum number of groups that must be formed?
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees.
The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager.
It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
Output
Print a single integer denoting the minimum number of groups that will be formed in the party.
Examples
Input
5
-1
1
2
1
-1
Output
3
Note
For the first example, three groups are sufficient, for example:
* Employee 1
* Employees 2 and 4
* Employees 3 and 5
Tags: dfs and similar, graphs, trees
Correct Solution:
```
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def value():
return map(int,input().split())
def array():
return [int(i) for i in input().split()]
#-------------------------code---------------------------#
#vsInput()
ind=[]
def dfs(adj,s,vis,c):
global ind
ind.append(c)
vis[s] = True
for i in adj[s]:
if vis[i] == False:
dfs(adj,i,vis,c+1)
adj=defaultdict(list)
n=int(input())
ar=[]
for i in range(n):
a=int(input())
ar.append(a)
if(a!=-1):
adj[a].append(i+1)
adj[i+1].append(a)
#print(adj)
ans=0
vis={i:False for i in range(1,n+1)}
for i in range(1,n+1):
if(ar[i-1]==-1 and vis[i]==False):
dfs(adj,i,vis,0)
print(max(ind)+1)
```
| 1,713 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true:
* Employee A is the immediate manager of employee B
* Employee B has an immediate manager employee C such that employee A is the superior of employee C.
The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.
Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.
What is the minimum number of groups that must be formed?
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees.
The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager.
It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
Output
Print a single integer denoting the minimum number of groups that will be formed in the party.
Examples
Input
5
-1
1
2
1
-1
Output
3
Note
For the first example, three groups are sufficient, for example:
* Employee 1
* Employees 2 and 4
* Employees 3 and 5
Tags: dfs and similar, graphs, trees
Correct Solution:
```
import sys
import math
import collections
import heapq
import decimal
input=sys.stdin.readline
n=int(input())
l=[]
for i in range(n):
l.append(int(input()))
m=0
for i in range(n):
c=0
while(i>-1):
c+=1
i=l[i]-1
m=max(m,c)
print(m)
```
| 1,714 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true:
* Employee A is the immediate manager of employee B
* Employee B has an immediate manager employee C such that employee A is the superior of employee C.
The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.
Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.
What is the minimum number of groups that must be formed?
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees.
The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager.
It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
Output
Print a single integer denoting the minimum number of groups that will be formed in the party.
Examples
Input
5
-1
1
2
1
-1
Output
3
Note
For the first example, three groups are sufficient, for example:
* Employee 1
* Employees 2 and 4
* Employees 3 and 5
Tags: dfs and similar, graphs, trees
Correct Solution:
```
from collections import deque
def bfs(u):
global n, al, dist, prev, used
q = deque()
q.append(u)
md = 1
used[u] = True
while len(q) > 0:
v = q.popleft()
for i in al[v]:
if not used[i]:
used[i] = True
dist[i] = dist[v] + 1
if dist[i] + 1 > md:
md = dist[i] + 1
q.append(i)
return md
n = int(input())
al = [[] for i in range(n)]
dist = [0] * n
prev = [0] * n
used = [False] * n
p = [-1] * n
for i in range(n):
x = int(input()) - 1
if x >= 0:
p[i] = x
al[x].append(i)
res = 0
a = []
for i in range(n):
if p[i] == -1:
a.append(i)
i = 0
while i < len(a):
if not used[a[i]]:
res = max(res, bfs(a[i]))
else:
i += 1
print(res)
```
| 1,715 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true:
* Employee A is the immediate manager of employee B
* Employee B has an immediate manager employee C such that employee A is the superior of employee C.
The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.
Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.
What is the minimum number of groups that must be formed?
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees.
The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager.
It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
Output
Print a single integer denoting the minimum number of groups that will be formed in the party.
Examples
Input
5
-1
1
2
1
-1
Output
3
Note
For the first example, three groups are sufficient, for example:
* Employee 1
* Employees 2 and 4
* Employees 3 and 5
Tags: dfs and similar, graphs, trees
Correct Solution:
```
def findDepth(a, i):
depth = 1
nextLevel = a[i][:]
while len(nextLevel) > 0:
depth += 1
children = nextLevel[:]
nextLevel = []
for child in children:
nextLevel += a[child]
return depth
n = int(input())
a = []
for i in range(n):
a.append([])
roots = []
for i in range(n):
x = int(input())
if x > 0:
a[x-1].append(i)
else:
roots.append(i)
print(max([findDepth(a, i) for i in roots]))
```
| 1,716 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true:
* Employee A is the immediate manager of employee B
* Employee B has an immediate manager employee C such that employee A is the superior of employee C.
The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.
Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.
What is the minimum number of groups that must be formed?
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees.
The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager.
It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
Output
Print a single integer denoting the minimum number of groups that will be formed in the party.
Examples
Input
5
-1
1
2
1
-1
Output
3
Note
For the first example, three groups are sufficient, for example:
* Employee 1
* Employees 2 and 4
* Employees 3 and 5
Tags: dfs and similar, graphs, trees
Correct Solution:
```
n=int(input())
p=[int(input())-1 for i in range(n)]
m=0
for i in range(len(p)):
c=0
while i!=-2:
c+=1
i=p[i]
m=max(c,m)
print(m)
# Made By Mostafa_Khaled
```
| 1,717 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true:
* Employee A is the immediate manager of employee B
* Employee B has an immediate manager employee C such that employee A is the superior of employee C.
The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.
Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.
What is the minimum number of groups that must be formed?
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees.
The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager.
It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
Output
Print a single integer denoting the minimum number of groups that will be formed in the party.
Examples
Input
5
-1
1
2
1
-1
Output
3
Note
For the first example, three groups are sufficient, for example:
* Employee 1
* Employees 2 and 4
* Employees 3 and 5
Submitted Solution:
```
from sys import setrecursionlimit
setrecursionlimit(30000)
maxl = -1
def dfs(v, lvl):
used[v] = True
global maxl
if lvl > maxl:
maxl = lvl
for u in ch[v]:
dfs(u, lvl + 1)
n = int(input())
used = [False] * n
p = [int(input()) - 1 for i in range(n)]
ch = [[] for i in range(n)]
for i in range(n):
if p[i] != -2:
ch[p[i]].append(i)
for i in range(n):
if p[i] == -2:
dfs(i, 1)
print(maxl)
```
Yes
| 1,718 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true:
* Employee A is the immediate manager of employee B
* Employee B has an immediate manager employee C such that employee A is the superior of employee C.
The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.
Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.
What is the minimum number of groups that must be formed?
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees.
The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager.
It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
Output
Print a single integer denoting the minimum number of groups that will be formed in the party.
Examples
Input
5
-1
1
2
1
-1
Output
3
Note
For the first example, three groups are sufficient, for example:
* Employee 1
* Employees 2 and 4
* Employees 3 and 5
Submitted Solution:
```
from collections import *
class graph:
# initialize graph
def __init__(self, gdict=None):
if gdict is None:
gdict = defaultdict(list)
self.gdict, self.edges = gdict, []
# Get verticies
def get_vertices(self):
return list(self.gdict.keys())
# add edge
def add_edge(self, node1, node2):
self.gdict[node1].append(node2)
# self.gdict[node2].append(node1)
self.edges.append([node1, node2])
def bfs_util(self, i):
queue, self.visit[i], level = deque([[i, 1]]), 1, 1
while queue:
# dequeue parent vertix
s, level = queue.popleft()
# enqueue child vertices
for i in self.gdict[s]:
if self.visit[i] == 0:
queue.append([i, level + 1])
self.visit[i] = 1
return level
def bfs(self):
self.visit, self.cnt = defaultdict(int), 0
for i in pars:
if self.visit[i] == 0:
self.cnt = max(self.bfs_util(i), self.cnt)
return self.cnt
n, g, pars = int(input()), graph(), []
for i in range(1, n + 1):
x = int(input())
if x == -1:
pars.append(i)
else:
g.add_edge(x, i)
print(g.bfs())
```
Yes
| 1,719 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true:
* Employee A is the immediate manager of employee B
* Employee B has an immediate manager employee C such that employee A is the superior of employee C.
The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.
Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.
What is the minimum number of groups that must be formed?
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees.
The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager.
It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
Output
Print a single integer denoting the minimum number of groups that will be formed in the party.
Examples
Input
5
-1
1
2
1
-1
Output
3
Note
For the first example, three groups are sufficient, for example:
* Employee 1
* Employees 2 and 4
* Employees 3 and 5
Submitted Solution:
```
inp,m = [int(input())-1 for n in range(int(input()))],0
for i in range(len(inp)):
c = 0
while i != -2:
c+=1; i = inp[i]
m = max(c,m)
print(m)
```
Yes
| 1,720 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true:
* Employee A is the immediate manager of employee B
* Employee B has an immediate manager employee C such that employee A is the superior of employee C.
The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.
Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.
What is the minimum number of groups that must be formed?
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees.
The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager.
It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
Output
Print a single integer denoting the minimum number of groups that will be formed in the party.
Examples
Input
5
-1
1
2
1
-1
Output
3
Note
For the first example, three groups are sufficient, for example:
* Employee 1
* Employees 2 and 4
* Employees 3 and 5
Submitted Solution:
```
# Hint: Find the longest chain of command.
size =int(input())
lis = [-1]*(size)
for y in range(size):
lis[y] = int(input()) - 1
r = [0]*(size)
for x in range(size):
c = x
while lis[c] >-1:
# Adding the employee to the manager
r[x] += 1
# Moving up the chain
c = lis[c]
print (max(r)+1)
```
Yes
| 1,721 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true:
* Employee A is the immediate manager of employee B
* Employee B has an immediate manager employee C such that employee A is the superior of employee C.
The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.
Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.
What is the minimum number of groups that must be formed?
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees.
The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager.
It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
Output
Print a single integer denoting the minimum number of groups that will be formed in the party.
Examples
Input
5
-1
1
2
1
-1
Output
3
Note
For the first example, three groups are sufficient, for example:
* Employee 1
* Employees 2 and 4
* Employees 3 and 5
Submitted Solution:
```
from collections import deque
def bfs(u):
global n, al, dist, prev, used
q = deque()
q.append(u)
md = 1
used[u] = True
while len(q) > 0:
v = q.popleft()
for i in al[v]:
if not used[i]:
used[i] = True
dist[i] = dist[v] + 1
if dist[i] + 1 > md:
md = dist[i] + 1
q.append(i)
return md
n = int(input())
al = [[] for i in range(n)]
dist = [0] * n
prev = [0] * n
used = [False] * n
for i in range(n):
x = int(input()) - 1
if x >= 0:
al[x].append(i)
res = 0
for i in range(n):
if not used[i]:
res = max(res, bfs(i))
print(res)
```
No
| 1,722 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true:
* Employee A is the immediate manager of employee B
* Employee B has an immediate manager employee C such that employee A is the superior of employee C.
The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.
Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.
What is the minimum number of groups that must be formed?
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees.
The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager.
It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
Output
Print a single integer denoting the minimum number of groups that will be formed in the party.
Examples
Input
5
-1
1
2
1
-1
Output
3
Note
For the first example, three groups are sufficient, for example:
* Employee 1
* Employees 2 and 4
* Employees 3 and 5
Submitted Solution:
```
n=int(input())
a=[]
for i in range(n+1):
a.append([])
for i in range(1,n+1):
p=int(input())
if p!=-1:
a[p].append(i)
ans=1
for b in a:
if len(b)>0: ans=2
for x in b:
if len(a[x])>0:
print(3)
exit()
print(ans)
```
No
| 1,723 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true:
* Employee A is the immediate manager of employee B
* Employee B has an immediate manager employee C such that employee A is the superior of employee C.
The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.
Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.
What is the minimum number of groups that must be formed?
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees.
The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager.
It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
Output
Print a single integer denoting the minimum number of groups that will be formed in the party.
Examples
Input
5
-1
1
2
1
-1
Output
3
Note
For the first example, three groups are sufficient, for example:
* Employee 1
* Employees 2 and 4
* Employees 3 and 5
Submitted Solution:
```
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def value():
return map(int,input().split())
def array():
return [int(i) for i in input().split()]
#-------------------------code---------------------------#
#vsInput()
def bfs(adj,s,n,vis):
vis[s]=True
qu=[s]
c=0
while(len(qu)!=0):
e=qu.pop(0)
flag=0
for i in adj[e]:
if(vis[i]!=True):
flag=1
qu.append(i)
vis[i]=True
if(flag==1):
c+=1
return c+1
adj=defaultdict(list)
n=int(input())
for i in range(n):
a=int(input())
if(a!=-1):
adj[a].append(i+1)
else:
adj[i+1]=[]
#print(adj)
ans=0
vis={i:False for i in range(1,n+1)}
for i in range(1,n+1):
if(vis[i]==False):
ans=max(ans,bfs(adj,i,n,vis))
#print(bfs(adj,i,n,vis),i)
print(ans)
```
No
| 1,724 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true:
* Employee A is the immediate manager of employee B
* Employee B has an immediate manager employee C such that employee A is the superior of employee C.
The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.
Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.
What is the minimum number of groups that must be formed?
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees.
The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager.
It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
Output
Print a single integer denoting the minimum number of groups that will be formed in the party.
Examples
Input
5
-1
1
2
1
-1
Output
3
Note
For the first example, three groups are sufficient, for example:
* Employee 1
* Employees 2 and 4
* Employees 3 and 5
Submitted Solution:
```
n=int(input())
a=[]
for i in range(n+1):
a.append([])
for i in range(1,n+1):
p=int(input())
if p!=-1:
a[p].append(i)
print(a)
ans=1
for b in a:
if len(b)>0: ans=2
for x in b:
if len(a[x])>0:
print(3)
exit()
print(ans)
```
No
| 1,725 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a prime number p, n integers a_1, a_2, …, a_n, and an integer k.
Find the number of pairs of indexes (i, j) (1 ≤ i < j ≤ n) for which (a_i + a_j)(a_i^2 + a_j^2) ≡ k mod p.
Input
The first line contains integers n, p, k (2 ≤ n ≤ 3 ⋅ 10^5, 2 ≤ p ≤ 10^9, 0 ≤ k ≤ p-1). p is guaranteed to be prime.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ p-1). It is guaranteed that all elements are different.
Output
Output a single integer — answer to the problem.
Examples
Input
3 3 0
0 1 2
Output
1
Input
6 7 2
1 2 3 4 5 6
Output
3
Note
In the first example:
(0+1)(0^2 + 1^2) = 1 ≡ 1 mod 3.
(0+2)(0^2 + 2^2) = 8 ≡ 2 mod 3.
(1+2)(1^2 + 2^2) = 15 ≡ 0 mod 3.
So only 1 pair satisfies the condition.
In the second example, there are 3 such pairs: (1, 5), (2, 3), (4, 6).
Tags: math, matrices, number theory, two pointers
Correct Solution:
```
n, p, k = map(int, input().split())
A = list(map(int, input().split()))
step4 = {}
for i in A:
h = (i ** 4) - (k * i)
h %= p
if h not in step4:
step4[h] = 0
step4[h] += 1
ans = 0
for u in step4:
ans += (step4[u]) * (step4[u] - 1) // 2
print(ans)
```
| 1,726 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a prime number p, n integers a_1, a_2, …, a_n, and an integer k.
Find the number of pairs of indexes (i, j) (1 ≤ i < j ≤ n) for which (a_i + a_j)(a_i^2 + a_j^2) ≡ k mod p.
Input
The first line contains integers n, p, k (2 ≤ n ≤ 3 ⋅ 10^5, 2 ≤ p ≤ 10^9, 0 ≤ k ≤ p-1). p is guaranteed to be prime.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ p-1). It is guaranteed that all elements are different.
Output
Output a single integer — answer to the problem.
Examples
Input
3 3 0
0 1 2
Output
1
Input
6 7 2
1 2 3 4 5 6
Output
3
Note
In the first example:
(0+1)(0^2 + 1^2) = 1 ≡ 1 mod 3.
(0+2)(0^2 + 2^2) = 8 ≡ 2 mod 3.
(1+2)(1^2 + 2^2) = 15 ≡ 0 mod 3.
So only 1 pair satisfies the condition.
In the second example, there are 3 such pairs: (1, 5), (2, 3), (4, 6).
Tags: math, matrices, number theory, two pointers
Correct Solution:
```
n, p, k = map(int, input().split())
a = list(map(int, input().split()))
a = [(i ** 4 - i * k) % p for i in a]
c = {i: 0 for i in a}
for i in a:
c[i] += 1
s = 0
for i in c:
i = c[i]
s += (i * (i - 1)) // 2
print(s)
```
| 1,727 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a prime number p, n integers a_1, a_2, …, a_n, and an integer k.
Find the number of pairs of indexes (i, j) (1 ≤ i < j ≤ n) for which (a_i + a_j)(a_i^2 + a_j^2) ≡ k mod p.
Input
The first line contains integers n, p, k (2 ≤ n ≤ 3 ⋅ 10^5, 2 ≤ p ≤ 10^9, 0 ≤ k ≤ p-1). p is guaranteed to be prime.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ p-1). It is guaranteed that all elements are different.
Output
Output a single integer — answer to the problem.
Examples
Input
3 3 0
0 1 2
Output
1
Input
6 7 2
1 2 3 4 5 6
Output
3
Note
In the first example:
(0+1)(0^2 + 1^2) = 1 ≡ 1 mod 3.
(0+2)(0^2 + 2^2) = 8 ≡ 2 mod 3.
(1+2)(1^2 + 2^2) = 15 ≡ 0 mod 3.
So only 1 pair satisfies the condition.
In the second example, there are 3 such pairs: (1, 5), (2, 3), (4, 6).
Tags: math, matrices, number theory, two pointers
Correct Solution:
```
n , p , k = map(int,input().split())
ar = list(map(int,input().split()))
ar = [(i**4 - k*i + p**4)%p for i in ar]
d = dict()
for i in ar:
if i in d:
d[i] += 1
else:
d[i] = 1
ans = 0
for key in d:
ans += (d[key]*(d[key] - 1) // 2);
print(ans)
```
| 1,728 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a prime number p, n integers a_1, a_2, …, a_n, and an integer k.
Find the number of pairs of indexes (i, j) (1 ≤ i < j ≤ n) for which (a_i + a_j)(a_i^2 + a_j^2) ≡ k mod p.
Input
The first line contains integers n, p, k (2 ≤ n ≤ 3 ⋅ 10^5, 2 ≤ p ≤ 10^9, 0 ≤ k ≤ p-1). p is guaranteed to be prime.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ p-1). It is guaranteed that all elements are different.
Output
Output a single integer — answer to the problem.
Examples
Input
3 3 0
0 1 2
Output
1
Input
6 7 2
1 2 3 4 5 6
Output
3
Note
In the first example:
(0+1)(0^2 + 1^2) = 1 ≡ 1 mod 3.
(0+2)(0^2 + 2^2) = 8 ≡ 2 mod 3.
(1+2)(1^2 + 2^2) = 15 ≡ 0 mod 3.
So only 1 pair satisfies the condition.
In the second example, there are 3 such pairs: (1, 5), (2, 3), (4, 6).
Tags: math, matrices, number theory, two pointers
Correct Solution:
```
def Sum(n):
"""
Entrada:
n -> cantidad de elementos a asociar
Descripción:
Dada la cantidad de elementos a asociar, encontrar el número de combinaciones de tamaño 2 que
se pueden formar
Salida:
Número de combinaciones de tamaño 2 que se pueden formar
"""
return n*(n-1)//2
def Solver(p, k, a):
"""
Entrada:
p -> primo en base al que se calcula el módulo
k -> entero k
a -> lista de enteros para hallar la cantidad de pares
Descripción:
Dado una lista de enteros a, encontrar el número de pares (ai, aj) que cumplen que:
(ai^4 - k*ai) % p = (aj^4 - k*aj) % p
Salida:
sol -> La cantidad de pares que cumplen la condición
"""
aux = [] #lista que guardará en la posición i el resultado de calcular (a[i]^4 - k*a[i]) % p
for i in a:
aux.append((i**4 - i*k)%p)
dic = {} #diccionario auxiliar que guardará en la llave i la cantiad de ocurrencias de i en aux
for i in aux:
if i in dic:
dic[i] += 1
else:
dic[i] = 1
val = list(dic.values()) #Se hace una lista donde a la posición i le corresponde el valor del la llave i en dic
sol = 0
for i in val:
if i > 1: #Si el valor es mayor que 1 se halla la cantidad de pares que se pueden formar
sol += Sum(i)
return sol
def Main():
n, p, k = map(int, input().split())
a = list(map(int, input().split()))
sol = Solver(p, k, a)
print(sol)
Main()
```
| 1,729 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a prime number p, n integers a_1, a_2, …, a_n, and an integer k.
Find the number of pairs of indexes (i, j) (1 ≤ i < j ≤ n) for which (a_i + a_j)(a_i^2 + a_j^2) ≡ k mod p.
Input
The first line contains integers n, p, k (2 ≤ n ≤ 3 ⋅ 10^5, 2 ≤ p ≤ 10^9, 0 ≤ k ≤ p-1). p is guaranteed to be prime.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ p-1). It is guaranteed that all elements are different.
Output
Output a single integer — answer to the problem.
Examples
Input
3 3 0
0 1 2
Output
1
Input
6 7 2
1 2 3 4 5 6
Output
3
Note
In the first example:
(0+1)(0^2 + 1^2) = 1 ≡ 1 mod 3.
(0+2)(0^2 + 2^2) = 8 ≡ 2 mod 3.
(1+2)(1^2 + 2^2) = 15 ≡ 0 mod 3.
So only 1 pair satisfies the condition.
In the second example, there are 3 such pairs: (1, 5), (2, 3), (4, 6).
Tags: math, matrices, number theory, two pointers
Correct Solution:
```
n, p, k = map(int, input().split())
a = list(map(int, input().split()))
b = dict()
ans = 0
for i in a:
j = (i ** 4 - k * i) % p
c = b.get(j, 0)
ans += c
b[j] = c + 1
print(ans)
```
| 1,730 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a prime number p, n integers a_1, a_2, …, a_n, and an integer k.
Find the number of pairs of indexes (i, j) (1 ≤ i < j ≤ n) for which (a_i + a_j)(a_i^2 + a_j^2) ≡ k mod p.
Input
The first line contains integers n, p, k (2 ≤ n ≤ 3 ⋅ 10^5, 2 ≤ p ≤ 10^9, 0 ≤ k ≤ p-1). p is guaranteed to be prime.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ p-1). It is guaranteed that all elements are different.
Output
Output a single integer — answer to the problem.
Examples
Input
3 3 0
0 1 2
Output
1
Input
6 7 2
1 2 3 4 5 6
Output
3
Note
In the first example:
(0+1)(0^2 + 1^2) = 1 ≡ 1 mod 3.
(0+2)(0^2 + 2^2) = 8 ≡ 2 mod 3.
(1+2)(1^2 + 2^2) = 15 ≡ 0 mod 3.
So only 1 pair satisfies the condition.
In the second example, there are 3 such pairs: (1, 5), (2, 3), (4, 6).
Tags: math, matrices, number theory, two pointers
Correct Solution:
```
from collections import Counter
def pr(a):return (a*(a-1))//2
n,p,k=map(int,input().split())
a=map(int,input().split())
a=Counter([(x**4-x*k+p)%p for x in a])
print(sum(pr(a[x]) for x in a))
```
| 1,731 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a prime number p, n integers a_1, a_2, …, a_n, and an integer k.
Find the number of pairs of indexes (i, j) (1 ≤ i < j ≤ n) for which (a_i + a_j)(a_i^2 + a_j^2) ≡ k mod p.
Input
The first line contains integers n, p, k (2 ≤ n ≤ 3 ⋅ 10^5, 2 ≤ p ≤ 10^9, 0 ≤ k ≤ p-1). p is guaranteed to be prime.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ p-1). It is guaranteed that all elements are different.
Output
Output a single integer — answer to the problem.
Examples
Input
3 3 0
0 1 2
Output
1
Input
6 7 2
1 2 3 4 5 6
Output
3
Note
In the first example:
(0+1)(0^2 + 1^2) = 1 ≡ 1 mod 3.
(0+2)(0^2 + 2^2) = 8 ≡ 2 mod 3.
(1+2)(1^2 + 2^2) = 15 ≡ 0 mod 3.
So only 1 pair satisfies the condition.
In the second example, there are 3 such pairs: (1, 5), (2, 3), (4, 6).
Tags: math, matrices, number theory, two pointers
Correct Solution:
```
from sys import stdin
n,p,k=map(int,stdin.readline().strip().split())
s=list(map(int,stdin.readline().strip().split()))
st=set()
d=dict()
for i in s:
x=(i**4-i*k)%p
if x in st:
d[x]+=1
else:
st.add(x)
d[x]=1
s.sort()
ans=0
for i in s:
x=(i**4-i*k)%p
if x in st:
ans+=(d[x]-1)*d[x]//2
d[x]=0
print(ans)
```
| 1,732 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a prime number p, n integers a_1, a_2, …, a_n, and an integer k.
Find the number of pairs of indexes (i, j) (1 ≤ i < j ≤ n) for which (a_i + a_j)(a_i^2 + a_j^2) ≡ k mod p.
Input
The first line contains integers n, p, k (2 ≤ n ≤ 3 ⋅ 10^5, 2 ≤ p ≤ 10^9, 0 ≤ k ≤ p-1). p is guaranteed to be prime.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ p-1). It is guaranteed that all elements are different.
Output
Output a single integer — answer to the problem.
Examples
Input
3 3 0
0 1 2
Output
1
Input
6 7 2
1 2 3 4 5 6
Output
3
Note
In the first example:
(0+1)(0^2 + 1^2) = 1 ≡ 1 mod 3.
(0+2)(0^2 + 2^2) = 8 ≡ 2 mod 3.
(1+2)(1^2 + 2^2) = 15 ≡ 0 mod 3.
So only 1 pair satisfies the condition.
In the second example, there are 3 such pairs: (1, 5), (2, 3), (4, 6).
Tags: math, matrices, number theory, two pointers
Correct Solution:
```
n,p,k=map(int,input().split())
arr=list(map(int,input().split()))
dict1={}
for i in range(n):
val=((pow(arr[i],4,p)-(k*arr[i])%p)+p)%p
try:
dict1[val]+=1
except:
KeyError
dict1[val]=1
ans=0
for i in dict1.keys():
ans+=(dict1[i]*(dict1[i]-1))//2
print(ans)
```
| 1,733 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a prime number p, n integers a_1, a_2, …, a_n, and an integer k.
Find the number of pairs of indexes (i, j) (1 ≤ i < j ≤ n) for which (a_i + a_j)(a_i^2 + a_j^2) ≡ k mod p.
Input
The first line contains integers n, p, k (2 ≤ n ≤ 3 ⋅ 10^5, 2 ≤ p ≤ 10^9, 0 ≤ k ≤ p-1). p is guaranteed to be prime.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ p-1). It is guaranteed that all elements are different.
Output
Output a single integer — answer to the problem.
Examples
Input
3 3 0
0 1 2
Output
1
Input
6 7 2
1 2 3 4 5 6
Output
3
Note
In the first example:
(0+1)(0^2 + 1^2) = 1 ≡ 1 mod 3.
(0+2)(0^2 + 2^2) = 8 ≡ 2 mod 3.
(1+2)(1^2 + 2^2) = 15 ≡ 0 mod 3.
So only 1 pair satisfies the condition.
In the second example, there are 3 such pairs: (1, 5), (2, 3), (4, 6).
Submitted Solution:
```
from collections import defaultdict as dc
n,p,k=map(int,input().split())
a=list(map(int,input().split()))
b=[]
for i in range(n):
x=((a[i]**2)%p)**2%p-(k*a[i])%p
if(x<0):
b.append(x+p)
else:
b.append(x)
d=dc(int)
for i in b:
d[i]+=1
def c(n):
return (n*(n-1))//2
cnt=0
for i in list(d.values()):
cnt+=c(i)
print(cnt)
```
Yes
| 1,734 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a prime number p, n integers a_1, a_2, …, a_n, and an integer k.
Find the number of pairs of indexes (i, j) (1 ≤ i < j ≤ n) for which (a_i + a_j)(a_i^2 + a_j^2) ≡ k mod p.
Input
The first line contains integers n, p, k (2 ≤ n ≤ 3 ⋅ 10^5, 2 ≤ p ≤ 10^9, 0 ≤ k ≤ p-1). p is guaranteed to be prime.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ p-1). It is guaranteed that all elements are different.
Output
Output a single integer — answer to the problem.
Examples
Input
3 3 0
0 1 2
Output
1
Input
6 7 2
1 2 3 4 5 6
Output
3
Note
In the first example:
(0+1)(0^2 + 1^2) = 1 ≡ 1 mod 3.
(0+2)(0^2 + 2^2) = 8 ≡ 2 mod 3.
(1+2)(1^2 + 2^2) = 15 ≡ 0 mod 3.
So only 1 pair satisfies the condition.
In the second example, there are 3 such pairs: (1, 5), (2, 3), (4, 6).
Submitted Solution:
```
cond = [int(x) for x in input().split()]
n = cond[0]
p = cond[1]
k = cond[2]
a = [int(x) for x in input().split()]
b = [(x**4-k*x)%p for x in a]
d = {}
r = 0
for x in b:
if x not in d:
d[x] = 0
r += d[x]
d[x] += 1
print(r)
```
Yes
| 1,735 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a prime number p, n integers a_1, a_2, …, a_n, and an integer k.
Find the number of pairs of indexes (i, j) (1 ≤ i < j ≤ n) for which (a_i + a_j)(a_i^2 + a_j^2) ≡ k mod p.
Input
The first line contains integers n, p, k (2 ≤ n ≤ 3 ⋅ 10^5, 2 ≤ p ≤ 10^9, 0 ≤ k ≤ p-1). p is guaranteed to be prime.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ p-1). It is guaranteed that all elements are different.
Output
Output a single integer — answer to the problem.
Examples
Input
3 3 0
0 1 2
Output
1
Input
6 7 2
1 2 3 4 5 6
Output
3
Note
In the first example:
(0+1)(0^2 + 1^2) = 1 ≡ 1 mod 3.
(0+2)(0^2 + 2^2) = 8 ≡ 2 mod 3.
(1+2)(1^2 + 2^2) = 15 ≡ 0 mod 3.
So only 1 pair satisfies the condition.
In the second example, there are 3 such pairs: (1, 5), (2, 3), (4, 6).
Submitted Solution:
```
"""This code was written by
Russell Emerine - linguist,
mathematician, coder,
musician, and metalhead."""
from collections import Counter
n, p, k = map(int, input().split())
a = [int(x) for x in input().split()]
b = [(x ** 4) % p for x in a]
c = [(x * k) % p for x in a]
d = [(b[i] - c[i] + p) % p for i in range(n)]
f = Counter(d)
s = 0
for _, e in f.items():
s += (e * (e - 1)) // 2
print(s)
```
Yes
| 1,736 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a prime number p, n integers a_1, a_2, …, a_n, and an integer k.
Find the number of pairs of indexes (i, j) (1 ≤ i < j ≤ n) for which (a_i + a_j)(a_i^2 + a_j^2) ≡ k mod p.
Input
The first line contains integers n, p, k (2 ≤ n ≤ 3 ⋅ 10^5, 2 ≤ p ≤ 10^9, 0 ≤ k ≤ p-1). p is guaranteed to be prime.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ p-1). It is guaranteed that all elements are different.
Output
Output a single integer — answer to the problem.
Examples
Input
3 3 0
0 1 2
Output
1
Input
6 7 2
1 2 3 4 5 6
Output
3
Note
In the first example:
(0+1)(0^2 + 1^2) = 1 ≡ 1 mod 3.
(0+2)(0^2 + 2^2) = 8 ≡ 2 mod 3.
(1+2)(1^2 + 2^2) = 15 ≡ 0 mod 3.
So only 1 pair satisfies the condition.
In the second example, there are 3 such pairs: (1, 5), (2, 3), (4, 6).
Submitted Solution:
```
n,p,k = map(int,input().split())
l = list(map(int,input().split()))
d = dict()
for y in range(n):
x = pow(l[y],4) - l[y]*(k)
if(x%p not in d):
d[x%p] = 1
else:
d[x%p] += 1
ct = 0
#print(d)
for k,v in d.items():
ct += v*(v-1)//2
print(ct)
```
Yes
| 1,737 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a prime number p, n integers a_1, a_2, …, a_n, and an integer k.
Find the number of pairs of indexes (i, j) (1 ≤ i < j ≤ n) for which (a_i + a_j)(a_i^2 + a_j^2) ≡ k mod p.
Input
The first line contains integers n, p, k (2 ≤ n ≤ 3 ⋅ 10^5, 2 ≤ p ≤ 10^9, 0 ≤ k ≤ p-1). p is guaranteed to be prime.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ p-1). It is guaranteed that all elements are different.
Output
Output a single integer — answer to the problem.
Examples
Input
3 3 0
0 1 2
Output
1
Input
6 7 2
1 2 3 4 5 6
Output
3
Note
In the first example:
(0+1)(0^2 + 1^2) = 1 ≡ 1 mod 3.
(0+2)(0^2 + 2^2) = 8 ≡ 2 mod 3.
(1+2)(1^2 + 2^2) = 15 ≡ 0 mod 3.
So only 1 pair satisfies the condition.
In the second example, there are 3 such pairs: (1, 5), (2, 3), (4, 6).
Submitted Solution:
```
# E. Count Pairs from Codeforces
n,p,k=input().split()
n=int(n)
p=int(p)
k=int(k)
c=0
a=list(map(int,input().split()))
for i in range(n) :
for j in range(i,n) :
if (((a[i]+a[j])*((a[i]*a[i])+(a[j]*a[j]))-k)%p) == 0:
c+=1
print(c)
```
No
| 1,738 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a prime number p, n integers a_1, a_2, …, a_n, and an integer k.
Find the number of pairs of indexes (i, j) (1 ≤ i < j ≤ n) for which (a_i + a_j)(a_i^2 + a_j^2) ≡ k mod p.
Input
The first line contains integers n, p, k (2 ≤ n ≤ 3 ⋅ 10^5, 2 ≤ p ≤ 10^9, 0 ≤ k ≤ p-1). p is guaranteed to be prime.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ p-1). It is guaranteed that all elements are different.
Output
Output a single integer — answer to the problem.
Examples
Input
3 3 0
0 1 2
Output
1
Input
6 7 2
1 2 3 4 5 6
Output
3
Note
In the first example:
(0+1)(0^2 + 1^2) = 1 ≡ 1 mod 3.
(0+2)(0^2 + 2^2) = 8 ≡ 2 mod 3.
(1+2)(1^2 + 2^2) = 15 ≡ 0 mod 3.
So only 1 pair satisfies the condition.
In the second example, there are 3 such pairs: (1, 5), (2, 3), (4, 6).
Submitted Solution:
```
from collections import Counter
n, p, k = map(int, input().split())
a = list(map(int, input().split()))
freqs = Counter([(x ** 4 + k * x) % p for x in a])
ans = sum([(x - 1) * x // 2 for x in freqs.values()])
print(ans)
```
No
| 1,739 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a prime number p, n integers a_1, a_2, …, a_n, and an integer k.
Find the number of pairs of indexes (i, j) (1 ≤ i < j ≤ n) for which (a_i + a_j)(a_i^2 + a_j^2) ≡ k mod p.
Input
The first line contains integers n, p, k (2 ≤ n ≤ 3 ⋅ 10^5, 2 ≤ p ≤ 10^9, 0 ≤ k ≤ p-1). p is guaranteed to be prime.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ p-1). It is guaranteed that all elements are different.
Output
Output a single integer — answer to the problem.
Examples
Input
3 3 0
0 1 2
Output
1
Input
6 7 2
1 2 3 4 5 6
Output
3
Note
In the first example:
(0+1)(0^2 + 1^2) = 1 ≡ 1 mod 3.
(0+2)(0^2 + 2^2) = 8 ≡ 2 mod 3.
(1+2)(1^2 + 2^2) = 15 ≡ 0 mod 3.
So only 1 pair satisfies the condition.
In the second example, there are 3 such pairs: (1, 5), (2, 3), (4, 6).
Submitted Solution:
```
#572_E
ln = [int(i) for i in input().split(" ")]
n = ln[0]
p = ln[1]
k = ln[2]
a = [int(i) for i in input().split(" ")]
cts = {}
ans = []
nm = 0
for i in range(0, len(a)):
an = ((a[i] ** 4) - (k * a[i])) % p
if an in cts:
cts[an] *= 2
nm += cts[an] // 2
else:
cts[an] = 1
print(nm)
```
No
| 1,740 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a prime number p, n integers a_1, a_2, …, a_n, and an integer k.
Find the number of pairs of indexes (i, j) (1 ≤ i < j ≤ n) for which (a_i + a_j)(a_i^2 + a_j^2) ≡ k mod p.
Input
The first line contains integers n, p, k (2 ≤ n ≤ 3 ⋅ 10^5, 2 ≤ p ≤ 10^9, 0 ≤ k ≤ p-1). p is guaranteed to be prime.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ p-1). It is guaranteed that all elements are different.
Output
Output a single integer — answer to the problem.
Examples
Input
3 3 0
0 1 2
Output
1
Input
6 7 2
1 2 3 4 5 6
Output
3
Note
In the first example:
(0+1)(0^2 + 1^2) = 1 ≡ 1 mod 3.
(0+2)(0^2 + 2^2) = 8 ≡ 2 mod 3.
(1+2)(1^2 + 2^2) = 15 ≡ 0 mod 3.
So only 1 pair satisfies the condition.
In the second example, there are 3 such pairs: (1, 5), (2, 3), (4, 6).
Submitted Solution:
```
import sys
n, p, k = list(map(int, sys.stdin.readline().strip().split()))
a = list(map(int, sys.stdin.readline().strip().split()))
for i in range (0, n):
a[i] = (a[i] ** 4 - k * a[i]) % p
a[i] = a[i] + 2 * p
a[i] = a[i] % p
a.sort()
print(a)
c = 1
x = a[0]
ans = 0
for i in range (1, n):
if a[i] == x:
c = c + 1
else:
ans = ans + (c * (c-1) // 2)
c = 1
x = a[i]
ans = ans + (c * (c-1) // 2)
print(ans)
```
No
| 1,741 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment [0, n] on OX axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval (x, x + 1) with integer x. So we can represent the road as a binary string consisting of n characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.
Usually, we can install the pipeline along the road on height of 1 unit with supporting pillars in each integer point (so, if we are responsible for [0, n] road, we must install n + 1 pillars). But on crossroads we should lift the pipeline up to the height 2, so the pipeline won't obstruct the way for cars.
We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment [x, x + 1] with integer x consisting of three parts: 0.5 units of horizontal pipe + 1 unit of vertical pipe + 0.5 of horizontal. Note that if pipeline is currently on height 2, the pillars that support it should also have length equal to 2 units.
<image>
Each unit of gas pipeline costs us a bourles, and each unit of pillar — b bourles. So, it's not always optimal to make the whole pipeline on the height 2. Find the shape of the pipeline with minimum possible cost and calculate that cost.
Note that you must start and finish the pipeline on height 1 and, also, it's guaranteed that the first and last characters of the input string are equal to 0.
Input
The fist line contains one integer T (1 ≤ T ≤ 100) — the number of queries. Next 2 ⋅ T lines contain independent queries — one query per two lines.
The first line contains three integers n, a, b (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ a ≤ 10^8, 1 ≤ b ≤ 10^8) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively.
The second line contains binary string s (|s| = n, s_i ∈ \{0, 1\}, s_1 = s_n = 0) — the description of the road.
It's guaranteed that the total length of all strings s doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per query. For each query print the minimum possible cost of the constructed pipeline.
Example
Input
4
8 2 5
00110010
8 1 1
00110010
9 100000000 100000000
010101010
2 5 1
00
Output
94
25
2900000000
13
Note
The optimal pipeline for the first query is shown at the picture above.
The optimal pipeline for the second query is pictured below:
<image>
The optimal (and the only possible) pipeline for the third query is shown below:
<image>
The optimal pipeline for the fourth query is shown below:
<image>
Tags: dp, greedy
Correct Solution:
```
t = int(input())
for j in range(t):
n, a, b = map(int, input().split())
s = input()
k = 0
z = 0
for i in range(n):
if s[i] == '0':
z += 1
else:
if z == 1:
if i == z:
k += 3 * b + 2 * a
else:
k += a + 2 * b
elif z > 1:
if i == z:
alter_1 = 3 * b + 2 * a + (z - 1) * (a + 2 * b)
alter_2 = 2 * b + a + (z - 2) * (a + b) + 2 * a + 2 * b
else:
alter_1 = z * (a + 2 * b)
alter_2 = 2 * a + b + (z - 2) * (a + b) + 2 * a + 2 * b
k += min(alter_1, alter_2)
k += a + 2 * b
z = 0
if z == n:
k = b + z * (a + b)
else:
alter_1 = (z - 1) * (a + 2 * b) + 2 * a + b
alter_2 = 2 * a + b + (z - 1) * (a + b)
k += min(alter_1, alter_2)
print(k)
```
| 1,742 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment [0, n] on OX axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval (x, x + 1) with integer x. So we can represent the road as a binary string consisting of n characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.
Usually, we can install the pipeline along the road on height of 1 unit with supporting pillars in each integer point (so, if we are responsible for [0, n] road, we must install n + 1 pillars). But on crossroads we should lift the pipeline up to the height 2, so the pipeline won't obstruct the way for cars.
We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment [x, x + 1] with integer x consisting of three parts: 0.5 units of horizontal pipe + 1 unit of vertical pipe + 0.5 of horizontal. Note that if pipeline is currently on height 2, the pillars that support it should also have length equal to 2 units.
<image>
Each unit of gas pipeline costs us a bourles, and each unit of pillar — b bourles. So, it's not always optimal to make the whole pipeline on the height 2. Find the shape of the pipeline with minimum possible cost and calculate that cost.
Note that you must start and finish the pipeline on height 1 and, also, it's guaranteed that the first and last characters of the input string are equal to 0.
Input
The fist line contains one integer T (1 ≤ T ≤ 100) — the number of queries. Next 2 ⋅ T lines contain independent queries — one query per two lines.
The first line contains three integers n, a, b (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ a ≤ 10^8, 1 ≤ b ≤ 10^8) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively.
The second line contains binary string s (|s| = n, s_i ∈ \{0, 1\}, s_1 = s_n = 0) — the description of the road.
It's guaranteed that the total length of all strings s doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per query. For each query print the minimum possible cost of the constructed pipeline.
Example
Input
4
8 2 5
00110010
8 1 1
00110010
9 100000000 100000000
010101010
2 5 1
00
Output
94
25
2900000000
13
Note
The optimal pipeline for the first query is shown at the picture above.
The optimal pipeline for the second query is pictured below:
<image>
The optimal (and the only possible) pipeline for the third query is shown below:
<image>
The optimal pipeline for the fourth query is shown below:
<image>
Tags: dp, greedy
Correct Solution:
```
t = int(input())
for _ in range(t):
n,a,b = map(int,input().rstrip().split())
s = input()+'0'
# if a<=b:
# c=0
# for i in s:
# if i=='1'
# c+=1
# break
# else:
# c+=1
m1,m2 = b,float('inf')
for i in range(n):
m3 = min(m1+2*a+2*b,m2+a+b*2)
if s[i+1]=='0' and s[i]=='0':
m1 = min(m1+a+b,m2+2*a+b)
else:
m1 = float('inf')
m2=m3
print(m1)
```
| 1,743 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment [0, n] on OX axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval (x, x + 1) with integer x. So we can represent the road as a binary string consisting of n characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.
Usually, we can install the pipeline along the road on height of 1 unit with supporting pillars in each integer point (so, if we are responsible for [0, n] road, we must install n + 1 pillars). But on crossroads we should lift the pipeline up to the height 2, so the pipeline won't obstruct the way for cars.
We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment [x, x + 1] with integer x consisting of three parts: 0.5 units of horizontal pipe + 1 unit of vertical pipe + 0.5 of horizontal. Note that if pipeline is currently on height 2, the pillars that support it should also have length equal to 2 units.
<image>
Each unit of gas pipeline costs us a bourles, and each unit of pillar — b bourles. So, it's not always optimal to make the whole pipeline on the height 2. Find the shape of the pipeline with minimum possible cost and calculate that cost.
Note that you must start and finish the pipeline on height 1 and, also, it's guaranteed that the first and last characters of the input string are equal to 0.
Input
The fist line contains one integer T (1 ≤ T ≤ 100) — the number of queries. Next 2 ⋅ T lines contain independent queries — one query per two lines.
The first line contains three integers n, a, b (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ a ≤ 10^8, 1 ≤ b ≤ 10^8) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively.
The second line contains binary string s (|s| = n, s_i ∈ \{0, 1\}, s_1 = s_n = 0) — the description of the road.
It's guaranteed that the total length of all strings s doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per query. For each query print the minimum possible cost of the constructed pipeline.
Example
Input
4
8 2 5
00110010
8 1 1
00110010
9 100000000 100000000
010101010
2 5 1
00
Output
94
25
2900000000
13
Note
The optimal pipeline for the first query is shown at the picture above.
The optimal pipeline for the second query is pictured below:
<image>
The optimal (and the only possible) pipeline for the third query is shown below:
<image>
The optimal pipeline for the fourth query is shown below:
<image>
Tags: dp, greedy
Correct Solution:
```
C=[]
for _ in range (int(input())):
n,a,b=map(int,input().split())
pre=None
pos=[None,None]
genc=False
x=0
cost=(a+b)*n+b
for i,cur in enumerate(input()):
if pre==None:
pre='0'
continue
if cur=='0':
if pre=='0':
if pos[0] == None and genc:
x+=1
elif genc:
cost+=(pos[1]-pos[0]+2)*b
x=1
pos[0]=None
pos[1]=None
else:pos[1]=i-1
else:
if pre=='0':
if pos[0]==None:
if genc:
cost+=min(b*x,2*a)
x=0
else:genc=True
pos[0]=i
pre=cur
if genc:
if pos[0] is not None:
cost+=2*a+(pos[1]-pos[0]+2)*b
else:
cost+=2*a
C.append(cost)
for c in C:
print(c)
```
| 1,744 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment [0, n] on OX axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval (x, x + 1) with integer x. So we can represent the road as a binary string consisting of n characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.
Usually, we can install the pipeline along the road on height of 1 unit with supporting pillars in each integer point (so, if we are responsible for [0, n] road, we must install n + 1 pillars). But on crossroads we should lift the pipeline up to the height 2, so the pipeline won't obstruct the way for cars.
We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment [x, x + 1] with integer x consisting of three parts: 0.5 units of horizontal pipe + 1 unit of vertical pipe + 0.5 of horizontal. Note that if pipeline is currently on height 2, the pillars that support it should also have length equal to 2 units.
<image>
Each unit of gas pipeline costs us a bourles, and each unit of pillar — b bourles. So, it's not always optimal to make the whole pipeline on the height 2. Find the shape of the pipeline with minimum possible cost and calculate that cost.
Note that you must start and finish the pipeline on height 1 and, also, it's guaranteed that the first and last characters of the input string are equal to 0.
Input
The fist line contains one integer T (1 ≤ T ≤ 100) — the number of queries. Next 2 ⋅ T lines contain independent queries — one query per two lines.
The first line contains three integers n, a, b (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ a ≤ 10^8, 1 ≤ b ≤ 10^8) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively.
The second line contains binary string s (|s| = n, s_i ∈ \{0, 1\}, s_1 = s_n = 0) — the description of the road.
It's guaranteed that the total length of all strings s doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per query. For each query print the minimum possible cost of the constructed pipeline.
Example
Input
4
8 2 5
00110010
8 1 1
00110010
9 100000000 100000000
010101010
2 5 1
00
Output
94
25
2900000000
13
Note
The optimal pipeline for the first query is shown at the picture above.
The optimal pipeline for the second query is pictured below:
<image>
The optimal (and the only possible) pipeline for the third query is shown below:
<image>
The optimal pipeline for the fourth query is shown below:
<image>
Tags: dp, greedy
Correct Solution:
```
t = int(input())
for i in range(t):
n,a,b=map(int,input().split())
s=input()
p=[]
p1=0
p2=0
for j in range(n):
if s[j]=='0':
p1+=1
if p2!=0:
p.append(p2)
p2=0
else:
p2+=1
if p1!=0:
p.append(p1)
p1=0
if p1!=0:
p.append(p1)
if p2!=0:
p.append(p2)
et=0
dld=0
dls=1
uk=0
for j in range(len(p)):
if s[uk]=='0':
if et==0:
if j==len(p)-1:
dld+=p[j]
uk+=p[j]
dls+=p[j]
else:
et=1
dld+=p[j]+1
dls+=p[j]+1
uk+=p[j]
elif et==1:
if j==len(p)-1:
dld+=2+p[j]-1
dls+=p[j]
uk+=p[j]
elif p[j]==1:
dld+=1
uk+=p[j]
dls+=2
elif (4+p[j]-2)*a+(p[j]-1)*b<=p[j]*a+(p[j]-1)*2*b:
dld+=4+p[j]-2
dls+=p[j]+1
uk+=p[j]
else:
dld+=p[j]
dls+=p[j]*2
uk+=p[j]
else:
dld+=p[j]
dls+=p[j]*2
uk+=p[j]
print(dld*a+dls*b)
```
| 1,745 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment [0, n] on OX axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval (x, x + 1) with integer x. So we can represent the road as a binary string consisting of n characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.
Usually, we can install the pipeline along the road on height of 1 unit with supporting pillars in each integer point (so, if we are responsible for [0, n] road, we must install n + 1 pillars). But on crossroads we should lift the pipeline up to the height 2, so the pipeline won't obstruct the way for cars.
We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment [x, x + 1] with integer x consisting of three parts: 0.5 units of horizontal pipe + 1 unit of vertical pipe + 0.5 of horizontal. Note that if pipeline is currently on height 2, the pillars that support it should also have length equal to 2 units.
<image>
Each unit of gas pipeline costs us a bourles, and each unit of pillar — b bourles. So, it's not always optimal to make the whole pipeline on the height 2. Find the shape of the pipeline with minimum possible cost and calculate that cost.
Note that you must start and finish the pipeline on height 1 and, also, it's guaranteed that the first and last characters of the input string are equal to 0.
Input
The fist line contains one integer T (1 ≤ T ≤ 100) — the number of queries. Next 2 ⋅ T lines contain independent queries — one query per two lines.
The first line contains three integers n, a, b (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ a ≤ 10^8, 1 ≤ b ≤ 10^8) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively.
The second line contains binary string s (|s| = n, s_i ∈ \{0, 1\}, s_1 = s_n = 0) — the description of the road.
It's guaranteed that the total length of all strings s doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per query. For each query print the minimum possible cost of the constructed pipeline.
Example
Input
4
8 2 5
00110010
8 1 1
00110010
9 100000000 100000000
010101010
2 5 1
00
Output
94
25
2900000000
13
Note
The optimal pipeline for the first query is shown at the picture above.
The optimal pipeline for the second query is pictured below:
<image>
The optimal (and the only possible) pipeline for the third query is shown below:
<image>
The optimal pipeline for the fourth query is shown below:
<image>
Tags: dp, greedy
Correct Solution:
```
t=int(input())
for it in range(t):
n,a,b=map(int,input().split())
s=input()
dp = [[int(1e18)]*2 for i in range(n+1)]
dp[0][0]=b
for i in range(n):
if(s[i]=='1'):
dp[i+1][1]=min(dp[i+1][1],dp[i][1]+a+2*b)
else:
dp[i+1][0] = min(dp[i+1][0],dp[i][0]+a+b)
dp[i+1][1] = min(dp[i+1][1],dp[i][0]+2*(a+b))
dp[i+1][1] = min(dp[i+1][1],dp[i][1]+a+2*b)
dp[i+1][0] = min(dp[i+1][0],dp[i][1]+2*a+b)
print(dp[n][0])
```
| 1,746 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment [0, n] on OX axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval (x, x + 1) with integer x. So we can represent the road as a binary string consisting of n characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.
Usually, we can install the pipeline along the road on height of 1 unit with supporting pillars in each integer point (so, if we are responsible for [0, n] road, we must install n + 1 pillars). But on crossroads we should lift the pipeline up to the height 2, so the pipeline won't obstruct the way for cars.
We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment [x, x + 1] with integer x consisting of three parts: 0.5 units of horizontal pipe + 1 unit of vertical pipe + 0.5 of horizontal. Note that if pipeline is currently on height 2, the pillars that support it should also have length equal to 2 units.
<image>
Each unit of gas pipeline costs us a bourles, and each unit of pillar — b bourles. So, it's not always optimal to make the whole pipeline on the height 2. Find the shape of the pipeline with minimum possible cost and calculate that cost.
Note that you must start and finish the pipeline on height 1 and, also, it's guaranteed that the first and last characters of the input string are equal to 0.
Input
The fist line contains one integer T (1 ≤ T ≤ 100) — the number of queries. Next 2 ⋅ T lines contain independent queries — one query per two lines.
The first line contains three integers n, a, b (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ a ≤ 10^8, 1 ≤ b ≤ 10^8) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively.
The second line contains binary string s (|s| = n, s_i ∈ \{0, 1\}, s_1 = s_n = 0) — the description of the road.
It's guaranteed that the total length of all strings s doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per query. For each query print the minimum possible cost of the constructed pipeline.
Example
Input
4
8 2 5
00110010
8 1 1
00110010
9 100000000 100000000
010101010
2 5 1
00
Output
94
25
2900000000
13
Note
The optimal pipeline for the first query is shown at the picture above.
The optimal pipeline for the second query is pictured below:
<image>
The optimal (and the only possible) pipeline for the third query is shown below:
<image>
The optimal pipeline for the fourth query is shown below:
<image>
Tags: dp, greedy
Correct Solution:
```
t = int(input())
def solve():
n,a,b = map(int,input().split())
dp = [[10**20,10**20] for i in range(n + 1)]
dp[0][0] = b
s = input()
s += '0'
for i in range(1,n + 1):
if s[i] == '1':
dp[i][1] = min(dp[i - 1][0] + 2*a + 2*b, dp[i - 1][1] + a + 2*b)
elif s[i - 1] != '1':
dp[i][0] = min(dp[i - 1][0] + a + b, dp[i - 1][1] + 2*a + b)
dp[i][1] = min(dp[i - 1][0] + 2*a + 2*b, dp[i - 1][1] + a + 2*b)
else:
dp[i][1] = dp[i - 1][1] + a + 2*b
print(dp[n][0])
for i in range(t):
solve()
```
| 1,747 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment [0, n] on OX axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval (x, x + 1) with integer x. So we can represent the road as a binary string consisting of n characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.
Usually, we can install the pipeline along the road on height of 1 unit with supporting pillars in each integer point (so, if we are responsible for [0, n] road, we must install n + 1 pillars). But on crossroads we should lift the pipeline up to the height 2, so the pipeline won't obstruct the way for cars.
We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment [x, x + 1] with integer x consisting of three parts: 0.5 units of horizontal pipe + 1 unit of vertical pipe + 0.5 of horizontal. Note that if pipeline is currently on height 2, the pillars that support it should also have length equal to 2 units.
<image>
Each unit of gas pipeline costs us a bourles, and each unit of pillar — b bourles. So, it's not always optimal to make the whole pipeline on the height 2. Find the shape of the pipeline with minimum possible cost and calculate that cost.
Note that you must start and finish the pipeline on height 1 and, also, it's guaranteed that the first and last characters of the input string are equal to 0.
Input
The fist line contains one integer T (1 ≤ T ≤ 100) — the number of queries. Next 2 ⋅ T lines contain independent queries — one query per two lines.
The first line contains three integers n, a, b (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ a ≤ 10^8, 1 ≤ b ≤ 10^8) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively.
The second line contains binary string s (|s| = n, s_i ∈ \{0, 1\}, s_1 = s_n = 0) — the description of the road.
It's guaranteed that the total length of all strings s doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per query. For each query print the minimum possible cost of the constructed pipeline.
Example
Input
4
8 2 5
00110010
8 1 1
00110010
9 100000000 100000000
010101010
2 5 1
00
Output
94
25
2900000000
13
Note
The optimal pipeline for the first query is shown at the picture above.
The optimal pipeline for the second query is pictured below:
<image>
The optimal (and the only possible) pipeline for the third query is shown below:
<image>
The optimal pipeline for the fourth query is shown below:
<image>
Tags: dp, greedy
Correct Solution:
```
t = int(input())
for _ in range(t):
n, a, b = map(int, input().split())
s = str(input())
last_seen = "0"
count = 0
counts = []
for i in range(len(s)):
if s[i] == last_seen:
count += 1
else:
counts.append(count)
last_seen = s[i]
count = 1
counts.append(count)
if len(counts)==1:
print((n+1)*b + n*a)
continue
total = 0
total += counts[0]*b + (counts[0]+1)*a
total += counts[-1]*b + (counts[-1]+1)*a
counts = counts[1:-1]
ind = 0
while True:
total += 2*(counts[ind]+1)*b + counts[ind]*a
if ind == len(counts) - 1:
break
cost1 = (counts[ind+1]-1)*b + (counts[ind+1]+2)*a #dip
cost2 = 2*(counts[ind+1]-1)*b + (counts[ind+1])*a #stay up
total += min(cost1,cost2)
ind+=2
print(total)
```
| 1,748 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment [0, n] on OX axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval (x, x + 1) with integer x. So we can represent the road as a binary string consisting of n characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.
Usually, we can install the pipeline along the road on height of 1 unit with supporting pillars in each integer point (so, if we are responsible for [0, n] road, we must install n + 1 pillars). But on crossroads we should lift the pipeline up to the height 2, so the pipeline won't obstruct the way for cars.
We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment [x, x + 1] with integer x consisting of three parts: 0.5 units of horizontal pipe + 1 unit of vertical pipe + 0.5 of horizontal. Note that if pipeline is currently on height 2, the pillars that support it should also have length equal to 2 units.
<image>
Each unit of gas pipeline costs us a bourles, and each unit of pillar — b bourles. So, it's not always optimal to make the whole pipeline on the height 2. Find the shape of the pipeline with minimum possible cost and calculate that cost.
Note that you must start and finish the pipeline on height 1 and, also, it's guaranteed that the first and last characters of the input string are equal to 0.
Input
The fist line contains one integer T (1 ≤ T ≤ 100) — the number of queries. Next 2 ⋅ T lines contain independent queries — one query per two lines.
The first line contains three integers n, a, b (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ a ≤ 10^8, 1 ≤ b ≤ 10^8) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively.
The second line contains binary string s (|s| = n, s_i ∈ \{0, 1\}, s_1 = s_n = 0) — the description of the road.
It's guaranteed that the total length of all strings s doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per query. For each query print the minimum possible cost of the constructed pipeline.
Example
Input
4
8 2 5
00110010
8 1 1
00110010
9 100000000 100000000
010101010
2 5 1
00
Output
94
25
2900000000
13
Note
The optimal pipeline for the first query is shown at the picture above.
The optimal pipeline for the second query is pictured below:
<image>
The optimal (and the only possible) pipeline for the third query is shown below:
<image>
The optimal pipeline for the fourth query is shown below:
<image>
Tags: dp, greedy
Correct Solution:
```
T = int(input())
for _ in range(T):
nab = list(map(int, input().split()))
n, a, b = nab[0], nab[1], nab[2]
s = str(input())
crp = list()
for i in range(n):
if s[i] == '1':
crp.append(i)
min_cost = (n+1)*b + (n*a)
if len(crp) == 0:
print(min_cost)
elif len(crp) == 1:
print(min_cost + 2*a + 2*b)
else:
min_cost += 2*a + 2*b
for i in range(len(crp)-1):
if crp[i] == crp[i+1]-1:
min_cost += b
else:
min_cost += min(2*a, (crp[i+1]-crp[i]-2)*b)
min_cost += 2*b
print(min_cost)
```
| 1,749 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment [0, n] on OX axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval (x, x + 1) with integer x. So we can represent the road as a binary string consisting of n characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.
Usually, we can install the pipeline along the road on height of 1 unit with supporting pillars in each integer point (so, if we are responsible for [0, n] road, we must install n + 1 pillars). But on crossroads we should lift the pipeline up to the height 2, so the pipeline won't obstruct the way for cars.
We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment [x, x + 1] with integer x consisting of three parts: 0.5 units of horizontal pipe + 1 unit of vertical pipe + 0.5 of horizontal. Note that if pipeline is currently on height 2, the pillars that support it should also have length equal to 2 units.
<image>
Each unit of gas pipeline costs us a bourles, and each unit of pillar — b bourles. So, it's not always optimal to make the whole pipeline on the height 2. Find the shape of the pipeline with minimum possible cost and calculate that cost.
Note that you must start and finish the pipeline on height 1 and, also, it's guaranteed that the first and last characters of the input string are equal to 0.
Input
The fist line contains one integer T (1 ≤ T ≤ 100) — the number of queries. Next 2 ⋅ T lines contain independent queries — one query per two lines.
The first line contains three integers n, a, b (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ a ≤ 10^8, 1 ≤ b ≤ 10^8) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively.
The second line contains binary string s (|s| = n, s_i ∈ \{0, 1\}, s_1 = s_n = 0) — the description of the road.
It's guaranteed that the total length of all strings s doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per query. For each query print the minimum possible cost of the constructed pipeline.
Example
Input
4
8 2 5
00110010
8 1 1
00110010
9 100000000 100000000
010101010
2 5 1
00
Output
94
25
2900000000
13
Note
The optimal pipeline for the first query is shown at the picture above.
The optimal pipeline for the second query is pictured below:
<image>
The optimal (and the only possible) pipeline for the third query is shown below:
<image>
The optimal pipeline for the fourth query is shown below:
<image>
Submitted Solution:
```
def gns():
return list(map(int,input().split()))
t=int(input())
for ti in range(t):
n,a,b=gns()#a pipe b pilar
s=input()
ans=s.split('1')
ans=[len(x) for x in ans if len(x)>0]
cst=a*n+2*a
cst+=(n+1)*2*b-ans[0]*b-ans[-1]*b
if len(ans)==1:
print((n+1)*b+n*a)
continue
for i in range(1,len(ans)-1):
x=ans[i]
cst=min(cst,cst-(x-1)*b+a*2)
print(cst)
```
Yes
| 1,750 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment [0, n] on OX axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval (x, x + 1) with integer x. So we can represent the road as a binary string consisting of n characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.
Usually, we can install the pipeline along the road on height of 1 unit with supporting pillars in each integer point (so, if we are responsible for [0, n] road, we must install n + 1 pillars). But on crossroads we should lift the pipeline up to the height 2, so the pipeline won't obstruct the way for cars.
We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment [x, x + 1] with integer x consisting of three parts: 0.5 units of horizontal pipe + 1 unit of vertical pipe + 0.5 of horizontal. Note that if pipeline is currently on height 2, the pillars that support it should also have length equal to 2 units.
<image>
Each unit of gas pipeline costs us a bourles, and each unit of pillar — b bourles. So, it's not always optimal to make the whole pipeline on the height 2. Find the shape of the pipeline with minimum possible cost and calculate that cost.
Note that you must start and finish the pipeline on height 1 and, also, it's guaranteed that the first and last characters of the input string are equal to 0.
Input
The fist line contains one integer T (1 ≤ T ≤ 100) — the number of queries. Next 2 ⋅ T lines contain independent queries — one query per two lines.
The first line contains three integers n, a, b (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ a ≤ 10^8, 1 ≤ b ≤ 10^8) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively.
The second line contains binary string s (|s| = n, s_i ∈ \{0, 1\}, s_1 = s_n = 0) — the description of the road.
It's guaranteed that the total length of all strings s doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per query. For each query print the minimum possible cost of the constructed pipeline.
Example
Input
4
8 2 5
00110010
8 1 1
00110010
9 100000000 100000000
010101010
2 5 1
00
Output
94
25
2900000000
13
Note
The optimal pipeline for the first query is shown at the picture above.
The optimal pipeline for the second query is pictured below:
<image>
The optimal (and the only possible) pipeline for the third query is shown below:
<image>
The optimal pipeline for the fourth query is shown below:
<image>
Submitted Solution:
```
q = int(input().strip())
for i in range(q):
n,a,b = [int(x) for x in input().strip().split()]
r = [int(x) for x in input().strip()]
i=0
r2 =[]
while i<n:
if r[i]==0:
r2.append([0,0])
while i<n and r[i]==0:
r2[-1][1]+=1
i+=1
#i-=1
else:
r2.append([1, 0])
while i<n and r[i] == 1:
r2[-1][1] += 1
i += 1
#i -= 1
d = True
c = 0
res = ''
for par in range(1,len(r2)-1):
if r2[par][0]==0:
if 2*a> (r2[par][1]-1)*b or r2[par][1]<2:
res+='1'*r2[par][1]
else:
res+='+'
res+=max((r2[par][1]-2),0)*'0'
res+='-'
else:
res+='1'*r2[par][1]
if len(r2)<=1:
res = '0'*r2[0][1]
else:
res = max(0,r2[0][1]-1)*'0'+'+'+res
res += '-'+max(0,r2[-1][1]-1)*'0'
c = b
for ch in res:
if ch=='0':
c+=a+b
elif ch=='1':
c+=a+2*b
elif ch=='+':
c+=2*(a+b)
elif ch=='-':
c+=2*a + b
print(c)
```
Yes
| 1,751 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment [0, n] on OX axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval (x, x + 1) with integer x. So we can represent the road as a binary string consisting of n characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.
Usually, we can install the pipeline along the road on height of 1 unit with supporting pillars in each integer point (so, if we are responsible for [0, n] road, we must install n + 1 pillars). But on crossroads we should lift the pipeline up to the height 2, so the pipeline won't obstruct the way for cars.
We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment [x, x + 1] with integer x consisting of three parts: 0.5 units of horizontal pipe + 1 unit of vertical pipe + 0.5 of horizontal. Note that if pipeline is currently on height 2, the pillars that support it should also have length equal to 2 units.
<image>
Each unit of gas pipeline costs us a bourles, and each unit of pillar — b bourles. So, it's not always optimal to make the whole pipeline on the height 2. Find the shape of the pipeline with minimum possible cost and calculate that cost.
Note that you must start and finish the pipeline on height 1 and, also, it's guaranteed that the first and last characters of the input string are equal to 0.
Input
The fist line contains one integer T (1 ≤ T ≤ 100) — the number of queries. Next 2 ⋅ T lines contain independent queries — one query per two lines.
The first line contains three integers n, a, b (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ a ≤ 10^8, 1 ≤ b ≤ 10^8) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively.
The second line contains binary string s (|s| = n, s_i ∈ \{0, 1\}, s_1 = s_n = 0) — the description of the road.
It's guaranteed that the total length of all strings s doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per query. For each query print the minimum possible cost of the constructed pipeline.
Example
Input
4
8 2 5
00110010
8 1 1
00110010
9 100000000 100000000
010101010
2 5 1
00
Output
94
25
2900000000
13
Note
The optimal pipeline for the first query is shown at the picture above.
The optimal pipeline for the second query is pictured below:
<image>
The optimal (and the only possible) pipeline for the third query is shown below:
<image>
The optimal pipeline for the fourth query is shown below:
<image>
Submitted Solution:
```
#Bhargey Mehta (Junior)
#DA-IICT, Gandhinagar
import sys, math, queue, collections
MOD = 10**9+7
#sys.stdin = open('input.txt', 'r')
for _ in range(int(input())):
n, a, b = map(int, input().split()) #pipeline, pillar
s = 'x'+input()
dp0 = [10**20 for i in range(n+1)]
dp1 = [10**20 for i in range(n+1)]
dp0[0] = b
for i in range(1, len(s)):
dp1[i] = min(dp1[i-1], dp0[i-1]+a)+a+2*b
if s[i] == '0':
dp0[i] = min(dp0[i-1], dp1[i-1]+a+b)+a+b
print(dp0[n])
```
Yes
| 1,752 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment [0, n] on OX axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval (x, x + 1) with integer x. So we can represent the road as a binary string consisting of n characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.
Usually, we can install the pipeline along the road on height of 1 unit with supporting pillars in each integer point (so, if we are responsible for [0, n] road, we must install n + 1 pillars). But on crossroads we should lift the pipeline up to the height 2, so the pipeline won't obstruct the way for cars.
We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment [x, x + 1] with integer x consisting of three parts: 0.5 units of horizontal pipe + 1 unit of vertical pipe + 0.5 of horizontal. Note that if pipeline is currently on height 2, the pillars that support it should also have length equal to 2 units.
<image>
Each unit of gas pipeline costs us a bourles, and each unit of pillar — b bourles. So, it's not always optimal to make the whole pipeline on the height 2. Find the shape of the pipeline with minimum possible cost and calculate that cost.
Note that you must start and finish the pipeline on height 1 and, also, it's guaranteed that the first and last characters of the input string are equal to 0.
Input
The fist line contains one integer T (1 ≤ T ≤ 100) — the number of queries. Next 2 ⋅ T lines contain independent queries — one query per two lines.
The first line contains three integers n, a, b (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ a ≤ 10^8, 1 ≤ b ≤ 10^8) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively.
The second line contains binary string s (|s| = n, s_i ∈ \{0, 1\}, s_1 = s_n = 0) — the description of the road.
It's guaranteed that the total length of all strings s doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per query. For each query print the minimum possible cost of the constructed pipeline.
Example
Input
4
8 2 5
00110010
8 1 1
00110010
9 100000000 100000000
010101010
2 5 1
00
Output
94
25
2900000000
13
Note
The optimal pipeline for the first query is shown at the picture above.
The optimal pipeline for the second query is pictured below:
<image>
The optimal (and the only possible) pipeline for the third query is shown below:
<image>
The optimal pipeline for the fourth query is shown below:
<image>
Submitted Solution:
```
t = int(input())
for i in range(t):
n,x,y = map(int, input().split())
a =input()
if a=='0'*n:
print((n+1)*y+n*x)
else:
r1 = 0
r2 = 0
s = 1
b = []
S = 0
k = 0
for i in range(1,n):
if a[i]!=a[i-1]:
b.append(s)
s = 1
else:
s +=1
if a[i]=='0':
k+=1
b.append(s)
s = 0
for i in range(1,len(b)):
if i%2==1:
S+=b[i]*x+(b[i]+1)*y*2
for i in range(0,len(b)):
if i%2==0:
if i==0 or i==len(b)-1:
S+=b[i]*y+b[i]*x+x
else:
f1 = b[i]*x+(b[i]-1)*2*y
f2 = (b[i]+2)*x+(b[i]-1)*y
S+=min(f1,f2)
print(S)
```
Yes
| 1,753 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment [0, n] on OX axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval (x, x + 1) with integer x. So we can represent the road as a binary string consisting of n characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.
Usually, we can install the pipeline along the road on height of 1 unit with supporting pillars in each integer point (so, if we are responsible for [0, n] road, we must install n + 1 pillars). But on crossroads we should lift the pipeline up to the height 2, so the pipeline won't obstruct the way for cars.
We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment [x, x + 1] with integer x consisting of three parts: 0.5 units of horizontal pipe + 1 unit of vertical pipe + 0.5 of horizontal. Note that if pipeline is currently on height 2, the pillars that support it should also have length equal to 2 units.
<image>
Each unit of gas pipeline costs us a bourles, and each unit of pillar — b bourles. So, it's not always optimal to make the whole pipeline on the height 2. Find the shape of the pipeline with minimum possible cost and calculate that cost.
Note that you must start and finish the pipeline on height 1 and, also, it's guaranteed that the first and last characters of the input string are equal to 0.
Input
The fist line contains one integer T (1 ≤ T ≤ 100) — the number of queries. Next 2 ⋅ T lines contain independent queries — one query per two lines.
The first line contains three integers n, a, b (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ a ≤ 10^8, 1 ≤ b ≤ 10^8) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively.
The second line contains binary string s (|s| = n, s_i ∈ \{0, 1\}, s_1 = s_n = 0) — the description of the road.
It's guaranteed that the total length of all strings s doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per query. For each query print the minimum possible cost of the constructed pipeline.
Example
Input
4
8 2 5
00110010
8 1 1
00110010
9 100000000 100000000
010101010
2 5 1
00
Output
94
25
2900000000
13
Note
The optimal pipeline for the first query is shown at the picture above.
The optimal pipeline for the second query is pictured below:
<image>
The optimal (and the only possible) pipeline for the third query is shown below:
<image>
The optimal pipeline for the fourth query is shown below:
<image>
Submitted Solution:
```
import sys
input = sys.stdin.readline
T = int(input())
for _ in range(T):
n,a,b = map(int, input().split())
l = input().strip()
p = 0
cur = 0
ans = 0
if '1' not in l:
print(b * (n + 1) + a * n)
else:
while p < n:
if l[p] == '1':
ans1 = 2 * b * (p + 1) + p * a
ans2 = b * p + 2 * b + (p + 1) * a
ans += min(ans1, ans2)
break
else:
p += 1
cur = p
while p < n:
if l[p] == '1':
diff = p - cur
if diff <= 2:
ans += 2 * b * diff + a * diff
cur = p
p += 1
else:
ans1 = 2 * b * diff + a * diff
ans2 = 2 * b * 2 + b * (diff - 2) + a * (diff + 2)
ans += min(ans1, ans2)
cur = p
p += 1
else:
p += 1
diff = n - cur
ans += 2 * b + (diff - 1) * b + a * (diff + 1)
print(ans)
```
No
| 1,754 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment [0, n] on OX axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval (x, x + 1) with integer x. So we can represent the road as a binary string consisting of n characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.
Usually, we can install the pipeline along the road on height of 1 unit with supporting pillars in each integer point (so, if we are responsible for [0, n] road, we must install n + 1 pillars). But on crossroads we should lift the pipeline up to the height 2, so the pipeline won't obstruct the way for cars.
We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment [x, x + 1] with integer x consisting of three parts: 0.5 units of horizontal pipe + 1 unit of vertical pipe + 0.5 of horizontal. Note that if pipeline is currently on height 2, the pillars that support it should also have length equal to 2 units.
<image>
Each unit of gas pipeline costs us a bourles, and each unit of pillar — b bourles. So, it's not always optimal to make the whole pipeline on the height 2. Find the shape of the pipeline with minimum possible cost and calculate that cost.
Note that you must start and finish the pipeline on height 1 and, also, it's guaranteed that the first and last characters of the input string are equal to 0.
Input
The fist line contains one integer T (1 ≤ T ≤ 100) — the number of queries. Next 2 ⋅ T lines contain independent queries — one query per two lines.
The first line contains three integers n, a, b (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ a ≤ 10^8, 1 ≤ b ≤ 10^8) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively.
The second line contains binary string s (|s| = n, s_i ∈ \{0, 1\}, s_1 = s_n = 0) — the description of the road.
It's guaranteed that the total length of all strings s doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per query. For each query print the minimum possible cost of the constructed pipeline.
Example
Input
4
8 2 5
00110010
8 1 1
00110010
9 100000000 100000000
010101010
2 5 1
00
Output
94
25
2900000000
13
Note
The optimal pipeline for the first query is shown at the picture above.
The optimal pipeline for the second query is pictured below:
<image>
The optimal (and the only possible) pipeline for the third query is shown below:
<image>
The optimal pipeline for the fourth query is shown below:
<image>
Submitted Solution:
```
maxx = 100000000000000000000000000001
q=int(input())
for i in range(q):
ch=input()
L=[int(i)for i in ch.split()]
n=L[0]
a=L[1]
b=L[2]
ch=input()
M=[[b,maxx]]+[[maxx,maxx]for i in range(n)]
for j in range(1,n+1):
if j==n or not((ch[j-1]=='1')or(ch[j]=='1')) :
M[j][1]=min(M[j-1][0]+2*b+2*a,M[j-1][1]+2*b+a)
M[j][0]=min(M[j-1][0]+a+b , M[j-1][1]+2*a+b)
else:
M[j][1]=min(M[j-1][0]+2*b+2*a,M[j-1][1]+2*b+a)
print(min(M[-1][0],M[-1][1]))
```
No
| 1,755 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment [0, n] on OX axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval (x, x + 1) with integer x. So we can represent the road as a binary string consisting of n characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.
Usually, we can install the pipeline along the road on height of 1 unit with supporting pillars in each integer point (so, if we are responsible for [0, n] road, we must install n + 1 pillars). But on crossroads we should lift the pipeline up to the height 2, so the pipeline won't obstruct the way for cars.
We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment [x, x + 1] with integer x consisting of three parts: 0.5 units of horizontal pipe + 1 unit of vertical pipe + 0.5 of horizontal. Note that if pipeline is currently on height 2, the pillars that support it should also have length equal to 2 units.
<image>
Each unit of gas pipeline costs us a bourles, and each unit of pillar — b bourles. So, it's not always optimal to make the whole pipeline on the height 2. Find the shape of the pipeline with minimum possible cost and calculate that cost.
Note that you must start and finish the pipeline on height 1 and, also, it's guaranteed that the first and last characters of the input string are equal to 0.
Input
The fist line contains one integer T (1 ≤ T ≤ 100) — the number of queries. Next 2 ⋅ T lines contain independent queries — one query per two lines.
The first line contains three integers n, a, b (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ a ≤ 10^8, 1 ≤ b ≤ 10^8) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively.
The second line contains binary string s (|s| = n, s_i ∈ \{0, 1\}, s_1 = s_n = 0) — the description of the road.
It's guaranteed that the total length of all strings s doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per query. For each query print the minimum possible cost of the constructed pipeline.
Example
Input
4
8 2 5
00110010
8 1 1
00110010
9 100000000 100000000
010101010
2 5 1
00
Output
94
25
2900000000
13
Note
The optimal pipeline for the first query is shown at the picture above.
The optimal pipeline for the second query is pictured below:
<image>
The optimal (and the only possible) pipeline for the third query is shown below:
<image>
The optimal pipeline for the fourth query is shown below:
<image>
Submitted Solution:
```
import math
t = int(input())
for _ in range(t):
(n, a, b) = [int(x) for x in input().split()]
s = input()
#print((n, a, b, s))
gap = math.ceil((2 * a) / b) + 1
#print((a, b, gap))
cost = b
state = 0
b2 = 2 * b
streak0 = 0
for i in range(n-1):
if s[i] == '1':
streak0 = 0
else:
streak0 += 1
if s[i+1] == '1':
if streak0 >= gap and state:
cost -= (gap - 1) * b
cost += 2 * a
#print('down\nup')
if not state:
state = 1
cost += a
#print('up')
cost += a + b
if state:
cost += b
#print(str(i) + ' ' + str(cost))
cost += a + b
streak0 += 1
if state:
cost -= (streak0-1) * b
cost += a
#print('down')
print(cost)
```
No
| 1,756 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment [0, n] on OX axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval (x, x + 1) with integer x. So we can represent the road as a binary string consisting of n characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.
Usually, we can install the pipeline along the road on height of 1 unit with supporting pillars in each integer point (so, if we are responsible for [0, n] road, we must install n + 1 pillars). But on crossroads we should lift the pipeline up to the height 2, so the pipeline won't obstruct the way for cars.
We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment [x, x + 1] with integer x consisting of three parts: 0.5 units of horizontal pipe + 1 unit of vertical pipe + 0.5 of horizontal. Note that if pipeline is currently on height 2, the pillars that support it should also have length equal to 2 units.
<image>
Each unit of gas pipeline costs us a bourles, and each unit of pillar — b bourles. So, it's not always optimal to make the whole pipeline on the height 2. Find the shape of the pipeline with minimum possible cost and calculate that cost.
Note that you must start and finish the pipeline on height 1 and, also, it's guaranteed that the first and last characters of the input string are equal to 0.
Input
The fist line contains one integer T (1 ≤ T ≤ 100) — the number of queries. Next 2 ⋅ T lines contain independent queries — one query per two lines.
The first line contains three integers n, a, b (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ a ≤ 10^8, 1 ≤ b ≤ 10^8) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively.
The second line contains binary string s (|s| = n, s_i ∈ \{0, 1\}, s_1 = s_n = 0) — the description of the road.
It's guaranteed that the total length of all strings s doesn't exceed 2 ⋅ 10^5.
Output
Print T integers — one per query. For each query print the minimum possible cost of the constructed pipeline.
Example
Input
4
8 2 5
00110010
8 1 1
00110010
9 100000000 100000000
010101010
2 5 1
00
Output
94
25
2900000000
13
Note
The optimal pipeline for the first query is shown at the picture above.
The optimal pipeline for the second query is pictured below:
<image>
The optimal (and the only possible) pipeline for the third query is shown below:
<image>
The optimal pipeline for the fourth query is shown below:
<image>
Submitted Solution:
```
from sys import stdin
input=stdin.readline
#import bisect
#i = bisect.bisect_left(a, k)
for _ in range (int(input())):
n,p,q=map(int, input().split())
s=input()
l=list(s)
cnt=0
if s.count('1')==0:
print(((q*(n+1))+(p*n)))
exit()
a=[0]
b=[1]
k=1
for i in range(1,n):
if s[i]==s[i-1]:
b[-1]+=1
continue
else:
a.append(int(s[i]))
b.append(1)
k=1
cp=1
#print(a,b)
ans=q
for i in range(len(a)):
n=b[i]
#print(ans)
if i==len(a)-1:
ans+=((n+1)*p)+(q*n)
break
if a[i]==0:
if cp==1:
ans+=(p*(n+1))
ans+=((n-1)*q)
cp=2
else:
ans+=( min( ((n+2)*p)+((n-1)*q), ((n)*p)+((n-1)*(2*q)) ))
cp=2
else:
ans+=(((n)*p)+((2*q)*(n+1)))
print(ans)
```
No
| 1,757 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n positive integers a_1, …, a_n, and an integer k ≥ 2. Count the number of pairs i, j such that 1 ≤ i < j ≤ n, and there exists an integer x such that a_i ⋅ a_j = x^k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100).
The second line contains n integers a_1, …, a_n (1 ≤ a_i ≤ 10^5).
Output
Print a single integer — the number of suitable pairs.
Example
Input
6 3
1 3 9 8 24 1
Output
5
Note
In the sample case, the suitable pairs are:
* a_1 ⋅ a_4 = 8 = 2^3;
* a_1 ⋅ a_6 = 1 = 1^3;
* a_2 ⋅ a_3 = 27 = 3^3;
* a_3 ⋅ a_5 = 216 = 6^3;
* a_4 ⋅ a_6 = 8 = 2^3.
Tags: hashing, math, number theory
Correct Solution:
```
import sys
input=sys.stdin.readline
from collections import defaultdict
n,k=map(int,input().split())
a=list(map(int,input().split()))
dd=defaultdict(int)
ans=0
for aa in a:
primes=[]
b=aa
for j in range(2,int(b**0.5)+1):
if b%j==0:
cnt=0
while b%j==0:
cnt+=1
b//=j
primes.append([j,cnt])
if b>1:
primes.append([b,1])
key1,key2=1,1
for p,c in primes:
if c%k!=0:
key1*=p**(c%k)
key2*=p**(k-c%k)
ans+=dd[key2]
dd[key1]+=1
print(ans)
```
| 1,758 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n positive integers a_1, …, a_n, and an integer k ≥ 2. Count the number of pairs i, j such that 1 ≤ i < j ≤ n, and there exists an integer x such that a_i ⋅ a_j = x^k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100).
The second line contains n integers a_1, …, a_n (1 ≤ a_i ≤ 10^5).
Output
Print a single integer — the number of suitable pairs.
Example
Input
6 3
1 3 9 8 24 1
Output
5
Note
In the sample case, the suitable pairs are:
* a_1 ⋅ a_4 = 8 = 2^3;
* a_1 ⋅ a_6 = 1 = 1^3;
* a_2 ⋅ a_3 = 27 = 3^3;
* a_3 ⋅ a_5 = 216 = 6^3;
* a_4 ⋅ a_6 = 8 = 2^3.
Tags: hashing, math, number theory
Correct Solution:
```
n, k = map(int, input().split())
a = list(map(int, input().split()))
d = {}
ans = 0
for el in a:
i = 2
a = []
b = []
while i*i <= el:
cnt = 0
while not(el%i):
el //= i
cnt += 1
if cnt%k:
a.append((i, cnt%k))
b.append((i, k-(cnt%k)))
i += 1
if el > 1:
a.append((el, 1))
b.append((el, k-1))
a = tuple(a)
b = tuple(b)
ans += d.get(b, 0)
d[a] = d.get(a, 0)+1
print(ans)
```
| 1,759 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n positive integers a_1, …, a_n, and an integer k ≥ 2. Count the number of pairs i, j such that 1 ≤ i < j ≤ n, and there exists an integer x such that a_i ⋅ a_j = x^k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100).
The second line contains n integers a_1, …, a_n (1 ≤ a_i ≤ 10^5).
Output
Print a single integer — the number of suitable pairs.
Example
Input
6 3
1 3 9 8 24 1
Output
5
Note
In the sample case, the suitable pairs are:
* a_1 ⋅ a_4 = 8 = 2^3;
* a_1 ⋅ a_6 = 1 = 1^3;
* a_2 ⋅ a_3 = 27 = 3^3;
* a_3 ⋅ a_5 = 216 = 6^3;
* a_4 ⋅ a_6 = 8 = 2^3.
Tags: hashing, math, number theory
Correct Solution:
```
from collections import defaultdict
# The largest prime of that divides i where 2 <= i <= N
largerPrime = list(range(10**5+1))
def largestPrime(N = 10**5):
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
#[0, 1, 2, 3, 2, 5, 3, 7, 2, 3, 5, 11, 3, 13, 7, 5, 2, 17, 3, 19, 5, 7, 11, 23, 3, 5, 13, 3, 7, 29, 5]
for i in range(2,N+1):
if(largerPrime[i] == i):
for j in range(i*2,N+1,i):
largerPrime[j] = i
largestPrime()
# Requires largerPrime Array (Type math.largestPrime to Access the array)
def primeFactors(n, k): # N Log log N
primeFactors = defaultdict(int)
while(n!=1):
primeFactors[largerPrime[n]] += 1
primeFactors[largerPrime[n]] %= k
n = int(n/largerPrime[n])
return primeFactors
def negate(pair, k):
neg = []
for key in pair:
if(pair[key]):
neg.append((key, k - pair[key]))
neg.sort()
if(neg):
return neg
return 1
n, k = map(int,input().split())
arr = [int(x) for x in input().split()]
one = 0
ans = 0
d = defaultdict(int)
for i in arr:
fac = primeFactors(i, k)
x = negate(fac, k)
if(x == 1):
ans += one
one += 1
else:
x = tuple(x)
ans += d[x]
save = []
for key in fac:
if(fac[key]):
save.append((key, fac[key]))
save.sort()
d[tuple(save)] += 1
print(ans)
```
| 1,760 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n positive integers a_1, …, a_n, and an integer k ≥ 2. Count the number of pairs i, j such that 1 ≤ i < j ≤ n, and there exists an integer x such that a_i ⋅ a_j = x^k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100).
The second line contains n integers a_1, …, a_n (1 ≤ a_i ≤ 10^5).
Output
Print a single integer — the number of suitable pairs.
Example
Input
6 3
1 3 9 8 24 1
Output
5
Note
In the sample case, the suitable pairs are:
* a_1 ⋅ a_4 = 8 = 2^3;
* a_1 ⋅ a_6 = 1 = 1^3;
* a_2 ⋅ a_3 = 27 = 3^3;
* a_3 ⋅ a_5 = 216 = 6^3;
* a_4 ⋅ a_6 = 8 = 2^3.
Tags: hashing, math, number theory
Correct Solution:
```
from collections import defaultdict
n, k = map(int, input().split())
a = list(map(int, input().split()))
n = int(max(a)**.5)
mark = [True]*(n+1)
primes = []
for i in range(2,n+1):
if mark[i]:
primes.append(i)
for j in range(i, n+1, i): mark[j] = False
d = defaultdict(int)
ans = 0
for i in a:
t, t1 = [], []
for j in primes:
if i%j == 0:
x = 0
while i%j==0:
i//=j
x += 1
z = x%k
if z:
t.append((j,z))
t1.append((j,k-z))
elif i == 1:break
if i != 1:
t.append((i,1))
t1.append((i,k-1))
t = tuple(t)
t1 = tuple(t1)
ans += d[t1]
d[t] += 1
print(ans)
```
| 1,761 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n positive integers a_1, …, a_n, and an integer k ≥ 2. Count the number of pairs i, j such that 1 ≤ i < j ≤ n, and there exists an integer x such that a_i ⋅ a_j = x^k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100).
The second line contains n integers a_1, …, a_n (1 ≤ a_i ≤ 10^5).
Output
Print a single integer — the number of suitable pairs.
Example
Input
6 3
1 3 9 8 24 1
Output
5
Note
In the sample case, the suitable pairs are:
* a_1 ⋅ a_4 = 8 = 2^3;
* a_1 ⋅ a_6 = 1 = 1^3;
* a_2 ⋅ a_3 = 27 = 3^3;
* a_3 ⋅ a_5 = 216 = 6^3;
* a_4 ⋅ a_6 = 8 = 2^3.
Tags: hashing, math, number theory
Correct Solution:
```
# -*- coding:utf-8 -*-
"""
created by shuangquan.huang at 2/11/20
"""
import collections
import time
import os
import sys
import bisect
import heapq
from typing import List
import math
def factors(val):
wc = []
for i in range(2, int(math.sqrt(val)) + 2):
if i > val:
break
if val % i == 0:
c = 0
while val % i == 0:
c += 1
val //= i
wc.append((i, c))
if val > 1:
wc.append((val, 1))
return wc
def expand(fc, maxd, k):
def dfs(index, mul):
if index >= len(fc):
return [mul]
w, c = fc[index]
d = k - (c % k) if c % k != 0 else 0
x = []
t = mul * (w ** d)
while t <= maxd:
x.extend(dfs(index + 1, t))
d += k
t *= w**k
return x
return dfs(0, 1)
def solve(N, K, A):
wc = collections.defaultdict(int)
ans = 0
for v in A:
fc = factors(v)
fc = [(f, c % K) for f, c in fc if c % K != 0]
key = '_'.join(['{}+{}'.format(f, c) for f, c in fc])
cov = [(f, K-c) for f, c in fc]
ckey = '_'.join(['{}+{}'.format(f, c) for f, c in cov])
ans += wc[ckey]
wc[key] += 1
return ans
N, K = map(int, input().split())
A = [int(x) for x in input().split()]
print(solve(N, K, A))
```
| 1,762 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n positive integers a_1, …, a_n, and an integer k ≥ 2. Count the number of pairs i, j such that 1 ≤ i < j ≤ n, and there exists an integer x such that a_i ⋅ a_j = x^k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100).
The second line contains n integers a_1, …, a_n (1 ≤ a_i ≤ 10^5).
Output
Print a single integer — the number of suitable pairs.
Example
Input
6 3
1 3 9 8 24 1
Output
5
Note
In the sample case, the suitable pairs are:
* a_1 ⋅ a_4 = 8 = 2^3;
* a_1 ⋅ a_6 = 1 = 1^3;
* a_2 ⋅ a_3 = 27 = 3^3;
* a_3 ⋅ a_5 = 216 = 6^3;
* a_4 ⋅ a_6 = 8 = 2^3.
Tags: hashing, math, number theory
Correct Solution:
```
import math as mt
from typing import Counter
# Calculando SPF (Smallest Prime Factor)
# para todo número hasta MAXN.
def sieve():
spf[1] = 1
for i in range(2, MAXN):
# Marcando como SPF de cada número
# para que sea el mismo
spf[i] = i
# Por separado se marca como spf
# de todo número par al 2
for i in range(4, MAXN, 2):
spf[i] = 2
for i in range(3, mt.ceil(mt.sqrt(MAXN))):
# Verificando si i es primo
if (spf[i] == i):
# Marcando spf para todo número
# divisible por i
for j in range(i * i, MAXN, i):
# Marcando spf[j] si no fue
# anteriormente marcado
if (spf[j] == j):
spf[j] = i
# Función que obtendrá la factorización
# prima módulo k de x, dividiendo por
# el spf en cada paso, y la retornará
# como tuplas (factor, exponente)
def getFactorization(x, k):
li = dict()
while (x != 1):
# Si no existe dicha llave se crea
if not spf[x] in li:
li[spf[x]] = 0
# Tantas veces como spf[x] divida a
# x será el valor de su exponente
li[spf[x]] += 1
# Si el exponente llega a k
# se elimina el factor pues
# al exponente se le efectúa mod k
if li[spf[x]] == k:
del li[spf[x]]
# Se divide x para encontrar
# el próximo factor
x = x // spf[x]
# Se computa la factorización módulo k
# del a_j necesario
li_prime = li.copy()
for i in li_prime.keys():
li_prime[i] = k - li_prime[i]
# Se devuelven ambas factorizaciones en forma de tupla de tuplas
return tuple(li.items()), tuple(li_prime.items())
# Función que devuelve la cantidad de pares
# que cumplan la condición del problema.
def Solution(n, k, array):
# Mapa (descomposición mod k, cant de apariciones)
lists = dict()
# Precálculo de la criba
sieve()
count = 0
for i in array:
# Comprueba si se ha calculado
# la descomposición mod k anteriormente
if len(mask_li[i]) == 0:
# Si no, hay que calcularlas
li, li_prime = getFactorization(i,k)
mask_li[i] = li
mask_li_prime[i] = li_prime
# Si la descomposición que machea con
# la de a_i está en el mapa sumamos a la respuesta
# la cantidad de apariciones
if mask_li_prime[i] in lists:
count += lists[mask_li_prime[i]]
# Se suma 1 a la cantidad de apariciones
# de la descomposición mod k de a_i pues
# ella puede ser el match para otra a_i
if mask_li[i] in lists:
lists[mask_li[i]] += 1
# Si la descomposición no existía
# se crea el nuevo par con aparición
# igua a 1
else : lists[mask_li[i]] = 1
return count
# Fragmento para computar la entrada
values = input().split()
n, k = int(values[0]), int(values[1])
a = list(map(int, input().split()))
# Se guarda el entero más grande
# de la entrada pues hasta ese valor
# se calculará la criba
maximun = max(a)
MAXN = maximun + 1
# Máscaras que guardarán las factorizaciones
# calculadas hasta el momento para evitar
# calcular factorizaciones que ya se hayan hecho
mask_li = [() for i in range(0, maximun + 1)]
mask_li_prime = [() for i in range(0, maximun + 1)]
# Almacena factor primo más
# pequeño para cada número
spf = [0 for i in range(MAXN)]
result = Solution(n, k, a)
print(result)
```
| 1,763 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n positive integers a_1, …, a_n, and an integer k ≥ 2. Count the number of pairs i, j such that 1 ≤ i < j ≤ n, and there exists an integer x such that a_i ⋅ a_j = x^k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100).
The second line contains n integers a_1, …, a_n (1 ≤ a_i ≤ 10^5).
Output
Print a single integer — the number of suitable pairs.
Example
Input
6 3
1 3 9 8 24 1
Output
5
Note
In the sample case, the suitable pairs are:
* a_1 ⋅ a_4 = 8 = 2^3;
* a_1 ⋅ a_6 = 1 = 1^3;
* a_2 ⋅ a_3 = 27 = 3^3;
* a_3 ⋅ a_5 = 216 = 6^3;
* a_4 ⋅ a_6 = 8 = 2^3.
Tags: hashing, math, number theory
Correct Solution:
```
from math import sqrt
def gd(n, k):
ans = 1
obrans = 1
for i in range(2, int(sqrt(n) + 1)):
j = 0
while n % i == 0:
j += 1
n //= i
ans *= pow(i, j%k)
obrans *= pow(i, (-j)%k)
ans *= n
obrans *= pow(n, (k-1))
return ans, obrans
n, k = map(int,input().split())
oba = set()
dct = {}
for i in list(map(int,input().split())):
a,b = gd(i, k)
dct[a] = dct.get(a, 0) + 1
a,b = min(a,b), max(a,b)
oba.add((a,b))
ans = 0
for i, j in oba:
if i == j:
ans += (dct.get(i, 0) * dct.get(j, 0) - dct.get(i, 0)) // 2
else:
ans += dct.get(i, 0) * dct.get(j, 0)
print(ans)
```
| 1,764 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n positive integers a_1, …, a_n, and an integer k ≥ 2. Count the number of pairs i, j such that 1 ≤ i < j ≤ n, and there exists an integer x such that a_i ⋅ a_j = x^k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100).
The second line contains n integers a_1, …, a_n (1 ≤ a_i ≤ 10^5).
Output
Print a single integer — the number of suitable pairs.
Example
Input
6 3
1 3 9 8 24 1
Output
5
Note
In the sample case, the suitable pairs are:
* a_1 ⋅ a_4 = 8 = 2^3;
* a_1 ⋅ a_6 = 1 = 1^3;
* a_2 ⋅ a_3 = 27 = 3^3;
* a_3 ⋅ a_5 = 216 = 6^3;
* a_4 ⋅ a_6 = 8 = 2^3.
Tags: hashing, math, number theory
Correct Solution:
```
n, k = map(int, input().split())
arr = list(map(int, input().split()))
ans = 0
d = {}
for i in range(n):
x = 2
a = []
b = []
y = arr[i]
while x * x <= arr[i]:
if arr[i] % x == 0:
c = 0
while y % x == 0:
y = y // x
c += 1
if c % k > 0:
a.append((x, c % k))
b.append((x, k - (c % k)))
x += 1
if y > 1:
a.append((y, 1 % k))
b.append((y, k - (1 % k)))
try:
ans += d[tuple(b)]
except:
pass
try:
d[tuple(a)] += 1
except:
d[tuple(a)] = 1
print(ans)
```
| 1,765 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n positive integers a_1, …, a_n, and an integer k ≥ 2. Count the number of pairs i, j such that 1 ≤ i < j ≤ n, and there exists an integer x such that a_i ⋅ a_j = x^k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100).
The second line contains n integers a_1, …, a_n (1 ≤ a_i ≤ 10^5).
Output
Print a single integer — the number of suitable pairs.
Example
Input
6 3
1 3 9 8 24 1
Output
5
Note
In the sample case, the suitable pairs are:
* a_1 ⋅ a_4 = 8 = 2^3;
* a_1 ⋅ a_6 = 1 = 1^3;
* a_2 ⋅ a_3 = 27 = 3^3;
* a_3 ⋅ a_5 = 216 = 6^3;
* a_4 ⋅ a_6 = 8 = 2^3.
Submitted Solution:
```
from collections import Counter as C
NN = 100000
X = [-1] * (NN+1)
L = [[] for _ in range(NN+1)]
k = 2
while k <= NN:
X[k] = 1
L[k].append(k)
for i in range(k*2, NN+1, k):
X[i] = 0
L[i].append(k)
d = 2
while k**d <= NN:
for i in range(k**d, NN+1, k**d):
L[i].append(k)
d += 1
while k <= NN and X[k] >= 0:
k += 1
P = [i for i in range(NN+1) if X[i] == 1]
K = 4
def free(ct):
a = 1
for c in ct:
a *= c ** (ct[c] % K)
return a
def inv(ct):
a = 1
for c in ct:
a *= c ** (-ct[c] % K)
return a
N, K = map(int, input().split())
A = [int(a) for a in input().split()]
D = {}
ans = 0
for a in A:
c = C(L[a])
invc = inv(c)
if invc in D:
ans += D[invc]
freec = free(c)
if freec in D:
D[freec] += 1
else:
D[freec] = 1
print(ans)
```
Yes
| 1,766 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n positive integers a_1, …, a_n, and an integer k ≥ 2. Count the number of pairs i, j such that 1 ≤ i < j ≤ n, and there exists an integer x such that a_i ⋅ a_j = x^k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100).
The second line contains n integers a_1, …, a_n (1 ≤ a_i ≤ 10^5).
Output
Print a single integer — the number of suitable pairs.
Example
Input
6 3
1 3 9 8 24 1
Output
5
Note
In the sample case, the suitable pairs are:
* a_1 ⋅ a_4 = 8 = 2^3;
* a_1 ⋅ a_6 = 1 = 1^3;
* a_2 ⋅ a_3 = 27 = 3^3;
* a_3 ⋅ a_5 = 216 = 6^3;
* a_4 ⋅ a_6 = 8 = 2^3.
Submitted Solution:
```
import math
from collections import Counter
n, k = map(int, input().split())
a = list(map(int, input().split()))
ans = 0
prev = Counter()
for x in a:
sig = []
p = 2
while p <= math.sqrt(x):
cnt = 0
while x % p == 0:
cnt += 1
x = x // p
cnt = cnt % k
if cnt > 0:
sig.append((p, cnt))
p += 1
if x > 1:
sig.append((x, 1))
com_sig = []
for p, val in sig:
com_sig.append((p, (k - val) % k))
ans += prev[tuple(sig)]
prev[tuple(com_sig)] += 1
print(ans)
```
Yes
| 1,767 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n positive integers a_1, …, a_n, and an integer k ≥ 2. Count the number of pairs i, j such that 1 ≤ i < j ≤ n, and there exists an integer x such that a_i ⋅ a_j = x^k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100).
The second line contains n integers a_1, …, a_n (1 ≤ a_i ≤ 10^5).
Output
Print a single integer — the number of suitable pairs.
Example
Input
6 3
1 3 9 8 24 1
Output
5
Note
In the sample case, the suitable pairs are:
* a_1 ⋅ a_4 = 8 = 2^3;
* a_1 ⋅ a_6 = 1 = 1^3;
* a_2 ⋅ a_3 = 27 = 3^3;
* a_3 ⋅ a_5 = 216 = 6^3;
* a_4 ⋅ a_6 = 8 = 2^3.
Submitted Solution:
```
# Legends Always Come Up with Solution
# Author: Manvir Singh
import os
import sys
from io import BytesIO, IOBase
from collections import Counter
def seieve_prime_factorisation(n):
p,i=[1]*(n+1),2
while i*i<=n:
if p[i]==1:
for j in range(i*i,n+1,i):
p[j]=i
i+=1
return p
def prime_factorisation_by_seive(p,x):
c=Counter()
while p[x]!=1:
c[p[x]]+=1
x=x//p[x]
c[x]+=1
return c
def main():
n,k=map(int,input().split())
a=list(map(int,input().split()))
ma=max(a)
p=seieve_prime_factorisation(ma)
b=Counter()
ans,z=0,0
for i in a:
if i!=1:
c,d=[],[]
e=prime_factorisation_by_seive(p,i)
for j in sorted(e.keys()):
y=e[j]%k
if y:
c.append((j,y))
d.append((j,k-y))
if c:
c,d=tuple(c),tuple(d)
b[c]+=1
ans+=b[d]-(c==d)
else:
z+=1
else:
z+=1
print(ans+z*(z-1)//2)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
```
Yes
| 1,768 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n positive integers a_1, …, a_n, and an integer k ≥ 2. Count the number of pairs i, j such that 1 ≤ i < j ≤ n, and there exists an integer x such that a_i ⋅ a_j = x^k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100).
The second line contains n integers a_1, …, a_n (1 ≤ a_i ≤ 10^5).
Output
Print a single integer — the number of suitable pairs.
Example
Input
6 3
1 3 9 8 24 1
Output
5
Note
In the sample case, the suitable pairs are:
* a_1 ⋅ a_4 = 8 = 2^3;
* a_1 ⋅ a_6 = 1 = 1^3;
* a_2 ⋅ a_3 = 27 = 3^3;
* a_3 ⋅ a_5 = 216 = 6^3;
* a_4 ⋅ a_6 = 8 = 2^3.
Submitted Solution:
```
#!/usr/bin/python3
import array
import math
import os
import sys
def main():
init_primes()
N, K = read_ints()
A = read_ints()
print(solve(N, K, A))
PRIMES = []
PMAX = 100000
def init_primes():
b = [0] * (PMAX + 1)
for i in range(2, PMAX + 1):
if not b[i]:
PRIMES.append(i)
for j in range(i + i, PMAX + 1, i):
b[j] = 1
def solve(N, K, A):
high = max(A)
D = dict()
for a in A:
if a not in D:
D[a] = 0
D[a] += 1
ans = 0
for a, c in D.items():
if a == 1:
ans += c * (c - 1)
continue
b = 1
x = a
for p in PRIMES:
if x == 1:
break
if x % p == 0:
b *= p
x //= p
while x % p == 0:
x //= p
assert x == 1
#dprint('a:', a, 'b:', b)
p = b ** K
i = 1
while True:
x = (i ** K) * p
#dprint(' x:', x)
if x > high * high:
break
if x % a == 0:
y = x // a
#dprint(' y:', y)
if a == y:
ans += c * (c - 1)
#dprint(' +', c * (c - 1))
elif y in D:
f = 1
if y == 1:
f = 2
ans += f * c * D[y]
#dprint(' +', f * c * D[y])
i += 1
return ans // 2
###############################################################################
# AUXILIARY FUNCTIONS
DEBUG = 'DEBUG' in os.environ
def inp():
return sys.stdin.readline().rstrip()
def read_int():
return int(inp())
def read_ints():
return [int(e) for e in inp().split()]
def dprint(*value, sep=' ', end='\n'):
if DEBUG:
print(*value, sep=sep, end=end)
if __name__ == '__main__':
main()
```
Yes
| 1,769 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n positive integers a_1, …, a_n, and an integer k ≥ 2. Count the number of pairs i, j such that 1 ≤ i < j ≤ n, and there exists an integer x such that a_i ⋅ a_j = x^k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100).
The second line contains n integers a_1, …, a_n (1 ≤ a_i ≤ 10^5).
Output
Print a single integer — the number of suitable pairs.
Example
Input
6 3
1 3 9 8 24 1
Output
5
Note
In the sample case, the suitable pairs are:
* a_1 ⋅ a_4 = 8 = 2^3;
* a_1 ⋅ a_6 = 1 = 1^3;
* a_2 ⋅ a_3 = 27 = 3^3;
* a_3 ⋅ a_5 = 216 = 6^3;
* a_4 ⋅ a_6 = 8 = 2^3.
Submitted Solution:
```
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 12 16:24:41 2019
# =============================================================================
# @author: Acer
# """
#
# n = int(input())
# dp = [[0 for x in range(10)] for y in range(n)]
# for i in range (0, 10):
# if (i != 0) and (i != 8):
# dp[0][i] = 1
# for i in range (1, n):
# dp[i][0] = dp[i - 1][4] + dp[i - 1][6]
# dp[i][1] = dp[i - 1][8] + dp[i - 1][6]
# dp[i][2] = dp[i - 1][7] + dp[i - 1][9]
# dp[i][3] = dp[i - 1][4] + dp[i - 1][8]
# dp[i][4] = dp[i - 1][3] + dp[i - 1][9] + dp[i - 1][0]
# dp[i][6] = dp[i - 1][1] + dp[i - 1][7] + dp[i - 1][0]
# dp[i][7] = dp[i - 1][2] + dp[i - 1][6]
# dp[i][8] = dp[i - 1][1] + dp[i - 1][3]
# dp[i][9] = dp[i - 1][4] + dp[i - 1][2]
# ans = 0;
# for j in range (0, 10):
# ans += dp[n - 1][j]
# # =============================================================================
# # print(ans)n
# # =============================================================================
#
# =============================================================================
import math
def fact(a):
res = {}
for i in range (2, int(math.sqrt(a)) + 1):
while a % i == 0:
if i in res:
res[i] += 1
else:
res[i] = 1
a /= i
if len(res) == 0:
res[a] = 1
res[1] = 1
return res
def process_list(a : []):
res = {}
for i in range (0, len(a)):
cur_fact = fact(a[i])
for k in cur_fact: # простые числа
pow = cur_fact[k]
if not k in res:
res[k] = {}
if not pow in res[k]:
res[k][pow] = [i]
else:
res[k][pow].append(i)
return res
n, k = map(int, input().split())
a = [int(x) for x in input().split()]
dict_primes = process_list(a) # простое число - степень - индексы
res = 0
for i in range (0, len(a)):
cur_fact = fact(a[i])
last_key = list(cur_fact.keys())[0]
last_val = cur_fact[last_key] % k
# print(last_key, last_val)
if last_key == 1:
last_val = k - 1
pos_vars = []
if last_val % k == 0:
pos_vars = list(range(i + 1, len(a)))
# print("!")
elif (k - last_val) in dict_primes[last_key]:
pos_vars = dict_primes[last_key][k - last_val]
for pv in pos_vars:
if pv <= i:
continue
pr = a[i] * a[pv]
# print (a[i], pv, pr)
x = int(round((math.pow(pr, 1 / k)), 0))
# print(x)
if (math.pow(x, k) == pr):
res += 1
# print(res)
print (res)
```
No
| 1,770 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n positive integers a_1, …, a_n, and an integer k ≥ 2. Count the number of pairs i, j such that 1 ≤ i < j ≤ n, and there exists an integer x such that a_i ⋅ a_j = x^k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100).
The second line contains n integers a_1, …, a_n (1 ≤ a_i ≤ 10^5).
Output
Print a single integer — the number of suitable pairs.
Example
Input
6 3
1 3 9 8 24 1
Output
5
Note
In the sample case, the suitable pairs are:
* a_1 ⋅ a_4 = 8 = 2^3;
* a_1 ⋅ a_6 = 1 = 1^3;
* a_2 ⋅ a_3 = 27 = 3^3;
* a_3 ⋅ a_5 = 216 = 6^3;
* a_4 ⋅ a_6 = 8 = 2^3.
Submitted Solution:
```
import math
def F(m):
L=[]
k=2
while True:
if m%k==0:
L.append(k)
m=m//k
else:
k+=1
if k>math.sqrt(m):
break
L.append(m)
k=0
while True:
if k>len(L)-KK:
break
else:
q=False
jt=k
while jt<k+KK-1:
if L[jt]!=L[jt+1]:
q=True
break
jt+=1
if q==False:
L=L[KK:]
k+=1
if not L:
L=[1]
return L
def FFF(a,b):
if len(a)!=len(b):
return False
if a[0][0]==1 and b[0][0]==1:
return True
k=0
while k<len(a):
if a[k][0]!=b[k][0]:
return False
if a[k][1]+b[k][1]!=KK:
return False
k+=1
return True
n,KK=map(int,input().split())
A=map(int,input().split())
B=[]
for i in A:
B.append(F(i))
B.sort()
C=[]
i=0
while i<len(B):
tmp=[]
e=0
while e < len(B[i]):
if len(tmp)==0:
tmp.append([B[i][e],1])
else:
if tmp[-1][0]==B[i][e]:
tmp[-1][1]+=1
else:
tmp.append([B[i][e],1])
e+=1
i+=1
C.append(tmp)
D=[]
last_i=0
i=1
while i<len(C):
if C[i]!=C[i-1]:
D.append([C[i-1],i-last_i])
last_i=i
i+=1
D.append([C[i-1],i-last_i])
ans=0
i=0
while True:
if i>=len(D):
break
k=i
while True:
if k==len(D):
i+=1
break
if FFF(D[i][0],D[k][0]):
if i==k:
ans+=D[i][1]*(D[k][1]-1)//2
i+=1
else:
ans+=D[i][1]*D[k][1]
D.pop(k)
i+=1
break
k+=1
print (ans)
```
No
| 1,771 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n positive integers a_1, …, a_n, and an integer k ≥ 2. Count the number of pairs i, j such that 1 ≤ i < j ≤ n, and there exists an integer x such that a_i ⋅ a_j = x^k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100).
The second line contains n integers a_1, …, a_n (1 ≤ a_i ≤ 10^5).
Output
Print a single integer — the number of suitable pairs.
Example
Input
6 3
1 3 9 8 24 1
Output
5
Note
In the sample case, the suitable pairs are:
* a_1 ⋅ a_4 = 8 = 2^3;
* a_1 ⋅ a_6 = 1 = 1^3;
* a_2 ⋅ a_3 = 27 = 3^3;
* a_3 ⋅ a_5 = 216 = 6^3;
* a_4 ⋅ a_6 = 8 = 2^3.
Submitted Solution:
```
n,k=input().split()
n=int(n)
k=int(k)
lst=input().split()
s=0
for i in range(n):
for j in range(n):
if j>i:
if pow(int(lst[i])*int(lst[j]),1.0/k).is_integer() or int(pow(int(lst[i])*int(lst[j]),1.0/k)*10)%10==9:
s+=1
#print(int(lst[i])*int(lst[j]))
print(s)
```
No
| 1,772 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n positive integers a_1, …, a_n, and an integer k ≥ 2. Count the number of pairs i, j such that 1 ≤ i < j ≤ n, and there exists an integer x such that a_i ⋅ a_j = x^k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100).
The second line contains n integers a_1, …, a_n (1 ≤ a_i ≤ 10^5).
Output
Print a single integer — the number of suitable pairs.
Example
Input
6 3
1 3 9 8 24 1
Output
5
Note
In the sample case, the suitable pairs are:
* a_1 ⋅ a_4 = 8 = 2^3;
* a_1 ⋅ a_6 = 1 = 1^3;
* a_2 ⋅ a_3 = 27 = 3^3;
* a_3 ⋅ a_5 = 216 = 6^3;
* a_4 ⋅ a_6 = 8 = 2^3.
Submitted Solution:
```
import math
n,k = [int(i) for i in input().split()]
ch = sorted([int(i) for i in input().split()])
c = 0
sch = 0
for i in ch[:-1]:
c += 1
for s in ch[c:]:
if s >= i:
r = math.exp(math.log(s*i)/k)
if (r - int(r)) <= 0.000000000000001:
sch += 1
print(sch)
```
No
| 1,773 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree, which consists of n vertices. Recall that a tree is a connected undirected graph without cycles.
<image> Example of a tree.
Vertices are numbered from 1 to n. All vertices have weights, the weight of the vertex v is a_v.
Recall that the distance between two vertices in the tree is the number of edges on a simple path between them.
Your task is to find the subset of vertices with the maximum total weight (the weight of the subset is the sum of weights of all vertices in it) such that there is no pair of vertices with the distance k or less between them in this subset.
Input
The first line of the input contains two integers n and k (1 ≤ n, k ≤ 200) — the number of vertices in the tree and the distance restriction, respectively.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^5), where a_i is the weight of the vertex i.
The next n - 1 lines contain edges of the tree. Edge i is denoted by two integers u_i and v_i — the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum total weight of the subset in which all pairs of vertices have distance more than k.
Examples
Input
5 1
1 2 3 4 5
1 2
2 3
3 4
3 5
Output
11
Input
7 2
2 1 2 1 2 1 1
6 4
1 5
3 1
2 3
7 5
7 4
Output
4
Tags: dp, trees
Correct Solution:
```
n, k = map(int, input().split())
a = list(map(int, input().split()))
g = {}
def dfs(v, p=-1):
c = [dfs(child, v) for child in g.get(v, set()) - {p}]
c.sort(key=len, reverse=True)
r = []
i = 0
while c:
if i >= len(c[-1]):
c.pop()
else:
o = max(i, k - i - 1)
s = q = 0
for x in c:
if len(x) <= o:
q = max(q, x[i])
else:
s += x[o]
q = max(q, x[i] - x[o])
r.append(q + s)
i += 1
r.append(0)
for i in range(len(r) - 1, 0, -1):
r[i - 1] = max(r[i - 1], r[i])
while len(r) > 1 and r[-2] == 0:
r.pop()
o = (r[k] if k < len(r) else 0) + a[v]
r.insert(0, max(o, r[0]))
return r
for _ in range(1, n):
u, v = map(lambda x: int(x) - 1, input().split())
g.setdefault(u, set()).add(v)
g.setdefault(v, set()).add(u)
print(dfs(0)[0])
```
| 1,774 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a permutation p_1, p_2, …, p_n.
In one move you can swap two adjacent values.
You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k.
Let f(k) be the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation.
You need to find f(1), f(2), …, f(n).
Input
The first line of input contains one integer n (1 ≤ n ≤ 200 000): the number of elements in the permutation.
The next line of input contains n integers p_1, p_2, …, p_n: given permutation (1 ≤ p_i ≤ n).
Output
Print n integers, the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation, for k=1, 2, …, n.
Examples
Input
5
5 4 3 2 1
Output
0 1 3 6 10
Input
3
1 2 3
Output
0 0 0
Tags: binary search, data structures
Correct Solution:
```
import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
class Binary_Indexed_Tree():
def __init__(self, n):
self.n = n
self.data = [0]*(n+1)
def add(self, i, x):
while i <= self.n:
self.data[i] += x
i += i & -i
def get(self, i):
return self.sum_range(i, i)
def sum(self, i):
ret = 0
while i:
ret += self.data[i]
i &= i-1
return ret
def sum_range(self, l, r):
return self.sum(r)-self.sum(l-1)
def lower_bound(self, w):
if w<=0:
return 0
i = 0
k = 1<<(self.n.bit_length())
while k:
if i+k <= self.n and self.data[i+k] < w:
w -= self.data[i+k]
i += k
k >>= 1
return i+1
n = int(input())
a = list(map(int, input().split()))
d = {j:i for i,j in enumerate(a)}
BIT1 = Binary_Indexed_Tree(n)
BIT2 = Binary_Indexed_Tree(n)
BIT3 = Binary_Indexed_Tree(n)
tentou = 0
ans = []
for i in range(n):
tmp = 0
p = d[i+1]
inv_p = n-p
tentou += BIT1.sum(inv_p)
BIT1.add(inv_p, 1)
BIT2.add(p+1, 1)
BIT3.add(p+1, p+1)
m = i//2+1
mean = BIT2.lower_bound(i//2+1)
tmp = 0
if i%2 == 0:
tmp -= m*(m-1)
else:
tmp -= m*m
tmp += tentou
left = BIT3.sum_range(1, mean)
right = BIT3.sum_range(mean, n)
if i%2 == 0:
left = mean*m - left
right = right - mean*m
else:
left = mean*m - left
right = right - mean*(m+1)
tmp += left + right
ans.append(tmp)
print(*ans)
```
| 1,775 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a permutation p_1, p_2, …, p_n.
In one move you can swap two adjacent values.
You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k.
Let f(k) be the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation.
You need to find f(1), f(2), …, f(n).
Input
The first line of input contains one integer n (1 ≤ n ≤ 200 000): the number of elements in the permutation.
The next line of input contains n integers p_1, p_2, …, p_n: given permutation (1 ≤ p_i ≤ n).
Output
Print n integers, the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation, for k=1, 2, …, n.
Examples
Input
5
5 4 3 2 1
Output
0 1 3 6 10
Input
3
1 2 3
Output
0 0 0
Tags: binary search, data structures
Correct Solution:
```
#Author:MVP
n = int(input())
arr = list(map(int,input().split()))
trees = [0]*(1+n)
dic = [0]*(n+1)
ans = [0]*n
def update(t,i,v):
while i < len(t):
t[i] += v
i += lowbit(i)
def lowbit(x):
return x&-x
def sum(t,i):
ans = 0
while i>0:
ans += t[i]
i -= lowbit(i)
return ans
def getmid(arr,l1,flag):
low,high = 1,n
if l1%2 == 0 and flag:
midv = l1//2
else:
midv = l1//2+1
#print(midv,l1,dic[i])
while low <= high:
mid = (low+high)//2
ret = sum(arr,mid)
if ret >= midv:
high = mid-1
else:
low = mid+1
return low
for i in range(n):
dic[arr[i]]=i+1
for i in range(1,n+1):
ans[i-1] += sum(trees,n)-sum(trees,dic[i])
if i>=2:
ans[i-1] += ans[i-2]
update(trees,dic[i],1)
visited = [0]*(1+n)
mid = 0
last = 0
for i in range(1,n+1):
update(visited,dic[i],1)
mid = getmid(visited,i,dic[i]>mid)
tt = sum(visited,dic[i])
minus = min(tt-1,i-tt)
tmp = abs(dic[i]-mid-(tt-sum(visited,mid)))- minus
#print(dic[i],mid,tt,sum(visited,mid),minus,i)
ans[i-1] += tmp+last
last = tmp+last
#print(ans,tmp,last,mid,i,dic[i])
print(" ".join(map(str,ans)))
```
| 1,776 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a permutation p_1, p_2, …, p_n.
In one move you can swap two adjacent values.
You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k.
Let f(k) be the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation.
You need to find f(1), f(2), …, f(n).
Input
The first line of input contains one integer n (1 ≤ n ≤ 200 000): the number of elements in the permutation.
The next line of input contains n integers p_1, p_2, …, p_n: given permutation (1 ≤ p_i ≤ n).
Output
Print n integers, the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation, for k=1, 2, …, n.
Examples
Input
5
5 4 3 2 1
Output
0 1 3 6 10
Input
3
1 2 3
Output
0 0 0
Tags: binary search, data structures
Correct Solution:
```
class Fenwick:
def __init__(self, max_val):
self.b = [0] * (max_val + 1)
def update(self, i, increment):
while i > 0 and i < len(self.b):
self.b[i] += increment
i += i & (-i)
def sum(self, i):
ans = 0
while i > 0:
ans += self.b[i]
i -= i & (-i)
return ans
def at_sum(self, k):
a, b = 0, len(self.b)
while a < b:
mid = (a + b) // 2
if k <= self.sum(mid):
b = mid
else:
a = mid + 1
return a
def solve(p):
pos = [0] * len(p)
for i, e in enumerate(p):
pos[e - 1] = i + 1
ans = 0
fenwick = Fenwick(len(p))
for i in range(1, len(p) + 1):
p = pos[i - 1]
fenwick.update(p, 1)
r = fenwick.sum(p)
m = (i + 1) // 2
if r <= m:
m = m + (i % 2 == 0)
ans += fenwick.at_sum(m) - p - m + 1 + i - r
else:
ans += p - fenwick.at_sum(m) + m - r
yield ans
input()
a = [int(_) for _ in input().split()]
print(*solve(a))
```
| 1,777 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a permutation p_1, p_2, …, p_n.
In one move you can swap two adjacent values.
You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k.
Let f(k) be the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation.
You need to find f(1), f(2), …, f(n).
Input
The first line of input contains one integer n (1 ≤ n ≤ 200 000): the number of elements in the permutation.
The next line of input contains n integers p_1, p_2, …, p_n: given permutation (1 ≤ p_i ≤ n).
Output
Print n integers, the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation, for k=1, 2, …, n.
Examples
Input
5
5 4 3 2 1
Output
0 1 3 6 10
Input
3
1 2 3
Output
0 0 0
Tags: binary search, data structures
Correct Solution:
```
import heapq
class DynamicMedian():
def __init__(self):
self.l_q = []
self.r_q = []
self.l_sum = 0
self.r_sum = 0
def add(self, val):
if len(self.l_q) == len(self.r_q):
self.l_sum += val
val = -heapq.heappushpop(self.l_q, -val)
self.l_sum -= val
heapq.heappush(self.r_q, val)
self.r_sum += val
else:
self.r_sum += val
val = heapq.heappushpop(self.r_q, val)
self.r_sum -= val
heapq.heappush(self.l_q, -val)
self.l_sum += val
def median_low(self):
if len(self.l_q) + 1 == len(self.r_q):
return self.r_q[0]
else:
return -self.l_q[0]
def median_high(self):
return self.r_q[0]
def minimum_query(self):
res1 = (len(self.l_q) * self.median_high() - self.l_sum)
res2 = (self.r_sum - len(self.r_q) * self.median_high())
return res1 + res2
#Binary Indexed Tree (Fenwick Tree)
class BIT():
def __init__(self, n):
self.n = n
self.bit = [0] * (n + 1)
def add(self, i, val):
i = i + 1
while i <= self.n:
self.bit[i] += val
i += i & -i
def _sum(self, i):
s = 0
while i > 0:
s += self.bit[i]
i -= i & -i
return s
def sum(self, i, j):
return self._sum(j) - self._sum(i)
import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
bit = BIT(n)
dm = DynamicMedian()
memo = {}
for i in range(n):
memo[a[i] - 1] = i
b = [0] * n
for i in range(n):
dm.add(memo[i])
b[i] = dm.minimum_query() - (i+1)**2 // 4
ans = [0] * n
tmp = 0
for i in range(len(a)):
bit.add(memo[i], 1)
tmp += bit.sum(memo[i] + 1, n)
ans[i] = tmp + b[i]
print(*ans)
```
| 1,778 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a permutation p_1, p_2, …, p_n.
In one move you can swap two adjacent values.
You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k.
Let f(k) be the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation.
You need to find f(1), f(2), …, f(n).
Input
The first line of input contains one integer n (1 ≤ n ≤ 200 000): the number of elements in the permutation.
The next line of input contains n integers p_1, p_2, …, p_n: given permutation (1 ≤ p_i ≤ n).
Output
Print n integers, the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation, for k=1, 2, …, n.
Examples
Input
5
5 4 3 2 1
Output
0 1 3 6 10
Input
3
1 2 3
Output
0 0 0
Tags: binary search, data structures
Correct Solution:
```
from bisect import bisect_right, bisect_left
# instead of AVLTree
class BITbisect():
def __init__(self, InputProbNumbers):
# 座圧
self.ind_to_co = [-10**18]
self.co_to_ind = {}
for ind, num in enumerate(sorted(list(set(InputProbNumbers)))):
self.ind_to_co.append(num)
self.co_to_ind[num] = ind+1
self.max = len(self.co_to_ind)
self.data = [0]*(self.max+1)
def __str__(self):
retList = []
for i in range(1, self.max+1):
x = self.ind_to_co[i]
if self.count(x):
c = self.count(x)
for _ in range(c):
retList.append(x)
return "[" + ", ".join([str(a) for a in retList]) + "]"
def __getitem__(self, key):
key += 1
s = 0
ind = 0
l = self.max.bit_length()
for i in reversed(range(l)):
if ind + (1<<i) <= self.max:
if s + self.data[ind+(1<<i)] < key:
s += self.data[ind+(1<<i)]
ind += (1<<i)
if ind == self.max or key < 0:
raise IndexError("BIT index out of range")
return self.ind_to_co[ind+1]
def __len__(self):
return self._query_sum(self.max)
def __contains__(self, num):
if not num in self.co_to_ind:
return False
return self.count(num) > 0
# 0からiまでの区間和
# 左に進んでいく
def _query_sum(self, i):
s = 0
while i > 0:
s += self.data[i]
i -= i & -i
return s
# i番目の要素にxを足す
# 上に登っていく
def _add(self, i, x):
while i <= self.max:
self.data[i] += x
i += i & -i
# 値xを挿入
def push(self, x):
if not x in self.co_to_ind:
raise KeyError("The pushing number didnt initialized")
self._add(self.co_to_ind[x], 1)
# 値xを削除
def delete(self, x):
if not x in self.co_to_ind:
raise KeyError("The deleting number didnt initialized")
if self.count(x) <= 0:
raise ValueError("The deleting number doesnt exist")
self._add(self.co_to_ind[x], -1)
# 要素xの個数
def count(self, x):
return self._query_sum(self.co_to_ind[x]) - self._query_sum(self.co_to_ind[x]-1)
# 値xを超える最低ind
def bisect_right(self, x):
if x in self.co_to_ind:
i = self.co_to_ind[x]
else:
i = bisect_right(self.ind_to_co, x) - 1
return self._query_sum(i)
# 値xを下回る最低ind
def bisect_left(self, x):
if x in self.co_to_ind:
i = self.co_to_ind[x]
else:
i = bisect_left(self.ind_to_co, x)
if i == 1:
return 0
return self._query_sum(i-1)
import sys
input = sys.stdin.readline
N = int(input())
A = list(map(int, input().split()))
Ind = [0]*(N+1)
for i, a in enumerate(A):
Ind[a] = i+1
Bit = BITbisect(list(range(N+1)))
ans = [0]
Bit.push(Ind[1])
a = 0
for n in range(2, N+1):
ind = Ind[n]
f = Bit.bisect_left(ind)
#print(Bit)
l = len(Bit)
if l%2 == 0:
if f == l//2:
a += l//2-l//2
elif f < l//2:
p1 = Bit[l//2-1]
a += (p1-ind-1) - (l//2-1) + l-f
else:
p2 = Bit[l//2]
a += (ind-p2-1) - (l//2-1) + l-f
else:
p1 = Bit[l//2]
#print(f, p1, ind, l)
if f <= l//2:
a += (p1-ind-1) - l//2 + l-f
else:
a += (ind-p1-1) - l//2 + l-f
ans.append(a)
Bit.push(ind)
print(*ans, sep=" ")
```
| 1,779 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a permutation p_1, p_2, …, p_n.
In one move you can swap two adjacent values.
You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k.
Let f(k) be the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation.
You need to find f(1), f(2), …, f(n).
Input
The first line of input contains one integer n (1 ≤ n ≤ 200 000): the number of elements in the permutation.
The next line of input contains n integers p_1, p_2, …, p_n: given permutation (1 ≤ p_i ≤ n).
Output
Print n integers, the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation, for k=1, 2, …, n.
Examples
Input
5
5 4 3 2 1
Output
0 1 3 6 10
Input
3
1 2 3
Output
0 0 0
Tags: binary search, data structures
Correct Solution:
```
n = int(input())
a = [0] + list(map(int, input().split()))
pos, pb, ps = [[0] * (n + 1) for x in range(3)]
def add(bit, i, val):
while i <= n:
bit[i] += val
i += i & -i
def sum(bit, i):
res = 0
while i > 0:
res += bit[i]
i -= i & -i
return res
def find(bit, sum):
i, t = 0, 0
if sum == 0:
return 0
for k in range(17, -1, -1):
i += 1 << k
if i <= n and t + bit[i] < sum:
t += bit[i]
else:
i -= 1 << k
return i + 1
for i in range(1, n + 1):
pos[a[i]] = i
invSum = 0
totalSum = 0
for i in range(1, n + 1):
totalSum += pos[i]
invSum += i - sum(pb, pos[i]) - 1
add(pb, pos[i], 1)
add(ps, pos[i], pos[i])
mid = find(pb, i // 2)
if i % 2 == 1:
mid2 = find(pb, i // 2 + 1)
seqSum = (i + 1) * (i // 2) // 2
else:
mid2 = mid
seqSum = i * (i // 2) // 2
leftSum = sum(ps, mid)
rightSum = totalSum - sum(ps, mid2)
print(rightSum - leftSum - seqSum + invSum, end=" ")
```
| 1,780 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a permutation p_1, p_2, …, p_n.
In one move you can swap two adjacent values.
You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k.
Let f(k) be the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation.
You need to find f(1), f(2), …, f(n).
Input
The first line of input contains one integer n (1 ≤ n ≤ 200 000): the number of elements in the permutation.
The next line of input contains n integers p_1, p_2, …, p_n: given permutation (1 ≤ p_i ≤ n).
Output
Print n integers, the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation, for k=1, 2, …, n.
Examples
Input
5
5 4 3 2 1
Output
0 1 3 6 10
Input
3
1 2 3
Output
0 0 0
Tags: binary search, data structures
Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
# all operations are log(n)
class bit:
def __init__(self, n):
self.n = n+1
self.mx_p = 0
while 1 << self.mx_p < self.n:
self.mx_p += 1
self.a = [0]*(self.n)
self.tot = 0
def add(self, idx, val):
self.tot += val
idx += 1
while idx < self.n:
self.a[idx] += val
idx += idx & -idx
def sum_prefix(self, idx):
tot = 0
idx += 1
while idx > 0:
tot += self.a[idx]
idx -= idx & -idx
return tot
def sum(self, l, r):
return self.sum_prefix(r) - self.sum_prefix(l-1)
# lowest idx such that sum_prefix(idx) = val else -1 if idx doesn't exist
# idx is the idx in the underlying array (idx-1)
def lower(self, val):
if val > self.tot:
return -1
tot = 0
idx = 0
for i in range(self.mx_p, -1, -1):
if idx + (1<<i) < self.n and tot + self.a[idx + (1 << i)] < val:
tot += self.a[idx + (1 << i)]
idx += 1 << i
return idx
n = int(input())
p = list(map(int,input().split()))
p = sorted([[p[i],i] for i in range(n)])
ones = bit(n+1) # 1 at positions
ones_idx = bit(n+1) # indices at positions
inversions = 0
for k in range(1,n+1):
val, i = p[k-1]
ones.add(i,1)
ones_idx.add(i,i)
inversions += ones.sum(i+1,n)
num1l = (k+1)//2
num1r = k - num1l
idxl = ones.lower((k+1)//2)
idxr = idxl + 1
num0l = idxl+1 - num1l
num0r = n - idxr - num1r
suml = ones_idx.sum_prefix(idxl)
sumr = ones_idx.tot - suml
movel = idxl*(idxl+1)//2 - suml - (num0l - 1)*(num0l)//2
mover = (n-1-idxr)*(n-1-idxr+1)//2 - (num1r*(n-1) - sumr) - (num0r-1)*(num0r)//2
print(inversions + movel + mover)
```
| 1,781 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a permutation p_1, p_2, …, p_n.
In one move you can swap two adjacent values.
You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k.
Let f(k) be the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation.
You need to find f(1), f(2), …, f(n).
Input
The first line of input contains one integer n (1 ≤ n ≤ 200 000): the number of elements in the permutation.
The next line of input contains n integers p_1, p_2, …, p_n: given permutation (1 ≤ p_i ≤ n).
Output
Print n integers, the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation, for k=1, 2, …, n.
Examples
Input
5
5 4 3 2 1
Output
0 1 3 6 10
Input
3
1 2 3
Output
0 0 0
Submitted Solution:
```
n = int(input())
l = list(map(int, input().split()))
i = 1
a = [0]
while i < n:
i1 = l.index(i)
i2 = l.index(i + 1)
if i2 > i1:
a.append(a[-1] + i2 - i1 - 1)
if a[-1] != a[-2]:
temp = []
if len(l[:i1+1]) > 1:
temp += l[:i1+1]
else:
temp += list(l[:i1+1])
temp += [l[i2]]
if len(l[i1+1:i2]) > 1:
temp += l[i1+1:i2]
else:
temp += list(l[i1+1:i2])
if len(l[i2+1:]) > 1:
temp += l[i2+1:]
else:
temp += list(l[i2+1:])
l = temp
else:
a.append(a[-1] + i1 - i2)
temp = []
if a[-1] != a[-2]:
if len(l[:i2]) > 1:
temp += l[:i2]
else:
temp += list(l[:i2])
if len(l[i2+1:i1]) > 1:
temp += l[i2+1:i1]
else:
temp += list(l[i2+1:i1])
temp += [l[i1], l[i2]]
if len(l[i1+1:]) > 1:
temp += l[i1+1:]
else:
temp += list(l[i1+1:])
l = temp
i += 1
print(*a, sep=' ')
```
No
| 1,782 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a permutation p_1, p_2, …, p_n.
In one move you can swap two adjacent values.
You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k.
Let f(k) be the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation.
You need to find f(1), f(2), …, f(n).
Input
The first line of input contains one integer n (1 ≤ n ≤ 200 000): the number of elements in the permutation.
The next line of input contains n integers p_1, p_2, …, p_n: given permutation (1 ≤ p_i ≤ n).
Output
Print n integers, the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation, for k=1, 2, …, n.
Examples
Input
5
5 4 3 2 1
Output
0 1 3 6 10
Input
3
1 2 3
Output
0 0 0
Submitted Solution:
```
from bisect import bisect_right, bisect_left
# instead of AVLTree
class BITbisect():
def __init__(self, InputProbNumbers):
# 座圧
self.ind_to_co = [-10**18]
self.co_to_ind = {}
for ind, num in enumerate(sorted(list(set(InputProbNumbers)))):
self.ind_to_co.append(num)
self.co_to_ind[num] = ind+1
self.max = len(self.co_to_ind)
self.data = [0]*(self.max+1)
def __str__(self):
retList = []
for i in range(1, self.max+1):
x = self.ind_to_co[i]
if self.count(x):
c = self.count(x)
for _ in range(c):
retList.append(x)
return "[" + ", ".join([str(a) for a in retList]) + "]"
def __getitem__(self, key):
key += 1
s = 0
ind = 0
l = self.max.bit_length()
for i in reversed(range(l)):
if ind + (1<<i) <= self.max:
if s + self.data[ind+(1<<i)] < key:
s += self.data[ind+(1<<i)]
ind += (1<<i)
if ind == self.max or key < 0:
raise IndexError("BIT index out of range")
return self.ind_to_co[ind+1]
def __len__(self):
return self._query_sum(self.max)
def __contains__(self, num):
if not num in self.co_to_ind:
return False
return self.count(num) > 0
# 0からiまでの区間和
# 左に進んでいく
def _query_sum(self, i):
s = 0
while i > 0:
s += self.data[i]
i -= i & -i
return s
# i番目の要素にxを足す
# 上に登っていく
def _add(self, i, x):
while i <= self.max:
self.data[i] += x
i += i & -i
# 値xを挿入
def push(self, x):
if not x in self.co_to_ind:
raise KeyError("The pushing number didnt initialized")
self._add(self.co_to_ind[x], 1)
# 値xを削除
def delete(self, x):
if not x in self.co_to_ind:
raise KeyError("The deleting number didnt initialized")
if self.count(x) <= 0:
raise ValueError("The deleting number doesnt exist")
self._add(self.co_to_ind[x], -1)
# 要素xの個数
def count(self, x):
return self._query_sum(self.co_to_ind[x]) - self._query_sum(self.co_to_ind[x]-1)
# 値xを超える最低ind
def bisect_right(self, x):
if x in self.co_to_ind:
i = self.co_to_ind[x]
else:
i = bisect_right(self.ind_to_co, x) - 1
return self._query_sum(i)
# 値xを下回る最低ind
def bisect_left(self, x):
if x in self.co_to_ind:
i = self.co_to_ind[x]
else:
i = bisect_left(self.ind_to_co, x)
if i == 1:
return 0
return self._query_sum(i-1)
import sys
input = sys.stdin.readline
N = int(input())
A = list(map(int, input().split()))
Ind = [0]*(N+1)
for i, a in enumerate(A):
Ind[a] = i+1
Bit = BITbisect(list(range(N+1)))
ans = [0]
Bit.push(Ind[1])
a = 0
for n in range(2, N+1):
ind = Ind[n]
f = Bit.bisect_left(ind)
#print(Bit)
l = len(Bit)
if l%2 == 0:
if f == l//2:
a += l//2
elif f < l//2:
p1 = Bit[l//2-1]
a += (p1-ind-1) - (l//2-1) + l-f
else:
p2 = Bit[l//2]
a += (ind-p2-1) - (l//2-1) + l-f
else:
p1 = Bit[l//2]
#print(f, p1, ind, l)
if f <= l//2:
a += (p1-ind-1) - l//2 + l-f
else:
a += (ind-p1-1) - l//2 + l-f
ans.append(a)
Bit.push(ind)
print(*ans, sep=" ")
```
No
| 1,783 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a permutation p_1, p_2, …, p_n.
In one move you can swap two adjacent values.
You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k.
Let f(k) be the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation.
You need to find f(1), f(2), …, f(n).
Input
The first line of input contains one integer n (1 ≤ n ≤ 200 000): the number of elements in the permutation.
The next line of input contains n integers p_1, p_2, …, p_n: given permutation (1 ≤ p_i ≤ n).
Output
Print n integers, the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation, for k=1, 2, …, n.
Examples
Input
5
5 4 3 2 1
Output
0 1 3 6 10
Input
3
1 2 3
Output
0 0 0
Submitted Solution:
```
n = int(input())
permutation = [int(x) for x in input().split()]
res = []
count = 0
for k in range(1, n+1):
if k == 1:
res.append(count)
else:
now = permutation.index(k)
target = permutation.index(k-1)
if now > target:
while permutation.index(k) != permutation.index(k-1) + 1:
permutation[now-1], permutation[now] = permutation[now], permutation[now-1]
now -= 1
count += 1
elif now < target:
while permutation.index(k) != permutation.index(k-1) + 1:
permutation[now+1], permutation[now] = permutation[now], permutation[now+1]
now += 1
count += 1
res.append(count)
for i in res:
print(i, end=" ")
print()
```
No
| 1,784 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a permutation p_1, p_2, …, p_n.
In one move you can swap two adjacent values.
You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k.
Let f(k) be the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation.
You need to find f(1), f(2), …, f(n).
Input
The first line of input contains one integer n (1 ≤ n ≤ 200 000): the number of elements in the permutation.
The next line of input contains n integers p_1, p_2, …, p_n: given permutation (1 ≤ p_i ≤ n).
Output
Print n integers, the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation, for k=1, 2, …, n.
Examples
Input
5
5 4 3 2 1
Output
0 1 3 6 10
Input
3
1 2 3
Output
0 0 0
Submitted Solution:
```
# Binary Indexed Tree (Fenwick Tree)
class BIT():
def __init__(self, n):
self.n = n
self.bit = [0] * (n + 1)
def add(self, i, val):
i = i + 1
while i <= self.n:
self.bit[i] += val
i += i & -i
def _sum(self, i):
s = 0
while i > 0:
s += self.bit[i]
i -= i & -i
return s
def sum(self, i, j):
return self._sum(j) - self._sum(i)
import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
bit = BIT(n)
memo = {}
for i in range(n):
memo[a[i] - 1] = i
ans = [0] * n
tmp = 0
for i in range(len(a)):
bit.add(memo[i], 1)
tmp += bit.sum(memo[i] + 1, n)
ans[i] = tmp
print(*ans)
```
No
| 1,785 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's define the function f of multiset a as the multiset of number of occurences of every number, that is present in a.
E.g., f(\{5, 5, 1, 2, 5, 2, 3, 3, 9, 5\}) = \{1, 1, 2, 2, 4\}.
Let's define f^k(a), as applying f to array a k times: f^k(a) = f(f^{k-1}(a)), f^0(a) = a.
E.g., f^2(\{5, 5, 1, 2, 5, 2, 3, 3, 9, 5\}) = \{1, 2, 2\}.
You are given integers n, k and you are asked how many different values the function f^k(a) can have, where a is arbitrary non-empty array with numbers of size no more than n. Print the answer modulo 998 244 353.
Input
The first and only line of input consists of two integers n, k (1 ≤ n, k ≤ 2020).
Output
Print one number — the number of different values of function f^k(a) on all possible non-empty arrays with no more than n elements modulo 998 244 353.
Examples
Input
3 1
Output
6
Input
5 6
Output
1
Input
10 1
Output
138
Input
10 2
Output
33
Submitted Solution:
```
from itertools import combinations_with_replacement
from collections import Counter
def check(n,k):
for q in range(k):
if q==0:
x = []
for p in range(n,0,-1):
for i in range(p):
s = p-i
for j in combinations_with_replacement([e for e in range(1,i+2)],s):
l = list(j)
if sum(l)==p:
x.append(l)
break
# print(x)
else:
b = []
for l in x:
a = []
c = dict(Counter(l))
# print(c)
for i in c:
a.append(c[i])
a.sort()
if a not in b:
b.append(a)
x = b[:]
return len(x)
nk = input().split()
n = int(nk[0])
k = int(nk[1])
print(check(n,k))
```
No
| 1,786 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's define the function f of multiset a as the multiset of number of occurences of every number, that is present in a.
E.g., f(\{5, 5, 1, 2, 5, 2, 3, 3, 9, 5\}) = \{1, 1, 2, 2, 4\}.
Let's define f^k(a), as applying f to array a k times: f^k(a) = f(f^{k-1}(a)), f^0(a) = a.
E.g., f^2(\{5, 5, 1, 2, 5, 2, 3, 3, 9, 5\}) = \{1, 2, 2\}.
You are given integers n, k and you are asked how many different values the function f^k(a) can have, where a is arbitrary non-empty array with numbers of size no more than n. Print the answer modulo 998 244 353.
Input
The first and only line of input consists of two integers n, k (1 ≤ n, k ≤ 2020).
Output
Print one number — the number of different values of function f^k(a) on all possible non-empty arrays with no more than n elements modulo 998 244 353.
Examples
Input
3 1
Output
6
Input
5 6
Output
1
Input
10 1
Output
138
Input
10 2
Output
33
Submitted Solution:
```
n,k = map(int, input().split())
arr = [5,5,1,2,5,2,3,3,9,5]
```
No
| 1,787 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 2 × 10^5) — the length of array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9) — the elements of a.
Output
Output a single integer — the number of good subarrays of a.
Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0.
Tags: binary search, data structures, implementation, two pointers
Correct Solution:
```
from collections import defaultdict
def solve(arr, n):
ma = defaultdict(list)
ma[0].append(-1)
p = [arr[i] for i in range(n)]
for i in range(1, n): p[i] += p[i-1]
cnt, lst = 0, -1
for i in range(n):
if ma[p[i]]: lst = max(lst, ma[p[i]][-1]+1)
#print(i, lst, p[i])
cnt += (i-lst)
ma[p[i]].append(i)
return cnt
def main():
n = int(input())
arr = list(map(int, input().strip().split()))
ret = solve(arr, n)
print(ret)
if __name__ == "__main__": main()
```
| 1,788 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 2 × 10^5) — the length of array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9) — the elements of a.
Output
Output a single integer — the number of good subarrays of a.
Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0.
Tags: binary search, data structures, implementation, two pointers
Correct Solution:
```
"""
3
41 -41 41
"""
def solve(n, a):
d = {0: -1}
s = 0 # 前缀和
res = 0
j = -1
for i in range(n):
s += a[i]
if (d.get(s) != None):
j = max(d[s] + 1, j)
d[s] = i
res += i - j
return res
def main():
n = int(input())
a = [int(x) for x in input().split()]
res = solve(n, a)
print(res)
main()
```
| 1,789 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 2 × 10^5) — the length of array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9) — the elements of a.
Output
Output a single integer — the number of good subarrays of a.
Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0.
Tags: binary search, data structures, implementation, two pointers
Correct Solution:
```
def sumoflength(arr, n):
# For maintaining distinct elements.
s = set()
# Initialize ending point and result
j = 0
ans = 0
# Fix starting point
for i in range(n):
# Find ending point for current
# subarray with distinct elements.
while (j < n and (arr[j] not in s)):
s.add(arr[j])
j += 1
# Calculating and adding all possible
# length subarrays in arr[i..j]
ans += (j - i-1)
# Remove arr[i] as we pick new
# stating point from next
s.remove(arr[i])
return ans
n = int(input().strip())
numbers= list(map(int,input().strip().split()))
prefsum = [0 for i in range(n+1)]
prefsum[0] = 0
for q in range(1,n+1):
prefsum[q] = prefsum[q-1] + numbers[q-1]
print(sumoflength(prefsum,n+1))
```
| 1,790 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 2 × 10^5) — the length of array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9) — the elements of a.
Output
Output a single integer — the number of good subarrays of a.
Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0.
Tags: binary search, data structures, implementation, two pointers
Correct Solution:
```
n=int(input())
a=[int(x) for x in input().split()]
for i in range(1,n):
a[i]+=a[i-1]
dic={}
dic[0]=0
ans=0
maximum=-1
for i in range(n):
val=dic.get(a[i],-1)
maximum=max(maximum,val)
ans+=i-maximum
dic[a[i]]=i+1
#print(dic,maximum,ans,i)
print(ans)
```
| 1,791 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 2 × 10^5) — the length of array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9) — the elements of a.
Output
Output a single integer — the number of good subarrays of a.
Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0.
Tags: binary search, data structures, implementation, two pointers
Correct Solution:
```
n = int(input())
last = 0
o = {0: -1}
t = 0
rs = 0
a = [int(x) for x in input().split()]
for i, ai in enumerate(a):
rs += ai
if rs in o:
last = max(last, o[rs] + 2)
o[rs] = i
t += i - last + 1
print(t)
```
| 1,792 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 2 × 10^5) — the length of array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9) — the elements of a.
Output
Output a single integer — the number of good subarrays of a.
Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0.
Tags: binary search, data structures, implementation, two pointers
Correct Solution:
```
n=int(input())
d={}
ar=list(map(int,input().split()))
pref=[0]*(n)
ans=0
d={}
uk=-1
pref[0]=ar[0]
d[0]=-1
for i in range(1,n):
pref[i]=pref[i-1]+ar[i]
for i in range(n):
if pref[i] in d:
uk=max(uk,d.get(pref[i])+1)
ans+=(i-uk)
d[pref[i]]=i
print(ans)
```
| 1,793 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 2 × 10^5) — the length of array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9) — the elements of a.
Output
Output a single integer — the number of good subarrays of a.
Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0.
Tags: binary search, data structures, implementation, two pointers
Correct Solution:
```
def I(): return(list(map(int,input().split())))
def sieve(n):
a=[1]*n
for i in range(2,n):
if a[i]:
for j in range(i*i,n,i):
a[j]=0
return a
n=int(input())
arr=I()
l=-1
d={0:-1}
prefix=[0]*(n+1)
prefix[0]=arr[0]
ans=0
for i in range(1,n):prefix[i]=arr[i]+prefix[i-1]
for i in range(n):
l=max(l,d.get(prefix[i],l-1)+1)
d[prefix[i]]=i
ans+=i-l
print(ans)
```
| 1,794 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 2 × 10^5) — the length of array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9) — the elements of a.
Output
Output a single integer — the number of good subarrays of a.
Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0.
Tags: binary search, data structures, implementation, two pointers
Correct Solution:
```
from itertools import accumulate
n = int(input())
a = [int(x) for x in input().split()]
sums = [0] + list(accumulate(a))
s = {0}
i, j = 0, 0
ans = 0
while i < n:
while j < n and sums[j+1] not in s:
s.add(sums[j+1])
j += 1
ans += j - i
s.remove(sums[i])
i += 1
print(ans)
```
| 1,795 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 2 × 10^5) — the length of array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9) — the elements of a.
Output
Output a single integer — the number of good subarrays of a.
Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0.
Submitted Solution:
```
N = int(input())
D = {0: -1}
A = [int(a) for a in input().split()]
m = -1
s = 0
ans = 0
for i, a in enumerate(A):
if a == 0:
m = i
continue
s += a
if s not in D:
D[s] = i
ans += i - m
else:
m = max(m, D[s] + 1)
ans += i - m
D[s] = i
print(ans)
```
Yes
| 1,796 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 2 × 10^5) — the length of array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9) — the elements of a.
Output
Output a single integer — the number of good subarrays of a.
Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0.
Submitted Solution:
```
import sys, math
input = sys.stdin.readline
def getInts():
return [int(s) for s in input().split()]
def getInt():
return int(input())
def getStrs():
return [s for s in input().split()]
def getStr():
return input().strip()
def listStr():
return list(input().strip())
import collections as col
import math,itertools
"""
For each element of the array, count right until it stops being a good subarray
Then start the next element at the right limit of the previous
"""
def solve():
N = getInt()
A = [0] + getInts()
P = []
curr_sum = 0
for a in A:
curr_sum += a
P.append(curr_sum)
right = 1
ans = 0
#print(P)
sums_seen = col.defaultdict(int)
#initially, the reference point is the first element
sums_seen[0] += 1
end = 1
for j in range(1,N+1):
#if anything matches the reference sum or a sum seen since, stop
#end slides as far right as possible for each j
while end < N+1 and sums_seen[P[end]] == 0:
sums_seen[P[end]] = 1
end += 1
#print(j,end,sums_seen)
ans += end-j
#we're only interested in the reference sums starting at each j, so we remove the earliest sum each time
sums_seen[P[j-1]] = 0
return ans
print(solve())
```
Yes
| 1,797 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 2 × 10^5) — the length of array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9) — the elements of a.
Output
Output a single integer — the number of good subarrays of a.
Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0.
Submitted Solution:
```
# -*- coding: utf-8 -*-
import sys
from itertools import accumulate
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7
N = INT()
A = LIST()
acc = [0] + list(accumulate(A))
D = {}
R = [N] * N
for i, a in enumerate(acc):
if a in D:
R[D[a]] = min(R[D[a]], i-1)
D[a] = i
for i in range(N-2, -1, -1):
R[i] = min(R[i], R[i+1])
ans = 0
for i in range(N):
ans += R[i] - i
print(ans)
```
Yes
| 1,798 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 2 × 10^5) — the length of array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9) — the elements of a.
Output
Output a single integer — the number of good subarrays of a.
Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0.
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
di = {}
di[0] = 0
ans = 0
total = 0
sub = -1
for i in range(n):
total += a[i]
if total in di:
sub = max(sub, di[total])
di[total] = i+1
ans += i-sub
print(ans)
```
Yes
| 1,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.