message stringlengths 2 65.1k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 0 108k | cluster float64 14 14 | __index_level_0__ int64 0 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are the planning manager of an animation production company. What animation production companies produce these days is not limited to animation itself. Related products, such as figures of characters and character song CDs, are also important sources of revenue. How much this profit can be increased depends solely on you, the director of the planning department.
Obviously, these related products are not something that should be released in the dark clouds. This is because it takes a lot of time and budget to develop a product. Even if you release a figure of an anime character, you have to limit it to popular characters that are expected to sell a lot.
One of the means to measure the popularity of a character is popularity voting. You've been planning some popularity polls so far, but it seems that viewers are becoming dissatisfied with the project. There is an urgent need to establish other methods for measuring popularity.
So you made a hypothesis. The popularity of a character is proportional to the total appearance time in the main part of the anime. To test this hypothesis, you decided to write a program that aggregates the appearance times of each character.
Input
The input consists of multiple cases. Each case is given in the following format.
n
name0 m0 d0,0 ... d0, m0-1
name1 m1 d1,0 ... d1, m1-1
..
..
..
namen-1 mn-1 dn-1,0 ... dn-1, mn-1-1
n represents the number of characters.
namei represents the name of the character.
mi represents the type of time the character was shown.
After mi, mi integers di and j are given.
di and j represent the time when the character was shown.
The end of the input is given by a line consisting of n = 0
If only one character appears on the screen at a given time, that character can get n points.
Every time one more character appears at the same time, the points obtained for the character reflected at that time decrease by one.
If n characters are shown at the same time, 1 point will be added to each of n characters.
The input satisfies the following constraints.
2 β€ n β€ 20
0 β€ mi β€ 30
0 β€ di, j <30
Di and j are all different for the i-th character.
namei contains only uppercase or lowercase letters and is no longer than 10.
Output
Output the points of the character with the smallest points and their names separated by a single space.
If there are multiple characters with the smallest points, select the person with the smallest name in lexicographical order.
Example
Input
4
akzakr 2 1 8
fnmyi 5 2 3 4 6 9
tsnukk 5 2 3 4 7 9
yskwcnt 6 3 4 7 8 9 10
4
akzakr 1 2
fnmyi 3 10 11 12
tsnukk 2 1 8
yskwcnt 2 1 8
5
knmmdk 2 13 19
akmhmr 4 13 15 19 22
mksyk 6 3 7 12 13 15 19
skrkyk 3 1 4 8
tmemm 3 1 17 24
5
knmmdk 5 5 6 16 18 26
akmhmr 9 3 4 7 11 14 15 17 18 20
mksyk 5 6 13 25 27 28
skrkyk 4 3 16 23 24
tmemm 3 6 12 20
14
hrkamm 6 4 6 8 10 20 22
mkhsi 6 1 10 12 15 22 27
hbkgnh 2 4 9
chyksrg 8 3 4 12 15 16 20 25 28
mktkkc 6 0 1 8 15 17 20
tknsj 6 6 8 18 19 25 26
yyitktk 3 3 12 18
ykhhgwr 5 3 9 10 11 24
amftm 7 2 6 8 12 13 14 17
mmftm 4 6 12 16 18
rtkakzk 3 14 15 21
azsmur 7 1 2 4 12 15 18 20
iormns 2 4 20
ktrotns 6 7 12 14 17 20 25
14
hrkamm 2 4 21
mkhsi 6 2 3 8 11 18 20
hbkgnh 4 4 16 28 29
chyksrg 5 0 3 9 17 22
mktkkc 2 7 18
tknsj 3 3 9 23
yyitktk 3 10 13 25
ykhhgwr 2 18 26
amftm 3 13 18 22
mmftm 4 1 20 24 27
rtkakzk 2 1 10
azsmur 5 2 5 10 14 17
iormns 3 9 15 16
ktrotns 5 7 12 16 17 20
0
Output
7 akzakr
4 akzakr
6 knmmdk
12 tmemm
19 iormns
24 mktkkc
Submitted Solution:
```
while True:
player_nun = int(input())
if player_nun == 0:
break
#?????????????????????
whole_data = []
for i in range(0, player_nun):
dat = input().split()
p_data = []
p_data.append(dat[0])
for x in dat[1:]:
p_data.append(int(x))
whole_data.append(p_data)
#???????????????????????????????????????
xel = {}
for i in whole_data:
for x in i[2:]:
if x in xel:
xel[x] += 1
else:
xel[x] = 1
#??????????????????????????Β’?????????
score = {}
for y in xel.keys():
score[y] = 5 - xel[y]
#????????Β’??Β¨????????????????????????????????????
result = []
for i in whole_data:
player_score = []
player_score.append(i[0])
player_score.append(0)
for x in i[2:]:
player_score[1] += score[x]
result.append(player_score)
#?????????????????????????Β¬?????????????????Β±???????
min_score = min(x[1] for x in result)
winners = []
for x in result:
if x[1] == min_score:
winners.append(x[0])
print(str(min_score) + " " + sorted(winners)[0])
``` | instruction | 0 | 80,768 | 14 | 161,536 |
No | output | 1 | 80,768 | 14 | 161,537 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hiasat registered a new account in NeckoForces and when his friends found out about that, each one of them asked to use his name as Hiasat's handle.
Luckily for Hiasat, he can change his handle in some points in time. Also he knows the exact moments friends will visit his profile page. Formally, you are given a sequence of events of two types:
* 1 β Hiasat can change his handle.
* 2 s β friend s visits Hiasat's profile.
The friend s will be happy, if each time he visits Hiasat's profile his handle would be s.
Hiasat asks you to help him, find the maximum possible number of happy friends he can get.
Input
The first line contains two integers n and m (1 β€ n β€ 10^5, 1 β€ m β€ 40) β the number of events and the number of friends.
Then n lines follow, each denoting an event of one of two types:
* 1 β Hiasat can change his handle.
* 2 s β friend s (1 β€ |s| β€ 40) visits Hiasat's profile.
It's guaranteed, that each friend's name consists only of lowercase Latin letters.
It's guaranteed, that the first event is always of the first type and each friend will visit Hiasat's profile at least once.
Output
Print a single integer β the maximum number of happy friends.
Examples
Input
5 3
1
2 motarack
2 mike
1
2 light
Output
2
Input
4 3
1
2 alice
2 bob
2 tanyaromanova
Output
1
Note
In the first example, the best way is to change the handle to the "motarack" in the first event and to the "light" in the fourth event. This way, "motarack" and "light" will be happy, but "mike" will not.
In the second example, you can choose either "alice", "bob" or "tanyaromanova" and only that friend will be happy. | instruction | 0 | 80,847 | 14 | 161,694 |
Tags: bitmasks, brute force, dp, meet-in-the-middle
Correct Solution:
```
import time
n, m =map(int, input().split())
names={None:0}
count={i:0 for i in range(1, m+1)}
a=[0]*(n+1)
for i in range(n):
l=list(input().split())
if l[0]=='2':
if l[1] not in names:
names[l[1]]=len(names)
a[i]=names[l[1]]
count[a[i]]=count[a[i]]+1
# else a[i] stays 0
dense=[set() for _ in range(m+1)]
bulk=set()
# filling dense array of arrays
for i in range(n):
if a[i]==0:
bulk.clear()
continue
if a[i] in bulk: continue
for j in bulk:
dense[j].add(a[i])
dense[a[i]].add(j)
bulk.add(a[i])
res=0
happy=set()
unhappy=set()
mindep=99
independent=set()
dependent=set()
for i in range(1, m+1):
if len(dense[i])==0: independent.add(i)
else:
dependent.add(i)
if len(dense[i])<mindep:
mindep=len(dense[i])
# print([i for i in dependent if mindep==len(dense[i])])
for k in list(dependent):
# iterate to... too sly
happy.clear()
unhappy.clear()
bulk.clear()
bulk.update(dependent)
happy.add(k)
bulk.remove(k)
for j in dense[k]:
if j in bulk:
unhappy.add(j)
bulk.remove(j)
# now making least connected happy
while bulk:
mini = min([len(dense[i]) for i in bulk])
for i in list(bulk):
if len(dense[i])==mini and (i in bulk):
happy.add(i)
bulk.remove(i)
for j in dense[i]:
if j in bulk:
unhappy.add(j)
bulk.remove(j)
continue
res=max(res,len(happy))
print(res+len(independent))
``` | output | 1 | 80,847 | 14 | 161,695 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hiasat registered a new account in NeckoForces and when his friends found out about that, each one of them asked to use his name as Hiasat's handle.
Luckily for Hiasat, he can change his handle in some points in time. Also he knows the exact moments friends will visit his profile page. Formally, you are given a sequence of events of two types:
* 1 β Hiasat can change his handle.
* 2 s β friend s visits Hiasat's profile.
The friend s will be happy, if each time he visits Hiasat's profile his handle would be s.
Hiasat asks you to help him, find the maximum possible number of happy friends he can get.
Input
The first line contains two integers n and m (1 β€ n β€ 10^5, 1 β€ m β€ 40) β the number of events and the number of friends.
Then n lines follow, each denoting an event of one of two types:
* 1 β Hiasat can change his handle.
* 2 s β friend s (1 β€ |s| β€ 40) visits Hiasat's profile.
It's guaranteed, that each friend's name consists only of lowercase Latin letters.
It's guaranteed, that the first event is always of the first type and each friend will visit Hiasat's profile at least once.
Output
Print a single integer β the maximum number of happy friends.
Examples
Input
5 3
1
2 motarack
2 mike
1
2 light
Output
2
Input
4 3
1
2 alice
2 bob
2 tanyaromanova
Output
1
Note
In the first example, the best way is to change the handle to the "motarack" in the first event and to the "light" in the fourth event. This way, "motarack" and "light" will be happy, but "mike" will not.
In the second example, you can choose either "alice", "bob" or "tanyaromanova" and only that friend will be happy. | instruction | 0 | 80,848 | 14 | 161,696 |
Tags: bitmasks, brute force, dp, meet-in-the-middle
Correct Solution:
```
import time
def find_max_clique(remain, size, max_, index, maxs):
# print(remain, size, max_)
result = max_
if size + len(remain) <= result:
# print('pruning (1)...')
return result
if not remain:
# print('trivial')
return size
while remain:
candidate = max(remain)
# print('get candidate:', candidate)
if maxs[candidate] + size <= result:
# print('pruning (2)...')
return result
if size + len(remain) <= result:
# print('pruning (3)...')
return result
remain.remove(candidate)
# print('entering...')
sub_result = find_max_clique(remain & index[candidate], size + 1 , result, index, maxs)
if sub_result > result:
# print('{} > {}, existing...'.format(sub_result, result))
result = sub_result
return result
# print('result:', result)
return result
def test_find():
# index = {1: {2, 3, 4}, 2: {1, 3, 4}, 3: {1, 2}, 4: {1, 2}}
index = [{2, 4, 5, 7}, {4, 5, 6}, {0, 5, 6, 7},
{5, 6 ,7}, {0, 1, 6, 7}, {0, 1, 2, 3}, {1, 2, 3, 4},
{0, 2, 3, 4}]
m = 8
maxs = [0] * m
whole = set()
for i in range(m):
# print('i:', i)
whole.add(i)
# print('w:', whole)
maxs[i] = max(maxs[i - 1], find_max_clique(whole & index[i], 1, maxs[i - 1], index, maxs))
# print()
# print(maxs)
def solve(events, m):
index = [set() for _ in range(m)]
r = []
while events:
ele = events.pop()
if ele is None:
# ele is None
r.clear()
else:
# ele not None.
for n in r:
index[n].add(ele)
index[ele].update(r)
r.append(ele)
whole = set(range(m))
# print('w:', whole)
for i in range(m):
index[i] = whole - index[i] - {i}
maxs = [0] * m
whole = set()
for i in range(m):
whole.add(i)
maxs[i] = max(maxs[i - 1], find_max_clique(whole & index[i], 1, maxs[i - 1], index, maxs))
return maxs[-1]
def test():
events = []
m = 700
for i in range(m):
events.extend([None, i])
tick = time.time()
print(solve(events, m))
tock = time.time()
print('T:', round(tock - tick, 5))
def main():
# Deal input here.
n, m = map(int, input().split())
events = []
d = {}
id_ = 0
for i in range(n):
line = input()
if line.startswith('1'):
events.append(None)
else:
if line not in d:
d[line] = id_
id_ += 1
events.append(d[line])
# tick = time.time()
print(solve(events, m))
# tock = time.time()
# print(round(tock - tick, 5))
if __name__ == '__main__':
main()
``` | output | 1 | 80,848 | 14 | 161,697 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hiasat registered a new account in NeckoForces and when his friends found out about that, each one of them asked to use his name as Hiasat's handle.
Luckily for Hiasat, he can change his handle in some points in time. Also he knows the exact moments friends will visit his profile page. Formally, you are given a sequence of events of two types:
* 1 β Hiasat can change his handle.
* 2 s β friend s visits Hiasat's profile.
The friend s will be happy, if each time he visits Hiasat's profile his handle would be s.
Hiasat asks you to help him, find the maximum possible number of happy friends he can get.
Input
The first line contains two integers n and m (1 β€ n β€ 10^5, 1 β€ m β€ 40) β the number of events and the number of friends.
Then n lines follow, each denoting an event of one of two types:
* 1 β Hiasat can change his handle.
* 2 s β friend s (1 β€ |s| β€ 40) visits Hiasat's profile.
It's guaranteed, that each friend's name consists only of lowercase Latin letters.
It's guaranteed, that the first event is always of the first type and each friend will visit Hiasat's profile at least once.
Output
Print a single integer β the maximum number of happy friends.
Examples
Input
5 3
1
2 motarack
2 mike
1
2 light
Output
2
Input
4 3
1
2 alice
2 bob
2 tanyaromanova
Output
1
Note
In the first example, the best way is to change the handle to the "motarack" in the first event and to the "light" in the fourth event. This way, "motarack" and "light" will be happy, but "mike" will not.
In the second example, you can choose either "alice", "bob" or "tanyaromanova" and only that friend will be happy.
Submitted Solution:
```
n, m = map(int, input().split())
numbers = []
tec = []
sum = 0
for i in range(n):
ran = input()
tec.append(ran)
numbers.append(int(ran[0]))
imya = [ ]
for i in range(1, n):
if numbers[i] == 2:
ifn = False
if imya != tec[i]:
ifn = True
if ifn == False:
sum += 1
if numbers[i - 1] == 1:
imya = tec[i][2:(len(tec[i]))]
sum += 1
print(sum)
``` | instruction | 0 | 80,849 | 14 | 161,698 |
No | output | 1 | 80,849 | 14 | 161,699 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hiasat registered a new account in NeckoForces and when his friends found out about that, each one of them asked to use his name as Hiasat's handle.
Luckily for Hiasat, he can change his handle in some points in time. Also he knows the exact moments friends will visit his profile page. Formally, you are given a sequence of events of two types:
* 1 β Hiasat can change his handle.
* 2 s β friend s visits Hiasat's profile.
The friend s will be happy, if each time he visits Hiasat's profile his handle would be s.
Hiasat asks you to help him, find the maximum possible number of happy friends he can get.
Input
The first line contains two integers n and m (1 β€ n β€ 10^5, 1 β€ m β€ 40) β the number of events and the number of friends.
Then n lines follow, each denoting an event of one of two types:
* 1 β Hiasat can change his handle.
* 2 s β friend s (1 β€ |s| β€ 40) visits Hiasat's profile.
It's guaranteed, that each friend's name consists only of lowercase Latin letters.
It's guaranteed, that the first event is always of the first type and each friend will visit Hiasat's profile at least once.
Output
Print a single integer β the maximum number of happy friends.
Examples
Input
5 3
1
2 motarack
2 mike
1
2 light
Output
2
Input
4 3
1
2 alice
2 bob
2 tanyaromanova
Output
1
Note
In the first example, the best way is to change the handle to the "motarack" in the first event and to the "light" in the fourth event. This way, "motarack" and "light" will be happy, but "mike" will not.
In the second example, you can choose either "alice", "bob" or "tanyaromanova" and only that friend will be happy.
Submitted Solution:
```
import time
n, m =map(int, input().split())
names={None:0}
count={i:0 for i in range(1, m+1)}
a=[0]*(n+1)
for i in range(n):
l=list(input().split())
if l[0]=='2':
if l[1] not in names:
names[l[1]]=len(names)
a[i]=names[l[1]]
count[a[i]]=count[a[i]]+1
# else a[i] stays 0
dense=[set() for _ in range(m+1)]
bulk=set()
# filling dense array of arrays
for i in range(n):
if a[i]==0:
bulk.clear()
continue
if a[i] in bulk: continue
for j in bulk:
dense[j].add(a[i])
dense[a[i]].add(j)
bulk.add(a[i])
res=0
happy=set()
unhappy=set()
mindep=99
independent=set()
dependent=set()
for i in range(1, m+1):
if len(dense[i])==0: independent.add(i)
else:
dependent.add(i)
if len(dense[i])<mindep:
mindep=len(dense[i])
# print([i for i in dependent if mindep==len(dense[i])])
for k in [i for i in dependent if mindep==len(dense[i])]:
happy.clear()
unhappy.clear()
bulk.clear()
bulk.update(dependent)
happy.add(k)
bulk.remove(k)
for j in dense[k]:
if j in bulk:
unhappy.add(j)
bulk.remove(j)
# making least connected happy
while bulk:
mini = min([len(dense[i]) for i in bulk])
for i in list(bulk):
if len(dense[i])==mini and (i in bulk):
happy.add(i)
bulk.remove(i)
for j in dense[i]:
if j in bulk:
unhappy.add(j)
bulk.remove(j)
continue
res=max(res,len(happy))
print(res+len(independent))
``` | instruction | 0 | 80,850 | 14 | 161,700 |
No | output | 1 | 80,850 | 14 | 161,701 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hiasat registered a new account in NeckoForces and when his friends found out about that, each one of them asked to use his name as Hiasat's handle.
Luckily for Hiasat, he can change his handle in some points in time. Also he knows the exact moments friends will visit his profile page. Formally, you are given a sequence of events of two types:
* 1 β Hiasat can change his handle.
* 2 s β friend s visits Hiasat's profile.
The friend s will be happy, if each time he visits Hiasat's profile his handle would be s.
Hiasat asks you to help him, find the maximum possible number of happy friends he can get.
Input
The first line contains two integers n and m (1 β€ n β€ 10^5, 1 β€ m β€ 40) β the number of events and the number of friends.
Then n lines follow, each denoting an event of one of two types:
* 1 β Hiasat can change his handle.
* 2 s β friend s (1 β€ |s| β€ 40) visits Hiasat's profile.
It's guaranteed, that each friend's name consists only of lowercase Latin letters.
It's guaranteed, that the first event is always of the first type and each friend will visit Hiasat's profile at least once.
Output
Print a single integer β the maximum number of happy friends.
Examples
Input
5 3
1
2 motarack
2 mike
1
2 light
Output
2
Input
4 3
1
2 alice
2 bob
2 tanyaromanova
Output
1
Note
In the first example, the best way is to change the handle to the "motarack" in the first event and to the "light" in the fourth event. This way, "motarack" and "light" will be happy, but "mike" will not.
In the second example, you can choose either "alice", "bob" or "tanyaromanova" and only that friend will be happy.
Submitted Solution:
```
a = input().split()
t = []
g = 0
for i in range(int(a[0])):
c = input().split()
t.append(c)
for i in range(int(a[0])-1):
if(t[i][0]=="1") and (t[i+1][0]=="2"):
g = g+1
print(g)
``` | instruction | 0 | 80,851 | 14 | 161,702 |
No | output | 1 | 80,851 | 14 | 161,703 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hiasat registered a new account in NeckoForces and when his friends found out about that, each one of them asked to use his name as Hiasat's handle.
Luckily for Hiasat, he can change his handle in some points in time. Also he knows the exact moments friends will visit his profile page. Formally, you are given a sequence of events of two types:
* 1 β Hiasat can change his handle.
* 2 s β friend s visits Hiasat's profile.
The friend s will be happy, if each time he visits Hiasat's profile his handle would be s.
Hiasat asks you to help him, find the maximum possible number of happy friends he can get.
Input
The first line contains two integers n and m (1 β€ n β€ 10^5, 1 β€ m β€ 40) β the number of events and the number of friends.
Then n lines follow, each denoting an event of one of two types:
* 1 β Hiasat can change his handle.
* 2 s β friend s (1 β€ |s| β€ 40) visits Hiasat's profile.
It's guaranteed, that each friend's name consists only of lowercase Latin letters.
It's guaranteed, that the first event is always of the first type and each friend will visit Hiasat's profile at least once.
Output
Print a single integer β the maximum number of happy friends.
Examples
Input
5 3
1
2 motarack
2 mike
1
2 light
Output
2
Input
4 3
1
2 alice
2 bob
2 tanyaromanova
Output
1
Note
In the first example, the best way is to change the handle to the "motarack" in the first event and to the "light" in the fourth event. This way, "motarack" and "light" will be happy, but "mike" will not.
In the second example, you can choose either "alice", "bob" or "tanyaromanova" and only that friend will be happy.
Submitted Solution:
```
def f(n, string_names):
# 0 <= n < len(data)
global max_len, m, found
if found:
return
if n == len(data) - 1:
for name in data[-1]:
if name not in string_names:
new_string_names = string_names[:]
new_string_names.append(name)
if len(new_string_names) == m:
found = True
if len(new_string_names) > max_len:
max_len = len(new_string_names)
# print(new_string_names)
return
for name in data[n]:
if name not in string_names:
new_string_names = string_names[:]
new_string_names.append(name)
f(n + 1, new_string_names)
n, m = [int(v) for v in input().split()]
data = []
max_len = -1
found = False
state = 0
for i in range(n):
tokens = input().split()
if state == 0 and len(tokens) == 1:
state = 1
elif state == 1 and len(tokens) == 2:
data.append([tokens[-1]])
state = 2
elif state == 2 and len(tokens) == 2:
if tokens[-1] not in data[-1]:
data[-1].append(tokens[-1])
elif state == 2 and len(tokens) == 1:
state = 1
f(0, [])
if found:
print(m)
else:
print(max_len)
``` | instruction | 0 | 80,852 | 14 | 161,704 |
No | output | 1 | 80,852 | 14 | 161,705 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 β€ ti β€ 10). Of course, one number can be assigned to any number of customers.
"Perfect Matching" wants to advertise its services and publish the number of opposite couples, that is, the couples who have opposite values of t. Each couple consists of exactly two clients. The customer can be included in a couple an arbitrary number of times. Help the agency and write the program that will find the sought number by the given sequence t1, t2, ..., tn. For example, if t = (1, - 1, 1, - 1), then any two elements ti and tj form a couple if i and j have different parity. Consequently, in this case the sought number equals 4.
Of course, a client can't form a couple with him/herself.
Input
The first line of the input data contains an integer n (1 β€ n β€ 105) which represents the number of registered clients of the "Couple Matching". The second line contains a sequence of integers t1, t2, ..., tn ( - 10 β€ ti β€ 10), ti β is the parameter of the i-th customer that has been assigned to the customer by the result of the analysis of his interests.
Output
Print the number of couples of customs with opposite t. The opposite number for x is number - x (0 is opposite to itself). Couples that only differ in the clients' order are considered the same.
Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator.
Examples
Input
5
-3 3 0 0 3
Output
3
Input
3
0 0 0
Output
3
Note
In the first sample the couples of opposite clients are: (1,2), (1,5) ΠΈ (3,4).
In the second sample any couple of clients is opposite. | instruction | 0 | 80,959 | 14 | 161,918 |
Tags: implementation, math
Correct Solution:
```
import sys
f = sys.stdin
#f = open("input.txt", "r")
f. readline()
t = [int(i) for i in f.readline().strip().split()]
times = dict().fromkeys(t)
for i in times:
times[i] = t.count(i)
count = 0
for i in times.keys():
if i!=0 and -1*i in times.keys():
count += times[i]*times[-1*i]
times[i] = times[-1*i] = 0
try:
count += sum(range(times[0]))
except:
pass
print(count)
``` | output | 1 | 80,959 | 14 | 161,919 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 β€ ti β€ 10). Of course, one number can be assigned to any number of customers.
"Perfect Matching" wants to advertise its services and publish the number of opposite couples, that is, the couples who have opposite values of t. Each couple consists of exactly two clients. The customer can be included in a couple an arbitrary number of times. Help the agency and write the program that will find the sought number by the given sequence t1, t2, ..., tn. For example, if t = (1, - 1, 1, - 1), then any two elements ti and tj form a couple if i and j have different parity. Consequently, in this case the sought number equals 4.
Of course, a client can't form a couple with him/herself.
Input
The first line of the input data contains an integer n (1 β€ n β€ 105) which represents the number of registered clients of the "Couple Matching". The second line contains a sequence of integers t1, t2, ..., tn ( - 10 β€ ti β€ 10), ti β is the parameter of the i-th customer that has been assigned to the customer by the result of the analysis of his interests.
Output
Print the number of couples of customs with opposite t. The opposite number for x is number - x (0 is opposite to itself). Couples that only differ in the clients' order are considered the same.
Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator.
Examples
Input
5
-3 3 0 0 3
Output
3
Input
3
0 0 0
Output
3
Note
In the first sample the couples of opposite clients are: (1,2), (1,5) ΠΈ (3,4).
In the second sample any couple of clients is opposite. | instruction | 0 | 80,960 | 14 | 161,920 |
Tags: implementation, math
Correct Solution:
```
d = {}
for i in range(-10,11):
d[i] = 0
n = input()
n = int(n)
t = input()
t = t.split()
for x in t:
d[int(x)]+=1
sum = 0
#for i in d:
# print(str(i)+" "+str(d[i]))
x = -10
while x<0:
sum += (d[x]*d[-x])
x = x+1
if d[0]>1:
sum += d[0]*(d[0]-1)/2
print(int(sum))
``` | output | 1 | 80,960 | 14 | 161,921 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 β€ ti β€ 10). Of course, one number can be assigned to any number of customers.
"Perfect Matching" wants to advertise its services and publish the number of opposite couples, that is, the couples who have opposite values of t. Each couple consists of exactly two clients. The customer can be included in a couple an arbitrary number of times. Help the agency and write the program that will find the sought number by the given sequence t1, t2, ..., tn. For example, if t = (1, - 1, 1, - 1), then any two elements ti and tj form a couple if i and j have different parity. Consequently, in this case the sought number equals 4.
Of course, a client can't form a couple with him/herself.
Input
The first line of the input data contains an integer n (1 β€ n β€ 105) which represents the number of registered clients of the "Couple Matching". The second line contains a sequence of integers t1, t2, ..., tn ( - 10 β€ ti β€ 10), ti β is the parameter of the i-th customer that has been assigned to the customer by the result of the analysis of his interests.
Output
Print the number of couples of customs with opposite t. The opposite number for x is number - x (0 is opposite to itself). Couples that only differ in the clients' order are considered the same.
Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator.
Examples
Input
5
-3 3 0 0 3
Output
3
Input
3
0 0 0
Output
3
Note
In the first sample the couples of opposite clients are: (1,2), (1,5) ΠΈ (3,4).
In the second sample any couple of clients is opposite. | instruction | 0 | 80,961 | 14 | 161,922 |
Tags: implementation, math
Correct Solution:
```
n = int(input())
clientlist = list(map(int, input().split()))
num_of_pairs = 0
set_of_numbers = dict()
for i in clientlist:
set_of_numbers[i] = set_of_numbers.get(i, 0) + 1
if 0 in set_of_numbers.keys():
if set_of_numbers[0] > 1:
num_of_pairs += ((set_of_numbers[0] - 1) * set_of_numbers[0]) / 2
for item in set_of_numbers:
if item != 0:
if -item in set_of_numbers:
num_of_pairs += (set_of_numbers[item] * set_of_numbers[-item]) / 2
print(int(num_of_pairs))
``` | output | 1 | 80,961 | 14 | 161,923 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 β€ ti β€ 10). Of course, one number can be assigned to any number of customers.
"Perfect Matching" wants to advertise its services and publish the number of opposite couples, that is, the couples who have opposite values of t. Each couple consists of exactly two clients. The customer can be included in a couple an arbitrary number of times. Help the agency and write the program that will find the sought number by the given sequence t1, t2, ..., tn. For example, if t = (1, - 1, 1, - 1), then any two elements ti and tj form a couple if i and j have different parity. Consequently, in this case the sought number equals 4.
Of course, a client can't form a couple with him/herself.
Input
The first line of the input data contains an integer n (1 β€ n β€ 105) which represents the number of registered clients of the "Couple Matching". The second line contains a sequence of integers t1, t2, ..., tn ( - 10 β€ ti β€ 10), ti β is the parameter of the i-th customer that has been assigned to the customer by the result of the analysis of his interests.
Output
Print the number of couples of customs with opposite t. The opposite number for x is number - x (0 is opposite to itself). Couples that only differ in the clients' order are considered the same.
Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator.
Examples
Input
5
-3 3 0 0 3
Output
3
Input
3
0 0 0
Output
3
Note
In the first sample the couples of opposite clients are: (1,2), (1,5) ΠΈ (3,4).
In the second sample any couple of clients is opposite. | instruction | 0 | 80,962 | 14 | 161,924 |
Tags: implementation, math
Correct Solution:
```
n = int(input())
arr = list(map(int,input().split()))
cnt_zero = 0
pos = [0] * 11
neg = [0] * 11
for i in range(n):
if arr[i] > 0: pos[arr[i]] += 1
elif arr[i] < 0: neg[abs(arr[i])] += 1
else: cnt_zero += 1
ans = 0
for i in range(1,cnt_zero):
ans += i
for i in range(1,11):
ans += pos[i] * neg[i]
print(ans)
``` | output | 1 | 80,962 | 14 | 161,925 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 β€ ti β€ 10). Of course, one number can be assigned to any number of customers.
"Perfect Matching" wants to advertise its services and publish the number of opposite couples, that is, the couples who have opposite values of t. Each couple consists of exactly two clients. The customer can be included in a couple an arbitrary number of times. Help the agency and write the program that will find the sought number by the given sequence t1, t2, ..., tn. For example, if t = (1, - 1, 1, - 1), then any two elements ti and tj form a couple if i and j have different parity. Consequently, in this case the sought number equals 4.
Of course, a client can't form a couple with him/herself.
Input
The first line of the input data contains an integer n (1 β€ n β€ 105) which represents the number of registered clients of the "Couple Matching". The second line contains a sequence of integers t1, t2, ..., tn ( - 10 β€ ti β€ 10), ti β is the parameter of the i-th customer that has been assigned to the customer by the result of the analysis of his interests.
Output
Print the number of couples of customs with opposite t. The opposite number for x is number - x (0 is opposite to itself). Couples that only differ in the clients' order are considered the same.
Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator.
Examples
Input
5
-3 3 0 0 3
Output
3
Input
3
0 0 0
Output
3
Note
In the first sample the couples of opposite clients are: (1,2), (1,5) ΠΈ (3,4).
In the second sample any couple of clients is opposite. | instruction | 0 | 80,963 | 14 | 161,926 |
Tags: implementation, math
Correct Solution:
```
n = int(input())
pos = [0]*20 ; neg = [0]*20 ; zero = 0
x = [int(e) for e in input().split()]
for v in x:
if(v > 0):
pos[v]+=1
elif(v < 0):
neg[-v]+=1
else:
zero+=1
ans = 0
for v in range(1,11):
ans += pos[v] * neg[v]
ans += (zero * (zero-1)) / 2
print(int(ans))
``` | output | 1 | 80,963 | 14 | 161,927 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 β€ ti β€ 10). Of course, one number can be assigned to any number of customers.
"Perfect Matching" wants to advertise its services and publish the number of opposite couples, that is, the couples who have opposite values of t. Each couple consists of exactly two clients. The customer can be included in a couple an arbitrary number of times. Help the agency and write the program that will find the sought number by the given sequence t1, t2, ..., tn. For example, if t = (1, - 1, 1, - 1), then any two elements ti and tj form a couple if i and j have different parity. Consequently, in this case the sought number equals 4.
Of course, a client can't form a couple with him/herself.
Input
The first line of the input data contains an integer n (1 β€ n β€ 105) which represents the number of registered clients of the "Couple Matching". The second line contains a sequence of integers t1, t2, ..., tn ( - 10 β€ ti β€ 10), ti β is the parameter of the i-th customer that has been assigned to the customer by the result of the analysis of his interests.
Output
Print the number of couples of customs with opposite t. The opposite number for x is number - x (0 is opposite to itself). Couples that only differ in the clients' order are considered the same.
Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator.
Examples
Input
5
-3 3 0 0 3
Output
3
Input
3
0 0 0
Output
3
Note
In the first sample the couples of opposite clients are: (1,2), (1,5) ΠΈ (3,4).
In the second sample any couple of clients is opposite. | instruction | 0 | 80,964 | 14 | 161,928 |
Tags: implementation, math
Correct Solution:
```
from collections import defaultdict
n=int(input())
a=list(map(int,input().split()))
d=defaultdict(int)
for i in a:
d[i]+=1
ans=0
z = [i for i in d.keys()]
for i in z:
if(i==0):
ans+=(d[i]*(d[i]-1))
else:
ans+=(d[i]*d[-i])
print(ans//2)
``` | output | 1 | 80,964 | 14 | 161,929 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 β€ ti β€ 10). Of course, one number can be assigned to any number of customers.
"Perfect Matching" wants to advertise its services and publish the number of opposite couples, that is, the couples who have opposite values of t. Each couple consists of exactly two clients. The customer can be included in a couple an arbitrary number of times. Help the agency and write the program that will find the sought number by the given sequence t1, t2, ..., tn. For example, if t = (1, - 1, 1, - 1), then any two elements ti and tj form a couple if i and j have different parity. Consequently, in this case the sought number equals 4.
Of course, a client can't form a couple with him/herself.
Input
The first line of the input data contains an integer n (1 β€ n β€ 105) which represents the number of registered clients of the "Couple Matching". The second line contains a sequence of integers t1, t2, ..., tn ( - 10 β€ ti β€ 10), ti β is the parameter of the i-th customer that has been assigned to the customer by the result of the analysis of his interests.
Output
Print the number of couples of customs with opposite t. The opposite number for x is number - x (0 is opposite to itself). Couples that only differ in the clients' order are considered the same.
Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator.
Examples
Input
5
-3 3 0 0 3
Output
3
Input
3
0 0 0
Output
3
Note
In the first sample the couples of opposite clients are: (1,2), (1,5) ΠΈ (3,4).
In the second sample any couple of clients is opposite. | instruction | 0 | 80,965 | 14 | 161,930 |
Tags: implementation, math
Correct Solution:
```
n = int(input())
t = list(map(int, input().split()))
p = {}
for i in t:
p[i] = p.get(i, 0) + 1
print(sum(p[i] * p.get(-i, 0) for i in p if i > 0) + (p.get(0, 0) * (p.get(0, 0) - 1)) // 2)
``` | output | 1 | 80,965 | 14 | 161,931 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 β€ ti β€ 10). Of course, one number can be assigned to any number of customers.
"Perfect Matching" wants to advertise its services and publish the number of opposite couples, that is, the couples who have opposite values of t. Each couple consists of exactly two clients. The customer can be included in a couple an arbitrary number of times. Help the agency and write the program that will find the sought number by the given sequence t1, t2, ..., tn. For example, if t = (1, - 1, 1, - 1), then any two elements ti and tj form a couple if i and j have different parity. Consequently, in this case the sought number equals 4.
Of course, a client can't form a couple with him/herself.
Input
The first line of the input data contains an integer n (1 β€ n β€ 105) which represents the number of registered clients of the "Couple Matching". The second line contains a sequence of integers t1, t2, ..., tn ( - 10 β€ ti β€ 10), ti β is the parameter of the i-th customer that has been assigned to the customer by the result of the analysis of his interests.
Output
Print the number of couples of customs with opposite t. The opposite number for x is number - x (0 is opposite to itself). Couples that only differ in the clients' order are considered the same.
Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator.
Examples
Input
5
-3 3 0 0 3
Output
3
Input
3
0 0 0
Output
3
Note
In the first sample the couples of opposite clients are: (1,2), (1,5) ΠΈ (3,4).
In the second sample any couple of clients is opposite. | instruction | 0 | 80,966 | 14 | 161,932 |
Tags: implementation, math
Correct Solution:
```
n = int(input())
t = [int(i) for i in input().split()]
pairs = 0
used = []
for i in set(t):
if used.count(-i) == 0:
if i == 0:
pairs += sum(range(1, t.count(i)))
else:
pairs += t.count(-i) * t.count(i)
used.append(i)
print(pairs)
``` | output | 1 | 80,966 | 14 | 161,933 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 β€ ti β€ 10). Of course, one number can be assigned to any number of customers.
"Perfect Matching" wants to advertise its services and publish the number of opposite couples, that is, the couples who have opposite values of t. Each couple consists of exactly two clients. The customer can be included in a couple an arbitrary number of times. Help the agency and write the program that will find the sought number by the given sequence t1, t2, ..., tn. For example, if t = (1, - 1, 1, - 1), then any two elements ti and tj form a couple if i and j have different parity. Consequently, in this case the sought number equals 4.
Of course, a client can't form a couple with him/herself.
Input
The first line of the input data contains an integer n (1 β€ n β€ 105) which represents the number of registered clients of the "Couple Matching". The second line contains a sequence of integers t1, t2, ..., tn ( - 10 β€ ti β€ 10), ti β is the parameter of the i-th customer that has been assigned to the customer by the result of the analysis of his interests.
Output
Print the number of couples of customs with opposite t. The opposite number for x is number - x (0 is opposite to itself). Couples that only differ in the clients' order are considered the same.
Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator.
Examples
Input
5
-3 3 0 0 3
Output
3
Input
3
0 0 0
Output
3
Note
In the first sample the couples of opposite clients are: (1,2), (1,5) ΠΈ (3,4).
In the second sample any couple of clients is opposite.
Submitted Solution:
```
mod = 1000000007
ii = lambda : int(input())
si = lambda : input()
dgl = lambda : list(map(int, input()))
f = lambda : map(int, input().split())
il = lambda : list(map(int, input().split()))
ls = lambda : list(input())
n=ii()
l=il()
l2=[0]*30
for i in l:
l2[i+10]+=1
sm=0
for i in range(10):
sm+=l2[i]*l2[20-i]
print(sm+(l2[10]*(l2[10]-1))//2)
``` | instruction | 0 | 80,967 | 14 | 161,934 |
Yes | output | 1 | 80,967 | 14 | 161,935 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 β€ ti β€ 10). Of course, one number can be assigned to any number of customers.
"Perfect Matching" wants to advertise its services and publish the number of opposite couples, that is, the couples who have opposite values of t. Each couple consists of exactly two clients. The customer can be included in a couple an arbitrary number of times. Help the agency and write the program that will find the sought number by the given sequence t1, t2, ..., tn. For example, if t = (1, - 1, 1, - 1), then any two elements ti and tj form a couple if i and j have different parity. Consequently, in this case the sought number equals 4.
Of course, a client can't form a couple with him/herself.
Input
The first line of the input data contains an integer n (1 β€ n β€ 105) which represents the number of registered clients of the "Couple Matching". The second line contains a sequence of integers t1, t2, ..., tn ( - 10 β€ ti β€ 10), ti β is the parameter of the i-th customer that has been assigned to the customer by the result of the analysis of his interests.
Output
Print the number of couples of customs with opposite t. The opposite number for x is number - x (0 is opposite to itself). Couples that only differ in the clients' order are considered the same.
Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator.
Examples
Input
5
-3 3 0 0 3
Output
3
Input
3
0 0 0
Output
3
Note
In the first sample the couples of opposite clients are: (1,2), (1,5) ΠΈ (3,4).
In the second sample any couple of clients is opposite.
Submitted Solution:
```
N=int(input())
a=tuple(map(int,input().split()))
b=[0]*21
for i in a:
b[i+10]+=1
print((b[10]*(b[10]-1))//2+sum(b[i]*b[20-i] for i in range(10)))
``` | instruction | 0 | 80,968 | 14 | 161,936 |
Yes | output | 1 | 80,968 | 14 | 161,937 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 β€ ti β€ 10). Of course, one number can be assigned to any number of customers.
"Perfect Matching" wants to advertise its services and publish the number of opposite couples, that is, the couples who have opposite values of t. Each couple consists of exactly two clients. The customer can be included in a couple an arbitrary number of times. Help the agency and write the program that will find the sought number by the given sequence t1, t2, ..., tn. For example, if t = (1, - 1, 1, - 1), then any two elements ti and tj form a couple if i and j have different parity. Consequently, in this case the sought number equals 4.
Of course, a client can't form a couple with him/herself.
Input
The first line of the input data contains an integer n (1 β€ n β€ 105) which represents the number of registered clients of the "Couple Matching". The second line contains a sequence of integers t1, t2, ..., tn ( - 10 β€ ti β€ 10), ti β is the parameter of the i-th customer that has been assigned to the customer by the result of the analysis of his interests.
Output
Print the number of couples of customs with opposite t. The opposite number for x is number - x (0 is opposite to itself). Couples that only differ in the clients' order are considered the same.
Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator.
Examples
Input
5
-3 3 0 0 3
Output
3
Input
3
0 0 0
Output
3
Note
In the first sample the couples of opposite clients are: (1,2), (1,5) ΠΈ (3,4).
In the second sample any couple of clients is opposite.
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
c = [0]*24
for i in range(n):
c[a[i]] += 1
s = c[0]*(c[0]-1)//2
for i in range(1, 11):
s += c[i]*c[-i]
print(s)
``` | instruction | 0 | 80,969 | 14 | 161,938 |
Yes | output | 1 | 80,969 | 14 | 161,939 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 β€ ti β€ 10). Of course, one number can be assigned to any number of customers.
"Perfect Matching" wants to advertise its services and publish the number of opposite couples, that is, the couples who have opposite values of t. Each couple consists of exactly two clients. The customer can be included in a couple an arbitrary number of times. Help the agency and write the program that will find the sought number by the given sequence t1, t2, ..., tn. For example, if t = (1, - 1, 1, - 1), then any two elements ti and tj form a couple if i and j have different parity. Consequently, in this case the sought number equals 4.
Of course, a client can't form a couple with him/herself.
Input
The first line of the input data contains an integer n (1 β€ n β€ 105) which represents the number of registered clients of the "Couple Matching". The second line contains a sequence of integers t1, t2, ..., tn ( - 10 β€ ti β€ 10), ti β is the parameter of the i-th customer that has been assigned to the customer by the result of the analysis of his interests.
Output
Print the number of couples of customs with opposite t. The opposite number for x is number - x (0 is opposite to itself). Couples that only differ in the clients' order are considered the same.
Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator.
Examples
Input
5
-3 3 0 0 3
Output
3
Input
3
0 0 0
Output
3
Note
In the first sample the couples of opposite clients are: (1,2), (1,5) ΠΈ (3,4).
In the second sample any couple of clients is opposite.
Submitted Solution:
```
# Author : nitish420 --------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
# mod=10**9+7
# sys.setrecursionlimit(10**6)
# mxm=sys.maxsize
# from functools import lru_cache
from collections import Counter
def main():
n=int(input())
c=Counter(list(map(int,input().split())))
ans=0
if 0 in c:
ans+=(c[0]*(c[0]-1))//2
for i in range(1,11):
if i in c and -i in c:
ans+=c[i]*c[-i]
print(ans)
#----------------------------------------------------------------------------------------
def nouse0():
# This is to save my code from plag due to use of FAST IO template in it.
a=420
b=420
print(f'i am nitish{(a+b)//2}')
def nouse1():
# This is to save my code from plag due to use of FAST IO template in it.
a=420
b=420
print(f'i am nitish{(a+b)//2}')
def nouse2():
# This is to save my code from plag due to use of FAST IO template in it.
a=420
b=420
print(f'i am nitish{(a+b)//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')
# endregion
if __name__ == '__main__':
main()
``` | instruction | 0 | 80,970 | 14 | 161,940 |
Yes | output | 1 | 80,970 | 14 | 161,941 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 β€ ti β€ 10). Of course, one number can be assigned to any number of customers.
"Perfect Matching" wants to advertise its services and publish the number of opposite couples, that is, the couples who have opposite values of t. Each couple consists of exactly two clients. The customer can be included in a couple an arbitrary number of times. Help the agency and write the program that will find the sought number by the given sequence t1, t2, ..., tn. For example, if t = (1, - 1, 1, - 1), then any two elements ti and tj form a couple if i and j have different parity. Consequently, in this case the sought number equals 4.
Of course, a client can't form a couple with him/herself.
Input
The first line of the input data contains an integer n (1 β€ n β€ 105) which represents the number of registered clients of the "Couple Matching". The second line contains a sequence of integers t1, t2, ..., tn ( - 10 β€ ti β€ 10), ti β is the parameter of the i-th customer that has been assigned to the customer by the result of the analysis of his interests.
Output
Print the number of couples of customs with opposite t. The opposite number for x is number - x (0 is opposite to itself). Couples that only differ in the clients' order are considered the same.
Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator.
Examples
Input
5
-3 3 0 0 3
Output
3
Input
3
0 0 0
Output
3
Note
In the first sample the couples of opposite clients are: (1,2), (1,5) ΠΈ (3,4).
In the second sample any couple of clients is opposite.
Submitted Solution:
```
"""
Brandt Smith, Lemuel Gorion and Peter Haddad
codeforces.com
Problem 131B
"""
n = int(input())
x = input().split(' ')
t = [0] * 21
total = 0
for k in x:
t[int(k) + 10] += 1
total += t[10]
for i in range(10):
total += int((t[i] * t[20 - i]) / 2)
print(total)
``` | instruction | 0 | 80,971 | 14 | 161,942 |
No | output | 1 | 80,971 | 14 | 161,943 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 β€ ti β€ 10). Of course, one number can be assigned to any number of customers.
"Perfect Matching" wants to advertise its services and publish the number of opposite couples, that is, the couples who have opposite values of t. Each couple consists of exactly two clients. The customer can be included in a couple an arbitrary number of times. Help the agency and write the program that will find the sought number by the given sequence t1, t2, ..., tn. For example, if t = (1, - 1, 1, - 1), then any two elements ti and tj form a couple if i and j have different parity. Consequently, in this case the sought number equals 4.
Of course, a client can't form a couple with him/herself.
Input
The first line of the input data contains an integer n (1 β€ n β€ 105) which represents the number of registered clients of the "Couple Matching". The second line contains a sequence of integers t1, t2, ..., tn ( - 10 β€ ti β€ 10), ti β is the parameter of the i-th customer that has been assigned to the customer by the result of the analysis of his interests.
Output
Print the number of couples of customs with opposite t. The opposite number for x is number - x (0 is opposite to itself). Couples that only differ in the clients' order are considered the same.
Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator.
Examples
Input
5
-3 3 0 0 3
Output
3
Input
3
0 0 0
Output
3
Note
In the first sample the couples of opposite clients are: (1,2), (1,5) ΠΈ (3,4).
In the second sample any couple of clients is opposite.
Submitted Solution:
```
N=int(input());
countp=0;
countn=0;
countz=0;
t=list(map(int,input().split()))
for i in range(N):
x=t[i]
if(x==0):
countz+=1
elif(x>0):
countp+=1;
else:
countn+=1;
print(countp*countn+(countz*(countz-1))//2);
``` | instruction | 0 | 80,972 | 14 | 161,944 |
No | output | 1 | 80,972 | 14 | 161,945 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 β€ ti β€ 10). Of course, one number can be assigned to any number of customers.
"Perfect Matching" wants to advertise its services and publish the number of opposite couples, that is, the couples who have opposite values of t. Each couple consists of exactly two clients. The customer can be included in a couple an arbitrary number of times. Help the agency and write the program that will find the sought number by the given sequence t1, t2, ..., tn. For example, if t = (1, - 1, 1, - 1), then any two elements ti and tj form a couple if i and j have different parity. Consequently, in this case the sought number equals 4.
Of course, a client can't form a couple with him/herself.
Input
The first line of the input data contains an integer n (1 β€ n β€ 105) which represents the number of registered clients of the "Couple Matching". The second line contains a sequence of integers t1, t2, ..., tn ( - 10 β€ ti β€ 10), ti β is the parameter of the i-th customer that has been assigned to the customer by the result of the analysis of his interests.
Output
Print the number of couples of customs with opposite t. The opposite number for x is number - x (0 is opposite to itself). Couples that only differ in the clients' order are considered the same.
Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator.
Examples
Input
5
-3 3 0 0 3
Output
3
Input
3
0 0 0
Output
3
Note
In the first sample the couples of opposite clients are: (1,2), (1,5) ΠΈ (3,4).
In the second sample any couple of clients is opposite.
Submitted Solution:
```
import math
def function(n, nums):
nums.sort()
total=0
for i in nums:
if i<0:
total+=nums.count(abs(i))
total+=nums.count(0)
return total
if __name__=="__main__":
n=int(input())
nums=list(map(int, input().rstrip().split()))
print(function(n, nums))
``` | instruction | 0 | 80,973 | 14 | 161,946 |
No | output | 1 | 80,973 | 14 | 161,947 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 β€ ti β€ 10). Of course, one number can be assigned to any number of customers.
"Perfect Matching" wants to advertise its services and publish the number of opposite couples, that is, the couples who have opposite values of t. Each couple consists of exactly two clients. The customer can be included in a couple an arbitrary number of times. Help the agency and write the program that will find the sought number by the given sequence t1, t2, ..., tn. For example, if t = (1, - 1, 1, - 1), then any two elements ti and tj form a couple if i and j have different parity. Consequently, in this case the sought number equals 4.
Of course, a client can't form a couple with him/herself.
Input
The first line of the input data contains an integer n (1 β€ n β€ 105) which represents the number of registered clients of the "Couple Matching". The second line contains a sequence of integers t1, t2, ..., tn ( - 10 β€ ti β€ 10), ti β is the parameter of the i-th customer that has been assigned to the customer by the result of the analysis of his interests.
Output
Print the number of couples of customs with opposite t. The opposite number for x is number - x (0 is opposite to itself). Couples that only differ in the clients' order are considered the same.
Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator.
Examples
Input
5
-3 3 0 0 3
Output
3
Input
3
0 0 0
Output
3
Note
In the first sample the couples of opposite clients are: (1,2), (1,5) ΠΈ (3,4).
In the second sample any couple of clients is opposite.
Submitted Solution:
```
import math
n=int(input())
x=list(map(int,input().split()))
num=(x.count(1)*x.count(-1))+(x.count(2)*x.count(-2))+(x.count(3)*x.count(-3))+(x.count(4)*x.count(-4))+(x.count(5)*x.count(-5))+(x.count(6)*x.count(-6))+(x.count(7)*x.count(-7))+(x.count(8)*x.count(-8))+(x.count(9)*x.count(-9))+(x.count(10)*x.count(-10))
if x.count(0)>1: print((x.count(0)*(x.count(0))-1)/2)
print(int(num))
``` | instruction | 0 | 80,974 | 14 | 161,948 |
No | output | 1 | 80,974 | 14 | 161,949 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Overall there are m actors in Berland. Each actor has a personal identifier β an integer from 1 to m (distinct actors have distinct identifiers). Vasya likes to watch Berland movies with Berland actors, and he has k favorite actors. He watched the movie trailers for the next month and wrote the following information for every movie: the movie title, the number of actors who starred in it, and the identifiers of these actors. Besides, he managed to copy the movie titles and how many actors starred there, but he didn't manage to write down the identifiers of some actors. Vasya looks at his records and wonders which movies may be his favourite, and which ones may not be. Once Vasya learns the exact cast of all movies, his favorite movies will be determined as follows: a movie becomes favorite movie, if no other movie from Vasya's list has more favorite actors.
Help the boy to determine the following for each movie:
* whether it surely will be his favourite movie;
* whether it surely won't be his favourite movie;
* can either be favourite or not.
Input
The first line of the input contains two integers m and k (1 β€ m β€ 100, 1 β€ k β€ m) β the number of actors in Berland and the number of Vasya's favourite actors.
The second line contains k distinct integers ai (1 β€ ai β€ m) β the identifiers of Vasya's favourite actors.
The third line contains a single integer n (1 β€ n β€ 100) β the number of movies in Vasya's list.
Then follow n blocks of lines, each block contains a movie's description. The i-th movie's description contains three lines:
* the first line contains string si (si consists of lowercase English letters and can have the length of from 1 to 10 characters, inclusive) β the movie's title,
* the second line contains a non-negative integer di (1 β€ di β€ m) β the number of actors who starred in this movie,
* the third line has di integers bi, j (0 β€ bi, j β€ m) β the identifiers of the actors who star in this movie. If bi, j = 0, than Vasya doesn't remember the identifier of the j-th actor. It is guaranteed that the list of actors for a movie doesn't contain the same actors.
All movies have distinct names. The numbers on the lines are separated by single spaces.
Output
Print n lines in the output. In the i-th line print:
* 0, if the i-th movie will surely be the favourite;
* 1, if the i-th movie won't surely be the favourite;
* 2, if the i-th movie can either be favourite, or not favourite.
Examples
Input
5 3
1 2 3
6
firstfilm
3
0 0 0
secondfilm
4
0 0 4 5
thirdfilm
1
2
fourthfilm
1
5
fifthfilm
1
4
sixthfilm
2
1 0
Output
2
2
1
1
1
2
Input
5 3
1 3 5
4
jumanji
3
0 0 0
theeagle
5
1 2 3 4 0
matrix
3
2 4 0
sourcecode
2
2 4
Output
2
0
1
1
Note
Note to the second sample:
* Movie jumanji can theoretically have from 1 to 3 Vasya's favourite actors.
* Movie theeagle has all three favourite actors, as the actor Vasya failed to remember, can only have identifier 5.
* Movie matrix can have exactly one favourite actor.
* Movie sourcecode doesn't have any favourite actors.
Thus, movie theeagle will surely be favourite, movies matrix and sourcecode won't surely be favourite, and movie jumanji can be either favourite (if it has all three favourite actors), or not favourite. | instruction | 0 | 81,081 | 14 | 162,162 |
Tags: implementation
Correct Solution:
```
import sys
try:
sys.stdin = open('input.txt')
sys.stdout = open('output.txt', 'w')
except:
pass
def compl(n, s):
return set(filter(lambda x: x not in s, range(1, n + 1)))
m, k = list(map(int, input().split()))
id = list(map(int, input().split()))
n = int(input())
favorite = set(id)
if n == 1:
print(0)
exit()
best = []
guaranteed = []
for i in range(n):
name = input()
cnt = int(input())
tmp = list(map(int, input().split()))
s = set()
cnt_zero = 0
for elem in tmp:
if elem != 0:
s.add(elem)
else:
cnt_zero += 1
inter = s & favorite
comp = compl(m, favorite | s)
pred = max(0, cnt_zero - len(comp))
g = len(inter) + pred
guaranteed.append(g)
cnt_zero -= pred
b = g + min(cnt_zero, len(favorite - s) - pred)
best.append(b)
max_g = max(guaranteed)
for i in range(n):
max_b = 0
for j in range(n):
if i == j:
continue
max_b = max(max_b, best[j])
if guaranteed[i] >= max_b:
print(0)
elif best[i] < max_g:
print(1)
else:
print(2)
``` | output | 1 | 81,081 | 14 | 162,163 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Overall there are m actors in Berland. Each actor has a personal identifier β an integer from 1 to m (distinct actors have distinct identifiers). Vasya likes to watch Berland movies with Berland actors, and he has k favorite actors. He watched the movie trailers for the next month and wrote the following information for every movie: the movie title, the number of actors who starred in it, and the identifiers of these actors. Besides, he managed to copy the movie titles and how many actors starred there, but he didn't manage to write down the identifiers of some actors. Vasya looks at his records and wonders which movies may be his favourite, and which ones may not be. Once Vasya learns the exact cast of all movies, his favorite movies will be determined as follows: a movie becomes favorite movie, if no other movie from Vasya's list has more favorite actors.
Help the boy to determine the following for each movie:
* whether it surely will be his favourite movie;
* whether it surely won't be his favourite movie;
* can either be favourite or not.
Input
The first line of the input contains two integers m and k (1 β€ m β€ 100, 1 β€ k β€ m) β the number of actors in Berland and the number of Vasya's favourite actors.
The second line contains k distinct integers ai (1 β€ ai β€ m) β the identifiers of Vasya's favourite actors.
The third line contains a single integer n (1 β€ n β€ 100) β the number of movies in Vasya's list.
Then follow n blocks of lines, each block contains a movie's description. The i-th movie's description contains three lines:
* the first line contains string si (si consists of lowercase English letters and can have the length of from 1 to 10 characters, inclusive) β the movie's title,
* the second line contains a non-negative integer di (1 β€ di β€ m) β the number of actors who starred in this movie,
* the third line has di integers bi, j (0 β€ bi, j β€ m) β the identifiers of the actors who star in this movie. If bi, j = 0, than Vasya doesn't remember the identifier of the j-th actor. It is guaranteed that the list of actors for a movie doesn't contain the same actors.
All movies have distinct names. The numbers on the lines are separated by single spaces.
Output
Print n lines in the output. In the i-th line print:
* 0, if the i-th movie will surely be the favourite;
* 1, if the i-th movie won't surely be the favourite;
* 2, if the i-th movie can either be favourite, or not favourite.
Examples
Input
5 3
1 2 3
6
firstfilm
3
0 0 0
secondfilm
4
0 0 4 5
thirdfilm
1
2
fourthfilm
1
5
fifthfilm
1
4
sixthfilm
2
1 0
Output
2
2
1
1
1
2
Input
5 3
1 3 5
4
jumanji
3
0 0 0
theeagle
5
1 2 3 4 0
matrix
3
2 4 0
sourcecode
2
2 4
Output
2
0
1
1
Note
Note to the second sample:
* Movie jumanji can theoretically have from 1 to 3 Vasya's favourite actors.
* Movie theeagle has all three favourite actors, as the actor Vasya failed to remember, can only have identifier 5.
* Movie matrix can have exactly one favourite actor.
* Movie sourcecode doesn't have any favourite actors.
Thus, movie theeagle will surely be favourite, movies matrix and sourcecode won't surely be favourite, and movie jumanji can be either favourite (if it has all three favourite actors), or not favourite.
Submitted Solution:
```
f = open('input.txt')
g = open('output.txt', 'w')
m, k = map(int, f.readline().strip().split(' '))
v = frozenset(map(int, f.readline().strip().split(' ')))
n = int(f.readline().strip())
x = []
maxyes = 0
maxnoeffort = 0
for _ in range(n):
f.readline().strip()
f.readline().strip()
info = [0, 0, 0] # yes no maybe
for a in map(int, f.readline().strip().split(' ')):
if a == 0:
info[2] += 1
elif a in v:
info[0] += 1
else:
info[1] += 1
mustbeyes = max(0, info[2] - ((m - k) - info[1]))
mustbeno = max(0, info[2] - (k - info[0]))
info[0] += mustbeyes
info[1] += mustbeno
info[2] -= (mustbeyes + mustbeno)
mi = info[0]
ma = info[0] + info[2]
x.append((mi, ma))
maxyes = max(maxyes, ma)
maxnoeffort = max(maxnoeffort, mi)
for a in x:
if a[0] >= maxyes:
g.write("0\n")
elif a[1] < maxnoeffort:
g.write("1\n")
else:
g.write("2\n")
``` | instruction | 0 | 81,082 | 14 | 162,164 |
No | output | 1 | 81,082 | 14 | 162,165 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Overall there are m actors in Berland. Each actor has a personal identifier β an integer from 1 to m (distinct actors have distinct identifiers). Vasya likes to watch Berland movies with Berland actors, and he has k favorite actors. He watched the movie trailers for the next month and wrote the following information for every movie: the movie title, the number of actors who starred in it, and the identifiers of these actors. Besides, he managed to copy the movie titles and how many actors starred there, but he didn't manage to write down the identifiers of some actors. Vasya looks at his records and wonders which movies may be his favourite, and which ones may not be. Once Vasya learns the exact cast of all movies, his favorite movies will be determined as follows: a movie becomes favorite movie, if no other movie from Vasya's list has more favorite actors.
Help the boy to determine the following for each movie:
* whether it surely will be his favourite movie;
* whether it surely won't be his favourite movie;
* can either be favourite or not.
Input
The first line of the input contains two integers m and k (1 β€ m β€ 100, 1 β€ k β€ m) β the number of actors in Berland and the number of Vasya's favourite actors.
The second line contains k distinct integers ai (1 β€ ai β€ m) β the identifiers of Vasya's favourite actors.
The third line contains a single integer n (1 β€ n β€ 100) β the number of movies in Vasya's list.
Then follow n blocks of lines, each block contains a movie's description. The i-th movie's description contains three lines:
* the first line contains string si (si consists of lowercase English letters and can have the length of from 1 to 10 characters, inclusive) β the movie's title,
* the second line contains a non-negative integer di (1 β€ di β€ m) β the number of actors who starred in this movie,
* the third line has di integers bi, j (0 β€ bi, j β€ m) β the identifiers of the actors who star in this movie. If bi, j = 0, than Vasya doesn't remember the identifier of the j-th actor. It is guaranteed that the list of actors for a movie doesn't contain the same actors.
All movies have distinct names. The numbers on the lines are separated by single spaces.
Output
Print n lines in the output. In the i-th line print:
* 0, if the i-th movie will surely be the favourite;
* 1, if the i-th movie won't surely be the favourite;
* 2, if the i-th movie can either be favourite, or not favourite.
Examples
Input
5 3
1 2 3
6
firstfilm
3
0 0 0
secondfilm
4
0 0 4 5
thirdfilm
1
2
fourthfilm
1
5
fifthfilm
1
4
sixthfilm
2
1 0
Output
2
2
1
1
1
2
Input
5 3
1 3 5
4
jumanji
3
0 0 0
theeagle
5
1 2 3 4 0
matrix
3
2 4 0
sourcecode
2
2 4
Output
2
0
1
1
Note
Note to the second sample:
* Movie jumanji can theoretically have from 1 to 3 Vasya's favourite actors.
* Movie theeagle has all three favourite actors, as the actor Vasya failed to remember, can only have identifier 5.
* Movie matrix can have exactly one favourite actor.
* Movie sourcecode doesn't have any favourite actors.
Thus, movie theeagle will surely be favourite, movies matrix and sourcecode won't surely be favourite, and movie jumanji can be either favourite (if it has all three favourite actors), or not favourite.
Submitted Solution:
```
fi = open('input.txt', 'r')
m, k = map(int, fi.readline().split())
f, n, v1, v2 = set(map(int, fi.readline().split())), int(fi.readline()), [], []
for i in range(n):
fi.readline()
c, a = int(fi.readline()), list(map(int, fi.readline().split()))
u, b = a.count(0), len(f & set(a))
v1.append(b + max(0, k + c - m - b))
v2.append(b + min(k - b, u))
vc1, vc2 = max(v1), max(v2)
fo = open('output.txt', 'w')
for i in range(n):
if v1[i] == vc2:
print('0', file=fo)
elif v2[i] < vc1:
print('1', file=fo)
else:
print('2', file=fo)
``` | instruction | 0 | 81,083 | 14 | 162,166 |
No | output | 1 | 81,083 | 14 | 162,167 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Overall there are m actors in Berland. Each actor has a personal identifier β an integer from 1 to m (distinct actors have distinct identifiers). Vasya likes to watch Berland movies with Berland actors, and he has k favorite actors. He watched the movie trailers for the next month and wrote the following information for every movie: the movie title, the number of actors who starred in it, and the identifiers of these actors. Besides, he managed to copy the movie titles and how many actors starred there, but he didn't manage to write down the identifiers of some actors. Vasya looks at his records and wonders which movies may be his favourite, and which ones may not be. Once Vasya learns the exact cast of all movies, his favorite movies will be determined as follows: a movie becomes favorite movie, if no other movie from Vasya's list has more favorite actors.
Help the boy to determine the following for each movie:
* whether it surely will be his favourite movie;
* whether it surely won't be his favourite movie;
* can either be favourite or not.
Input
The first line of the input contains two integers m and k (1 β€ m β€ 100, 1 β€ k β€ m) β the number of actors in Berland and the number of Vasya's favourite actors.
The second line contains k distinct integers ai (1 β€ ai β€ m) β the identifiers of Vasya's favourite actors.
The third line contains a single integer n (1 β€ n β€ 100) β the number of movies in Vasya's list.
Then follow n blocks of lines, each block contains a movie's description. The i-th movie's description contains three lines:
* the first line contains string si (si consists of lowercase English letters and can have the length of from 1 to 10 characters, inclusive) β the movie's title,
* the second line contains a non-negative integer di (1 β€ di β€ m) β the number of actors who starred in this movie,
* the third line has di integers bi, j (0 β€ bi, j β€ m) β the identifiers of the actors who star in this movie. If bi, j = 0, than Vasya doesn't remember the identifier of the j-th actor. It is guaranteed that the list of actors for a movie doesn't contain the same actors.
All movies have distinct names. The numbers on the lines are separated by single spaces.
Output
Print n lines in the output. In the i-th line print:
* 0, if the i-th movie will surely be the favourite;
* 1, if the i-th movie won't surely be the favourite;
* 2, if the i-th movie can either be favourite, or not favourite.
Examples
Input
5 3
1 2 3
6
firstfilm
3
0 0 0
secondfilm
4
0 0 4 5
thirdfilm
1
2
fourthfilm
1
5
fifthfilm
1
4
sixthfilm
2
1 0
Output
2
2
1
1
1
2
Input
5 3
1 3 5
4
jumanji
3
0 0 0
theeagle
5
1 2 3 4 0
matrix
3
2 4 0
sourcecode
2
2 4
Output
2
0
1
1
Note
Note to the second sample:
* Movie jumanji can theoretically have from 1 to 3 Vasya's favourite actors.
* Movie theeagle has all three favourite actors, as the actor Vasya failed to remember, can only have identifier 5.
* Movie matrix can have exactly one favourite actor.
* Movie sourcecode doesn't have any favourite actors.
Thus, movie theeagle will surely be favourite, movies matrix and sourcecode won't surely be favourite, and movie jumanji can be either favourite (if it has all three favourite actors), or not favourite.
Submitted Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq,bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
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")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=2**51, func=lambda a, b: a & b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: max(a , b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] < key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
m,k=map(int,input().split())
l=set(map(int,input().split()))
n=int(input())
ma=[]
mi=[]
kl=[]
for i in range(n):
s=input()
w=int(input())
li=list(map(int,input().split()))
er=0
fav=0
unfav=0
for i in li:
if i==0:
er+=1
continue
if i in l:
fav+=1
else:
unfav+=1
kl.append((fav+min(er,k-fav),w-(unfav+min(m-k-unfav,er))))
if n==1:
print(1)
sys.exit(0)
for i in range(n):
t=0
rt=0
for j in range(n):
if j==i:
continue
if kl[i][0]<kl[j][1]:
print(1)
t=1
break
if not kl[i][1]>=kl[j][0]:
rt=1
if t==0 and rt==1:
print(2)
elif t==0 and rt==0:
print(0)
``` | instruction | 0 | 81,084 | 14 | 162,168 |
No | output | 1 | 81,084 | 14 | 162,169 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Overall there are m actors in Berland. Each actor has a personal identifier β an integer from 1 to m (distinct actors have distinct identifiers). Vasya likes to watch Berland movies with Berland actors, and he has k favorite actors. He watched the movie trailers for the next month and wrote the following information for every movie: the movie title, the number of actors who starred in it, and the identifiers of these actors. Besides, he managed to copy the movie titles and how many actors starred there, but he didn't manage to write down the identifiers of some actors. Vasya looks at his records and wonders which movies may be his favourite, and which ones may not be. Once Vasya learns the exact cast of all movies, his favorite movies will be determined as follows: a movie becomes favorite movie, if no other movie from Vasya's list has more favorite actors.
Help the boy to determine the following for each movie:
* whether it surely will be his favourite movie;
* whether it surely won't be his favourite movie;
* can either be favourite or not.
Input
The first line of the input contains two integers m and k (1 β€ m β€ 100, 1 β€ k β€ m) β the number of actors in Berland and the number of Vasya's favourite actors.
The second line contains k distinct integers ai (1 β€ ai β€ m) β the identifiers of Vasya's favourite actors.
The third line contains a single integer n (1 β€ n β€ 100) β the number of movies in Vasya's list.
Then follow n blocks of lines, each block contains a movie's description. The i-th movie's description contains three lines:
* the first line contains string si (si consists of lowercase English letters and can have the length of from 1 to 10 characters, inclusive) β the movie's title,
* the second line contains a non-negative integer di (1 β€ di β€ m) β the number of actors who starred in this movie,
* the third line has di integers bi, j (0 β€ bi, j β€ m) β the identifiers of the actors who star in this movie. If bi, j = 0, than Vasya doesn't remember the identifier of the j-th actor. It is guaranteed that the list of actors for a movie doesn't contain the same actors.
All movies have distinct names. The numbers on the lines are separated by single spaces.
Output
Print n lines in the output. In the i-th line print:
* 0, if the i-th movie will surely be the favourite;
* 1, if the i-th movie won't surely be the favourite;
* 2, if the i-th movie can either be favourite, or not favourite.
Examples
Input
5 3
1 2 3
6
firstfilm
3
0 0 0
secondfilm
4
0 0 4 5
thirdfilm
1
2
fourthfilm
1
5
fifthfilm
1
4
sixthfilm
2
1 0
Output
2
2
1
1
1
2
Input
5 3
1 3 5
4
jumanji
3
0 0 0
theeagle
5
1 2 3 4 0
matrix
3
2 4 0
sourcecode
2
2 4
Output
2
0
1
1
Note
Note to the second sample:
* Movie jumanji can theoretically have from 1 to 3 Vasya's favourite actors.
* Movie theeagle has all three favourite actors, as the actor Vasya failed to remember, can only have identifier 5.
* Movie matrix can have exactly one favourite actor.
* Movie sourcecode doesn't have any favourite actors.
Thus, movie theeagle will surely be favourite, movies matrix and sourcecode won't surely be favourite, and movie jumanji can be either favourite (if it has all three favourite actors), or not favourite.
Submitted Solution:
```
import sys
try:
sys.stdin = open('input.txt')
sys.stdout = open('output.txt', 'w')
except:
pass
def compl(n, s):
return set(filter(lambda x: x not in s, range(1, n + 1)))
m, k = list(map(int, input().split()))
id = list(map(int, input().split()))
n = int(input())
favorite = set(id)
if n == 1:
print(0)
exit()
best = []
guaranteed = []
for i in range(n):
name = input()
cnt = int(input())
tmp = list(map(int, input().split()))
s = set()
cnt_zero = 0
for elem in tmp:
if elem != 0:
s.add(elem)
else:
cnt_zero += 1
inter = s & favorite
comp = compl(m, favorite | s)
pred = max(0, cnt_zero - len(comp))
g = len(inter) + pred
guaranteed.append(g)
cnt_zero -= pred
b = g + min(cnt_zero, len(favorite - s) - pred)
best.append(b)
for i in range(n):
max_g, max_b = 0, 0
for j in range(n):
if i == j:
continue
max_g = max(max_g, guaranteed[j])
max_b = max(max_b, best[j])
if guaranteed[i] == max_b:
print(0)
elif best[i] < max_g:
print(1)
else:
print(2)
``` | instruction | 0 | 81,085 | 14 | 162,170 |
No | output | 1 | 81,085 | 14 | 162,171 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little penguin Polo loves his home village. The village has n houses, indexed by integers from 1 to n. Each house has a plaque containing an integer, the i-th house has a plaque containing integer pi (1 β€ pi β€ n).
Little penguin Polo loves walking around this village. The walk looks like that. First he stands by a house number x. Then he goes to the house whose number is written on the plaque of house x (that is, to house px), then he goes to the house whose number is written on the plaque of house px (that is, to house ppx), and so on.
We know that:
1. When the penguin starts walking from any house indexed from 1 to k, inclusive, he can walk to house number 1.
2. When the penguin starts walking from any house indexed from k + 1 to n, inclusive, he definitely cannot walk to house number 1.
3. When the penguin starts walking from house number 1, he can get back to house number 1 after some non-zero number of walks from a house to a house.
You need to find the number of ways you may write the numbers on the houses' plaques so as to fulfill the three above described conditions. Print the remainder after dividing this number by 1000000007 (109 + 7).
Input
The single line contains two space-separated integers n and k (1 β€ n β€ 1000, 1 β€ k β€ min(8, n)) β the number of the houses and the number k from the statement.
Output
In a single line print a single integer β the answer to the problem modulo 1000000007 (109 + 7).
Examples
Input
5 2
Output
54
Input
7 4
Output
1728 | instruction | 0 | 81,092 | 14 | 162,184 |
Tags: combinatorics
Correct Solution:
```
def g(n2, l):
if n2==0: return c(l)
n3 = 0
for i in range(m):
if i==m-n2: continue
n3 += g(n2-1, l+[i])
return n3%mod
def c(l):
v = [10,0,0,0,0,0,0,0]
for i in range(1,len(l)):
if v[i]: continue
n2 = i
while True:
v[n2] = i
n2 = l[n2]
if v[n2]==i: return 0
if v[n2]: break
return 1
mod = int(1e9+7)
t = input().split()
n=int(t[0])
m=int(t[1])
b = 1
for i in range(n-m):
b = (b*(n-m))%mod
if m>1:
print(str(((g(m, [])//(m-1))*m*b)%mod))
else:
print(str(b))
``` | output | 1 | 81,092 | 14 | 162,185 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little penguin Polo loves his home village. The village has n houses, indexed by integers from 1 to n. Each house has a plaque containing an integer, the i-th house has a plaque containing integer pi (1 β€ pi β€ n).
Little penguin Polo loves walking around this village. The walk looks like that. First he stands by a house number x. Then he goes to the house whose number is written on the plaque of house x (that is, to house px), then he goes to the house whose number is written on the plaque of house px (that is, to house ppx), and so on.
We know that:
1. When the penguin starts walking from any house indexed from 1 to k, inclusive, he can walk to house number 1.
2. When the penguin starts walking from any house indexed from k + 1 to n, inclusive, he definitely cannot walk to house number 1.
3. When the penguin starts walking from house number 1, he can get back to house number 1 after some non-zero number of walks from a house to a house.
You need to find the number of ways you may write the numbers on the houses' plaques so as to fulfill the three above described conditions. Print the remainder after dividing this number by 1000000007 (109 + 7).
Input
The single line contains two space-separated integers n and k (1 β€ n β€ 1000, 1 β€ k β€ min(8, n)) β the number of the houses and the number k from the statement.
Output
In a single line print a single integer β the answer to the problem modulo 1000000007 (109 + 7).
Examples
Input
5 2
Output
54
Input
7 4
Output
1728 | instruction | 0 | 81,095 | 14 | 162,190 |
Tags: combinatorics
Correct Solution:
```
n, k = map(int, input().split())
mod = 1000000007
print((pow(k, k-1, mod) * pow(n-k, n-k, mod)) % mod)
``` | output | 1 | 81,095 | 14 | 162,191 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little penguin Polo loves his home village. The village has n houses, indexed by integers from 1 to n. Each house has a plaque containing an integer, the i-th house has a plaque containing integer pi (1 β€ pi β€ n).
Little penguin Polo loves walking around this village. The walk looks like that. First he stands by a house number x. Then he goes to the house whose number is written on the plaque of house x (that is, to house px), then he goes to the house whose number is written on the plaque of house px (that is, to house ppx), and so on.
We know that:
1. When the penguin starts walking from any house indexed from 1 to k, inclusive, he can walk to house number 1.
2. When the penguin starts walking from any house indexed from k + 1 to n, inclusive, he definitely cannot walk to house number 1.
3. When the penguin starts walking from house number 1, he can get back to house number 1 after some non-zero number of walks from a house to a house.
You need to find the number of ways you may write the numbers on the houses' plaques so as to fulfill the three above described conditions. Print the remainder after dividing this number by 1000000007 (109 + 7).
Input
The single line contains two space-separated integers n and k (1 β€ n β€ 1000, 1 β€ k β€ min(8, n)) β the number of the houses and the number k from the statement.
Output
In a single line print a single integer β the answer to the problem modulo 1000000007 (109 + 7).
Examples
Input
5 2
Output
54
Input
7 4
Output
1728 | instruction | 0 | 81,098 | 14 | 162,196 |
Tags: combinatorics
Correct Solution:
```
n, k = map(int, input().split())
d = 1000000007
def f(a, b):
if b == 0: return 1
s, c = 0, b * a
for i in range(1, b + 1):
s += c * f(i, b - i)
c = (a * c * (b - i)) // (i + 1)
return s
print((k * f(1, k - 1) * pow(n - k, n - k, d)) % d)
``` | output | 1 | 81,098 | 14 | 162,197 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little penguin Polo loves his home village. The village has n houses, indexed by integers from 1 to n. Each house has a plaque containing an integer, the i-th house has a plaque containing integer pi (1 β€ pi β€ n).
Little penguin Polo loves walking around this village. The walk looks like that. First he stands by a house number x. Then he goes to the house whose number is written on the plaque of house x (that is, to house px), then he goes to the house whose number is written on the plaque of house px (that is, to house ppx), and so on.
We know that:
1. When the penguin starts walking from any house indexed from 1 to k, inclusive, he can walk to house number 1.
2. When the penguin starts walking from any house indexed from k + 1 to n, inclusive, he definitely cannot walk to house number 1.
3. When the penguin starts walking from house number 1, he can get back to house number 1 after some non-zero number of walks from a house to a house.
You need to find the number of ways you may write the numbers on the houses' plaques so as to fulfill the three above described conditions. Print the remainder after dividing this number by 1000000007 (109 + 7).
Input
The single line contains two space-separated integers n and k (1 β€ n β€ 1000, 1 β€ k β€ min(8, n)) β the number of the houses and the number k from the statement.
Output
In a single line print a single integer β the answer to the problem modulo 1000000007 (109 + 7).
Examples
Input
5 2
Output
54
Input
7 4
Output
1728 | instruction | 0 | 81,099 | 14 | 162,198 |
Tags: combinatorics
Correct Solution:
```
MOD = 10 ** 9 + 7
n, k = map(int, input().split())
ans = pow(n - k, n - k, MOD) * pow(k, k - 1, MOD)
print(ans % MOD)
``` | output | 1 | 81,099 | 14 | 162,199 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub helps his grandfather at the farm. Today he must milk the cows. There are n cows sitting in a row, numbered from 1 to n from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of milk that they can give. A cow facing left sees all the cows with lower indices than her index, and a cow facing right sees all the cows with higher indices than her index. A cow that got scared once can get scared again (and lose one more unit of milk). A cow that has been milked once cannot get scared and lose any more milk. You can assume that a cow never loses all the milk she can give (a cow gives an infinitely amount of milk).
Iahub can decide the order in which he milks the cows. But he must milk each cow exactly once. Iahub wants to lose as little milk as possible. Print the minimum amount of milk that is lost.
Input
The first line contains an integer n (1 β€ n β€ 200000). The second line contains n integers a1, a2, ..., an, where ai is 0 if the cow number i is facing left, and 1 if it is facing right.
Output
Print a single integer, the minimum amount of lost milk.
Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
4
0 0 1 0
Output
1
Input
5
1 0 1 0 1
Output
3
Note
In the first sample Iahub milks the cows in the following order: cow 3, cow 4, cow 2, cow 1. When he milks cow 3, cow 4 loses 1 unit of milk. After that, no more milk is lost. | instruction | 0 | 81,129 | 14 | 162,258 |
Tags: data structures, greedy
Correct Solution:
```
n=int(input())
l=list(map(int,input().split()))
x=l.count(0)
y=l.count(1)
if x>=y:
a=[]
k=0
for i in range(n-1,-1,-1):
if l[i]==1:
a.append(k)
else:
k+=1
else:
a=[]
k=0
for i in range(n):
if l[i]==0:
a.append(k)
else:
k+=1
print(sum(a))
``` | output | 1 | 81,129 | 14 | 162,259 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub helps his grandfather at the farm. Today he must milk the cows. There are n cows sitting in a row, numbered from 1 to n from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of milk that they can give. A cow facing left sees all the cows with lower indices than her index, and a cow facing right sees all the cows with higher indices than her index. A cow that got scared once can get scared again (and lose one more unit of milk). A cow that has been milked once cannot get scared and lose any more milk. You can assume that a cow never loses all the milk she can give (a cow gives an infinitely amount of milk).
Iahub can decide the order in which he milks the cows. But he must milk each cow exactly once. Iahub wants to lose as little milk as possible. Print the minimum amount of milk that is lost.
Input
The first line contains an integer n (1 β€ n β€ 200000). The second line contains n integers a1, a2, ..., an, where ai is 0 if the cow number i is facing left, and 1 if it is facing right.
Output
Print a single integer, the minimum amount of lost milk.
Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
4
0 0 1 0
Output
1
Input
5
1 0 1 0 1
Output
3
Note
In the first sample Iahub milks the cows in the following order: cow 3, cow 4, cow 2, cow 1. When he milks cow 3, cow 4 loses 1 unit of milk. After that, no more milk is lost. | instruction | 0 | 81,130 | 14 | 162,260 |
Tags: data structures, greedy
Correct Solution:
```
# Made By Mostafa_Khaled
bot = True
n = int(input())
s = k = 0
for i in input()[::2]:
if i == '1':
k += 1
else:
s += k
print(s)
# Made By Mostafa_Khaled
``` | output | 1 | 81,130 | 14 | 162,261 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub helps his grandfather at the farm. Today he must milk the cows. There are n cows sitting in a row, numbered from 1 to n from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of milk that they can give. A cow facing left sees all the cows with lower indices than her index, and a cow facing right sees all the cows with higher indices than her index. A cow that got scared once can get scared again (and lose one more unit of milk). A cow that has been milked once cannot get scared and lose any more milk. You can assume that a cow never loses all the milk she can give (a cow gives an infinitely amount of milk).
Iahub can decide the order in which he milks the cows. But he must milk each cow exactly once. Iahub wants to lose as little milk as possible. Print the minimum amount of milk that is lost.
Input
The first line contains an integer n (1 β€ n β€ 200000). The second line contains n integers a1, a2, ..., an, where ai is 0 if the cow number i is facing left, and 1 if it is facing right.
Output
Print a single integer, the minimum amount of lost milk.
Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
4
0 0 1 0
Output
1
Input
5
1 0 1 0 1
Output
3
Note
In the first sample Iahub milks the cows in the following order: cow 3, cow 4, cow 2, cow 1. When he milks cow 3, cow 4 loses 1 unit of milk. After that, no more milk is lost. | instruction | 0 | 81,131 | 14 | 162,262 |
Tags: data structures, greedy
Correct Solution:
```
n = int(input())
arr = list(map(int, input().split()))
zero_count = [0] * n
zero_count[n - 1] = int(arr[n - 1] == 0)
for i in reversed(range(n - 1)):
zero_count[i] = zero_count[i + 1] + int(arr[i] == 0)
res = 0
for i in range(n - 1):
if arr[i] == 1:
res += zero_count[i + 1]
print(res)
``` | output | 1 | 81,131 | 14 | 162,263 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub helps his grandfather at the farm. Today he must milk the cows. There are n cows sitting in a row, numbered from 1 to n from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of milk that they can give. A cow facing left sees all the cows with lower indices than her index, and a cow facing right sees all the cows with higher indices than her index. A cow that got scared once can get scared again (and lose one more unit of milk). A cow that has been milked once cannot get scared and lose any more milk. You can assume that a cow never loses all the milk she can give (a cow gives an infinitely amount of milk).
Iahub can decide the order in which he milks the cows. But he must milk each cow exactly once. Iahub wants to lose as little milk as possible. Print the minimum amount of milk that is lost.
Input
The first line contains an integer n (1 β€ n β€ 200000). The second line contains n integers a1, a2, ..., an, where ai is 0 if the cow number i is facing left, and 1 if it is facing right.
Output
Print a single integer, the minimum amount of lost milk.
Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
4
0 0 1 0
Output
1
Input
5
1 0 1 0 1
Output
3
Note
In the first sample Iahub milks the cows in the following order: cow 3, cow 4, cow 2, cow 1. When he milks cow 3, cow 4 loses 1 unit of milk. After that, no more milk is lost. | instruction | 0 | 81,132 | 14 | 162,264 |
Tags: data structures, greedy
Correct Solution:
```
n = int(input())
array = list(map(int, input().split()))
cnt = 0
s = [0 for i in range(n)]
s[n - 1] = 1 * (array[n - 1] == 0)
for i in range(n - 2, -1, -1):
s[i] = s[i + 1] + 1 * (array[i] == 0)
for i in range(n):
cnt += s[i] * (array[i] == 1)
print(cnt)
``` | output | 1 | 81,132 | 14 | 162,265 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub helps his grandfather at the farm. Today he must milk the cows. There are n cows sitting in a row, numbered from 1 to n from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of milk that they can give. A cow facing left sees all the cows with lower indices than her index, and a cow facing right sees all the cows with higher indices than her index. A cow that got scared once can get scared again (and lose one more unit of milk). A cow that has been milked once cannot get scared and lose any more milk. You can assume that a cow never loses all the milk she can give (a cow gives an infinitely amount of milk).
Iahub can decide the order in which he milks the cows. But he must milk each cow exactly once. Iahub wants to lose as little milk as possible. Print the minimum amount of milk that is lost.
Input
The first line contains an integer n (1 β€ n β€ 200000). The second line contains n integers a1, a2, ..., an, where ai is 0 if the cow number i is facing left, and 1 if it is facing right.
Output
Print a single integer, the minimum amount of lost milk.
Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
4
0 0 1 0
Output
1
Input
5
1 0 1 0 1
Output
3
Note
In the first sample Iahub milks the cows in the following order: cow 3, cow 4, cow 2, cow 1. When he milks cow 3, cow 4 loses 1 unit of milk. After that, no more milk is lost. | instruction | 0 | 81,133 | 14 | 162,266 |
Tags: data structures, greedy
Correct Solution:
```
n=int(input())
a=list(map(int,input().split()))
b=[0,0]
ans=0
for i in range(n):
b[a[i]]+=1
if a[i]==0: ans+=b[1]
print(ans)
``` | output | 1 | 81,133 | 14 | 162,267 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub helps his grandfather at the farm. Today he must milk the cows. There are n cows sitting in a row, numbered from 1 to n from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of milk that they can give. A cow facing left sees all the cows with lower indices than her index, and a cow facing right sees all the cows with higher indices than her index. A cow that got scared once can get scared again (and lose one more unit of milk). A cow that has been milked once cannot get scared and lose any more milk. You can assume that a cow never loses all the milk she can give (a cow gives an infinitely amount of milk).
Iahub can decide the order in which he milks the cows. But he must milk each cow exactly once. Iahub wants to lose as little milk as possible. Print the minimum amount of milk that is lost.
Input
The first line contains an integer n (1 β€ n β€ 200000). The second line contains n integers a1, a2, ..., an, where ai is 0 if the cow number i is facing left, and 1 if it is facing right.
Output
Print a single integer, the minimum amount of lost milk.
Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
4
0 0 1 0
Output
1
Input
5
1 0 1 0 1
Output
3
Note
In the first sample Iahub milks the cows in the following order: cow 3, cow 4, cow 2, cow 1. When he milks cow 3, cow 4 loses 1 unit of milk. After that, no more milk is lost. | instruction | 0 | 81,134 | 14 | 162,268 |
Tags: data structures, greedy
Correct Solution:
```
#n,k=map(int, input().split())
n=int(input())
arr=list(map(int,input().split()))
cnt=[0]*n
cnt[0]=arr[0]
for i in range(1,n):
cnt[i]=cnt[i-1]+arr[i]
ans=0
for i in range(n):
if arr[i]==0:
ans+=cnt[i]
print(ans)
``` | output | 1 | 81,134 | 14 | 162,269 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub helps his grandfather at the farm. Today he must milk the cows. There are n cows sitting in a row, numbered from 1 to n from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of milk that they can give. A cow facing left sees all the cows with lower indices than her index, and a cow facing right sees all the cows with higher indices than her index. A cow that got scared once can get scared again (and lose one more unit of milk). A cow that has been milked once cannot get scared and lose any more milk. You can assume that a cow never loses all the milk she can give (a cow gives an infinitely amount of milk).
Iahub can decide the order in which he milks the cows. But he must milk each cow exactly once. Iahub wants to lose as little milk as possible. Print the minimum amount of milk that is lost.
Input
The first line contains an integer n (1 β€ n β€ 200000). The second line contains n integers a1, a2, ..., an, where ai is 0 if the cow number i is facing left, and 1 if it is facing right.
Output
Print a single integer, the minimum amount of lost milk.
Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
4
0 0 1 0
Output
1
Input
5
1 0 1 0 1
Output
3
Note
In the first sample Iahub milks the cows in the following order: cow 3, cow 4, cow 2, cow 1. When he milks cow 3, cow 4 loses 1 unit of milk. After that, no more milk is lost. | instruction | 0 | 81,135 | 14 | 162,270 |
Tags: data structures, greedy
Correct Solution:
```
n=int(input())
a=list(map(int,input().split()))
b=0
c=0
d=0
e=0
for i in range(n):
b+=a[i]
c+=b*(1-a[i])
for i in range(n-1,-1,-1):
d+=1-a[i]
e+=d*a[i]
print(min(c,e))
``` | output | 1 | 81,135 | 14 | 162,271 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub helps his grandfather at the farm. Today he must milk the cows. There are n cows sitting in a row, numbered from 1 to n from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of milk that they can give. A cow facing left sees all the cows with lower indices than her index, and a cow facing right sees all the cows with higher indices than her index. A cow that got scared once can get scared again (and lose one more unit of milk). A cow that has been milked once cannot get scared and lose any more milk. You can assume that a cow never loses all the milk she can give (a cow gives an infinitely amount of milk).
Iahub can decide the order in which he milks the cows. But he must milk each cow exactly once. Iahub wants to lose as little milk as possible. Print the minimum amount of milk that is lost.
Input
The first line contains an integer n (1 β€ n β€ 200000). The second line contains n integers a1, a2, ..., an, where ai is 0 if the cow number i is facing left, and 1 if it is facing right.
Output
Print a single integer, the minimum amount of lost milk.
Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
4
0 0 1 0
Output
1
Input
5
1 0 1 0 1
Output
3
Note
In the first sample Iahub milks the cows in the following order: cow 3, cow 4, cow 2, cow 1. When he milks cow 3, cow 4 loses 1 unit of milk. After that, no more milk is lost. | instruction | 0 | 81,136 | 14 | 162,272 |
Tags: data structures, greedy
Correct Solution:
```
n = input()
a = [int(x) for x in input().split()]
ans=sum=0
for i in a:
if i==1:
sum+=1
else:
ans+=sum
print(ans)
``` | output | 1 | 81,136 | 14 | 162,273 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A social network for dogs called DH (DogHouse) has k special servers to recompress uploaded videos of cute cats. After each video is uploaded, it should be recompressed on one (any) of the servers, and only after that it can be saved in the social network.
We know that each server takes one second to recompress a one minute fragment. Thus, any server takes m seconds to recompress a m minute video.
We know the time when each of the n videos were uploaded to the network (in seconds starting from the moment all servers started working). All videos appear at different moments of time and they are recompressed in the order they appear. If some video appeared at time s, then its recompressing can start at that very moment, immediately. Some videos can await recompressing when all the servers are busy. In this case, as soon as a server is available, it immediately starts recompressing another video. The videos that await recompressing go in a queue. If by the moment the videos started being recompressed some servers are available, then any of them starts recompressing the video.
For each video find the moment it stops being recompressed.
Input
The first line of the input contains integers n and k (1 β€ n, k β€ 5Β·105) β the number of videos and servers, respectively.
Next n lines contain the descriptions of the videos as pairs of integers si, mi (1 β€ si, mi β€ 109), where si is the time in seconds when the i-th video appeared and mi is its duration in minutes. It is guaranteed that all the si's are distinct and the videos are given in the chronological order of upload, that is in the order of increasing si.
Output
Print n numbers e1, e2, ..., en, where ei is the time in seconds after the servers start working, when the i-th video will be recompressed.
Examples
Input
3 2
1 5
2 5
3 5
Output
6
7
11
Input
6 1
1 1000000000
2 1000000000
3 1000000000
4 1000000000
5 1000000000
6 3
Output
1000000001
2000000001
3000000001
4000000001
5000000001
5000000004 | instruction | 0 | 81,202 | 14 | 162,404 |
Tags: *special, data structures, implementation
Correct Solution:
```
import heapq
n, k = map(int, input().split())
pq = [0] * k
res = [None] * n
for i in range(n):
s, m = map(int, input().split())
time = max(pq[0], s) + m
heapq.heapreplace(pq, time)
res[i] = time
print("\n".join(map(str, res)))
``` | output | 1 | 81,202 | 14 | 162,405 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A social network for dogs called DH (DogHouse) has k special servers to recompress uploaded videos of cute cats. After each video is uploaded, it should be recompressed on one (any) of the servers, and only after that it can be saved in the social network.
We know that each server takes one second to recompress a one minute fragment. Thus, any server takes m seconds to recompress a m minute video.
We know the time when each of the n videos were uploaded to the network (in seconds starting from the moment all servers started working). All videos appear at different moments of time and they are recompressed in the order they appear. If some video appeared at time s, then its recompressing can start at that very moment, immediately. Some videos can await recompressing when all the servers are busy. In this case, as soon as a server is available, it immediately starts recompressing another video. The videos that await recompressing go in a queue. If by the moment the videos started being recompressed some servers are available, then any of them starts recompressing the video.
For each video find the moment it stops being recompressed.
Input
The first line of the input contains integers n and k (1 β€ n, k β€ 5Β·105) β the number of videos and servers, respectively.
Next n lines contain the descriptions of the videos as pairs of integers si, mi (1 β€ si, mi β€ 109), where si is the time in seconds when the i-th video appeared and mi is its duration in minutes. It is guaranteed that all the si's are distinct and the videos are given in the chronological order of upload, that is in the order of increasing si.
Output
Print n numbers e1, e2, ..., en, where ei is the time in seconds after the servers start working, when the i-th video will be recompressed.
Examples
Input
3 2
1 5
2 5
3 5
Output
6
7
11
Input
6 1
1 1000000000
2 1000000000
3 1000000000
4 1000000000
5 1000000000
6 3
Output
1000000001
2000000001
3000000001
4000000001
5000000001
5000000004 | instruction | 0 | 81,203 | 14 | 162,406 |
Tags: *special, data structures, implementation
Correct Solution:
```
import heapq
from sys import stdin, stdout
def __main__(n, k):
servers = [0] * k
times = []
for i in range(n):
s, m = list(map(int, stdin.readline().split()))
time = max(servers[0], s)
heapq.heapreplace(servers, time + m)
times.append(time + m)
stdout.write('\n'.join(str(time) for time in times) + '\n')
if __name__ == '__main__':
n, k = list(map(int, stdin.readline().split()))
__main__(n, k)
``` | output | 1 | 81,203 | 14 | 162,407 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A social network for dogs called DH (DogHouse) has k special servers to recompress uploaded videos of cute cats. After each video is uploaded, it should be recompressed on one (any) of the servers, and only after that it can be saved in the social network.
We know that each server takes one second to recompress a one minute fragment. Thus, any server takes m seconds to recompress a m minute video.
We know the time when each of the n videos were uploaded to the network (in seconds starting from the moment all servers started working). All videos appear at different moments of time and they are recompressed in the order they appear. If some video appeared at time s, then its recompressing can start at that very moment, immediately. Some videos can await recompressing when all the servers are busy. In this case, as soon as a server is available, it immediately starts recompressing another video. The videos that await recompressing go in a queue. If by the moment the videos started being recompressed some servers are available, then any of them starts recompressing the video.
For each video find the moment it stops being recompressed.
Input
The first line of the input contains integers n and k (1 β€ n, k β€ 5Β·105) β the number of videos and servers, respectively.
Next n lines contain the descriptions of the videos as pairs of integers si, mi (1 β€ si, mi β€ 109), where si is the time in seconds when the i-th video appeared and mi is its duration in minutes. It is guaranteed that all the si's are distinct and the videos are given in the chronological order of upload, that is in the order of increasing si.
Output
Print n numbers e1, e2, ..., en, where ei is the time in seconds after the servers start working, when the i-th video will be recompressed.
Examples
Input
3 2
1 5
2 5
3 5
Output
6
7
11
Input
6 1
1 1000000000
2 1000000000
3 1000000000
4 1000000000
5 1000000000
6 3
Output
1000000001
2000000001
3000000001
4000000001
5000000001
5000000004 | instruction | 0 | 81,204 | 14 | 162,408 |
Tags: *special, data structures, implementation
Correct Solution:
```
import atexit
import io
import sys
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER
@atexit.register
def write():
sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
def main():
import heapq
n, k = [int(i) for i in input().split()]
s, m = [0] * n, [0] * n
for i in range(n):
s[i], m[i] = [int(i) for i in input().split()]
current_time = 0
event = []
ans = [0] * n
i = 0
while len(event) or i < n:
if (len(event) == 0):
current_time = max(current_time, s[i])
heapq.heappush(event, (current_time + m[i], i))
i += 1
continue
e_time, e_id = event[0]
if e_time == current_time or i == n:
current_time = max(current_time, e_time)
ans[e_id] = e_time
heapq.heappop(event)
continue
if s[i] < e_time and len(event) < k:
current_time = max(current_time, s[i])
heapq.heappush(event, (current_time + m[i], i))
i += 1
continue
else:
current_time = ans[e_id] = e_time
heapq.heappop(event)
continue
print("\n".join([str(i) for i in ans]))
main()
``` | output | 1 | 81,204 | 14 | 162,409 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A social network for dogs called DH (DogHouse) has k special servers to recompress uploaded videos of cute cats. After each video is uploaded, it should be recompressed on one (any) of the servers, and only after that it can be saved in the social network.
We know that each server takes one second to recompress a one minute fragment. Thus, any server takes m seconds to recompress a m minute video.
We know the time when each of the n videos were uploaded to the network (in seconds starting from the moment all servers started working). All videos appear at different moments of time and they are recompressed in the order they appear. If some video appeared at time s, then its recompressing can start at that very moment, immediately. Some videos can await recompressing when all the servers are busy. In this case, as soon as a server is available, it immediately starts recompressing another video. The videos that await recompressing go in a queue. If by the moment the videos started being recompressed some servers are available, then any of them starts recompressing the video.
For each video find the moment it stops being recompressed.
Input
The first line of the input contains integers n and k (1 β€ n, k β€ 5Β·105) β the number of videos and servers, respectively.
Next n lines contain the descriptions of the videos as pairs of integers si, mi (1 β€ si, mi β€ 109), where si is the time in seconds when the i-th video appeared and mi is its duration in minutes. It is guaranteed that all the si's are distinct and the videos are given in the chronological order of upload, that is in the order of increasing si.
Output
Print n numbers e1, e2, ..., en, where ei is the time in seconds after the servers start working, when the i-th video will be recompressed.
Examples
Input
3 2
1 5
2 5
3 5
Output
6
7
11
Input
6 1
1 1000000000
2 1000000000
3 1000000000
4 1000000000
5 1000000000
6 3
Output
1000000001
2000000001
3000000001
4000000001
5000000001
5000000004 | instruction | 0 | 81,205 | 14 | 162,410 |
Tags: *special, data structures, implementation
Correct Solution:
```
import heapq
def __main__(n, k):
servers = [0] * k
times = []
for i in range(n):
s, m = list(map(int, input().split()))
time = max(servers[0], s)
heapq.heapreplace(servers, time + m)
times.append(time + m)
print('\n'.join(str(time) for time in times))
if __name__ == '__main__':
n, k = list(map(int, input().split()))
__main__(n, k)
``` | output | 1 | 81,205 | 14 | 162,411 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A social network for dogs called DH (DogHouse) has k special servers to recompress uploaded videos of cute cats. After each video is uploaded, it should be recompressed on one (any) of the servers, and only after that it can be saved in the social network.
We know that each server takes one second to recompress a one minute fragment. Thus, any server takes m seconds to recompress a m minute video.
We know the time when each of the n videos were uploaded to the network (in seconds starting from the moment all servers started working). All videos appear at different moments of time and they are recompressed in the order they appear. If some video appeared at time s, then its recompressing can start at that very moment, immediately. Some videos can await recompressing when all the servers are busy. In this case, as soon as a server is available, it immediately starts recompressing another video. The videos that await recompressing go in a queue. If by the moment the videos started being recompressed some servers are available, then any of them starts recompressing the video.
For each video find the moment it stops being recompressed.
Input
The first line of the input contains integers n and k (1 β€ n, k β€ 5Β·105) β the number of videos and servers, respectively.
Next n lines contain the descriptions of the videos as pairs of integers si, mi (1 β€ si, mi β€ 109), where si is the time in seconds when the i-th video appeared and mi is its duration in minutes. It is guaranteed that all the si's are distinct and the videos are given in the chronological order of upload, that is in the order of increasing si.
Output
Print n numbers e1, e2, ..., en, where ei is the time in seconds after the servers start working, when the i-th video will be recompressed.
Examples
Input
3 2
1 5
2 5
3 5
Output
6
7
11
Input
6 1
1 1000000000
2 1000000000
3 1000000000
4 1000000000
5 1000000000
6 3
Output
1000000001
2000000001
3000000001
4000000001
5000000001
5000000004 | instruction | 0 | 81,206 | 14 | 162,412 |
Tags: *special, data structures, implementation
Correct Solution:
```
import sys
input = sys.stdin.readline
rInt = lambda: int(input())
mInt = lambda: map(int, input().split())
rList = lambda: list(map(int, input().split()))
n, k = mInt()
inp = []
for i in range(n):
inp.append(rList())
avail = k
from heapq import *
events = []
from collections import deque
queue = deque()
out = [-1] * n
heappush(events, (inp[0][0], 1, 0))
while events:
nex = heappop(events)
if nex[1]:
queue.append(nex[2])
if nex[2] < n - 1:
heappush(events, (inp[nex[2] + 1][0], 1, nex[2] + 1))
else:
avail += 1
t = nex[0]
while avail and queue:
avail -= 1
nex = queue.popleft()
end = t + inp[nex][1]
out[nex] = end
heappush(events, (end, 0))
print(*out, sep='\n')
``` | output | 1 | 81,206 | 14 | 162,413 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A social network for dogs called DH (DogHouse) has k special servers to recompress uploaded videos of cute cats. After each video is uploaded, it should be recompressed on one (any) of the servers, and only after that it can be saved in the social network.
We know that each server takes one second to recompress a one minute fragment. Thus, any server takes m seconds to recompress a m minute video.
We know the time when each of the n videos were uploaded to the network (in seconds starting from the moment all servers started working). All videos appear at different moments of time and they are recompressed in the order they appear. If some video appeared at time s, then its recompressing can start at that very moment, immediately. Some videos can await recompressing when all the servers are busy. In this case, as soon as a server is available, it immediately starts recompressing another video. The videos that await recompressing go in a queue. If by the moment the videos started being recompressed some servers are available, then any of them starts recompressing the video.
For each video find the moment it stops being recompressed.
Input
The first line of the input contains integers n and k (1 β€ n, k β€ 5Β·105) β the number of videos and servers, respectively.
Next n lines contain the descriptions of the videos as pairs of integers si, mi (1 β€ si, mi β€ 109), where si is the time in seconds when the i-th video appeared and mi is its duration in minutes. It is guaranteed that all the si's are distinct and the videos are given in the chronological order of upload, that is in the order of increasing si.
Output
Print n numbers e1, e2, ..., en, where ei is the time in seconds after the servers start working, when the i-th video will be recompressed.
Examples
Input
3 2
1 5
2 5
3 5
Output
6
7
11
Input
6 1
1 1000000000
2 1000000000
3 1000000000
4 1000000000
5 1000000000
6 3
Output
1000000001
2000000001
3000000001
4000000001
5000000001
5000000004 | instruction | 0 | 81,207 | 14 | 162,414 |
Tags: *special, data structures, implementation
Correct Solution:
```
# tested by Hightail - https://github.com/dj3500/hightail
from __future__ import print_function
from heapq import heappop, heappush
from sys import stdin, stdout
read, read_array = stdin.readline, lambda: stdin.readline().split()
write = lambda *args, **kw: stdout.write(kw.get('sep', ' ').join(str(a) for a in args) + kw.get('end', '\n'))
write_array = lambda arr, **kw: stdout.write(kw.get('sep', ' ').join(str(a) for a in arr) + kw.get('end', '\n'))
read_int, read_int_array = lambda: int(read()), lambda: [int(p) for p in read_array()]
read_float, read_float_array = lambda: float(read()), lambda: [float(p) for p in read_array()]
n, k = read_int_array()
heap = []
busy = 0
time = 0
finish = [0] * n
for i in range(n):
if busy == k:
time = heappop(heap)
busy -= 1
else:
time = 0
start, minutes = read_int_array()
if start > time:
time = start
heappush(heap, time + minutes)
finish[i] = time + minutes
busy += 1
write_array(finish, sep='\n')
``` | output | 1 | 81,207 | 14 | 162,415 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A social network for dogs called DH (DogHouse) has k special servers to recompress uploaded videos of cute cats. After each video is uploaded, it should be recompressed on one (any) of the servers, and only after that it can be saved in the social network.
We know that each server takes one second to recompress a one minute fragment. Thus, any server takes m seconds to recompress a m minute video.
We know the time when each of the n videos were uploaded to the network (in seconds starting from the moment all servers started working). All videos appear at different moments of time and they are recompressed in the order they appear. If some video appeared at time s, then its recompressing can start at that very moment, immediately. Some videos can await recompressing when all the servers are busy. In this case, as soon as a server is available, it immediately starts recompressing another video. The videos that await recompressing go in a queue. If by the moment the videos started being recompressed some servers are available, then any of them starts recompressing the video.
For each video find the moment it stops being recompressed.
Input
The first line of the input contains integers n and k (1 β€ n, k β€ 5Β·105) β the number of videos and servers, respectively.
Next n lines contain the descriptions of the videos as pairs of integers si, mi (1 β€ si, mi β€ 109), where si is the time in seconds when the i-th video appeared and mi is its duration in minutes. It is guaranteed that all the si's are distinct and the videos are given in the chronological order of upload, that is in the order of increasing si.
Output
Print n numbers e1, e2, ..., en, where ei is the time in seconds after the servers start working, when the i-th video will be recompressed.
Examples
Input
3 2
1 5
2 5
3 5
Output
6
7
11
Input
6 1
1 1000000000
2 1000000000
3 1000000000
4 1000000000
5 1000000000
6 3
Output
1000000001
2000000001
3000000001
4000000001
5000000001
5000000004 | instruction | 0 | 81,208 | 14 | 162,416 |
Tags: *special, data structures, implementation
Correct Solution:
```
import heapq
f = lambda: map(int, input().split())
n, k = f()
p = [0] * k
q = [0] * n
for i in range(n):
s, m = f()
q[i] = max(p[0], s) + m
heapq.heapreplace(p, q[i])
print('\n'.join(map(str, q)))
``` | output | 1 | 81,208 | 14 | 162,417 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A social network for dogs called DH (DogHouse) has k special servers to recompress uploaded videos of cute cats. After each video is uploaded, it should be recompressed on one (any) of the servers, and only after that it can be saved in the social network.
We know that each server takes one second to recompress a one minute fragment. Thus, any server takes m seconds to recompress a m minute video.
We know the time when each of the n videos were uploaded to the network (in seconds starting from the moment all servers started working). All videos appear at different moments of time and they are recompressed in the order they appear. If some video appeared at time s, then its recompressing can start at that very moment, immediately. Some videos can await recompressing when all the servers are busy. In this case, as soon as a server is available, it immediately starts recompressing another video. The videos that await recompressing go in a queue. If by the moment the videos started being recompressed some servers are available, then any of them starts recompressing the video.
For each video find the moment it stops being recompressed.
Input
The first line of the input contains integers n and k (1 β€ n, k β€ 5Β·105) β the number of videos and servers, respectively.
Next n lines contain the descriptions of the videos as pairs of integers si, mi (1 β€ si, mi β€ 109), where si is the time in seconds when the i-th video appeared and mi is its duration in minutes. It is guaranteed that all the si's are distinct and the videos are given in the chronological order of upload, that is in the order of increasing si.
Output
Print n numbers e1, e2, ..., en, where ei is the time in seconds after the servers start working, when the i-th video will be recompressed.
Examples
Input
3 2
1 5
2 5
3 5
Output
6
7
11
Input
6 1
1 1000000000
2 1000000000
3 1000000000
4 1000000000
5 1000000000
6 3
Output
1000000001
2000000001
3000000001
4000000001
5000000001
5000000004 | instruction | 0 | 81,209 | 14 | 162,418 |
Tags: *special, data structures, implementation
Correct Solution:
```
import heapq
from sys import stdin, stdout
def __main__(n, k):
servers = [0] * k
times = []
for i in range(n):
s, m = [int(x) for x in stdin.readline().split()]
time = max(servers[0], s)
heapq.heapreplace(servers, time + m)
times.append(time + m)
stdout.write('\n'.join(str(time) for time in times) + '\n')
if __name__ == '__main__':
n, k = list(map(int, stdin.readline().split()))
__main__(n, k)
``` | output | 1 | 81,209 | 14 | 162,419 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A social network for dogs called DH (DogHouse) has k special servers to recompress uploaded videos of cute cats. After each video is uploaded, it should be recompressed on one (any) of the servers, and only after that it can be saved in the social network.
We know that each server takes one second to recompress a one minute fragment. Thus, any server takes m seconds to recompress a m minute video.
We know the time when each of the n videos were uploaded to the network (in seconds starting from the moment all servers started working). All videos appear at different moments of time and they are recompressed in the order they appear. If some video appeared at time s, then its recompressing can start at that very moment, immediately. Some videos can await recompressing when all the servers are busy. In this case, as soon as a server is available, it immediately starts recompressing another video. The videos that await recompressing go in a queue. If by the moment the videos started being recompressed some servers are available, then any of them starts recompressing the video.
For each video find the moment it stops being recompressed.
Input
The first line of the input contains integers n and k (1 β€ n, k β€ 5Β·105) β the number of videos and servers, respectively.
Next n lines contain the descriptions of the videos as pairs of integers si, mi (1 β€ si, mi β€ 109), where si is the time in seconds when the i-th video appeared and mi is its duration in minutes. It is guaranteed that all the si's are distinct and the videos are given in the chronological order of upload, that is in the order of increasing si.
Output
Print n numbers e1, e2, ..., en, where ei is the time in seconds after the servers start working, when the i-th video will be recompressed.
Examples
Input
3 2
1 5
2 5
3 5
Output
6
7
11
Input
6 1
1 1000000000
2 1000000000
3 1000000000
4 1000000000
5 1000000000
6 3
Output
1000000001
2000000001
3000000001
4000000001
5000000001
5000000004
Submitted Solution:
```
from sys import stdin, stdout
import heapq
lines = stdin.readlines()
n, k = int(lines[0].split()[0], 10), int(lines[0].split()[1], 10)
a = [int(x.split()[0], 10) for x in lines[1:]]
b = [int(x.split()[1], 10) for x in lines[1:]]
heap = [a[i]+b[i] for i in range(k)]
answers = heap[:]
heapq.heapify(heap)
for i in range(k,n):
will_load = int(max(int(heapq.heappop(heap)), a[i])+b[i]) #11111111
heapq.heappush(heap, will_load)
answers.append(will_load)
stdout.write('\n'.join([str(x) for x in answers]))
``` | instruction | 0 | 81,210 | 14 | 162,420 |
Yes | output | 1 | 81,210 | 14 | 162,421 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A social network for dogs called DH (DogHouse) has k special servers to recompress uploaded videos of cute cats. After each video is uploaded, it should be recompressed on one (any) of the servers, and only after that it can be saved in the social network.
We know that each server takes one second to recompress a one minute fragment. Thus, any server takes m seconds to recompress a m minute video.
We know the time when each of the n videos were uploaded to the network (in seconds starting from the moment all servers started working). All videos appear at different moments of time and they are recompressed in the order they appear. If some video appeared at time s, then its recompressing can start at that very moment, immediately. Some videos can await recompressing when all the servers are busy. In this case, as soon as a server is available, it immediately starts recompressing another video. The videos that await recompressing go in a queue. If by the moment the videos started being recompressed some servers are available, then any of them starts recompressing the video.
For each video find the moment it stops being recompressed.
Input
The first line of the input contains integers n and k (1 β€ n, k β€ 5Β·105) β the number of videos and servers, respectively.
Next n lines contain the descriptions of the videos as pairs of integers si, mi (1 β€ si, mi β€ 109), where si is the time in seconds when the i-th video appeared and mi is its duration in minutes. It is guaranteed that all the si's are distinct and the videos are given in the chronological order of upload, that is in the order of increasing si.
Output
Print n numbers e1, e2, ..., en, where ei is the time in seconds after the servers start working, when the i-th video will be recompressed.
Examples
Input
3 2
1 5
2 5
3 5
Output
6
7
11
Input
6 1
1 1000000000
2 1000000000
3 1000000000
4 1000000000
5 1000000000
6 3
Output
1000000001
2000000001
3000000001
4000000001
5000000001
5000000004
Submitted Solution:
```
import atexit
import io
import sys
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER
@atexit.register
def write():
sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
import heapq
n, k = [int(i) for i in input().split()]
s, m = [0] * n, [0] * n
for i in range(n):
s[i], m[i] = [int(i) for i in input().split()]
current_time = 0
event = []
ans = [0] * n
i = 0
while len(event) or i < n:
if (len(event) == 0):
current_time = max(current_time, s[i])
heapq.heappush(event, (current_time + m[i], i))
i += 1
continue
e_time, e_id = event[0]
if e_time == current_time or i == n:
current_time = max(current_time, e_time)
ans[e_id] = e_time
heapq.heappop(event)
continue
if s[i] < e_time and len(event) < k:
current_time = max(current_time, s[i])
heapq.heappush(event, (current_time + m[i], i))
i += 1
continue
else:
current_time = ans[e_id] = e_time
heapq.heappop(event)
continue
print("\n".join([str(i) for i in ans]))
``` | instruction | 0 | 81,211 | 14 | 162,422 |
Yes | output | 1 | 81,211 | 14 | 162,423 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.