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.
Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).
q events are about to happen (in chronological order). They are of three types:
1. Application x generates a notification (this new notification is unread).
2. Thor reads all notifications generated so far by application x (he may re-read some notifications).
3. Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation.
Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone.
Input
The first line of input contains two integers n and q (1 β€ n, q β€ 300 000) β the number of applications and the number of events to happen.
The next q lines contain the events. The i-th of these lines starts with an integer typei β type of the i-th event. If typei = 1 or typei = 2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1 β€ typei β€ 3, 1 β€ xi β€ n, 1 β€ ti β€ q).
Output
Print the number of unread notifications after each event.
Examples
Input
3 4
1 3
1 1
1 2
2 3
Output
1
2
3
2
Input
4 6
1 2
1 4
1 2
3 3
1 3
1 3
Output
1
2
3
0
1
2
Note
In the first sample:
1. Application 3 generates a notification (there is 1 unread notification).
2. Application 1 generates a notification (there are 2 unread notifications).
3. Application 2 generates a notification (there are 3 unread notifications).
4. Thor reads the notification generated by application 3, there are 2 unread notifications left.
In the second sample test:
1. Application 2 generates a notification (there is 1 unread notification).
2. Application 4 generates a notification (there are 2 unread notifications).
3. Application 2 generates a notification (there are 3 unread notifications).
4. Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left.
5. Application 3 generates a notification (there is 1 unread notification).
6. Application 3 generates a notification (there are 2 unread notifications).
Submitted Solution:
```
def binsearch(nums, target):
left = 0
right = len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] > target:
right = mid - 1
elif nums[mid] < target:
left = mid + 1
return left
n, q = map(int, input().split())
apps = {}
notifs = []
unread = 0
read = []
k = 0
for query in range(q):
t, x = map(int, input().split())
if t == 1:
k += 1
notifs.append(query)
if not apps.get(x):
apps[x] = []
apps[x].append(k)
unread += 1
if t == 2:
if not apps.get(x):
apps[x] = []
for i in range(len(apps[x])):
read.append(apps[x][i])
unread -= len(apps[x])
apps[x] = []
if t == 3:
timestamp = x
remplace = binsearch(read, timestamp+.1)
unread -= (x - remplace)
print(unread)
``` | instruction | 0 | 103,357 | 14 | 206,714 |
No | output | 1 | 103,357 | 14 | 206,715 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).
q events are about to happen (in chronological order). They are of three types:
1. Application x generates a notification (this new notification is unread).
2. Thor reads all notifications generated so far by application x (he may re-read some notifications).
3. Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation.
Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone.
Input
The first line of input contains two integers n and q (1 β€ n, q β€ 300 000) β the number of applications and the number of events to happen.
The next q lines contain the events. The i-th of these lines starts with an integer typei β type of the i-th event. If typei = 1 or typei = 2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1 β€ typei β€ 3, 1 β€ xi β€ n, 1 β€ ti β€ q).
Output
Print the number of unread notifications after each event.
Examples
Input
3 4
1 3
1 1
1 2
2 3
Output
1
2
3
2
Input
4 6
1 2
1 4
1 2
3 3
1 3
1 3
Output
1
2
3
0
1
2
Note
In the first sample:
1. Application 3 generates a notification (there is 1 unread notification).
2. Application 1 generates a notification (there are 2 unread notifications).
3. Application 2 generates a notification (there are 3 unread notifications).
4. Thor reads the notification generated by application 3, there are 2 unread notifications left.
In the second sample test:
1. Application 2 generates a notification (there is 1 unread notification).
2. Application 4 generates a notification (there are 2 unread notifications).
3. Application 2 generates a notification (there are 3 unread notifications).
4. Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left.
5. Application 3 generates a notification (there is 1 unread notification).
6. Application 3 generates a notification (there are 2 unread notifications).
Submitted Solution:
```
"""
#If FastIO not needed, used this and don't forget to strip
#import sys, math
#input = sys.stdin.readline
"""
import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
self.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")
from collections import defaultdict as dd, deque as dq
import math, string
def getInts():
return [int(s) for s in input().split()]
def getInt():
return int(input())
def getStrs():
return [s for s in input().split()]
def getStr():
return input()
def listStr():
return list(input())
MOD = 10**9+7
"""
We need to maintain a set of unread notifications from which we can remove the first max(ti), and also the first xi for each application
[3,4,4,1,1,1,2,2,1,3,3,2,4,4,1,2,3,2,4,4]
N applications. At any given time the number of unread notifications is the sum of the number of unread notifications for each application, which lends itself to a Fenwick Tree
But how do we maintain the order?
As we delete the first N elements, we can also subtract one from the rolling sum and from the element total.
As we clear an element of type X, we can subtract that many from the rolling total
"""
def solve():
N, Q = getInts()
order = dq([])
cur_total = 0
cur_del = -1
els = [0]*(N+1)
del_up_to = [-1]*(N+1)
for q in range(Q):
T, X = getInts()
if T == 1:
order.append(X)
els[X] += 1
cur_total += 1
print(cur_total)
elif T == 2:
cur_total -= els[X]
els[X] = 0
del_up_to[X] = q
print(cur_total)
elif T == 3:
for i in range(cur_del+1,X):
if del_up_to[order[i]] < i:
cur_total -= 1
del_up_to[order[i]] = max(i,del_up_to[order[i]])
cur_del = X-1
print(cur_total)
return
#for _ in range(getInt()):
solve()
``` | instruction | 0 | 103,358 | 14 | 206,716 |
No | output | 1 | 103,358 | 14 | 206,717 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).
q events are about to happen (in chronological order). They are of three types:
1. Application x generates a notification (this new notification is unread).
2. Thor reads all notifications generated so far by application x (he may re-read some notifications).
3. Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation.
Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone.
Input
The first line of input contains two integers n and q (1 β€ n, q β€ 300 000) β the number of applications and the number of events to happen.
The next q lines contain the events. The i-th of these lines starts with an integer typei β type of the i-th event. If typei = 1 or typei = 2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1 β€ typei β€ 3, 1 β€ xi β€ n, 1 β€ ti β€ q).
Output
Print the number of unread notifications after each event.
Examples
Input
3 4
1 3
1 1
1 2
2 3
Output
1
2
3
2
Input
4 6
1 2
1 4
1 2
3 3
1 3
1 3
Output
1
2
3
0
1
2
Note
In the first sample:
1. Application 3 generates a notification (there is 1 unread notification).
2. Application 1 generates a notification (there are 2 unread notifications).
3. Application 2 generates a notification (there are 3 unread notifications).
4. Thor reads the notification generated by application 3, there are 2 unread notifications left.
In the second sample test:
1. Application 2 generates a notification (there is 1 unread notification).
2. Application 4 generates a notification (there are 2 unread notifications).
3. Application 2 generates a notification (there are 3 unread notifications).
4. Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left.
5. Application 3 generates a notification (there is 1 unread notification).
6. Application 3 generates a notification (there are 2 unread notifications).
Submitted Solution:
```
from heapq import *
from bisect import *
from collections import defaultdict
import heapq
total = 0
N, Q = map(int, input().split())
q = []
for i in range(Q):
t, x = map(int, input().split())
if t == 1:
heappush(q, (i, x))
elif t == 2:
next_q = []
for j, y in q:
if y == x:
continue
next_q.append((j, y))
if len(next_q) != len(q):
q = next_q
heapify(q)
else:
while q and q[0][0] <= x - 1:
heappop(q)
print(len(q))
``` | instruction | 0 | 103,359 | 14 | 206,718 |
No | output | 1 | 103,359 | 14 | 206,719 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bonnie are sisters, but they don't like each other very much. So when some old family photos were found in the attic, they started to argue about who should receive which photos. In the end, they decided that they would take turns picking photos. Alice goes first.
There are n stacks of photos. Each stack contains exactly two photos. In each turn, a player may take only a photo from the top of one of the stacks.
Each photo is described by two non-negative integers a and b, indicating that it is worth a units of happiness to Alice and b units of happiness to Bonnie. Values of a and b might differ for different photos.
It's allowed to pass instead of taking a photo. The game ends when all photos are taken or both players pass consecutively.
The players don't act to maximize their own happiness. Instead, each player acts to maximize the amount by which her happiness exceeds her sister's. Assuming both players play optimal, find the difference between Alice's and Bonnie's happiness. That is, if there's a perfectly-played game such that Alice has x happiness and Bonnie has y happiness at the end, you should print x - y.
Input
The first line of input contains a single integer n (1 β€ n β€ 100 000) β the number of two-photo stacks. Then follow n lines, each describing one of the stacks. A stack is described by four space-separated non-negative integers a1, b1, a2 and b2, each not exceeding 109. a1 and b1 describe the top photo in the stack, while a2 and b2 describe the bottom photo in the stack.
Output
Output a single integer: the difference between Alice's and Bonnie's happiness if both play optimally.
Examples
Input
2
12 3 4 7
1 15 9 1
Output
1
Input
2
5 4 8 8
4 12 14 0
Output
4
Input
1
0 10 0 10
Output
-10 | instruction | 0 | 103,360 | 14 | 206,720 |
Tags: games, greedy
Correct Solution:
```
num_stacks = int(input())
answer = 0
array = []
for i in range(num_stacks):
a1, b1, a2, b2 = map(int, input().split(' '))
if a1 + b1 >= a2 + b2:
answer += a1 + a2
array.append(a2 + b2)
array.append(a1 + b1)
elif a1 > b2:
answer += a1 - b2
elif b1 > a2:
answer += a2 - b1
# Elif both side skip
array.sort()
for i in range(0, len(array), 2):
answer -= array[i]
print(answer)
``` | output | 1 | 103,360 | 14 | 206,721 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bonnie are sisters, but they don't like each other very much. So when some old family photos were found in the attic, they started to argue about who should receive which photos. In the end, they decided that they would take turns picking photos. Alice goes first.
There are n stacks of photos. Each stack contains exactly two photos. In each turn, a player may take only a photo from the top of one of the stacks.
Each photo is described by two non-negative integers a and b, indicating that it is worth a units of happiness to Alice and b units of happiness to Bonnie. Values of a and b might differ for different photos.
It's allowed to pass instead of taking a photo. The game ends when all photos are taken or both players pass consecutively.
The players don't act to maximize their own happiness. Instead, each player acts to maximize the amount by which her happiness exceeds her sister's. Assuming both players play optimal, find the difference between Alice's and Bonnie's happiness. That is, if there's a perfectly-played game such that Alice has x happiness and Bonnie has y happiness at the end, you should print x - y.
Input
The first line of input contains a single integer n (1 β€ n β€ 100 000) β the number of two-photo stacks. Then follow n lines, each describing one of the stacks. A stack is described by four space-separated non-negative integers a1, b1, a2 and b2, each not exceeding 109. a1 and b1 describe the top photo in the stack, while a2 and b2 describe the bottom photo in the stack.
Output
Output a single integer: the difference between Alice's and Bonnie's happiness if both play optimally.
Examples
Input
2
12 3 4 7
1 15 9 1
Output
1
Input
2
5 4 8 8
4 12 14 0
Output
4
Input
1
0 10 0 10
Output
-10 | instruction | 0 | 103,361 | 14 | 206,722 |
Tags: games, greedy
Correct Solution:
```
num_stacks = int(input())
answer = 0
array = []
for i in range(num_stacks):
a1, b1, a2, b2 = input().split(' ')
a1 = int(a1)
a2 = int(a2)
b1 = int(b1)
b2 = int(b2)
if a1 + b1 >= a2 + b2:
answer += a1 + a2
array.append(a2 + b2)
array.append(a1 + b1)
elif a1 > b2:
answer += a1 - b2
elif b1 > a2:
answer += a2 - b1
# Elif both side skip
array.sort()
for i in range(0, len(array), 2):
answer -= array[i]
print(answer)
``` | output | 1 | 103,361 | 14 | 206,723 |
Provide a correct Python 3 solution for this coding contest problem.
There is a very long bench. The bench is divided into M sections, where M is a very large integer.
Initially, the bench is vacant. Then, M people come to the bench one by one, and perform the following action:
* We call a section comfortable if the section is currently unoccupied and is not adjacent to any occupied sections. If there is no comfortable section, the person leaves the bench. Otherwise, the person chooses one of comfortable sections uniformly at random, and sits there. (The choices are independent from each other).
After all M people perform actions, Snuke chooses an interval of N consecutive sections uniformly at random (from M-N+1 possible intervals), and takes a photo. His photo can be described by a string of length N consisting of `X` and `-`: the i-th character of the string is `X` if the i-th section from the left in the interval is occupied, and `-` otherwise. Note that the photo is directed. For example, `-X--X` and `X--X-` are different photos.
What is the probability that the photo matches a given string s? This probability depends on M. You need to compute the limit of this probability when M goes infinity.
Here, we can prove that the limit can be uniquely written in the following format using three rational numbers p, q, r and e = 2.718 \ldots (the base of natural logarithm):
p + \frac{q}{e} + \frac{r}{e^2}
Your task is to compute these three rational numbers, and print them modulo 10^9 + 7, as described in Notes section.
Constraints
* 1 \leq N \leq 1000
* |s| = N
* s consists of `X` and `-`.
Input
Input is given from Standard Input in the following format:
N
s
Output
Print three rational numbers p, q, r, separated by spaces.
Examples
Input
1
X
Output
500000004 0 500000003
Input
3
---
Output
0 0 0
Input
5
X--X-
Output
0 0 1
Input
5
X-X-X
Output
500000004 0 833333337
Input
20
-X--X--X-X--X--X-X-X
Output
0 0 183703705
Input
100
X-X-X-X-X-X-X-X-X-X--X-X-X-X-X-X-X-X-X-X-X-X-X-X-X--X--X-X-X-X--X--X-X-X--X-X-X--X-X--X--X-X--X-X-X-
Output
0 0 435664291 | instruction | 0 | 103,488 | 14 | 206,976 |
"Correct Solution:
```
#εθURL
#https://qiita.com/ageprocpp/items/104c051b2ec2086f5a9b
mod=10**9+7
def value(obj):
if type(obj)==modint:
tmp=obj.number
else:
tmp=obj
return tmp%mod
class modint():
number=0
def __init__(self,num):
self.number=num%mod
def __add__(self,other):
tmp=value(other)
return modint(self.number+tmp)
def __iadd__(self,other):
tmp=value(other)
self.number+=tmp
self.number%=mod
return self
def __sub__(self,other):
tmp=value(other)
return modint(self.number-tmp)
def __isub__(self,other):
tmp=value(other)
self.number-=tmp
self.number%=mod
return self
def __mul__(self,other):
tmp=value(other)
return modint(self.number*tmp)
def __imul__(self,other):
tmp=value(other)
self.number*=tmp
self.number%=mod
return self
def __truediv__(self,other):
tmp=value(other)
return self*pow(tmp,mod-2,mod)
def __itruediv(self,other):
tmp=value(other)
self.number=self/tmp
self.number%=mod
return self
def __repr__(self):
return str(self.number)
def __eq__(self,other):
return value(self)==value(other)
def __ne__(self,other):
return value(self)!=value(other)
def __str__(self):
return str(self.number)
def __int__(self):
return self.number
def __hash__(self):
return self.number
class polynomial():
sequence=[0]
def __init__(self,seq):
self.sequence=[]
for i in seq:
self.sequence.append(value(i))
def get(self,x):
res=modint(0)
tmp=modint(1)
for a in self.sequence:
res+=tmp*a
tmp*=x
if tmp==0:
break
return res
def __add__(self,other):
res=[]
for i,a in enumerate(self.sequence):
try:
res[i]=a
except IndexError:
res.append(modint(0))
res[i]=a
for i,a in enumerate(other.sequence):
try:
res[i]+=a
except IndexError:
res.append(modint(0))
res[i]+=a
return polynomial(res)
def __iadd__(self,other):
return self+other
def __sub__(self,other):
res=[]
for i,a in enumerate(self.sequence):
try:
res[i]=a
except IndexError:
res.append(modint(0))
res[i]=a
for i,a in enumerate(other.sequence):
try:
res[i]-=a
except IndexError:
res.append(modint(0))
res[i]-=a
return polynomial(res)
def __isub__(self,other):
return self-other
def indef_integral(self):
res=[modint(0)]
for i,a in enumerate(self.sequence):
res.append(modint(a)/(i+1))
return polynomial(res)
def integrate(self,flag):
#0: 0->x
#1:x->1
if flag==0:
return self.indef_integral()
else:
tmp=self.indef_integral()
return polynomial([tmp.get(1)])-tmp
def __repr__(self):
return str(self.sequence)
def __str__(self):
return str(self.sequence)
class func():
P=polynomial([modint(0)])
Q=polynomial([modint(0)])
C=modint(0)
def __init__(self,poly1,poly2,cnst):
self.P=poly1
self.Q=poly2
self.C=cnst
def __add__(self,other):
PP=self.P+other.P
QQ=self.Q+other.Q
CC=self.C+other.C
return func(PP,QQ,CC)
def __iadd__(self,other):
return self+other
def __sub__(self,other):
PP=self.P-other.P
QQ=self.Q-other.Q
CC=self.C-other.C
return func(PP,QQ,CC)
def __isub__(self,other):
return self-other
def dintegrate(self,flag):
if flag==0:
PP=self.P.integrate(0)+polynomial([self.C])
QQ=self.Q.integrate(0)
CC=modint(-1)*self.C
else:
PP=self.P.integrate(1)
QQ=self.Q.integrate(1)+polynomial([modint(-1)*self.C])
CC=self.C
return func(PP,QQ,CC)
MAX_N=1009
N=int(input())
s=input()
fact=[modint(0) for i in range(MAX_N+1)]
inv=[modint(0) for i in range(MAX_N+1)]
fact[0]=modint(1)
for i in range(MAX_N):
fact[i+1]=fact[i]*(i+1)
inv[-1]=modint(1)/fact[-1]
for i in range(MAX_N-1,-1,-1):
inv[i]=inv[i+1]*(i+1)
dp=[[[[func(polynomial([modint(0)]),polynomial([modint(0)]),modint(0)) for l in range(2)]for k in range(2)]for j in range(2)] for i in range(MAX_N+1)]
if s[0]=="X":
dp[0][0][1][0]=func(polynomial([modint(0)]),polynomial([modint(0)]),modint(1))
else:
dp[0][0][0][1]=func(polynomial([modint(0)]),polynomial([modint(0)]),modint(1))
dp[0][1][1][1]=func(polynomial([modint(1)]),polynomial([modint(0)]),modint(-1))
for i in range(1,N):
if s[i]=="X":
dp[i][0][1][0]+=dp[i-1][1][1][0].dintegrate(0)
dp[i][0][1][0]+=dp[i-1][1][1][1].dintegrate(0)
dp[i][0][1][0]+=dp[i-1][0][0][1].dintegrate(1)
dp[i][0][1][0]+=dp[i-1][0][1][1].dintegrate(1)
dp[i][0][1][0]+=dp[i-1][1][0][1].dintegrate(1)
dp[i][0][1][0]+=dp[i-1][1][1][1].dintegrate(1)
else:
dp[i][0][0][1]+=dp[i-1][1][1][0].dintegrate(0)
dp[i][0][0][1]+=dp[i-1][1][1][1].dintegrate(0)
dp[i][1][1][1]+=dp[i-1][0][1][0].dintegrate(0)
dp[i][1][1][1]+=dp[i-1][0][1][1].dintegrate(0)
dp[i][0][0][1]+=dp[i-1][0][1][0].dintegrate(1)
dp[i][0][0][1]+=dp[i-1][0][1][1].dintegrate(1)
dp[i][0][0][1]+=dp[i-1][1][1][0].dintegrate(1)
dp[i][0][0][1]+=dp[i-1][1][1][1].dintegrate(1)
a=modint(0)
b=modint(0)
c=modint(0)
p = dp[N-1][0][1][1].P.integrate(0)
a+= p.get(1)-p.get(0)
p = dp[N-1][0][1][1].Q.integrate(0)
b+= p.get(1)-p.get(0)
a+= dp[N-1][0][1][1].C
b-= dp[N-1][0][1][1].C
p = dp[N-1][1][1][1].P.integrate(0)
a+= p.get(1)-p.get(0)
p = dp[N-1][1][1][1].Q.integrate(0)
b+= p.get(1)-p.get(0)
a+= dp[N-1][1][1][1].C
b-= dp[N-1][1][1][1].C
for x in range(2):
for i,v in enumerate(dp[N-1][x][1][0].P.sequence):
a+=modint(1)*v*fact[i]
for j in range(i+1):
b-=modint(1)*v*fact[i]*inv[j]
for i,v in enumerate(dp[N-1][x][1][0].Q.sequence):
b+=modint(1)*v*fact[i]
for j in range(i+1):
c-=modint(1)*v*fact[i]*inv[j]
a+=dp[N-1][x][1][0].C/2
c-=dp[N-1][x][1][0].C/2
p = dp[N-1][0][0][1].P.integrate(0)
a+= p.get(1)-p.get(0)
p = dp[N-1][0][0][1].Q.integrate(0)
b+= p.get(1)-p.get(0)
a+= dp[N-1][0][0][1].C
b-= dp[N-1][0][0][1].C
p = dp[N-1][1][0][1].P.integrate(0)
a+= p.get(1)-p.get(0)
p = dp[N-1][1][0][1].Q.integrate(0)
b+= p.get(1)-p.get(0)
a+= dp[N-1][1][0][1].C
b-= dp[N-1][1][0][1].C
for x in range(2):
for i,v in enumerate(dp[N-1][x][0][1].P.sequence):
a-=modint(1)*v*fact[i]
for j in range(i+1):
b+=modint(1)*v*fact[i]*inv[j]
for i,v in enumerate(dp[N-1][x][0][1].Q.sequence):
b-=modint(1)*v*fact[i]
for j in range(i+1):
c+=modint(1)*v*fact[i]*inv[j]
a-=dp[N-1][x][0][1].C/2
c+=dp[N-1][x][0][1].C/2
print(a,b,c)
``` | output | 1 | 103,488 | 14 | 206,977 |
Provide a correct Python 3 solution for this coding contest problem.
There is a very long bench. The bench is divided into M sections, where M is a very large integer.
Initially, the bench is vacant. Then, M people come to the bench one by one, and perform the following action:
* We call a section comfortable if the section is currently unoccupied and is not adjacent to any occupied sections. If there is no comfortable section, the person leaves the bench. Otherwise, the person chooses one of comfortable sections uniformly at random, and sits there. (The choices are independent from each other).
After all M people perform actions, Snuke chooses an interval of N consecutive sections uniformly at random (from M-N+1 possible intervals), and takes a photo. His photo can be described by a string of length N consisting of `X` and `-`: the i-th character of the string is `X` if the i-th section from the left in the interval is occupied, and `-` otherwise. Note that the photo is directed. For example, `-X--X` and `X--X-` are different photos.
What is the probability that the photo matches a given string s? This probability depends on M. You need to compute the limit of this probability when M goes infinity.
Here, we can prove that the limit can be uniquely written in the following format using three rational numbers p, q, r and e = 2.718 \ldots (the base of natural logarithm):
p + \frac{q}{e} + \frac{r}{e^2}
Your task is to compute these three rational numbers, and print them modulo 10^9 + 7, as described in Notes section.
Constraints
* 1 \leq N \leq 1000
* |s| = N
* s consists of `X` and `-`.
Input
Input is given from Standard Input in the following format:
N
s
Output
Print three rational numbers p, q, r, separated by spaces.
Examples
Input
1
X
Output
500000004 0 500000003
Input
3
---
Output
0 0 0
Input
5
X--X-
Output
0 0 1
Input
5
X-X-X
Output
500000004 0 833333337
Input
20
-X--X--X-X--X--X-X-X
Output
0 0 183703705
Input
100
X-X-X-X-X-X-X-X-X-X--X-X-X-X-X-X-X-X-X-X-X-X-X-X-X--X--X-X-X-X--X--X-X-X--X-X-X--X-X--X--X-X--X-X-X-
Output
0 0 435664291 | instruction | 0 | 103,489 | 14 | 206,978 |
"Correct Solution:
```
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return input().rstrip()
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = 1e10
fc = [1] * 1010
ifc = [1] * 1010
Bn = [0] * 1010
def ad(x, y=0):
return (x + y) % mod
def mlt(x, y=1):
return (x * y) % mod
def pwr(x, y):
return pow(x, y, mod)
def inv(x):
return pwr(x, mod - 2)
def bn(x):
if x > 0 and Bn[x] == 0: Bn[x] = ad(1, mlt(x, bn(x - 1)))
return Bn[x]
#solve
def solve():
for i in range(1, 1010): fc[i] = fc[i - 1] * i
for i in range(1010): ifc[i] = inv(fc[i])
num = 1
dp = [[[0] * 1010 for _ in range(2)] for k in range(1010)]
dpc = [0] * 1010
f = [False] * 1010
n = II()
s = S()
if n == 1 and s == "-":
print("{} 0 {}".format((mod + 1) // 2, (mod + 1) // 2))
return
q = 0
r = n
n = -1
if s[q] == "-":
q += 1
if s[q] == "-":
q += 1
n += 1
num += 1
if s[q] == "-":
print("0 0 0")
return
for i in range(q, r):
if s[i] == "X":
if num == 0:
print("0 0 0")
return
if n >= 0:
f[n] = num - 1
n += 1
num = 0
else:
if num > 1:
print("0 0 0")
return
num += 1
if num == 2:
f[n] = 1
n += 1
dpc[0] = 1
for i in range(n):
if f[i]:
for j in range(2):
for k in range(2 * n + 2):
kari = inv(k * k + 3 * k + 2)
dp[i + 1][j][0] = ad(dp[i + 1][j][0], mlt(dp[i][j][k], kari))
dp[i + 1][j][1] = ad(dp[i + 1][j][1], mlt(dp[i][j][k], mod - kari))
dp[i + 1][1][0] = ad(dp[i + 1][1][0], dpc[i])
dp[i + 1][1][1] = ad(dp[i + 1][1][1], mod - dpc[i])
else:
for j in range(2):
for k in range(2 * n + 2):
kari = inv(k + 1)
dp[i + 1][j][0] = ad(dp[i + 1][j][0], mlt(dp[i][j][k], kari))
dp[i + 1][j][1] = ad(dp[i + 1][j][1], mlt(dp[i][j][k], mod - kari))
dp[i + 1][j][k + 2] = ad(dp[i + 1][j][k + 2], mlt(dp[i][j][k], inv(k * k + 3 * k + 2)))
dp[i + 1][1][1] = ad(dp[i + 1][1][1], dpc[i])
dp[i + 1][1][0] = ad(dp[i + 1][1][0], mod - dpc[i])
dpc[i + 1] = ad(dpc[i + 1], dpc[i])
ans = [0] * 3
for j in range(2):
for k in range(2 * n + 2):
ans[j] = ad(ans[j], mlt(dp[n][j][k], fc[k]))
ans[j + 1] = ad(ans[j + 1], mlt(dp[n][j][k], mod - ad(fc[k], bn(k))))
kari = (mod + 1) // 2
ans[0] = ad(ans[0], mlt(dpc[n], kari))
ans[2] = ad(ans[2], mlt(dpc[n], mod - kari))
print("{} {} {}".format(ans[0], ans[1], ans[2]))
return
#main
if __name__ == '__main__':
solve()
``` | output | 1 | 103,489 | 14 | 206,979 |
Provide a correct Python 3 solution for this coding contest problem.
There is a very long bench. The bench is divided into M sections, where M is a very large integer.
Initially, the bench is vacant. Then, M people come to the bench one by one, and perform the following action:
* We call a section comfortable if the section is currently unoccupied and is not adjacent to any occupied sections. If there is no comfortable section, the person leaves the bench. Otherwise, the person chooses one of comfortable sections uniformly at random, and sits there. (The choices are independent from each other).
After all M people perform actions, Snuke chooses an interval of N consecutive sections uniformly at random (from M-N+1 possible intervals), and takes a photo. His photo can be described by a string of length N consisting of `X` and `-`: the i-th character of the string is `X` if the i-th section from the left in the interval is occupied, and `-` otherwise. Note that the photo is directed. For example, `-X--X` and `X--X-` are different photos.
What is the probability that the photo matches a given string s? This probability depends on M. You need to compute the limit of this probability when M goes infinity.
Here, we can prove that the limit can be uniquely written in the following format using three rational numbers p, q, r and e = 2.718 \ldots (the base of natural logarithm):
p + \frac{q}{e} + \frac{r}{e^2}
Your task is to compute these three rational numbers, and print them modulo 10^9 + 7, as described in Notes section.
Constraints
* 1 \leq N \leq 1000
* |s| = N
* s consists of `X` and `-`.
Input
Input is given from Standard Input in the following format:
N
s
Output
Print three rational numbers p, q, r, separated by spaces.
Examples
Input
1
X
Output
500000004 0 500000003
Input
3
---
Output
0 0 0
Input
5
X--X-
Output
0 0 1
Input
5
X-X-X
Output
500000004 0 833333337
Input
20
-X--X--X-X--X--X-X-X
Output
0 0 183703705
Input
100
X-X-X-X-X-X-X-X-X-X--X-X-X-X-X-X-X-X-X-X-X-X-X-X-X--X--X-X-X-X--X--X-X-X--X-X-X--X-X--X--X-X--X-X-X-
Output
0 0 435664291 | instruction | 0 | 103,490 | 14 | 206,980 |
"Correct Solution:
```
from copy import *
N=int(input())
S=input()
DP=[[[[0]*2 for i in range(2)] for j in range(2)] for k in range(N)]
mod=10**9+7
for i in range(N):
for j in range(2):
for k in range(2):
for l in range(2):
DP[i][j][k][l]=[[],[],0]
if S[0]=='X':
DP[0][0][1][0]=[[],[],1]
else:
DP[0][0][0][1]=[[],[],1]
DP[0][1][1][1]=[[1],[],mod-1]
g1=[1,1]
g2=[1,1]
inv=[0,1]
c=[1,2]
for i in range(2,N+5):
g1.append((g1[-1]*i)%mod)
inv.append((-inv[mod%i]*(mod//i))%mod)
g2.append((g2[-1]*inv[-1])%mod)
c.append((c[-1]+g2[i])%mod)
def add(x,y):
for j in range(2):
for i in range(len(y[j])-len(x[j])):
x[j].append(0)
for i in range(len(y[j])):
x[j][i]=(x[j][i]+y[j][i])%mod
x[2]=(x[2]+y[2])%mod
def integrate(p):
p[2]=-p[2]%mod
for j in range(2):
p[j].append(0)
for i in range(len(p[j])-2,-1,-1):
p[j][i+1]=p[j][i]*inv[i+1]%mod
p[j][i]=0
def fx0(p):
integrate(p)
p[0][0]=(p[0][0]-p[2])%mod
def f1x(p):
integrate(p)
for j in range(2):
for i in range(len(p[j])):
p[j][i]=-p[j][i]%mod
p[2]=-p[2]%mod
for i in range(2):
p[i][0]=-sum(p[i])%mod
p[1][0]=(p[1][0]-p[2])%mod
for i in range(N-1):
if S[i+1]=='X':
add(DP[i][1][1][0],DP[i][1][1][1])
fx0(DP[i][1][1][0])
add(DP[i][1][1][1],DP[i][1][0][1])
add(DP[i][1][1][1],DP[i][0][1][1])
add(DP[i][1][1][1],DP[i][0][0][1])
f1x(DP[i][1][1][1])
for j in range(2):
add(DP[i+1][0][1][0],DP[i][1][1][j])
else:
t=[[],[],0]
add(DP[i][0][1][0],DP[i][0][1][1])
add(DP[i][1][1][0],DP[i][1][1][1])
add(DP[i+1][1][1][1],DP[i][0][1][0])
fx0(DP[i+1][1][1][1])
add(t,DP[i][0][1][0])
add(t,DP[i][1][1][0])
f1x(t)
fx0(DP[i][1][1][0])
add(DP[i+1][0][0][1],DP[i][1][1][0])
add(DP[i+1][0][0][1],t)
def f10(p,o,e):
r=[0]*3
q=deepcopy(p)
integrate(q)
r[0]=(sum(q[0])-q[2])*o%mod
r[1]=(sum(q[1])+q[2])*o%mod
for j in range(2):
for i in range(len(p[j])):
r[j]=(r[j]+p[j][i]*g1[i]*e)%mod
r[j+1]=(r[j+1]-p[j][i]*g1[i]*c[i]*e)%mod
r[0]=(r[0]+p[2]*inv[2]*e)%mod
r[2]=(r[2]-p[2]*inv[2]*e)%mod
return r
add(DP[-1][0][1][1],DP[-1][1][1][1])
add(DP[-1][0][1][0],DP[-1][1][1][0])
add(DP[-1][0][0][1],DP[-1][1][0][1])
X=[f10(DP[-1][0][1][1],1,0),f10(DP[-1][0][1][0],0,1),f10(DP[-1][0][0][1],1,mod-1)]
A=[sum(map(lambda x:x[i],X))%mod for i in range(3)]
print(*A)
``` | output | 1 | 103,490 | 14 | 206,981 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a very long bench. The bench is divided into M sections, where M is a very large integer.
Initially, the bench is vacant. Then, M people come to the bench one by one, and perform the following action:
* We call a section comfortable if the section is currently unoccupied and is not adjacent to any occupied sections. If there is no comfortable section, the person leaves the bench. Otherwise, the person chooses one of comfortable sections uniformly at random, and sits there. (The choices are independent from each other).
After all M people perform actions, Snuke chooses an interval of N consecutive sections uniformly at random (from M-N+1 possible intervals), and takes a photo. His photo can be described by a string of length N consisting of `X` and `-`: the i-th character of the string is `X` if the i-th section from the left in the interval is occupied, and `-` otherwise. Note that the photo is directed. For example, `-X--X` and `X--X-` are different photos.
What is the probability that the photo matches a given string s? This probability depends on M. You need to compute the limit of this probability when M goes infinity.
Here, we can prove that the limit can be uniquely written in the following format using three rational numbers p, q, r and e = 2.718 \ldots (the base of natural logarithm):
p + \frac{q}{e} + \frac{r}{e^2}
Your task is to compute these three rational numbers, and print them modulo 10^9 + 7, as described in Notes section.
Constraints
* 1 \leq N \leq 1000
* |s| = N
* s consists of `X` and `-`.
Input
Input is given from Standard Input in the following format:
N
s
Output
Print three rational numbers p, q, r, separated by spaces.
Examples
Input
1
X
Output
500000004 0 500000003
Input
3
---
Output
0 0 0
Input
5
X--X-
Output
0 0 1
Input
5
X-X-X
Output
500000004 0 833333337
Input
20
-X--X--X-X--X--X-X-X
Output
0 0 183703705
Input
100
X-X-X-X-X-X-X-X-X-X--X-X-X-X-X-X-X-X-X-X-X-X-X-X-X--X--X-X-X-X--X--X-X-X--X-X-X--X-X--X--X-X--X-X-X-
Output
0 0 435664291
Submitted Solution:
```
#εθURL
#https://qiita.com/ageprocpp/items/104c051b2ec2086f5a9b
mod=10**9+7
def value(obj):
if type(obj)==modint:
tmp=obj.number
else:
tmp=obj
return tmp%mod
class modint():
number=0
def __init__(self,num):
self.number=num%mod
def __add__(self,other):
tmp=value(other)
return modint(self.number+tmp)
def __iadd__(self,other):
tmp=value(other)
self.number+=tmp
self.number%=mod
return self
def __sub__(self,other):
tmp=value(other)
return modint(self.number-tmp)
def __isub__(self,other):
tmp=value(other)
self.number-=tmp
self.number%=mod
return self
def __mul__(self,other):
tmp=value(other)
return modint(self.number*tmp)
def __imul__(self,other):
tmp=value(other)
self.number*=tmp
self.number%=mod
return self
def __truediv__(self,other):
tmp=value(other)
return self*pow(tmp,mod-2,mod)
def __itruediv(self,other):
tmp=value(other)
self.number=self/tmp
self.number%=mod
return self
def __repr__(self):
return str(self.number)
def __eq__(self,other):
return value(self)==value(other)
def __ne__(self,other):
return value(self)!=value(other)
def __str__(self):
return str(self.number)
def __int__(self):
return self.number
def __hash__(self):
return self.number
class polynomial():
sequence=[0]
def __init__(self,seq):
self.sequence=[]
for i in seq:
self.sequence.append(value(i))
def get(self,x):
res=modint(0)
tmp=modint(1)
for a in self.sequence:
res+=tmp*a
tmp*=x
if tmp==0:
break
return res
def __add__(self,other):
res=[]
for i,a in enumerate(self.sequence):
try:
res[i]=a
except IndexError:
res.append(modint(0))
res[i]=a
for i,a in enumerate(other.sequence):
try:
res[i]+=a
except IndexError:
res.append(modint(0))
res[i]+=a
return polynomial(res)
def __iadd__(self,other):
return self+other
def __sub__(self,other):
res=[]
for i,a in enumerate(self.sequence):
try:
res[i]=a
except IndexError:
res.append(modint(0))
res[i]=a
for i,a in enumerate(other.sequence):
try:
res[i]-=a
except IndexError:
res.append(modint(0))
res[i]-=a
return polynomial(res)
def __isub__(self,other):
return self-other
def indef_integral(self):
res=[modint(0)]
for i,a in enumerate(self.sequence):
res.append(modint(a)/(i+1))
return polynomial(res)
def integrate(self,flag):
#0: 0->x
#1:x->1
if flag==0:
return self.indef_integral()
else:
tmp=self.indef_integral()
return polynomial([tmp.get(1)])-tmp
def __repr__(self):
return str(self.sequence)
def __str__(self):
return str(self.sequence)
class func():
P=polynomial([modint(0)])
Q=polynomial([modint(0)])
C=modint(0)
def __init__(self,poly1,poly2,cnst):
self.P=poly1
self.Q=poly2
self.C=cnst
def __add__(self,other):
PP=self.P+other.P
QQ=self.Q+other.Q
CC=self.C+other.C
return func(PP,QQ,CC)
def __iadd__(self,other):
return self+other
def __sub__(self,other):
PP=self.P-other.P
QQ=self.Q-other.Q
CC=self.C-other.C
return func(PP,QQ,CC)
def __isub__(self,other):
return self-other
def dintegrate(self,flag):
if flag==0:
PP=self.P.integrate(0)+polynomial([self.C])
QQ=self.Q.integrate(0)
CC=modint(-1)*self.C
else:
PP=self.P.integrate(1)
QQ=self.Q.integrate(1)+polynomial([modint(-1)*self.C])
CC=self.C
return func(PP,QQ,CC)
MAX_N=1009
N=int(input())
s=input()
fact=[modint(0) for i in range(MAX_N+1)]
inv=[modint(0) for i in range(MAX_N+1)]
fact[0]=modint(1)
for i in range(MAX_N):
fact[i+1]=fact[i]*(i+1)
inv[-1]=modint(1)/fact[-1]
for i in range(MAX_N-1,-1,-1):
inv[i]=inv[i+1]*(i+1)
dp=[[[[func(polynomial([modint(0)]),polynomial([modint(0)]),modint(0)) for l in range(2)]for k in range(2)]for j in range(2)] for i in range(MAX_N+1)]
if s[0]=="X":
dp[0][0][1][0]=func(polynomial([modint(0)]),polynomial([modint(0)]),modint(1))
else:
dp[0][0][0][1]=func(polynomial([modint(0)]),polynomial([modint(0)]),modint(1))
dp[0][1][1][1]=func(polynomial([modint(1)]),polynomial([modint(0)]),modint(-1))
for i in range(1,N):
if s[i]=="X":
dp[i][0][1][0]+=dp[i-1][1][1][0].dintegrate(0)
dp[i][0][1][0]+=dp[i-1][1][1][1].dintegrate(0)
dp[i][0][1][0]+=dp[i-1][0][0][1].dintegrate(1)
dp[i][0][1][0]+=dp[i-1][0][1][1].dintegrate(1)
dp[i][0][1][0]+=dp[i-1][1][0][1].dintegrate(1)
dp[i][0][1][0]+=dp[i-1][1][1][1].dintegrate(1)
else:
dp[i][0][0][1]+=dp[i-1][1][1][0].dintegrate(0)
dp[i][0][0][1]+=dp[i-1][1][1][1].dintegrate(0)
dp[i][1][1][1]+=dp[i-1][0][1][0].dintegrate(0)
dp[i][1][1][1]+=dp[i-1][0][1][1].dintegrate(0)
dp[i][0][0][1]+=dp[i-1][0][1][0].dintegrate(1)
dp[i][0][0][1]+=dp[i-1][0][1][1].dintegrate(1)
dp[i][0][0][1]+=dp[i-1][1][1][0].dintegrate(1)
dp[i][0][0][1]+=dp[i-1][1][1][1].dintegrate(1)
a=modint(0)
b=modint(0)
c=modint(0)
p = dp[N-1][0][1][1].P.integrate(0)
a+= p.get(1)-p.get(0)
p = dp[N-1][0][1][1].Q.integrate(0)
b+= p.get(1)-p.get(0)
a+= dp[N-1][0][1][1].C
b-= dp[N-1][0][1][1].C
p = dp[N-1][1][1][1].P.integrate(0)
a+= p.get(1)-p.get(0)
p = dp[N-1][1][1][1].Q.integrate(0)
b+= p.get(1)-p.get(0)
a+= dp[N-1][1][1][1].C
b-= dp[N-1][1][1][1].C
for x in range(2):
for i,v in enumerate(dp[N-1][x][1][0].P.sequence):
a+=modint(1)*v*fact[i]
for j in range(i+1):
b-=modint(1)*v*fact[i]*inv[j]
for i,v in enumerate(dp[N-1][x][1][0].Q.sequence):
b+=modint(1)*v*fact[i]
for j in range(i+1):
c-=modint(1)*v*fact[i]*inv[j]
a+=dp[N-1][x][1][0].C/2
c-=dp[N-1][x][1][0].C/2
p = dp[N-1][0][0][1].P.integrate(0)
a+= p.get(1)-p.get(0)
p = dp[N-1][0][0][1].Q.integrate(0)
b+= p.get(1)-p.get(0)
a+= dp[N-1][0][0][1].C
b-= dp[N-1][0][0][1].C
p = dp[N-1][1][0][1].P.integrate(0)
a+= p.get(1)-p.get(0)
p = dp[N-1][1][0][1].Q.integrate(0)
b+= p.get(1)-p.get(0)
a+= dp[N-1][1][0][1].C
b-= dp[N-1][1][0][1].C
for x in range(2):
for i,v in enumerate(dp[N-1][x][0][1].P.sequence):
a-=modint(1)*v*fact[i]
for j in range(i+1):
b+=modint(1)*v*fact[i]*inv[j]
for i,v in enumerate(dp[N-1][x][0][1].Q.sequence):
b-=modint(1)*v*fact[i]
for j in range(i+1):
c+=modint(1)*v*fact[i]*inv[j]
a-=dp[N-1][x][0][1].C/2
c+=dp[N-1][x][0][1].C/2
print(a,b,c)
``` | instruction | 0 | 103,491 | 14 | 206,982 |
No | output | 1 | 103,491 | 14 | 206,983 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a very long bench. The bench is divided into M sections, where M is a very large integer.
Initially, the bench is vacant. Then, M people come to the bench one by one, and perform the following action:
* We call a section comfortable if the section is currently unoccupied and is not adjacent to any occupied sections. If there is no comfortable section, the person leaves the bench. Otherwise, the person chooses one of comfortable sections uniformly at random, and sits there. (The choices are independent from each other).
After all M people perform actions, Snuke chooses an interval of N consecutive sections uniformly at random (from M-N+1 possible intervals), and takes a photo. His photo can be described by a string of length N consisting of `X` and `-`: the i-th character of the string is `X` if the i-th section from the left in the interval is occupied, and `-` otherwise. Note that the photo is directed. For example, `-X--X` and `X--X-` are different photos.
What is the probability that the photo matches a given string s? This probability depends on M. You need to compute the limit of this probability when M goes infinity.
Here, we can prove that the limit can be uniquely written in the following format using three rational numbers p, q, r and e = 2.718 \ldots (the base of natural logarithm):
p + \frac{q}{e} + \frac{r}{e^2}
Your task is to compute these three rational numbers, and print them modulo 10^9 + 7, as described in Notes section.
Constraints
* 1 \leq N \leq 1000
* |s| = N
* s consists of `X` and `-`.
Input
Input is given from Standard Input in the following format:
N
s
Output
Print three rational numbers p, q, r, separated by spaces.
Examples
Input
1
X
Output
500000004 0 500000003
Input
3
---
Output
0 0 0
Input
5
X--X-
Output
0 0 1
Input
5
X-X-X
Output
500000004 0 833333337
Input
20
-X--X--X-X--X--X-X-X
Output
0 0 183703705
Input
100
X-X-X-X-X-X-X-X-X-X--X-X-X-X-X-X-X-X-X-X-X-X-X-X-X--X--X-X-X-X--X--X-X-X--X-X-X--X-X--X--X-X--X-X-X-
Output
0 0 435664291
Submitted Solution:
```
print("Hello World")
``` | instruction | 0 | 103,492 | 14 | 206,984 |
No | output | 1 | 103,492 | 14 | 206,985 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a very long bench. The bench is divided into M sections, where M is a very large integer.
Initially, the bench is vacant. Then, M people come to the bench one by one, and perform the following action:
* We call a section comfortable if the section is currently unoccupied and is not adjacent to any occupied sections. If there is no comfortable section, the person leaves the bench. Otherwise, the person chooses one of comfortable sections uniformly at random, and sits there. (The choices are independent from each other).
After all M people perform actions, Snuke chooses an interval of N consecutive sections uniformly at random (from M-N+1 possible intervals), and takes a photo. His photo can be described by a string of length N consisting of `X` and `-`: the i-th character of the string is `X` if the i-th section from the left in the interval is occupied, and `-` otherwise. Note that the photo is directed. For example, `-X--X` and `X--X-` are different photos.
What is the probability that the photo matches a given string s? This probability depends on M. You need to compute the limit of this probability when M goes infinity.
Here, we can prove that the limit can be uniquely written in the following format using three rational numbers p, q, r and e = 2.718 \ldots (the base of natural logarithm):
p + \frac{q}{e} + \frac{r}{e^2}
Your task is to compute these three rational numbers, and print them modulo 10^9 + 7, as described in Notes section.
Constraints
* 1 \leq N \leq 1000
* |s| = N
* s consists of `X` and `-`.
Input
Input is given from Standard Input in the following format:
N
s
Output
Print three rational numbers p, q, r, separated by spaces.
Examples
Input
1
X
Output
500000004 0 500000003
Input
3
---
Output
0 0 0
Input
5
X--X-
Output
0 0 1
Input
5
X-X-X
Output
500000004 0 833333337
Input
20
-X--X--X-X--X--X-X-X
Output
0 0 183703705
Input
100
X-X-X-X-X-X-X-X-X-X--X-X-X-X-X-X-X-X-X-X-X-X-X-X-X--X--X-X-X-X--X--X-X-X--X-X-X--X-X--X--X-X--X-X-X-
Output
0 0 435664291
Submitted Solution:
```
print('I am tourist')
``` | instruction | 0 | 103,493 | 14 | 206,986 |
No | output | 1 | 103,493 | 14 | 206,987 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a very long bench. The bench is divided into M sections, where M is a very large integer.
Initially, the bench is vacant. Then, M people come to the bench one by one, and perform the following action:
* We call a section comfortable if the section is currently unoccupied and is not adjacent to any occupied sections. If there is no comfortable section, the person leaves the bench. Otherwise, the person chooses one of comfortable sections uniformly at random, and sits there. (The choices are independent from each other).
After all M people perform actions, Snuke chooses an interval of N consecutive sections uniformly at random (from M-N+1 possible intervals), and takes a photo. His photo can be described by a string of length N consisting of `X` and `-`: the i-th character of the string is `X` if the i-th section from the left in the interval is occupied, and `-` otherwise. Note that the photo is directed. For example, `-X--X` and `X--X-` are different photos.
What is the probability that the photo matches a given string s? This probability depends on M. You need to compute the limit of this probability when M goes infinity.
Here, we can prove that the limit can be uniquely written in the following format using three rational numbers p, q, r and e = 2.718 \ldots (the base of natural logarithm):
p + \frac{q}{e} + \frac{r}{e^2}
Your task is to compute these three rational numbers, and print them modulo 10^9 + 7, as described in Notes section.
Constraints
* 1 \leq N \leq 1000
* |s| = N
* s consists of `X` and `-`.
Input
Input is given from Standard Input in the following format:
N
s
Output
Print three rational numbers p, q, r, separated by spaces.
Examples
Input
1
X
Output
500000004 0 500000003
Input
3
---
Output
0 0 0
Input
5
X--X-
Output
0 0 1
Input
5
X-X-X
Output
500000004 0 833333337
Input
20
-X--X--X-X--X--X-X-X
Output
0 0 183703705
Input
100
X-X-X-X-X-X-X-X-X-X--X-X-X-X-X-X-X-X-X-X-X-X-X-X-X--X--X-X-X-X--X--X-X-X--X-X-X--X-X--X--X-X--X-X-X-
Output
0 0 435664291
Submitted Solution:
```
from copy import *
N=int(input())
S=input()
DP=[[[[0]*2 for i in range(2)] for j in range(2)] for k in range(N)]
mod=10**9+7
for i in range(N):
for j in range(2):
for k in range(2):
for l in range(2):
DP[i][j][k][l]=[[],[],0]
if S[0]=='X':
DP[0][0][1][0]=[[],[],1]
else:
DP[0][0][0][1]=[[],[],1]
DP[0][1][1][1]=[[1],[],mod-1]
g1=[1,1]
g2=[1,1]
inv=[0,1]
c=[1,2]
for i in range(2,N+5):
g1.append((g1[-1]*i)%mod)
inv.append((-inv[mod%i]*(mod//i))%mod)
g2.append((g2[-1]*inv[-1])%mod)
c.append((c[-1]+g2[i])%mod)
def add(x,y):
for j in range(2):
for i in range(len(y[j])-len(x[j])):
x[j].append(0)
for i in range(len(y[j])):
x[j][i]=(x[j][i]+y[j][i])%mod
x[2]=(x[2]+y[2])%mod
def integrate(p):
p[2]=-p[2]%mod
for j in range(2):
p[j].append(0)
for i in range(len(p[j])-2,-1,-1):
p[j][i+1]=p[j][i]*inv[i+1]%mod
p[j][i]=0
def fx0(p):
integrate(p)
p[0][0]=(p[0][0]-p[2])%mod
def f1x(p):
integrate(p)
for j in range(2):
for i in range(len(p[j])):
p[j][i]=-p[j][i]%mod
p[2]=-p[2]%mod
for i in range(2):
p[i][0]=-sum(p[i])%mod
p[1][0]=(p[1][0]-p[2])%mod
for i in range(N-1):
if S[i+1]=='X':
add(DP[i][1][1][0],DP[i][1][1][1])
fx0(DP[i][1][1][0])
add(DP[i][1][1][1],DP[i][1][0][1])
add(DP[i][1][1][1],DP[i][0][1][1])
add(DP[i][1][1][1],DP[i][0][0][1])
f1x(DP[i][1][1][1])
for j in range(2):
add(DP[i+1][0][1][0],DP[i][1][1][j])
else:
t=[[],[],0]
add(DP[i][0][1][0],DP[i][0][1][1])
add(DP[i][1][1][0],DP[i][1][1][1])
add(DP[i+1][1][1][1],DP[i][0][1][0])
fx0(DP[i+1][1][1][1])
add(t,DP[i][0][1][0])
add(t,DP[i][1][1][0])
f1x(t)
fx0(DP[i][1][1][0])
add(DP[i+1][0][0][1],DP[i][1][1][0])
add(DP[i+1][0][0][1],t)
def f10(p,o,e):
r=[0]*3
q=deepcopy(p)
integrate(q)
r[0]=(sum(q[0])-q[2])*o%mod
r[1]=(sum(q[1])+q[2])*o%mod
for j in range(2):
for i in range(len(p[j])):
r[j]=(r[j]+p[j][i]*g1[i]*e)%mod
r[j+1]=(r[j+1]-p[j][i]*g1[i]*c[i]*e)%mod
r[0]=(r[0]+p[2]*inv[2])%mod
r[2]=(r[2]-p[2]*inv[2])%mod
return r
add(DP[-1][0][1][1],DP[-1][1][1][1])
add(DP[-1][0][1][0],DP[-1][1][1][0])
add(DP[-1][0][0][1],DP[-1][1][0][1])
X=[f10(DP[-1][0][1][1],1,0),f10(DP[-1][0][1][0],0,1),f10(DP[-1][0][0][1],1,mod-1)]
A=[sum(map(lambda x:x[i],X))%mod for i in range(3)]
print(*A)
``` | instruction | 0 | 103,494 | 14 | 206,988 |
No | output | 1 | 103,494 | 14 | 206,989 |
Provide a correct Python 3 solution for this coding contest problem.
There are N persons, conveniently numbered 1 through N. They will take 3y3s Challenge for N-1 seconds.
During the challenge, each person must look at each of the N-1 other persons for 1 seconds, in some order.
If any two persons look at each other during the challenge, the challenge ends in failure.
Find the order in which each person looks at each of the N-1 other persons, to be successful in the challenge.
Constraints
* 2 \leq N \leq 100
Input
The input is given from Standard Input in the following format:
N
Output
If there exists no way to be successful in the challenge, print `-1`.
If there exists a way to be successful in the challenge, print any such way in the following format:
A_{1,1} A_{1,2} ... A_{1, N-1}
A_{2,1} A_{2,2} ... A_{2, N-1}
:
A_{N,1} A_{N,2} ... A_{N, N-1}
where A_{i, j} is the index of the person that the person numbered i looks at during the j-th second.
Judging
The output is considered correct only if all of the following conditions are satisfied:
* 1 \leq A_{i,j} \leq N
* For each i, A_{i,1}, A_{i,2}, ... , A_{i, N-1} are pairwise distinct.
* Let X = A_{i, j}, then A_{X, j} \neq i always holds.
Examples
Input
7
Output
2 3 4 5 6 7
5 3 1 6 4 7
2 7 4 1 5 6
2 1 7 5 3 6
1 4 3 7 6 2
2 5 7 3 4 1
2 6 1 4 5 3
Input
2
Output
-1 | instruction | 0 | 103,559 | 14 | 207,118 |
"Correct Solution:
```
n = int(input())
if n==2: print(-1)
else:
for i in range(1,n+1):
num = 0
if i%2==1:
for j in range(1,n+1):
if i!=j and num!=n-2:
print(j,end=" ")
num += 1
elif i!=j:
print(j)
break
else:
if i==n: print(n-1,end=" ")
else: print(n,end=" ")
for j in range(1,n+1):
if i!=j and num!=n-3:
print(j,end=" ")
num += 1
elif i!=j:
print(j)
break
``` | output | 1 | 103,559 | 14 | 207,119 |
Provide a correct Python 3 solution for this coding contest problem.
There are N persons, conveniently numbered 1 through N. They will take 3y3s Challenge for N-1 seconds.
During the challenge, each person must look at each of the N-1 other persons for 1 seconds, in some order.
If any two persons look at each other during the challenge, the challenge ends in failure.
Find the order in which each person looks at each of the N-1 other persons, to be successful in the challenge.
Constraints
* 2 \leq N \leq 100
Input
The input is given from Standard Input in the following format:
N
Output
If there exists no way to be successful in the challenge, print `-1`.
If there exists a way to be successful in the challenge, print any such way in the following format:
A_{1,1} A_{1,2} ... A_{1, N-1}
A_{2,1} A_{2,2} ... A_{2, N-1}
:
A_{N,1} A_{N,2} ... A_{N, N-1}
where A_{i, j} is the index of the person that the person numbered i looks at during the j-th second.
Judging
The output is considered correct only if all of the following conditions are satisfied:
* 1 \leq A_{i,j} \leq N
* For each i, A_{i,1}, A_{i,2}, ... , A_{i, N-1} are pairwise distinct.
* Let X = A_{i, j}, then A_{X, j} \neq i always holds.
Examples
Input
7
Output
2 3 4 5 6 7
5 3 1 6 4 7
2 7 4 1 5 6
2 1 7 5 3 6
1 4 3 7 6 2
2 5 7 3 4 1
2 6 1 4 5 3
Input
2
Output
-1 | instruction | 0 | 103,560 | 14 | 207,120 |
"Correct Solution:
```
n = int(input())
if n == 2:
print(-1)
exit()
if n % 2 == 1:
for i in range(n):
print(" ".join([str((item + i + 1) % n + 1) for item in range(n-1)]))
else:
for i in range(n):
ans = [(item + i + 1) % n + 1 for item in range(n-1) if item != n // 2 - 1]
ans.insert(0, (n // 2 + i) % n + 1)
if i < n // 2:
ans[0], ans[1] = ans[1], ans[0]
print(" ".join([str(item) for item in ans]))
``` | output | 1 | 103,560 | 14 | 207,121 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Elections in Berland are coming. There are only two candidates β Alice and Bob.
The main Berland TV channel plans to show political debates. There are n people who want to take part in the debate as a spectator. Each person is described by their influence and political views. There are four kinds of political views:
* supporting none of candidates (this kind is denoted as "00"),
* supporting Alice but not Bob (this kind is denoted as "10"),
* supporting Bob but not Alice (this kind is denoted as "01"),
* supporting both candidates (this kind is denoted as "11").
The direction of the TV channel wants to invite some of these people to the debate. The set of invited spectators should satisfy three conditions:
* at least half of spectators support Alice (i.e. 2 β
a β₯ m, where a is number of spectators supporting Alice and m is the total number of spectators),
* at least half of spectators support Bob (i.e. 2 β
b β₯ m, where b is number of spectators supporting Bob and m is the total number of spectators),
* the total influence of spectators is maximal possible.
Help the TV channel direction to select such non-empty set of spectators, or tell that this is impossible.
Input
The first line contains integer n (1 β€ n β€ 4β
10^5) β the number of people who want to take part in the debate as a spectator.
These people are described on the next n lines. Each line describes a single person and contains the string s_i and integer a_i separated by space (1 β€ a_i β€ 5000), where s_i denotes person's political views (possible values β "00", "10", "01", "11") and a_i β the influence of the i-th person.
Output
Print a single integer β maximal possible total influence of a set of spectators so that at least half of them support Alice and at least half of them support Bob. If it is impossible print 0 instead.
Examples
Input
6
11 6
10 4
01 3
00 3
00 7
00 9
Output
22
Input
5
11 1
01 1
00 100
10 1
01 1
Output
103
Input
6
11 19
10 22
00 18
00 29
11 29
10 28
Output
105
Input
3
00 5000
00 5000
00 5000
Output
0
Note
In the first example 4 spectators can be invited to maximize total influence: 1, 2, 3 and 6. Their political views are: "11", "10", "01" and "00". So in total 2 out of 4 spectators support Alice and 2 out of 4 spectators support Bob. The total influence is 6+4+3+9=22.
In the second example the direction can select all the people except the 5-th person.
In the third example the direction can select people with indices: 1, 4, 5 and 6.
In the fourth example it is impossible to select any non-empty set of spectators. | instruction | 0 | 103,699 | 14 | 207,398 |
Tags: greedy
Correct Solution:
```
if __name__=="__main__":
n = int(input())
supporters = {}
supporters[0]=[]
supporters[1]=[]
supporters[10]=[]
supporters[11]=[]
for i in range(n):
[x,y] = [int(x) for x in input().split()]
supporters[x].append(y)
#print(x,y)
for x in supporters:
supporters[x].sort(reverse=True)
#print(supporters[x])
t = 0
res = 0
x = len(supporters[11])
y = len(supporters[10])
z = len(supporters[1])
if y>z:
t = min(x+y,z)
else:
t = min(x+z,y)
k = 0
for val in supporters[11]:
res += val
k+=1
for i in range(y):
if i>=t:
supporters[0].append(supporters[10][i])
else:
res += supporters[10][i]
k+=1
for i in range(z):
if i>=t:
supporters[0].append(supporters[1][i])
else:
res += supporters[1][i]
k+=1
supporters[0].sort(reverse=True)
t = min(x+y,x+z)
i = 0
#print(res)
while 2*t > k and i<len(supporters[0]):
k+=1
#print(supporters[0][i])
res += supporters[0][i]
i+=1
print(res)
``` | output | 1 | 103,699 | 14 | 207,399 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Elections in Berland are coming. There are only two candidates β Alice and Bob.
The main Berland TV channel plans to show political debates. There are n people who want to take part in the debate as a spectator. Each person is described by their influence and political views. There are four kinds of political views:
* supporting none of candidates (this kind is denoted as "00"),
* supporting Alice but not Bob (this kind is denoted as "10"),
* supporting Bob but not Alice (this kind is denoted as "01"),
* supporting both candidates (this kind is denoted as "11").
The direction of the TV channel wants to invite some of these people to the debate. The set of invited spectators should satisfy three conditions:
* at least half of spectators support Alice (i.e. 2 β
a β₯ m, where a is number of spectators supporting Alice and m is the total number of spectators),
* at least half of spectators support Bob (i.e. 2 β
b β₯ m, where b is number of spectators supporting Bob and m is the total number of spectators),
* the total influence of spectators is maximal possible.
Help the TV channel direction to select such non-empty set of spectators, or tell that this is impossible.
Input
The first line contains integer n (1 β€ n β€ 4β
10^5) β the number of people who want to take part in the debate as a spectator.
These people are described on the next n lines. Each line describes a single person and contains the string s_i and integer a_i separated by space (1 β€ a_i β€ 5000), where s_i denotes person's political views (possible values β "00", "10", "01", "11") and a_i β the influence of the i-th person.
Output
Print a single integer β maximal possible total influence of a set of spectators so that at least half of them support Alice and at least half of them support Bob. If it is impossible print 0 instead.
Examples
Input
6
11 6
10 4
01 3
00 3
00 7
00 9
Output
22
Input
5
11 1
01 1
00 100
10 1
01 1
Output
103
Input
6
11 19
10 22
00 18
00 29
11 29
10 28
Output
105
Input
3
00 5000
00 5000
00 5000
Output
0
Note
In the first example 4 spectators can be invited to maximize total influence: 1, 2, 3 and 6. Their political views are: "11", "10", "01" and "00". So in total 2 out of 4 spectators support Alice and 2 out of 4 spectators support Bob. The total influence is 6+4+3+9=22.
In the second example the direction can select all the people except the 5-th person.
In the third example the direction can select people with indices: 1, 4, 5 and 6.
In the fourth example it is impossible to select any non-empty set of spectators. | instruction | 0 | 103,700 | 14 | 207,400 |
Tags: greedy
Correct Solution:
```
from collections import defaultdict
c = defaultdict(int)
m = defaultdict(list)
n = int(input())
for i in range(n):
s,a = input().split()
m[s].append(int(a))
c[s]+=1
ali = c['10']
bob = c['01']
co = c['11']
no = c['00']
if(ali==0 or bob==0) and (co==0):
print(0)
else:
if(ali>bob):
ali-=(ali-bob)
else:
bob-=(bob-ali)
x = m['10']
y = m['01']
x.sort(reverse=True)
y.sort(reverse=True)
ans = sum(x[:ali])+sum(y[:ali])
rem = x[ali:]+y[ali:]+m['00']
tot = ali+bob
if(co>0):
ans+=sum(m['11'])
tot+=co
ali+=co
bob+=co
#print(ali,bob,tot)
rem.sort(reverse=True)
#print(rem)
mn = min(ali,bob)
re = max(2*mn-tot,0)
#print(re)
ans+=sum(rem[:re])
print(ans)
``` | output | 1 | 103,700 | 14 | 207,401 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Elections in Berland are coming. There are only two candidates β Alice and Bob.
The main Berland TV channel plans to show political debates. There are n people who want to take part in the debate as a spectator. Each person is described by their influence and political views. There are four kinds of political views:
* supporting none of candidates (this kind is denoted as "00"),
* supporting Alice but not Bob (this kind is denoted as "10"),
* supporting Bob but not Alice (this kind is denoted as "01"),
* supporting both candidates (this kind is denoted as "11").
The direction of the TV channel wants to invite some of these people to the debate. The set of invited spectators should satisfy three conditions:
* at least half of spectators support Alice (i.e. 2 β
a β₯ m, where a is number of spectators supporting Alice and m is the total number of spectators),
* at least half of spectators support Bob (i.e. 2 β
b β₯ m, where b is number of spectators supporting Bob and m is the total number of spectators),
* the total influence of spectators is maximal possible.
Help the TV channel direction to select such non-empty set of spectators, or tell that this is impossible.
Input
The first line contains integer n (1 β€ n β€ 4β
10^5) β the number of people who want to take part in the debate as a spectator.
These people are described on the next n lines. Each line describes a single person and contains the string s_i and integer a_i separated by space (1 β€ a_i β€ 5000), where s_i denotes person's political views (possible values β "00", "10", "01", "11") and a_i β the influence of the i-th person.
Output
Print a single integer β maximal possible total influence of a set of spectators so that at least half of them support Alice and at least half of them support Bob. If it is impossible print 0 instead.
Examples
Input
6
11 6
10 4
01 3
00 3
00 7
00 9
Output
22
Input
5
11 1
01 1
00 100
10 1
01 1
Output
103
Input
6
11 19
10 22
00 18
00 29
11 29
10 28
Output
105
Input
3
00 5000
00 5000
00 5000
Output
0
Note
In the first example 4 spectators can be invited to maximize total influence: 1, 2, 3 and 6. Their political views are: "11", "10", "01" and "00". So in total 2 out of 4 spectators support Alice and 2 out of 4 spectators support Bob. The total influence is 6+4+3+9=22.
In the second example the direction can select all the people except the 5-th person.
In the third example the direction can select people with indices: 1, 4, 5 and 6.
In the fourth example it is impossible to select any non-empty set of spectators. | instruction | 0 | 103,701 | 14 | 207,402 |
Tags: greedy
Correct Solution:
```
from math import ceil
n, A = int(input()), []
a = b = ab = ab_ = ans = 0
for _ in range(n):
t, tt = input().split()
tt = int(tt)
if t != '11':
A.append([t, tt])
if t == '10':
a += 1
elif t == '01':
b += 1
else:
ab_ += 1
else:
ans += tt
ab += 1
A.sort(reverse=True, key=lambda x: x[1])
x = y = t = ttt = ab
k, j = a, b
for i in A:
if i[0] == '10' and (j or ttt):
ans += i[1]
t += 1
x += 1
if j == 0 and ttt:
ttt -= 1
j = 1
j -= 1
elif i[0] == '01' and (k or ttt):
ans += i[1]
t += 1
y += 1
if k == 0 and ttt:
ttt -= 1
k = 1
k -= 1
elif i[0] == '00' and ttt:
ans += i[1]
ttt -= 1
t += 1
print(ans)
``` | output | 1 | 103,701 | 14 | 207,403 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Elections in Berland are coming. There are only two candidates β Alice and Bob.
The main Berland TV channel plans to show political debates. There are n people who want to take part in the debate as a spectator. Each person is described by their influence and political views. There are four kinds of political views:
* supporting none of candidates (this kind is denoted as "00"),
* supporting Alice but not Bob (this kind is denoted as "10"),
* supporting Bob but not Alice (this kind is denoted as "01"),
* supporting both candidates (this kind is denoted as "11").
The direction of the TV channel wants to invite some of these people to the debate. The set of invited spectators should satisfy three conditions:
* at least half of spectators support Alice (i.e. 2 β
a β₯ m, where a is number of spectators supporting Alice and m is the total number of spectators),
* at least half of spectators support Bob (i.e. 2 β
b β₯ m, where b is number of spectators supporting Bob and m is the total number of spectators),
* the total influence of spectators is maximal possible.
Help the TV channel direction to select such non-empty set of spectators, or tell that this is impossible.
Input
The first line contains integer n (1 β€ n β€ 4β
10^5) β the number of people who want to take part in the debate as a spectator.
These people are described on the next n lines. Each line describes a single person and contains the string s_i and integer a_i separated by space (1 β€ a_i β€ 5000), where s_i denotes person's political views (possible values β "00", "10", "01", "11") and a_i β the influence of the i-th person.
Output
Print a single integer β maximal possible total influence of a set of spectators so that at least half of them support Alice and at least half of them support Bob. If it is impossible print 0 instead.
Examples
Input
6
11 6
10 4
01 3
00 3
00 7
00 9
Output
22
Input
5
11 1
01 1
00 100
10 1
01 1
Output
103
Input
6
11 19
10 22
00 18
00 29
11 29
10 28
Output
105
Input
3
00 5000
00 5000
00 5000
Output
0
Note
In the first example 4 spectators can be invited to maximize total influence: 1, 2, 3 and 6. Their political views are: "11", "10", "01" and "00". So in total 2 out of 4 spectators support Alice and 2 out of 4 spectators support Bob. The total influence is 6+4+3+9=22.
In the second example the direction can select all the people except the 5-th person.
In the third example the direction can select people with indices: 1, 4, 5 and 6.
In the fourth example it is impossible to select any non-empty set of spectators. | instruction | 0 | 103,702 | 14 | 207,404 |
Tags: greedy
Correct Solution:
```
from collections import defaultdict
n = int(input())
a=defaultdict(list)
for i in range(n):
h,m=list(map(int,input().split()))
a[h].append(m)
k=sum(a[11])
a[10].sort()
a[1].sort()
a[0].sort()
g=0
if len(a[1])>len(a[10]):
z=len(a[10])
g=1
else:
g=10
z=len(a[1])
while z>0:
k+=a[1].pop()
k+=a[10].pop()
z-=1
l=len(a[11])
while l>0:
if len(a[g])>0 and len(a[0])>0:
if a[0][-1]>a[g][-1]:
k+=a[0].pop()
else:
k+=a[g].pop()
elif len(a[g])>0:
k+=a[g].pop()
elif len(a[0])>0:
k+=a[0].pop()
else:
break
l-=1
print(k)
``` | output | 1 | 103,702 | 14 | 207,405 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Elections in Berland are coming. There are only two candidates β Alice and Bob.
The main Berland TV channel plans to show political debates. There are n people who want to take part in the debate as a spectator. Each person is described by their influence and political views. There are four kinds of political views:
* supporting none of candidates (this kind is denoted as "00"),
* supporting Alice but not Bob (this kind is denoted as "10"),
* supporting Bob but not Alice (this kind is denoted as "01"),
* supporting both candidates (this kind is denoted as "11").
The direction of the TV channel wants to invite some of these people to the debate. The set of invited spectators should satisfy three conditions:
* at least half of spectators support Alice (i.e. 2 β
a β₯ m, where a is number of spectators supporting Alice and m is the total number of spectators),
* at least half of spectators support Bob (i.e. 2 β
b β₯ m, where b is number of spectators supporting Bob and m is the total number of spectators),
* the total influence of spectators is maximal possible.
Help the TV channel direction to select such non-empty set of spectators, or tell that this is impossible.
Input
The first line contains integer n (1 β€ n β€ 4β
10^5) β the number of people who want to take part in the debate as a spectator.
These people are described on the next n lines. Each line describes a single person and contains the string s_i and integer a_i separated by space (1 β€ a_i β€ 5000), where s_i denotes person's political views (possible values β "00", "10", "01", "11") and a_i β the influence of the i-th person.
Output
Print a single integer β maximal possible total influence of a set of spectators so that at least half of them support Alice and at least half of them support Bob. If it is impossible print 0 instead.
Examples
Input
6
11 6
10 4
01 3
00 3
00 7
00 9
Output
22
Input
5
11 1
01 1
00 100
10 1
01 1
Output
103
Input
6
11 19
10 22
00 18
00 29
11 29
10 28
Output
105
Input
3
00 5000
00 5000
00 5000
Output
0
Note
In the first example 4 spectators can be invited to maximize total influence: 1, 2, 3 and 6. Their political views are: "11", "10", "01" and "00". So in total 2 out of 4 spectators support Alice and 2 out of 4 spectators support Bob. The total influence is 6+4+3+9=22.
In the second example the direction can select all the people except the 5-th person.
In the third example the direction can select people with indices: 1, 4, 5 and 6.
In the fourth example it is impossible to select any non-empty set of spectators. | instruction | 0 | 103,703 | 14 | 207,406 |
Tags: greedy
Correct Solution:
```
n = int(input())
t_11=[]
t_10=[]
t_01=[]
t_00=[]
for x in range(n):
tmp=list(input().split())
supp = str(tmp[0])
m = int(tmp[1])
t_tmp = [supp, m]
if supp == '11':
t_11.append(t_tmp)
elif supp == '01':
t_01.append(t_tmp)
elif supp == '10':
t_10.append(t_tmp)
else:
t_00.append(t_tmp)
t_00=sorted(t_00, key=lambda x: x[1])
t_10=sorted(t_10, key=lambda x: x[1])
t_01=sorted(t_01, key=lambda x: x[1])
t_11=sorted(t_11, key=lambda x: x[1])
pop_a = 0
pop_b = 0
tot_inf = 0
pop_tot=0
l_t_11 = len(t_11)-1
for x in range(l_t_11,-1,-1):
pop_a+=1
pop_b+=1
pop_tot+=1
tot_inf+=t_11[-1][1]
del t_11[-1]
for x in range(min(len(t_10),len(t_01))-1,-1,-1):
pop_b+=1
pop_a+=1
pop_tot+=2
tot_inf+=t_01[-1][1]+t_10[-1][1]
del t_01[-1]
del t_10[-1]
tmp_inf_1 = 0
tmp_inf_2 = 0
tmp_inf_3 = 0
tmp_t1 = []
tmp_t2 = []
if len(t_10)!=0:
for x in t_10:
tmp_t1.append(x)
for x in t_00:
tmp_t1.append(x)
tmp_t1 = sorted(tmp_t1, key=lambda x: x[1])
while True:
if len(tmp_t1)==0 or pop_a*2==pop_tot or pop_b*2==pop_a or pop_b*2==pop_tot:
break
tot_inf+=tmp_t1[-1][1]
if tmp_t1[-1][0] == '10':
pop_a+=1
pop_tot+=1
else:
pop_tot+=1
del tmp_t1[-1]
print(tot_inf)
elif len(t_01)!=0:
for x in t_01:
tmp_t2.append(x)
for x in t_00:
tmp_t2.append(x)
tmp_t2 = sorted(tmp_t2, key=lambda x: x[1])
while True:
if len(tmp_t2)==0 or pop_b*2==pop_tot or pop_a*2==pop_b or pop_a*2==pop_tot:
break
tot_inf+=tmp_t2[-1][1]
if tmp_t2[-1][0] == '01':
pop_b+=1
pop_tot+=1
else:
pop_tot+=1
del tmp_t2[-1]
print(tot_inf)
else:
if len(t_00)==0:
print(tot_inf)
exit(0)
else:
while True:
if len(t_00)==0 or pop_a*2==pop_tot or pop_b*2==pop_tot:
break
tot_inf+=t_00[-1][1]
pop_tot+=1
del t_00[-1]
print(tot_inf)
``` | output | 1 | 103,703 | 14 | 207,407 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Elections in Berland are coming. There are only two candidates β Alice and Bob.
The main Berland TV channel plans to show political debates. There are n people who want to take part in the debate as a spectator. Each person is described by their influence and political views. There are four kinds of political views:
* supporting none of candidates (this kind is denoted as "00"),
* supporting Alice but not Bob (this kind is denoted as "10"),
* supporting Bob but not Alice (this kind is denoted as "01"),
* supporting both candidates (this kind is denoted as "11").
The direction of the TV channel wants to invite some of these people to the debate. The set of invited spectators should satisfy three conditions:
* at least half of spectators support Alice (i.e. 2 β
a β₯ m, where a is number of spectators supporting Alice and m is the total number of spectators),
* at least half of spectators support Bob (i.e. 2 β
b β₯ m, where b is number of spectators supporting Bob and m is the total number of spectators),
* the total influence of spectators is maximal possible.
Help the TV channel direction to select such non-empty set of spectators, or tell that this is impossible.
Input
The first line contains integer n (1 β€ n β€ 4β
10^5) β the number of people who want to take part in the debate as a spectator.
These people are described on the next n lines. Each line describes a single person and contains the string s_i and integer a_i separated by space (1 β€ a_i β€ 5000), where s_i denotes person's political views (possible values β "00", "10", "01", "11") and a_i β the influence of the i-th person.
Output
Print a single integer β maximal possible total influence of a set of spectators so that at least half of them support Alice and at least half of them support Bob. If it is impossible print 0 instead.
Examples
Input
6
11 6
10 4
01 3
00 3
00 7
00 9
Output
22
Input
5
11 1
01 1
00 100
10 1
01 1
Output
103
Input
6
11 19
10 22
00 18
00 29
11 29
10 28
Output
105
Input
3
00 5000
00 5000
00 5000
Output
0
Note
In the first example 4 spectators can be invited to maximize total influence: 1, 2, 3 and 6. Their political views are: "11", "10", "01" and "00". So in total 2 out of 4 spectators support Alice and 2 out of 4 spectators support Bob. The total influence is 6+4+3+9=22.
In the second example the direction can select all the people except the 5-th person.
In the third example the direction can select people with indices: 1, 4, 5 and 6.
In the fourth example it is impossible to select any non-empty set of spectators. | instruction | 0 | 103,704 | 14 | 207,408 |
Tags: greedy
Correct Solution:
```
import math as ma
import sys
from sys import exit
from decimal import Decimal as dec
from itertools import permutations
def li():
return list(map(int , input().split()))
def num():
return map(int , input().split())
def nu():
return int(input())
def find_gcd(x , y):
while (y):
x , y = y , x % y
return x
n=nu()
al=[]
bo=[]
to=[]
ze=[]
for i in range(n):
x,y=input().split()
if(x=="00"):
ze.append(int(y))
if(x=="11"):
to.append(int(y))
if (x == "10"):
al.append(int(y))
if (x == "01"):
bo.append(int(y))
al.sort(reverse=True)
bo.sort(reverse=True)
to.sort(reverse=True)
ze.sort(reverse=True)
zz=0
if(len(al)<=len(bo)):
zz=sum(al)+sum(bo[0:len(al)])
gh=bo[len(al):]+ze
zz=zz+sum(to)
gh.sort(reverse=True)
cc=0
for i in range(len(gh)):
if(cc==len(to)):
break
zz+=gh[i]
cc+=1
print(zz)
else:
zz = sum(bo) + sum(al[0:len(bo)])
gh = al[len(bo):] + ze
zz = zz + sum(to)
gh.sort(reverse=True)
cc = 0
for i in range(len(gh)):
if (cc == len(to)):
break
zz += gh[i]
cc += 1
print(zz)
``` | output | 1 | 103,704 | 14 | 207,409 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Elections in Berland are coming. There are only two candidates β Alice and Bob.
The main Berland TV channel plans to show political debates. There are n people who want to take part in the debate as a spectator. Each person is described by their influence and political views. There are four kinds of political views:
* supporting none of candidates (this kind is denoted as "00"),
* supporting Alice but not Bob (this kind is denoted as "10"),
* supporting Bob but not Alice (this kind is denoted as "01"),
* supporting both candidates (this kind is denoted as "11").
The direction of the TV channel wants to invite some of these people to the debate. The set of invited spectators should satisfy three conditions:
* at least half of spectators support Alice (i.e. 2 β
a β₯ m, where a is number of spectators supporting Alice and m is the total number of spectators),
* at least half of spectators support Bob (i.e. 2 β
b β₯ m, where b is number of spectators supporting Bob and m is the total number of spectators),
* the total influence of spectators is maximal possible.
Help the TV channel direction to select such non-empty set of spectators, or tell that this is impossible.
Input
The first line contains integer n (1 β€ n β€ 4β
10^5) β the number of people who want to take part in the debate as a spectator.
These people are described on the next n lines. Each line describes a single person and contains the string s_i and integer a_i separated by space (1 β€ a_i β€ 5000), where s_i denotes person's political views (possible values β "00", "10", "01", "11") and a_i β the influence of the i-th person.
Output
Print a single integer β maximal possible total influence of a set of spectators so that at least half of them support Alice and at least half of them support Bob. If it is impossible print 0 instead.
Examples
Input
6
11 6
10 4
01 3
00 3
00 7
00 9
Output
22
Input
5
11 1
01 1
00 100
10 1
01 1
Output
103
Input
6
11 19
10 22
00 18
00 29
11 29
10 28
Output
105
Input
3
00 5000
00 5000
00 5000
Output
0
Note
In the first example 4 spectators can be invited to maximize total influence: 1, 2, 3 and 6. Their political views are: "11", "10", "01" and "00". So in total 2 out of 4 spectators support Alice and 2 out of 4 spectators support Bob. The total influence is 6+4+3+9=22.
In the second example the direction can select all the people except the 5-th person.
In the third example the direction can select people with indices: 1, 4, 5 and 6.
In the fourth example it is impossible to select any non-empty set of spectators. | instruction | 0 | 103,705 | 14 | 207,410 |
Tags: greedy
Correct Solution:
```
import math
n=int(input())
d={}
d['00']=[]
d['01']=[]
d['10']=[]
d['11']=[]
count={'00':0,'01':0,'10':0,'11':0}
ans=0
length=0
if(n==1):
x,y=input().split()
if(x=='00'):
print(0)
elif(x=='11'):
print(int(y))
else:
print(0)
else:
for i in range(n):
x,y=input().split()
d[x].append(int(y))
l1=d['00']
l2=d['01']
l3=d['10']
l4=d['11']
l1,l2,l3,l4=sorted(l1),sorted(l2),sorted(l3),sorted(l4)
j=len(l4)-1
#print(l1,l2,l3,l4)
while(j>=0):
ans+=l4[j]
j-=1
count['11']+=1
c1,c4=len(l1)-1,-1
i=len(l2)-1
j=len(l3)-1
if(len(l2)>0 and len(l3)>0):
while(i>=0 and j>=0):
ans+=l2[i]
ans+=l3[j]
count['10']+=1
count['01']+=1
length+=2
i-=1
j-=1
c2,c3=i,j
else:
c2,c3=len(l2)-1,len(l3)-1
# while(c4>=0):
# ans+=l1[c4]
# count['11']+=1
# length+=1
t=count['00']+count['01']+count['10']+count['11']
t1=count['11']+count['10']
t2=count['11']+count['01']
#print(c1,c2,c3,c4,len(l2),len(l3),l2,l3,l3[1])
while(t1>math.ceil(t//2) and t2>math.ceil(t//2)):
#print("YES")
if(c3<0):
if(c2>=0 and c1>=0):
if(l2[c2]>l1[c1]):
t+=1
ans+=l2[c2]
c2-=1
count['01']+=1
else:
t+=1
ans+=l1[c1]
c1-=1
else:
if(t1>math.ceil(t//2) and t2>math.ceil(t//2)):
if(c2>=0):
ans+=l2[c2]
c2-=1
t+=1
count['01']+=1
if(t1>math.ceil(t//2) and t2>math.ceil(t//2)):
if(c1>=0):
t+=1
ans+=l1[c1]
c1-=1
if(c2<0 and c1<0):
break
# else:
# break
elif(c2<0):
if(c3>=0 and c1>=0):
if(l3[c3]>l1[c1]):
t+=1
ans+=l3[c3]
c3-=1
count['10']+=1
else:
t+=1
ans+=l1[c1]
c1-=1
else:
if(t1>math.ceil(t//2) and t2>math.ceil(t//2)):
if(c3>=0):
ans+=l3[c3]
c3-=1
t+=1
#print("Doing it ",l3[c3+1])
count['10']+=1
if(t1>math.ceil(t//2) and t2>math.ceil(t//2)):
if(c1>=0):
t+=1
ans+=l1[c1]
#print("DOing it",l1[c1])
c1-=1
if(c3<0 and c1<0):
break
t1=count['11']+count['10']
t2=count['11']+count['01']
print(ans)
``` | output | 1 | 103,705 | 14 | 207,411 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Elections in Berland are coming. There are only two candidates β Alice and Bob.
The main Berland TV channel plans to show political debates. There are n people who want to take part in the debate as a spectator. Each person is described by their influence and political views. There are four kinds of political views:
* supporting none of candidates (this kind is denoted as "00"),
* supporting Alice but not Bob (this kind is denoted as "10"),
* supporting Bob but not Alice (this kind is denoted as "01"),
* supporting both candidates (this kind is denoted as "11").
The direction of the TV channel wants to invite some of these people to the debate. The set of invited spectators should satisfy three conditions:
* at least half of spectators support Alice (i.e. 2 β
a β₯ m, where a is number of spectators supporting Alice and m is the total number of spectators),
* at least half of spectators support Bob (i.e. 2 β
b β₯ m, where b is number of spectators supporting Bob and m is the total number of spectators),
* the total influence of spectators is maximal possible.
Help the TV channel direction to select such non-empty set of spectators, or tell that this is impossible.
Input
The first line contains integer n (1 β€ n β€ 4β
10^5) β the number of people who want to take part in the debate as a spectator.
These people are described on the next n lines. Each line describes a single person and contains the string s_i and integer a_i separated by space (1 β€ a_i β€ 5000), where s_i denotes person's political views (possible values β "00", "10", "01", "11") and a_i β the influence of the i-th person.
Output
Print a single integer β maximal possible total influence of a set of spectators so that at least half of them support Alice and at least half of them support Bob. If it is impossible print 0 instead.
Examples
Input
6
11 6
10 4
01 3
00 3
00 7
00 9
Output
22
Input
5
11 1
01 1
00 100
10 1
01 1
Output
103
Input
6
11 19
10 22
00 18
00 29
11 29
10 28
Output
105
Input
3
00 5000
00 5000
00 5000
Output
0
Note
In the first example 4 spectators can be invited to maximize total influence: 1, 2, 3 and 6. Their political views are: "11", "10", "01" and "00". So in total 2 out of 4 spectators support Alice and 2 out of 4 spectators support Bob. The total influence is 6+4+3+9=22.
In the second example the direction can select all the people except the 5-th person.
In the third example the direction can select people with indices: 1, 4, 5 and 6.
In the fourth example it is impossible to select any non-empty set of spectators. | instruction | 0 | 103,706 | 14 | 207,412 |
Tags: greedy
Correct Solution:
```
n=int(input())
a=[];b=[];c=[];d=[]
for i in range(n):
opt,num=[int(x) for x in input().split()]
if opt==0:
a.append(num)
if opt==10:
b.append(num)
if opt==1:
c.append(num)
if opt==11:
d.append(num)
ans=sum(d)
b.sort(reverse=True) # from the largest then choose: greedy
c.sort(reverse=True) # make sortings is O(nlogn)
if len(b)<len(c):
ans+=sum(b)+sum(c[0:len(b)])
a.extend(c[len(b):])
else:
ans+=sum(c)+sum(b[0:len(c)])
a.extend(b[len(c):])
a.sort(reverse=True)
ans+=sum(a[0:len(d)])
print(ans)
``` | output | 1 | 103,706 | 14 | 207,413 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Elections in Berland are coming. There are only two candidates β Alice and Bob.
The main Berland TV channel plans to show political debates. There are n people who want to take part in the debate as a spectator. Each person is described by their influence and political views. There are four kinds of political views:
* supporting none of candidates (this kind is denoted as "00"),
* supporting Alice but not Bob (this kind is denoted as "10"),
* supporting Bob but not Alice (this kind is denoted as "01"),
* supporting both candidates (this kind is denoted as "11").
The direction of the TV channel wants to invite some of these people to the debate. The set of invited spectators should satisfy three conditions:
* at least half of spectators support Alice (i.e. 2 β
a β₯ m, where a is number of spectators supporting Alice and m is the total number of spectators),
* at least half of spectators support Bob (i.e. 2 β
b β₯ m, where b is number of spectators supporting Bob and m is the total number of spectators),
* the total influence of spectators is maximal possible.
Help the TV channel direction to select such non-empty set of spectators, or tell that this is impossible.
Input
The first line contains integer n (1 β€ n β€ 4β
10^5) β the number of people who want to take part in the debate as a spectator.
These people are described on the next n lines. Each line describes a single person and contains the string s_i and integer a_i separated by space (1 β€ a_i β€ 5000), where s_i denotes person's political views (possible values β "00", "10", "01", "11") and a_i β the influence of the i-th person.
Output
Print a single integer β maximal possible total influence of a set of spectators so that at least half of them support Alice and at least half of them support Bob. If it is impossible print 0 instead.
Examples
Input
6
11 6
10 4
01 3
00 3
00 7
00 9
Output
22
Input
5
11 1
01 1
00 100
10 1
01 1
Output
103
Input
6
11 19
10 22
00 18
00 29
11 29
10 28
Output
105
Input
3
00 5000
00 5000
00 5000
Output
0
Note
In the first example 4 spectators can be invited to maximize total influence: 1, 2, 3 and 6. Their political views are: "11", "10", "01" and "00". So in total 2 out of 4 spectators support Alice and 2 out of 4 spectators support Bob. The total influence is 6+4+3+9=22.
In the second example the direction can select all the people except the 5-th person.
In the third example the direction can select people with indices: 1, 4, 5 and 6.
In the fourth example it is impossible to select any non-empty set of spectators.
Submitted Solution:
```
import sys
read = lambda: sys.stdin.readline().strip()
readi = lambda: map(int, read().split())
from collections import *
n = int(read())
a = list() # 00
b = list() # 01
c = list() # 01
d = list() # 11
for _ in range(n):
type, val = read().split()
val = int(val)
if type == "00": a.append(val)
if type == "01": b.append(val)
if type == "10": c.append(val)
if type == "11": d.append(val)
# a.sort(reverse = True)
b.sort(reverse = True)
c.sort(reverse = True)
# d.sort(reverse = True)
## case 1
peepsCanTake = 0
peopleCount = 0
influenceScore = 0
# take all 11
peopleCount += len(d)
influenceScore += sum(d)
peepsCanTake += peopleCount
# take equal amount of 10 and 01
bothPeeps = min(len(b), len(c))
peopleCount += bothPeeps
influenceScore += sum(b[:bothPeeps]) + sum(c[:bothPeeps])
b = b[bothPeeps:]
c = c[bothPeeps:]
temp = sorted(b + c + a, reverse = True)
influenceScore += sum(temp[:peepsCanTake])
print(influenceScore)
``` | instruction | 0 | 103,707 | 14 | 207,414 |
Yes | output | 1 | 103,707 | 14 | 207,415 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Elections in Berland are coming. There are only two candidates β Alice and Bob.
The main Berland TV channel plans to show political debates. There are n people who want to take part in the debate as a spectator. Each person is described by their influence and political views. There are four kinds of political views:
* supporting none of candidates (this kind is denoted as "00"),
* supporting Alice but not Bob (this kind is denoted as "10"),
* supporting Bob but not Alice (this kind is denoted as "01"),
* supporting both candidates (this kind is denoted as "11").
The direction of the TV channel wants to invite some of these people to the debate. The set of invited spectators should satisfy three conditions:
* at least half of spectators support Alice (i.e. 2 β
a β₯ m, where a is number of spectators supporting Alice and m is the total number of spectators),
* at least half of spectators support Bob (i.e. 2 β
b β₯ m, where b is number of spectators supporting Bob and m is the total number of spectators),
* the total influence of spectators is maximal possible.
Help the TV channel direction to select such non-empty set of spectators, or tell that this is impossible.
Input
The first line contains integer n (1 β€ n β€ 4β
10^5) β the number of people who want to take part in the debate as a spectator.
These people are described on the next n lines. Each line describes a single person and contains the string s_i and integer a_i separated by space (1 β€ a_i β€ 5000), where s_i denotes person's political views (possible values β "00", "10", "01", "11") and a_i β the influence of the i-th person.
Output
Print a single integer β maximal possible total influence of a set of spectators so that at least half of them support Alice and at least half of them support Bob. If it is impossible print 0 instead.
Examples
Input
6
11 6
10 4
01 3
00 3
00 7
00 9
Output
22
Input
5
11 1
01 1
00 100
10 1
01 1
Output
103
Input
6
11 19
10 22
00 18
00 29
11 29
10 28
Output
105
Input
3
00 5000
00 5000
00 5000
Output
0
Note
In the first example 4 spectators can be invited to maximize total influence: 1, 2, 3 and 6. Their political views are: "11", "10", "01" and "00". So in total 2 out of 4 spectators support Alice and 2 out of 4 spectators support Bob. The total influence is 6+4+3+9=22.
In the second example the direction can select all the people except the 5-th person.
In the third example the direction can select people with indices: 1, 4, 5 and 6.
In the fourth example it is impossible to select any non-empty set of spectators.
Submitted Solution:
```
n = int(input())
no = []
a = []
b = []
bo = []
for _ in range(n):
t, s = map(int, input().split())
if t == 11:
bo.append(s)
elif t == 10:
a.append(s)
elif t == 1:
b.append(s)
else:
no.append(s)
ans = 0
for i in bo:
ans += i
a.sort(reverse=True)
b.sort(reverse=True)
if len(a) > len(b):
for i in range(len(b)):
ans += a[i]
ans += b[i]
for i in range(len(b), len(a)):
no.append(a[i])
else:
for i in range(len(a)):
ans += a[i]
ans += b[i]
for i in range(len(a), len(b)):
no.append(b[i])
no.sort(reverse=True)
for i in range(min(len(bo), len(no))):
ans += no[i]
print(ans)
``` | instruction | 0 | 103,708 | 14 | 207,416 |
Yes | output | 1 | 103,708 | 14 | 207,417 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Elections in Berland are coming. There are only two candidates β Alice and Bob.
The main Berland TV channel plans to show political debates. There are n people who want to take part in the debate as a spectator. Each person is described by their influence and political views. There are four kinds of political views:
* supporting none of candidates (this kind is denoted as "00"),
* supporting Alice but not Bob (this kind is denoted as "10"),
* supporting Bob but not Alice (this kind is denoted as "01"),
* supporting both candidates (this kind is denoted as "11").
The direction of the TV channel wants to invite some of these people to the debate. The set of invited spectators should satisfy three conditions:
* at least half of spectators support Alice (i.e. 2 β
a β₯ m, where a is number of spectators supporting Alice and m is the total number of spectators),
* at least half of spectators support Bob (i.e. 2 β
b β₯ m, where b is number of spectators supporting Bob and m is the total number of spectators),
* the total influence of spectators is maximal possible.
Help the TV channel direction to select such non-empty set of spectators, or tell that this is impossible.
Input
The first line contains integer n (1 β€ n β€ 4β
10^5) β the number of people who want to take part in the debate as a spectator.
These people are described on the next n lines. Each line describes a single person and contains the string s_i and integer a_i separated by space (1 β€ a_i β€ 5000), where s_i denotes person's political views (possible values β "00", "10", "01", "11") and a_i β the influence of the i-th person.
Output
Print a single integer β maximal possible total influence of a set of spectators so that at least half of them support Alice and at least half of them support Bob. If it is impossible print 0 instead.
Examples
Input
6
11 6
10 4
01 3
00 3
00 7
00 9
Output
22
Input
5
11 1
01 1
00 100
10 1
01 1
Output
103
Input
6
11 19
10 22
00 18
00 29
11 29
10 28
Output
105
Input
3
00 5000
00 5000
00 5000
Output
0
Note
In the first example 4 spectators can be invited to maximize total influence: 1, 2, 3 and 6. Their political views are: "11", "10", "01" and "00". So in total 2 out of 4 spectators support Alice and 2 out of 4 spectators support Bob. The total influence is 6+4+3+9=22.
In the second example the direction can select all the people except the 5-th person.
In the third example the direction can select people with indices: 1, 4, 5 and 6.
In the fourth example it is impossible to select any non-empty set of spectators.
Submitted Solution:
```
import traceback
import math
from collections import defaultdict
from functools import lru_cache
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def geti():
return int(input())
def gets():
return input()
def getil():
return list(map(int, input().split()))
def getsl():
return input().split()
def get2d(nrows, ncols, n=0):
return [[n] * ncols for r in range(nrows)]
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
ceil = lambda x: int(math.ceil(x))
inf = float('inf')
mod = 10 ** 9 + 7
def main():
N = geti()
g = defaultdict(list)
for _ in range(N):
x, n = getsl()
g[x].append(int(n))
for x in g:
g[x].sort(reverse=True)
ans = sum(g['11'])
c = len(g['11'])
sz = min(len(g['10']), len(g['01']))
ans += sum(g['10'][:sz]) + sum(g['01'][:sz])
g['00'].extend(g['10'][sz:] + g['01'][sz:])
g['00'].sort(reverse=True)
ans += sum(g['00'][:c])
return ans
try:
ans = main()
# ans = 'Yes' if ans else 'No'
print(ans)
except Exception as e:
traceback.print_exc()
``` | instruction | 0 | 103,709 | 14 | 207,418 |
Yes | output | 1 | 103,709 | 14 | 207,419 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Elections in Berland are coming. There are only two candidates β Alice and Bob.
The main Berland TV channel plans to show political debates. There are n people who want to take part in the debate as a spectator. Each person is described by their influence and political views. There are four kinds of political views:
* supporting none of candidates (this kind is denoted as "00"),
* supporting Alice but not Bob (this kind is denoted as "10"),
* supporting Bob but not Alice (this kind is denoted as "01"),
* supporting both candidates (this kind is denoted as "11").
The direction of the TV channel wants to invite some of these people to the debate. The set of invited spectators should satisfy three conditions:
* at least half of spectators support Alice (i.e. 2 β
a β₯ m, where a is number of spectators supporting Alice and m is the total number of spectators),
* at least half of spectators support Bob (i.e. 2 β
b β₯ m, where b is number of spectators supporting Bob and m is the total number of spectators),
* the total influence of spectators is maximal possible.
Help the TV channel direction to select such non-empty set of spectators, or tell that this is impossible.
Input
The first line contains integer n (1 β€ n β€ 4β
10^5) β the number of people who want to take part in the debate as a spectator.
These people are described on the next n lines. Each line describes a single person and contains the string s_i and integer a_i separated by space (1 β€ a_i β€ 5000), where s_i denotes person's political views (possible values β "00", "10", "01", "11") and a_i β the influence of the i-th person.
Output
Print a single integer β maximal possible total influence of a set of spectators so that at least half of them support Alice and at least half of them support Bob. If it is impossible print 0 instead.
Examples
Input
6
11 6
10 4
01 3
00 3
00 7
00 9
Output
22
Input
5
11 1
01 1
00 100
10 1
01 1
Output
103
Input
6
11 19
10 22
00 18
00 29
11 29
10 28
Output
105
Input
3
00 5000
00 5000
00 5000
Output
0
Note
In the first example 4 spectators can be invited to maximize total influence: 1, 2, 3 and 6. Their political views are: "11", "10", "01" and "00". So in total 2 out of 4 spectators support Alice and 2 out of 4 spectators support Bob. The total influence is 6+4+3+9=22.
In the second example the direction can select all the people except the 5-th person.
In the third example the direction can select people with indices: 1, 4, 5 and 6.
In the fourth example it is impossible to select any non-empty set of spectators.
Submitted Solution:
```
#!usr/bin/python
n = int(input());
s = [[], [], [], []];
for i in range(n):
x = input().strip().split();
if x[0] == "11":
s[3].append(int(x[1]));
elif x[0] == "10":
s[2].append(int(x[1]));
elif x[0] == "01":
s[1].append(int(x[1]));
else:
s[0].append(int(x[1]));
ans = 0;
for i in range(len(s[3])):
ans = ans + s[3][i];
s[2] = sorted(s[2], reverse = True);
s[1] = sorted(s[1], reverse = True);
tlen = min(len(s[1]),len(s[2]));
for i in range(1, 3):
for j in range(tlen):
ans = ans + s[i][j];
for j in range(tlen,len(s[i])):
s[0].append(s[i][j]);
s[0] = sorted(s[0], reverse = True);
tlen = min(len(s[3]),len(s[0]));
for i in range(tlen):
ans = ans + s[0][i];
print(ans);
``` | instruction | 0 | 103,710 | 14 | 207,420 |
Yes | output | 1 | 103,710 | 14 | 207,421 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Elections in Berland are coming. There are only two candidates β Alice and Bob.
The main Berland TV channel plans to show political debates. There are n people who want to take part in the debate as a spectator. Each person is described by their influence and political views. There are four kinds of political views:
* supporting none of candidates (this kind is denoted as "00"),
* supporting Alice but not Bob (this kind is denoted as "10"),
* supporting Bob but not Alice (this kind is denoted as "01"),
* supporting both candidates (this kind is denoted as "11").
The direction of the TV channel wants to invite some of these people to the debate. The set of invited spectators should satisfy three conditions:
* at least half of spectators support Alice (i.e. 2 β
a β₯ m, where a is number of spectators supporting Alice and m is the total number of spectators),
* at least half of spectators support Bob (i.e. 2 β
b β₯ m, where b is number of spectators supporting Bob and m is the total number of spectators),
* the total influence of spectators is maximal possible.
Help the TV channel direction to select such non-empty set of spectators, or tell that this is impossible.
Input
The first line contains integer n (1 β€ n β€ 4β
10^5) β the number of people who want to take part in the debate as a spectator.
These people are described on the next n lines. Each line describes a single person and contains the string s_i and integer a_i separated by space (1 β€ a_i β€ 5000), where s_i denotes person's political views (possible values β "00", "10", "01", "11") and a_i β the influence of the i-th person.
Output
Print a single integer β maximal possible total influence of a set of spectators so that at least half of them support Alice and at least half of them support Bob. If it is impossible print 0 instead.
Examples
Input
6
11 6
10 4
01 3
00 3
00 7
00 9
Output
22
Input
5
11 1
01 1
00 100
10 1
01 1
Output
103
Input
6
11 19
10 22
00 18
00 29
11 29
10 28
Output
105
Input
3
00 5000
00 5000
00 5000
Output
0
Note
In the first example 4 spectators can be invited to maximize total influence: 1, 2, 3 and 6. Their political views are: "11", "10", "01" and "00". So in total 2 out of 4 spectators support Alice and 2 out of 4 spectators support Bob. The total influence is 6+4+3+9=22.
In the second example the direction can select all the people except the 5-th person.
In the third example the direction can select people with indices: 1, 4, 5 and 6.
In the fourth example it is impossible to select any non-empty set of spectators.
Submitted Solution:
```
from math import ceil
n, A = int(input()), []
a = b = ab = ab_ = ans = 0
for _ in range(n):
t, tt = input().split()
tt = int(tt)
if t != '11':
A.append([t, tt])
if t == '10':
a += 1
elif t == '01':
b += 1
else:
ab_ += 1
else:
ans += tt
ab += 1
A.sort(reverse=True, key=lambda x: x[1])
x = y = t = ttt = ab
k, j = a, b
for i in A:
if i[0] == '10' and (j or ttt):
ans += i[1]
t += 1
x += 1
if j == 0 and ttt:
ttt -= 1
j = 1
j -= 1
elif i[0] == '01' and (k or ttt):
ans += i[1]
t += 1
y += 1
if k == 0 and ttt:
ttt -= 1
k = 1
k -= 1
elif i[0] == '00' and 2 * x >= t + 1 and 2 * y >= t + 1:
ans += i[1]
ttt -= 1
t += 1
print(ans)
``` | instruction | 0 | 103,711 | 14 | 207,422 |
No | output | 1 | 103,711 | 14 | 207,423 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Elections in Berland are coming. There are only two candidates β Alice and Bob.
The main Berland TV channel plans to show political debates. There are n people who want to take part in the debate as a spectator. Each person is described by their influence and political views. There are four kinds of political views:
* supporting none of candidates (this kind is denoted as "00"),
* supporting Alice but not Bob (this kind is denoted as "10"),
* supporting Bob but not Alice (this kind is denoted as "01"),
* supporting both candidates (this kind is denoted as "11").
The direction of the TV channel wants to invite some of these people to the debate. The set of invited spectators should satisfy three conditions:
* at least half of spectators support Alice (i.e. 2 β
a β₯ m, where a is number of spectators supporting Alice and m is the total number of spectators),
* at least half of spectators support Bob (i.e. 2 β
b β₯ m, where b is number of spectators supporting Bob and m is the total number of spectators),
* the total influence of spectators is maximal possible.
Help the TV channel direction to select such non-empty set of spectators, or tell that this is impossible.
Input
The first line contains integer n (1 β€ n β€ 4β
10^5) β the number of people who want to take part in the debate as a spectator.
These people are described on the next n lines. Each line describes a single person and contains the string s_i and integer a_i separated by space (1 β€ a_i β€ 5000), where s_i denotes person's political views (possible values β "00", "10", "01", "11") and a_i β the influence of the i-th person.
Output
Print a single integer β maximal possible total influence of a set of spectators so that at least half of them support Alice and at least half of them support Bob. If it is impossible print 0 instead.
Examples
Input
6
11 6
10 4
01 3
00 3
00 7
00 9
Output
22
Input
5
11 1
01 1
00 100
10 1
01 1
Output
103
Input
6
11 19
10 22
00 18
00 29
11 29
10 28
Output
105
Input
3
00 5000
00 5000
00 5000
Output
0
Note
In the first example 4 spectators can be invited to maximize total influence: 1, 2, 3 and 6. Their political views are: "11", "10", "01" and "00". So in total 2 out of 4 spectators support Alice and 2 out of 4 spectators support Bob. The total influence is 6+4+3+9=22.
In the second example the direction can select all the people except the 5-th person.
In the third example the direction can select people with indices: 1, 4, 5 and 6.
In the fourth example it is impossible to select any non-empty set of spectators.
Submitted Solution:
```
n=int(input())
no=[]
a=[]
b=[]
bo=[]
for _ in range(n):
t,s=map(int,input().split())
if t==11:
bo.append(s)
elif t==10:
a.append(s)
elif t==1:
b.append(s)
else:
no.append(s)
ans=0
for i in bo:
ans+=i
a.sort(reverse=True)
b.sort(reverse=True)
if len(a)>len(b):
for i in range(len(b)):
ans+=a[i]
ans+=b[i]
for i in range(len(b),len(a)):
no.append(a[i])
else :
for i in range(len(a)):
ans+=a[i]
ans+=b[i]
for i in range(len(a),len(b)):
no.append(b[i])
no.sort(reverse=True)
for i in range(len(no)):
ans+=no[i]
print(ans)
``` | instruction | 0 | 103,712 | 14 | 207,424 |
No | output | 1 | 103,712 | 14 | 207,425 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Elections in Berland are coming. There are only two candidates β Alice and Bob.
The main Berland TV channel plans to show political debates. There are n people who want to take part in the debate as a spectator. Each person is described by their influence and political views. There are four kinds of political views:
* supporting none of candidates (this kind is denoted as "00"),
* supporting Alice but not Bob (this kind is denoted as "10"),
* supporting Bob but not Alice (this kind is denoted as "01"),
* supporting both candidates (this kind is denoted as "11").
The direction of the TV channel wants to invite some of these people to the debate. The set of invited spectators should satisfy three conditions:
* at least half of spectators support Alice (i.e. 2 β
a β₯ m, where a is number of spectators supporting Alice and m is the total number of spectators),
* at least half of spectators support Bob (i.e. 2 β
b β₯ m, where b is number of spectators supporting Bob and m is the total number of spectators),
* the total influence of spectators is maximal possible.
Help the TV channel direction to select such non-empty set of spectators, or tell that this is impossible.
Input
The first line contains integer n (1 β€ n β€ 4β
10^5) β the number of people who want to take part in the debate as a spectator.
These people are described on the next n lines. Each line describes a single person and contains the string s_i and integer a_i separated by space (1 β€ a_i β€ 5000), where s_i denotes person's political views (possible values β "00", "10", "01", "11") and a_i β the influence of the i-th person.
Output
Print a single integer β maximal possible total influence of a set of spectators so that at least half of them support Alice and at least half of them support Bob. If it is impossible print 0 instead.
Examples
Input
6
11 6
10 4
01 3
00 3
00 7
00 9
Output
22
Input
5
11 1
01 1
00 100
10 1
01 1
Output
103
Input
6
11 19
10 22
00 18
00 29
11 29
10 28
Output
105
Input
3
00 5000
00 5000
00 5000
Output
0
Note
In the first example 4 spectators can be invited to maximize total influence: 1, 2, 3 and 6. Their political views are: "11", "10", "01" and "00". So in total 2 out of 4 spectators support Alice and 2 out of 4 spectators support Bob. The total influence is 6+4+3+9=22.
In the second example the direction can select all the people except the 5-th person.
In the third example the direction can select people with indices: 1, 4, 5 and 6.
In the fourth example it is impossible to select any non-empty set of spectators.
Submitted Solution:
```
from functools import *
n = int(input())
t = [[],[],[],[]]
for i in range(n):
a,b = input().split()
if a == '00':
t[0].append(int(b))
elif a == '01':
t[1].append(int(b))
elif a == '10':
t[2].append(int(b))
else:
t[3].append(int(b))
ans = reduce(lambda x,y : x+y,t[3]) if len(t[3])>0 else 0
abl = len(t[3])
t1 = len(t[1])
t2 = len(t[2])
abl1 = min(len(t[1]),len(t[2]))
t[0] = sorted(t[0])
t[1] = sorted(t[1])
t[2] = sorted(t[2])
t[0] = t[0][::-1]
t[1] = t[1][::-1]
t[2] = t[2][::-1]
if abl1 > 0:
ans += reduce(lambda x,y : x+y,t[1][:abl1]) + reduce(lambda x,y : x+y,t[2][:abl1])
# print(ans)
# print(t)
if t1 > t2 and t2 > 0:
# print(1)
for i in range(abl):
# print(ans)
if abl1+1 < len(t[1]) and 0 < len(t[0]):
ans += max(t[1][abl1+1],t[0][0])
if t[1][abl1+1] > t[0][0]:
del t[1][abl1+1]
else:
del t[0][0]
elif abl1+1 >= len(t[1]) and 0 < len(t[0]):
ans += t[0][i] if i < len(t[0]) else 0
elif abl1+1 < len(t[1]) and 0 >= len(t[0]):
ans += t[1][i+abl1+1] if i+abl1+1 < len(t[1]) else 0
elif t1 > t2 and t2 == 0:
# print(2)
for i in range(abl):
# print(ans)
if abl1 < len(t[1]) and 0 < len(t[0]):
ans += max(t[1][abl1],t[0][0])
if t[1][abl1] > t[0][0]:
del t[1][abl1]
else:
del t[0][0]
elif abl1 >= len(t[1]) and 0 < len(t[0]):
ans += t[0][i] if i < len(t[0]) else 0
elif abl1 < len(t[1]) and 0 >= len(t[0]):
ans += t[1][i+abl1] if i+abl1 < len(t[1]) else 0
elif t2 > t1 and t1 == 0:
# print(3)
for i in range(abl):
# print(ans)
if abl1 < len(t[2]) and 0 < len(t[0]):
ans += max(t[2][abl1],t[0][0])
if t[2][abl1] > t[0][0]:
del t[2][abl1]
else:
del t[0][0]
elif abl1 >= len(t[2]) and 0 < len(t[0]):
ans += t[0][i] if i < len(t[0]) else 0
elif abl1 < len(t[2]) and 0 >= len(t[0]):
ans += t[2][i+abl1] if i+abl1 < len(t[2]) else 0
else:
# print(4)
# print(ans)
for i in range(abl):
# print(ans)
if abl1+1 < len(t[2]) and 0 < len(t[0]):
ans += max(t[2][abl1+1],t[0][0])
if t[2][abl1+1] > t[0][0]:
del t[2][abl1+1]
else:
del t[0][0]
elif abl1+1 >= len(t[2]) and 0 < len(t[0]):
ans += t[0][i] if i < len(t[0]) else 0
elif abl1+1 < len(t[2]) and 0 >= len(t[0]):
ans += t[2][i+abl1+1] if i+abl1+1 < len(t[2]) else 0
# print(ans)
print(ans)
``` | instruction | 0 | 103,713 | 14 | 207,426 |
No | output | 1 | 103,713 | 14 | 207,427 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Elections in Berland are coming. There are only two candidates β Alice and Bob.
The main Berland TV channel plans to show political debates. There are n people who want to take part in the debate as a spectator. Each person is described by their influence and political views. There are four kinds of political views:
* supporting none of candidates (this kind is denoted as "00"),
* supporting Alice but not Bob (this kind is denoted as "10"),
* supporting Bob but not Alice (this kind is denoted as "01"),
* supporting both candidates (this kind is denoted as "11").
The direction of the TV channel wants to invite some of these people to the debate. The set of invited spectators should satisfy three conditions:
* at least half of spectators support Alice (i.e. 2 β
a β₯ m, where a is number of spectators supporting Alice and m is the total number of spectators),
* at least half of spectators support Bob (i.e. 2 β
b β₯ m, where b is number of spectators supporting Bob and m is the total number of spectators),
* the total influence of spectators is maximal possible.
Help the TV channel direction to select such non-empty set of spectators, or tell that this is impossible.
Input
The first line contains integer n (1 β€ n β€ 4β
10^5) β the number of people who want to take part in the debate as a spectator.
These people are described on the next n lines. Each line describes a single person and contains the string s_i and integer a_i separated by space (1 β€ a_i β€ 5000), where s_i denotes person's political views (possible values β "00", "10", "01", "11") and a_i β the influence of the i-th person.
Output
Print a single integer β maximal possible total influence of a set of spectators so that at least half of them support Alice and at least half of them support Bob. If it is impossible print 0 instead.
Examples
Input
6
11 6
10 4
01 3
00 3
00 7
00 9
Output
22
Input
5
11 1
01 1
00 100
10 1
01 1
Output
103
Input
6
11 19
10 22
00 18
00 29
11 29
10 28
Output
105
Input
3
00 5000
00 5000
00 5000
Output
0
Note
In the first example 4 spectators can be invited to maximize total influence: 1, 2, 3 and 6. Their political views are: "11", "10", "01" and "00". So in total 2 out of 4 spectators support Alice and 2 out of 4 spectators support Bob. The total influence is 6+4+3+9=22.
In the second example the direction can select all the people except the 5-th person.
In the third example the direction can select people with indices: 1, 4, 5 and 6.
In the fourth example it is impossible to select any non-empty set of spectators.
Submitted Solution:
```
n = int(input())
t_11=[]
t_10=[]
t_01=[]
t_00=[]
for x in range(n):
tmp=list(input().split())
supp = str(tmp[0])
m = int(tmp[1])
t_tmp = [supp, m]
if supp == '11':
t_11.append(t_tmp)
elif supp == '01':
t_01.append(t_tmp)
elif supp == '10':
t_10.append(t_tmp)
else:
t_00.append(t_tmp)
t_00=sorted(t_00, key=lambda x: x[1])
t_10=sorted(t_10, key=lambda x: x[1])
t_01=sorted(t_01, key=lambda x: x[1])
t_11=sorted(t_11, key=lambda x: x[1])
pop_a = 0
pop_b = 0
tot_inf = 0
pop_tot=0
l_t_11 = len(t_11)-1
for x in range(l_t_11,-1,-1):
pop_a+=1
pop_b+=1
pop_tot+=1
tot_inf+=t_11[x][1]
del t_11[-1]
for x in range(min(len(t_10),len(t_01))-1,-1,-1):
pop_b+=1
pop_a+=1
pop_tot+=2
tot_inf+=t_01[x][1]+t_10[x][1]
del t_01[-1]
del t_10[-1]
tmp_inf_1 = 0
tmp_inf_2 = 0
tmp_inf_3 = 0
tmp_t1 = []
tmp_t2 = []
if len(t_10)!=0:
for x in t_10:
tmp_t1.append(x)
for x in t_00:
tmp_t1.append(x)
tmp_t1 = sorted(tmp_t1, key=lambda x: x[1])
while True:
if len(tmp_t1)==0 or pop_a*2==pop_tot or pop_b*2==pop_a or pop_b*2==pop_tot:
break
tot_inf+=tmp_t1[-1][1]
if tmp_t1[-1][0] == '10':
pop_a+=1
pop_tot+=1
else:
pop_tot+=1
del tmp_t1[-1]
print(tot_inf)
elif len(t_01)!=0:
for x in t_01:
tmp_t2.append(x)
for x in t_00:
tmp_t2.append(x)
tmp_t2 = sorted(tmp_t2, key=lambda x: x[1])
while True:
if len(tmp_t2)==0 or pop_b*2==pop_tot or pop_a*2==pop_b or pop_a*2==pop_tot:
break
tot_inf+=tmp_t2[-1][1]
if tmp_t2[-1][0] == '01':
pop_b+=1
pop_tot+=1
else:
pop_tot+=1
del tmp_t2[-1]
print(tot_inf)
else:
if len(t_00)==0:
print(tot_inf)
exit(0)
else:
while True:
if len(t_00)==0 or pop_a*2==pop_tot or pop_b*2==pop_tot:
break
tot_inf+=t_00[-1][1]
pop_tot+=1
del t_00[-1]
print(tot_inf)
``` | instruction | 0 | 103,714 | 14 | 207,428 |
No | output | 1 | 103,714 | 14 | 207,429 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya is about to take his first university exam in about several minutes. And it's not just some ordinary exam, it's on mathematical analysis. Of course, right now Vasya can only think of one thing: what the result of his talk with the examiner will be...
To prepare for the exam, one has to study proofs of n theorems. It is known that there will be k examination cards on the exam and each card contains <image> distinct theorems. Besides, no theorem is mentioned in more than one card (that is, <image> theorems won't be mentioned in any card). During the exam several students may get the same card.
We do not know the exact way theorems are distributed by cards, however the students that took the exam before Vasya told him what theorems their cards contained. Vasya evaluates his level of proficiency in the i-th theorem by some number ai. The level of proficiency in some card is the average of the levels of proficiency in the theorems that are included in the card. Now Vasya wants to know the minimally and maximally possible levels of his proficiency in the card he gets on the exam. Vasya wants to determine it by the data he has collected from other students. Unfortunately, Vasya has no time left to do the math and he asked you to help him.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 100) β the number of theorems and the number of cards correspondingly. The second line contains n integers ai (0 β€ ai β€ 100), the i-th number (1 β€ i β€ n) corresponds to Vasya's proficiency in the i-th theorem.
The third line contains number q (0 β€ q β€ 100) β the number of people that have taken the exam before Vasya. Each of the following q lines contains the description of a student's card: <image> integers from 1 to n inclusive. They are the numbers of theorems included in the card in the order in which they are enumerated in the input data. The numbers are given in an arbitrary order. It is guaranteed that the given cards are valid (that is, that all theorems in one card are different and that different people get cards that either don't contain the same theorems or coincide up to the theorems' permutation).
Output
Print two real numbers, representing Vasya's minimum and maximum proficiency in the card he will get on the exam. The absolute or relative error should not exceed 10 - 6.
Examples
Input
7 3
7 15 0 19 10 5 12
2
1 6
7 4
Output
5.0000000000 15.5000000000
Input
4 2
10 8 1 17
2
2 3
3 2
Output
4.5000000000 13.5000000000
Note
Let's analyze the first sample. Vasya's proficiency in the cards whose content he already knows equals 6 and 15.5 correspondingly. The three theorems that are left are only enough to make one exam card. If we consider all possible variants of theorems included in the card we can see that in the best case scenario Vasya gets the card that contains theorems 4 and 7 (his proficiency would equal 15.5) and in the worst case scenario he gets theorems 3 and 5 (his proficiency would equal 5).
The β xβ operation denotes taking integer part of real number x (rounding down). | instruction | 0 | 103,780 | 14 | 207,560 |
Tags: constructive algorithms, implementation, sortings
Correct Solution:
```
num_problems, num_cards = map(int, input().split())
card_size = num_problems // num_cards
skill = [ 0 ] + list(map(int, input().split()))
seen = (num_problems + 1) * [ False ]
num_queries = int(input())
low = 100
high = 0
for i in range(num_queries):
proficiency = 0
for pos in map(int, input().split()):
proficiency += skill[pos]
seen[pos] = True
proficiency /= card_size
low = min(low, proficiency)
high = max(high, proficiency)
remaining = []
for pos in range(1, num_problems + 1):
if not seen[pos]:
remaining.append(skill[pos])
if len(remaining) != num_problems - num_cards * card_size:
remaining.sort()
low = min(low, sum(remaining[:card_size]) / card_size)
high = max(high, sum(remaining[-card_size:]) / card_size)
print('%.8f %.8f' % (low, high))
``` | output | 1 | 103,780 | 14 | 207,561 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya is about to take his first university exam in about several minutes. And it's not just some ordinary exam, it's on mathematical analysis. Of course, right now Vasya can only think of one thing: what the result of his talk with the examiner will be...
To prepare for the exam, one has to study proofs of n theorems. It is known that there will be k examination cards on the exam and each card contains <image> distinct theorems. Besides, no theorem is mentioned in more than one card (that is, <image> theorems won't be mentioned in any card). During the exam several students may get the same card.
We do not know the exact way theorems are distributed by cards, however the students that took the exam before Vasya told him what theorems their cards contained. Vasya evaluates his level of proficiency in the i-th theorem by some number ai. The level of proficiency in some card is the average of the levels of proficiency in the theorems that are included in the card. Now Vasya wants to know the minimally and maximally possible levels of his proficiency in the card he gets on the exam. Vasya wants to determine it by the data he has collected from other students. Unfortunately, Vasya has no time left to do the math and he asked you to help him.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 100) β the number of theorems and the number of cards correspondingly. The second line contains n integers ai (0 β€ ai β€ 100), the i-th number (1 β€ i β€ n) corresponds to Vasya's proficiency in the i-th theorem.
The third line contains number q (0 β€ q β€ 100) β the number of people that have taken the exam before Vasya. Each of the following q lines contains the description of a student's card: <image> integers from 1 to n inclusive. They are the numbers of theorems included in the card in the order in which they are enumerated in the input data. The numbers are given in an arbitrary order. It is guaranteed that the given cards are valid (that is, that all theorems in one card are different and that different people get cards that either don't contain the same theorems or coincide up to the theorems' permutation).
Output
Print two real numbers, representing Vasya's minimum and maximum proficiency in the card he will get on the exam. The absolute or relative error should not exceed 10 - 6.
Examples
Input
7 3
7 15 0 19 10 5 12
2
1 6
7 4
Output
5.0000000000 15.5000000000
Input
4 2
10 8 1 17
2
2 3
3 2
Output
4.5000000000 13.5000000000
Note
Let's analyze the first sample. Vasya's proficiency in the cards whose content he already knows equals 6 and 15.5 correspondingly. The three theorems that are left are only enough to make one exam card. If we consider all possible variants of theorems included in the card we can see that in the best case scenario Vasya gets the card that contains theorems 4 and 7 (his proficiency would equal 15.5) and in the worst case scenario he gets theorems 3 and 5 (his proficiency would equal 5).
The β xβ operation denotes taking integer part of real number x (rounding down). | instruction | 0 | 103,781 | 14 | 207,562 |
Tags: constructive algorithms, implementation, sortings
Correct Solution:
```
n, k = map(int, input().split(" "))
a = list(map(int, input().split(" ")))
temp = [0 for i in range(n)]
b = []
min = 10000000
max = 0
q = int(input())
for i in range(q):
ls = list(map(int, input().split(" ")))
tmp = 0
for j in ls:
tmp += a[j - 1]
temp[j - 1] = 1
if min > tmp:
min = tmp
if max < tmp:
max = tmp
for i, x in enumerate(temp):
if x == 0:
b.append(a[i])
if sum(temp) < k*int(n/k):
b.sort()
tmp = sum(b[:int(n/k)])
if min > tmp:
min = tmp
tmp = sum(b[-int(n/k):])
if max < tmp:
max = tmp
print(str(min/int(n/k)) + " " + str(max/int(n/k)))
# Made By Mostafa_Khaled
``` | output | 1 | 103,781 | 14 | 207,563 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya is about to take his first university exam in about several minutes. And it's not just some ordinary exam, it's on mathematical analysis. Of course, right now Vasya can only think of one thing: what the result of his talk with the examiner will be...
To prepare for the exam, one has to study proofs of n theorems. It is known that there will be k examination cards on the exam and each card contains <image> distinct theorems. Besides, no theorem is mentioned in more than one card (that is, <image> theorems won't be mentioned in any card). During the exam several students may get the same card.
We do not know the exact way theorems are distributed by cards, however the students that took the exam before Vasya told him what theorems their cards contained. Vasya evaluates his level of proficiency in the i-th theorem by some number ai. The level of proficiency in some card is the average of the levels of proficiency in the theorems that are included in the card. Now Vasya wants to know the minimally and maximally possible levels of his proficiency in the card he gets on the exam. Vasya wants to determine it by the data he has collected from other students. Unfortunately, Vasya has no time left to do the math and he asked you to help him.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 100) β the number of theorems and the number of cards correspondingly. The second line contains n integers ai (0 β€ ai β€ 100), the i-th number (1 β€ i β€ n) corresponds to Vasya's proficiency in the i-th theorem.
The third line contains number q (0 β€ q β€ 100) β the number of people that have taken the exam before Vasya. Each of the following q lines contains the description of a student's card: <image> integers from 1 to n inclusive. They are the numbers of theorems included in the card in the order in which they are enumerated in the input data. The numbers are given in an arbitrary order. It is guaranteed that the given cards are valid (that is, that all theorems in one card are different and that different people get cards that either don't contain the same theorems or coincide up to the theorems' permutation).
Output
Print two real numbers, representing Vasya's minimum and maximum proficiency in the card he will get on the exam. The absolute or relative error should not exceed 10 - 6.
Examples
Input
7 3
7 15 0 19 10 5 12
2
1 6
7 4
Output
5.0000000000 15.5000000000
Input
4 2
10 8 1 17
2
2 3
3 2
Output
4.5000000000 13.5000000000
Note
Let's analyze the first sample. Vasya's proficiency in the cards whose content he already knows equals 6 and 15.5 correspondingly. The three theorems that are left are only enough to make one exam card. If we consider all possible variants of theorems included in the card we can see that in the best case scenario Vasya gets the card that contains theorems 4 and 7 (his proficiency would equal 15.5) and in the worst case scenario he gets theorems 3 and 5 (his proficiency would equal 5).
The β xβ operation denotes taking integer part of real number x (rounding down). | instruction | 0 | 103,782 | 14 | 207,564 |
Tags: constructive algorithms, implementation, sortings
Correct Solution:
```
n, k = map(int, input().split(" "))
a = list(map(int, input().split(" ")))
temp = [0 for i in range(n)]
b = []
min = 10000000
max = 0
q = int(input())
for i in range(q):
ls = list(map(int, input().split(" ")))
tmp = 0
for j in ls:
tmp += a[j - 1]
temp[j - 1] = 1
if min > tmp:
min = tmp
if max < tmp:
max = tmp
for i, x in enumerate(temp):
if x == 0:
b.append(a[i])
if sum(temp) < k*int(n/k):
b.sort()
tmp = sum(b[:int(n/k)])
if min > tmp:
min = tmp
tmp = sum(b[-int(n/k):])
if max < tmp:
max = tmp
print(str(min/int(n/k)) + " " + str(max/int(n/k)))
``` | output | 1 | 103,782 | 14 | 207,565 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya is about to take his first university exam in about several minutes. And it's not just some ordinary exam, it's on mathematical analysis. Of course, right now Vasya can only think of one thing: what the result of his talk with the examiner will be...
To prepare for the exam, one has to study proofs of n theorems. It is known that there will be k examination cards on the exam and each card contains <image> distinct theorems. Besides, no theorem is mentioned in more than one card (that is, <image> theorems won't be mentioned in any card). During the exam several students may get the same card.
We do not know the exact way theorems are distributed by cards, however the students that took the exam before Vasya told him what theorems their cards contained. Vasya evaluates his level of proficiency in the i-th theorem by some number ai. The level of proficiency in some card is the average of the levels of proficiency in the theorems that are included in the card. Now Vasya wants to know the minimally and maximally possible levels of his proficiency in the card he gets on the exam. Vasya wants to determine it by the data he has collected from other students. Unfortunately, Vasya has no time left to do the math and he asked you to help him.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 100) β the number of theorems and the number of cards correspondingly. The second line contains n integers ai (0 β€ ai β€ 100), the i-th number (1 β€ i β€ n) corresponds to Vasya's proficiency in the i-th theorem.
The third line contains number q (0 β€ q β€ 100) β the number of people that have taken the exam before Vasya. Each of the following q lines contains the description of a student's card: <image> integers from 1 to n inclusive. They are the numbers of theorems included in the card in the order in which they are enumerated in the input data. The numbers are given in an arbitrary order. It is guaranteed that the given cards are valid (that is, that all theorems in one card are different and that different people get cards that either don't contain the same theorems or coincide up to the theorems' permutation).
Output
Print two real numbers, representing Vasya's minimum and maximum proficiency in the card he will get on the exam. The absolute or relative error should not exceed 10 - 6.
Examples
Input
7 3
7 15 0 19 10 5 12
2
1 6
7 4
Output
5.0000000000 15.5000000000
Input
4 2
10 8 1 17
2
2 3
3 2
Output
4.5000000000 13.5000000000
Note
Let's analyze the first sample. Vasya's proficiency in the cards whose content he already knows equals 6 and 15.5 correspondingly. The three theorems that are left are only enough to make one exam card. If we consider all possible variants of theorems included in the card we can see that in the best case scenario Vasya gets the card that contains theorems 4 and 7 (his proficiency would equal 15.5) and in the worst case scenario he gets theorems 3 and 5 (his proficiency would equal 5).
The β xβ operation denotes taking integer part of real number x (rounding down). | instruction | 0 | 103,783 | 14 | 207,566 |
Tags: constructive algorithms, implementation, sortings
Correct Solution:
```
n,k = map(int, input().split())
a = list(map(int, input().split()))
ansMin, ansMax = 10**10, -10**10
were = [0]*n
sz = n//k
for i in range(int(input())):
cur = 0.0
t = map(int, input().split())
for x in t:
were[x-1]=1
cur+=a[x-1]
cur/=sz
ansMin = min(ansMin, cur)
ansMax = max(ansMax, cur)
remain = []
for i in range(n):
if not were[i]:
remain.append(a[i])
remain.sort()
if len(remain)-n%k>=sz:
ansMin = min(ansMin, 1.0*sum(remain[:sz])/sz)
ansMax = max(ansMax, 1.0*sum(remain[-sz:])/sz)
print('%.10f %.10f' % (ansMin, ansMax))
``` | output | 1 | 103,783 | 14 | 207,567 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya is about to take his first university exam in about several minutes. And it's not just some ordinary exam, it's on mathematical analysis. Of course, right now Vasya can only think of one thing: what the result of his talk with the examiner will be...
To prepare for the exam, one has to study proofs of n theorems. It is known that there will be k examination cards on the exam and each card contains <image> distinct theorems. Besides, no theorem is mentioned in more than one card (that is, <image> theorems won't be mentioned in any card). During the exam several students may get the same card.
We do not know the exact way theorems are distributed by cards, however the students that took the exam before Vasya told him what theorems their cards contained. Vasya evaluates his level of proficiency in the i-th theorem by some number ai. The level of proficiency in some card is the average of the levels of proficiency in the theorems that are included in the card. Now Vasya wants to know the minimally and maximally possible levels of his proficiency in the card he gets on the exam. Vasya wants to determine it by the data he has collected from other students. Unfortunately, Vasya has no time left to do the math and he asked you to help him.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 100) β the number of theorems and the number of cards correspondingly. The second line contains n integers ai (0 β€ ai β€ 100), the i-th number (1 β€ i β€ n) corresponds to Vasya's proficiency in the i-th theorem.
The third line contains number q (0 β€ q β€ 100) β the number of people that have taken the exam before Vasya. Each of the following q lines contains the description of a student's card: <image> integers from 1 to n inclusive. They are the numbers of theorems included in the card in the order in which they are enumerated in the input data. The numbers are given in an arbitrary order. It is guaranteed that the given cards are valid (that is, that all theorems in one card are different and that different people get cards that either don't contain the same theorems or coincide up to the theorems' permutation).
Output
Print two real numbers, representing Vasya's minimum and maximum proficiency in the card he will get on the exam. The absolute or relative error should not exceed 10 - 6.
Examples
Input
7 3
7 15 0 19 10 5 12
2
1 6
7 4
Output
5.0000000000 15.5000000000
Input
4 2
10 8 1 17
2
2 3
3 2
Output
4.5000000000 13.5000000000
Note
Let's analyze the first sample. Vasya's proficiency in the cards whose content he already knows equals 6 and 15.5 correspondingly. The three theorems that are left are only enough to make one exam card. If we consider all possible variants of theorems included in the card we can see that in the best case scenario Vasya gets the card that contains theorems 4 and 7 (his proficiency would equal 15.5) and in the worst case scenario he gets theorems 3 and 5 (his proficiency would equal 5).
The β xβ operation denotes taking integer part of real number x (rounding down). | instruction | 0 | 103,784 | 14 | 207,568 |
Tags: constructive algorithms, implementation, sortings
Correct Solution:
```
n, m = map(int, input().split())
a = [0] + list(map(int, input().split()))
p, t, k = [], [True] * (n + 1), n // m
u, v = 10001, -1
for i in range(int(input())):
q = list(map(int, input().split()))
if t[q[0]]:
for i in q: t[i] = False
x = sum(a[i] for i in q)
if x < u: u = x
if x > v: v = x
m -= 1
q = sorted(a[i] for i in range(1, n + 1) if t[i])
if len(q) >= k and m:
x, y = sum(q[: k]), sum(q[-k: ])
if x < u: u = x
if y > v: v = y
print(u / k, v / k)
``` | output | 1 | 103,784 | 14 | 207,569 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Everyone knows that hobbits love to organize all sorts of parties and celebrations. There are n hobbits living in the Shire. They decided to organize the Greatest Party (GP) that would last for several days. Next day the hobbits wrote a guest list, some non-empty set containing all the inhabitants of the Shire. To ensure that everybody enjoy themselves and nobody gets bored, for any two days (say, days A and B) of the GP there existed at least one hobbit, invited to come on day A and on day B. However, to ensure that nobody has a row, for any three different days A, B, C there shouldn't be a hobbit invited on days A, B and C. The Shire inhabitants are keen on keeping the GP going for as long as possible. Your task is given number n, to indicate the GP's maximum duration and the guest lists for each day.
Input
The first line contains an integer n (3 β€ n β€ 10000), representing the number of hobbits.
Output
In the first output line print a number k β the maximum duration of GP in days. Then on k lines print the guest lists, (the guests should be separated by spaces). Print each guest list on the single line. Each list can contain an arbitrary positive number of hobbits. The hobbits are numbered with integers from 1 to n.
Examples
Input
4
Output
3
1 2
1 3
2 3
Input
5
Output
3
1 2
1 3
2 3 | instruction | 0 | 103,815 | 14 | 207,630 |
Tags: constructive algorithms, greedy
Correct Solution:
```
'''
Author : thekushalghosh
Team : CodeDiggers
'''
n = int(input())
q = int(0.5 + (1 + 8*n)**0.5 / 2)
w = 1
qw = [[] for _ in range(q)]
for i in range(q):
j = i + 1
while len(qw[i]) < q - 1:
qw[i].append(str(w))
qw[j].append(str(w))
w = w + 1
j = j + 1
print(q)
for q in qw:
print(" ".join(q))
``` | output | 1 | 103,815 | 14 | 207,631 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Everyone knows that hobbits love to organize all sorts of parties and celebrations. There are n hobbits living in the Shire. They decided to organize the Greatest Party (GP) that would last for several days. Next day the hobbits wrote a guest list, some non-empty set containing all the inhabitants of the Shire. To ensure that everybody enjoy themselves and nobody gets bored, for any two days (say, days A and B) of the GP there existed at least one hobbit, invited to come on day A and on day B. However, to ensure that nobody has a row, for any three different days A, B, C there shouldn't be a hobbit invited on days A, B and C. The Shire inhabitants are keen on keeping the GP going for as long as possible. Your task is given number n, to indicate the GP's maximum duration and the guest lists for each day.
Input
The first line contains an integer n (3 β€ n β€ 10000), representing the number of hobbits.
Output
In the first output line print a number k β the maximum duration of GP in days. Then on k lines print the guest lists, (the guests should be separated by spaces). Print each guest list on the single line. Each list can contain an arbitrary positive number of hobbits. The hobbits are numbered with integers from 1 to n.
Examples
Input
4
Output
3
1 2
1 3
2 3
Input
5
Output
3
1 2
1 3
2 3 | instruction | 0 | 103,816 | 14 | 207,632 |
Tags: constructive algorithms, greedy
Correct Solution:
```
n=int(input())
res=1
while((res*(res+1)//2)<=n):res+=1
ns=[[] for _ in range(res+1)]
cur=1
for i in range(1,res+1):
for j in range(i+1,res+1):
ns[i].append(cur)
ns[j].append(cur)
cur+=1
print(res)
for e in ns[1:]:
print(*e)
``` | output | 1 | 103,816 | 14 | 207,633 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Everyone knows that hobbits love to organize all sorts of parties and celebrations. There are n hobbits living in the Shire. They decided to organize the Greatest Party (GP) that would last for several days. Next day the hobbits wrote a guest list, some non-empty set containing all the inhabitants of the Shire. To ensure that everybody enjoy themselves and nobody gets bored, for any two days (say, days A and B) of the GP there existed at least one hobbit, invited to come on day A and on day B. However, to ensure that nobody has a row, for any three different days A, B, C there shouldn't be a hobbit invited on days A, B and C. The Shire inhabitants are keen on keeping the GP going for as long as possible. Your task is given number n, to indicate the GP's maximum duration and the guest lists for each day.
Input
The first line contains an integer n (3 β€ n β€ 10000), representing the number of hobbits.
Output
In the first output line print a number k β the maximum duration of GP in days. Then on k lines print the guest lists, (the guests should be separated by spaces). Print each guest list on the single line. Each list can contain an arbitrary positive number of hobbits. The hobbits are numbered with integers from 1 to n.
Examples
Input
4
Output
3
1 2
1 3
2 3
Input
5
Output
3
1 2
1 3
2 3 | instruction | 0 | 103,817 | 14 | 207,634 |
Tags: constructive algorithms, greedy
Correct Solution:
```
n=int(input())
x=1
while x*(x-1)//2<=n:
x+=1
x-=1
print(x)
z=x*(x-1)//2
a=[]
z=0
for i in range(x-1):
a.append(z-i+1)
z+=x-i
for i in range(x):
j=i
for k in range(i):
print(a[k],end=' ')
a[k]+=1
j=a[i] if i!=x-1 else 0
for k in range(x-1-i):
print(j,end=' ')
j+=1
print()
``` | output | 1 | 103,817 | 14 | 207,635 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Everyone knows that hobbits love to organize all sorts of parties and celebrations. There are n hobbits living in the Shire. They decided to organize the Greatest Party (GP) that would last for several days. Next day the hobbits wrote a guest list, some non-empty set containing all the inhabitants of the Shire. To ensure that everybody enjoy themselves and nobody gets bored, for any two days (say, days A and B) of the GP there existed at least one hobbit, invited to come on day A and on day B. However, to ensure that nobody has a row, for any three different days A, B, C there shouldn't be a hobbit invited on days A, B and C. The Shire inhabitants are keen on keeping the GP going for as long as possible. Your task is given number n, to indicate the GP's maximum duration and the guest lists for each day.
Input
The first line contains an integer n (3 β€ n β€ 10000), representing the number of hobbits.
Output
In the first output line print a number k β the maximum duration of GP in days. Then on k lines print the guest lists, (the guests should be separated by spaces). Print each guest list on the single line. Each list can contain an arbitrary positive number of hobbits. The hobbits are numbered with integers from 1 to n.
Examples
Input
4
Output
3
1 2
1 3
2 3
Input
5
Output
3
1 2
1 3
2 3 | instruction | 0 | 103,818 | 14 | 207,636 |
Tags: constructive algorithms, greedy
Correct Solution:
```
n = int(input())
d = int(0.5 + (1 + 8*n)**0.5 / 2)
curr = 1
res = [[] for _ in range(d)]
for i in range(d):
j = i + 1
while len(res[i]) < d - 1:
res[i].append(str(curr))
res[j].append(str(curr))
curr += 1
j += 1
print(d)
for l in res:
print(' '.join(l))
``` | output | 1 | 103,818 | 14 | 207,637 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Everyone knows that hobbits love to organize all sorts of parties and celebrations. There are n hobbits living in the Shire. They decided to organize the Greatest Party (GP) that would last for several days. Next day the hobbits wrote a guest list, some non-empty set containing all the inhabitants of the Shire. To ensure that everybody enjoy themselves and nobody gets bored, for any two days (say, days A and B) of the GP there existed at least one hobbit, invited to come on day A and on day B. However, to ensure that nobody has a row, for any three different days A, B, C there shouldn't be a hobbit invited on days A, B and C. The Shire inhabitants are keen on keeping the GP going for as long as possible. Your task is given number n, to indicate the GP's maximum duration and the guest lists for each day.
Input
The first line contains an integer n (3 β€ n β€ 10000), representing the number of hobbits.
Output
In the first output line print a number k β the maximum duration of GP in days. Then on k lines print the guest lists, (the guests should be separated by spaces). Print each guest list on the single line. Each list can contain an arbitrary positive number of hobbits. The hobbits are numbered with integers from 1 to n.
Examples
Input
4
Output
3
1 2
1 3
2 3
Input
5
Output
3
1 2
1 3
2 3 | instruction | 0 | 103,819 | 14 | 207,638 |
Tags: constructive algorithms, greedy
Correct Solution:
```
N = int(input())
k = 1
while 1:
if k * (k - 1) // 2 > N:
k -= 1
print(k)
D = [[]]
for i in range (k):
D.append ([])
p = 1
for i in range(k):
for j in range(i + 1, k):
D[i].append (p)
D [j].append (p)
p += 1
for i in D:
for j in i:
print (j, end = ' ')
print ()
break
else:
k += 1
``` | output | 1 | 103,819 | 14 | 207,639 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Everyone knows that hobbits love to organize all sorts of parties and celebrations. There are n hobbits living in the Shire. They decided to organize the Greatest Party (GP) that would last for several days. Next day the hobbits wrote a guest list, some non-empty set containing all the inhabitants of the Shire. To ensure that everybody enjoy themselves and nobody gets bored, for any two days (say, days A and B) of the GP there existed at least one hobbit, invited to come on day A and on day B. However, to ensure that nobody has a row, for any three different days A, B, C there shouldn't be a hobbit invited on days A, B and C. The Shire inhabitants are keen on keeping the GP going for as long as possible. Your task is given number n, to indicate the GP's maximum duration and the guest lists for each day.
Input
The first line contains an integer n (3 β€ n β€ 10000), representing the number of hobbits.
Output
In the first output line print a number k β the maximum duration of GP in days. Then on k lines print the guest lists, (the guests should be separated by spaces). Print each guest list on the single line. Each list can contain an arbitrary positive number of hobbits. The hobbits are numbered with integers from 1 to n.
Examples
Input
4
Output
3
1 2
1 3
2 3
Input
5
Output
3
1 2
1 3
2 3
Submitted Solution:
```
n = int(input())
a = n//36
b = (n-a*36)//3
rem = (n-a*36)%3
if(rem==2):
b+=1
print(a,b)
``` | instruction | 0 | 103,820 | 14 | 207,640 |
No | output | 1 | 103,820 | 14 | 207,641 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Everyone knows that hobbits love to organize all sorts of parties and celebrations. There are n hobbits living in the Shire. They decided to organize the Greatest Party (GP) that would last for several days. Next day the hobbits wrote a guest list, some non-empty set containing all the inhabitants of the Shire. To ensure that everybody enjoy themselves and nobody gets bored, for any two days (say, days A and B) of the GP there existed at least one hobbit, invited to come on day A and on day B. However, to ensure that nobody has a row, for any three different days A, B, C there shouldn't be a hobbit invited on days A, B and C. The Shire inhabitants are keen on keeping the GP going for as long as possible. Your task is given number n, to indicate the GP's maximum duration and the guest lists for each day.
Input
The first line contains an integer n (3 β€ n β€ 10000), representing the number of hobbits.
Output
In the first output line print a number k β the maximum duration of GP in days. Then on k lines print the guest lists, (the guests should be separated by spaces). Print each guest list on the single line. Each list can contain an arbitrary positive number of hobbits. The hobbits are numbered with integers from 1 to n.
Examples
Input
4
Output
3
1 2
1 3
2 3
Input
5
Output
3
1 2
1 3
2 3
Submitted Solution:
```
n=int(input())
n=n-n%3
count=1
print(n)
for i in range(1,n):
if count%4!=0:
for j in range(1,3):
if count%4==0:
break
print(i,"",i+j)
count=count+1
else:
count=count+1
``` | instruction | 0 | 103,821 | 14 | 207,642 |
No | output | 1 | 103,821 | 14 | 207,643 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As Sherlock Holmes was investigating a crime, he identified n suspects. He knows for sure that exactly one of them committed the crime. To find out which one did it, the detective lines up the suspects and numbered them from 1 to n. After that, he asked each one: "Which one committed the crime?". Suspect number i answered either "The crime was committed by suspect number ai", or "Suspect number ai didn't commit the crime". Also, the suspect could say so about himself (ai = i).
Sherlock Holmes understood for sure that exactly m answers were the truth and all other answers were a lie. Now help him understand this: which suspect lied and which one told the truth?
Input
The first line contains two integers n and m (1 β€ n β€ 105, 0 β€ m β€ n) β the total number of suspects and the number of suspects who told the truth. Next n lines contain the suspects' answers. The i-th line contains either "+ai" (without the quotes), if the suspect number i says that the crime was committed by suspect number ai, or "-ai" (without the quotes), if the suspect number i says that the suspect number ai didn't commit the crime (ai is an integer, 1 β€ ai β€ n).
It is guaranteed that at least one suspect exists, such that if he committed the crime, then exactly m people told the truth.
Output
Print n lines. Line number i should contain "Truth" if suspect number i has told the truth for sure. Print "Lie" if the suspect number i lied for sure and print "Not defined" if he could lie and could tell the truth, too, depending on who committed the crime.
Examples
Input
1 1
+1
Output
Truth
Input
3 2
-1
-2
-3
Output
Not defined
Not defined
Not defined
Input
4 1
+2
-3
+4
-1
Output
Lie
Not defined
Lie
Not defined
Note
The first sample has the single person and he confesses to the crime, and Sherlock Holmes knows that one person is telling the truth. That means that this person is telling the truth.
In the second sample there are three suspects and each one denies his guilt. Sherlock Holmes knows that only two of them are telling the truth. Any one of them can be the criminal, so we don't know for any of them, whether this person is telling the truth or not.
In the third sample the second and the fourth suspect defend the first and the third one. But only one is telling the truth, thus, the first or the third one is the criminal. Both of them can be criminals, so the second and the fourth one can either be lying or telling the truth. The first and the third one are lying for sure as they are blaming the second and the fourth one. | instruction | 0 | 103,939 | 14 | 207,878 |
Tags: constructive algorithms, data structures, implementation
Correct Solution:
```
from sys import stdin, stdout
n, m = map(int, stdin.readline().split())
cntf = [0 for i in range(n + 1)]
cnts = [0 for i in range(n + 1)]
challengers = []
for i in range(n):
s = stdin.readline().strip()
challengers.append(s)
if s[0] == '+':
cntf[int(s[1:])] += 1
else:
cnts[int(s[1:])] += 1
first = sum(cntf)
second = sum(cnts)
ans = set()
for i in range(1, n + 1):
if cntf[i] + second - cnts[i] == m:
ans.add(i)
for i in range(n):
s = challengers[i]
if s[0] == '+':
if int(s[1:]) in ans:
if len(ans) > 1:
stdout.write('Not defined\n')
else:
stdout.write('Truth\n')
else:
stdout.write('Lie\n')
else:
if int(s[1:]) in ans:
if len(ans) > 1:
stdout.write('Not defined\n')
else:
stdout.write('Lie\n')
else:
stdout.write('Truth\n')
``` | output | 1 | 103,939 | 14 | 207,879 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As Sherlock Holmes was investigating a crime, he identified n suspects. He knows for sure that exactly one of them committed the crime. To find out which one did it, the detective lines up the suspects and numbered them from 1 to n. After that, he asked each one: "Which one committed the crime?". Suspect number i answered either "The crime was committed by suspect number ai", or "Suspect number ai didn't commit the crime". Also, the suspect could say so about himself (ai = i).
Sherlock Holmes understood for sure that exactly m answers were the truth and all other answers were a lie. Now help him understand this: which suspect lied and which one told the truth?
Input
The first line contains two integers n and m (1 β€ n β€ 105, 0 β€ m β€ n) β the total number of suspects and the number of suspects who told the truth. Next n lines contain the suspects' answers. The i-th line contains either "+ai" (without the quotes), if the suspect number i says that the crime was committed by suspect number ai, or "-ai" (without the quotes), if the suspect number i says that the suspect number ai didn't commit the crime (ai is an integer, 1 β€ ai β€ n).
It is guaranteed that at least one suspect exists, such that if he committed the crime, then exactly m people told the truth.
Output
Print n lines. Line number i should contain "Truth" if suspect number i has told the truth for sure. Print "Lie" if the suspect number i lied for sure and print "Not defined" if he could lie and could tell the truth, too, depending on who committed the crime.
Examples
Input
1 1
+1
Output
Truth
Input
3 2
-1
-2
-3
Output
Not defined
Not defined
Not defined
Input
4 1
+2
-3
+4
-1
Output
Lie
Not defined
Lie
Not defined
Note
The first sample has the single person and he confesses to the crime, and Sherlock Holmes knows that one person is telling the truth. That means that this person is telling the truth.
In the second sample there are three suspects and each one denies his guilt. Sherlock Holmes knows that only two of them are telling the truth. Any one of them can be the criminal, so we don't know for any of them, whether this person is telling the truth or not.
In the third sample the second and the fourth suspect defend the first and the third one. But only one is telling the truth, thus, the first or the third one is the criminal. Both of them can be criminals, so the second and the fourth one can either be lying or telling the truth. The first and the third one are lying for sure as they are blaming the second and the fourth one. | instruction | 0 | 103,940 | 14 | 207,880 |
Tags: constructive algorithms, data structures, implementation
Correct Solution:
```
"""
Brandt Smith, Lemuel Gorion and Peter Haddad
codeforces.com
Problem 156B
"""
import sys
n, m = map(int, input().split(' '))
inp = []
guess = [0] * (n + 1)
for i in range(n):
temp = int(input())
inp.append(temp)
if temp < 0:
m -= 1
guess[-temp] -= 1
else:
guess[temp] += 1
dic = {temp for temp in range(1, n + 1) if guess[temp] == m}
if len(dic) == 0:
for i in range(n):
print('Not defined')
elif len(dic) == 1:
temp = dic.pop()
for i in inp:
if i == temp or (i < 0 and i + temp):
print('Truth')
else:
print('Lie')
else:
temp = dic.update({-i for i in dic})
for i in inp:
if i in dic:
print('Not defined')
else:
if i < 0:
print('Truth')
else:
print('Lie')
# Made By Mostafa_Khaled
``` | output | 1 | 103,940 | 14 | 207,881 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Once upon a time there lived a good fairy A. One day a fine young man B came to her and asked to predict his future. The fairy looked into her magic ball and said that soon the fine young man will meet the most beautiful princess ever and will marry her. Then she drew on a sheet of paper n points and joined some of them with segments, each of the segments starts in some point and ends in some other point. Having drawn that picture, she asked the young man to erase one of the segments from the sheet. Then she tries to colour each point red or blue so, that there is no segment having points of the same colour as its ends. If she manages to do so, the prediction will come true. B wants to meet the most beautiful princess, that's why he asks you to help him. Find all the segments that will help him to meet the princess.
Input
The first input line contains two integer numbers: n β amount of the drawn points and m β amount of the drawn segments (1 β€ n β€ 104, 0 β€ m β€ 104). The following m lines contain the descriptions of the segments. Each description contains two different space-separated integer numbers v, u (1 β€ v β€ n, 1 β€ u β€ n) β indexes of the points, joined by this segment. No segment is met in the description twice.
Output
In the first line output number k β amount of the segments in the answer. In the second line output k space-separated numbers β indexes of these segments in ascending order. Each index should be output only once. Segments are numbered from 1 in the input order.
Examples
Input
4 4
1 2
1 3
2 4
3 4
Output
4
1 2 3 4
Input
4 5
1 2
2 3
3 4
4 1
1 3
Output
1
5
Submitted Solution:
```
import sys
sys.setrecursionlimit(1000000)
n, m = [int(x) for x in input().split()]
adj = [[] for _ in range(n)]
edges = []
for i in range(m):
u,v = [int(x) for x in input().split()]
adj[u-1].append([v-1, i])
adj[v-1].append([u-1, i])
edges.append([u-1,v-1])
color = [-1]*n
parent = [-1]*m
cycles = [0]*m
count = 0
def dfs(i,p,c,s):
global count
if(color[i]!=-1):
#Found Cycle
if(c == color[i]):
return 0
#Found Odd Cycle
count += 1
while True:
cycles[s]+=1
if i in edges[s]:
break
s = parent[s]
return 0
color[i] = c
for ch,r in adj[i]:
if(ch == p):
continue
parent[r] = s
dfs(ch,i,1-c,r)
for i in range(n):
if(color[i]==-1):
dfs(i,-1,1,-1)
ans = []
for i in range(m):
if(cycles[i]==count):
ans.append(i+1)
print(len(ans))
print(*ans,sep = " ")
print()
``` | instruction | 0 | 103,942 | 14 | 207,884 |
No | output | 1 | 103,942 | 14 | 207,885 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Once upon a time there lived a good fairy A. One day a fine young man B came to her and asked to predict his future. The fairy looked into her magic ball and said that soon the fine young man will meet the most beautiful princess ever and will marry her. Then she drew on a sheet of paper n points and joined some of them with segments, each of the segments starts in some point and ends in some other point. Having drawn that picture, she asked the young man to erase one of the segments from the sheet. Then she tries to colour each point red or blue so, that there is no segment having points of the same colour as its ends. If she manages to do so, the prediction will come true. B wants to meet the most beautiful princess, that's why he asks you to help him. Find all the segments that will help him to meet the princess.
Input
The first input line contains two integer numbers: n β amount of the drawn points and m β amount of the drawn segments (1 β€ n β€ 104, 0 β€ m β€ 104). The following m lines contain the descriptions of the segments. Each description contains two different space-separated integer numbers v, u (1 β€ v β€ n, 1 β€ u β€ n) β indexes of the points, joined by this segment. No segment is met in the description twice.
Output
In the first line output number k β amount of the segments in the answer. In the second line output k space-separated numbers β indexes of these segments in ascending order. Each index should be output only once. Segments are numbered from 1 in the input order.
Examples
Input
4 4
1 2
1 3
2 4
3 4
Output
4
1 2 3 4
Input
4 5
1 2
2 3
3 4
4 1
1 3
Output
1
5
Submitted Solution:
```
print("big pp")
``` | instruction | 0 | 103,943 | 14 | 207,886 |
No | output | 1 | 103,943 | 14 | 207,887 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Once upon a time there lived a good fairy A. One day a fine young man B came to her and asked to predict his future. The fairy looked into her magic ball and said that soon the fine young man will meet the most beautiful princess ever and will marry her. Then she drew on a sheet of paper n points and joined some of them with segments, each of the segments starts in some point and ends in some other point. Having drawn that picture, she asked the young man to erase one of the segments from the sheet. Then she tries to colour each point red or blue so, that there is no segment having points of the same colour as its ends. If she manages to do so, the prediction will come true. B wants to meet the most beautiful princess, that's why he asks you to help him. Find all the segments that will help him to meet the princess.
Input
The first input line contains two integer numbers: n β amount of the drawn points and m β amount of the drawn segments (1 β€ n β€ 104, 0 β€ m β€ 104). The following m lines contain the descriptions of the segments. Each description contains two different space-separated integer numbers v, u (1 β€ v β€ n, 1 β€ u β€ n) β indexes of the points, joined by this segment. No segment is met in the description twice.
Output
In the first line output number k β amount of the segments in the answer. In the second line output k space-separated numbers β indexes of these segments in ascending order. Each index should be output only once. Segments are numbered from 1 in the input order.
Examples
Input
4 4
1 2
1 3
2 4
3 4
Output
4
1 2 3 4
Input
4 5
1 2
2 3
3 4
4 1
1 3
Output
1
5
Submitted Solution:
```
import sys
sys.setrecursionlimit(1000000)
n, m = [int(x) for x in input().split()]
adj = [[] for _ in range(n)]
edges = []
for i in range(m):
u,v = [int(x) for x in input().split()]
adj[u-1].append([v-1, i])
adj[v-1].append([u-1, i])
edges.append([u-1,v-1])
color = [-1]*n
parent = [-1]*m
cycles = [0]*m
count = 0
def dfs(i,p,c,s):
global count
if(color[i]!=-1):
#Found Cycle
if(c == color[i]):
return 0
#Found Odd Cycle
count += 1
while True:
cycles[s]+=1
if i in edges[s]:
break
s = parent[s]
return 0
color[i] = c
for ch,r in adj[i]:
if(ch == p):
continue
parent[r] = s
dfs(ch,i,1-c,r)
dfs(0,-1,1,-1)
ans = []
for i in range(m):
if(cycles[i]==count):
ans.append(i+1)
print(len(ans))
print(*ans,sep = " ")
print()
``` | instruction | 0 | 103,944 | 14 | 207,888 |
No | output | 1 | 103,944 | 14 | 207,889 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As it has been found out recently, all the Berland's current economical state can be described using a simple table n Γ m in size. n β the number of days in each Berland month, m β the number of months. Thus, a table cell corresponds to a day and a month of the Berland's year. Each cell will contain either 1, or -1, which means the state's gains in a particular month, on a particular day. 1 corresponds to profits, -1 corresponds to losses. It turned out important for successful development to analyze the data on the state of the economy of the previous year, however when the treasurers referred to the archives to retrieve the data, it turned out that the table had been substantially damaged. In some table cells the number values had faded and were impossible to be deciphered. It is known that the number of cells in which the data had been preserved is strictly less than max(n, m). However, there is additional information β the product of the numbers in each line and column equaled -1. Your task is to find out how many different tables may conform to the preserved data. As the answer to the task can be quite large, you have to find it modulo p.
Input
The first line contains integers n and m (1 β€ n, m β€ 1000). The second line contains the integer k (0 β€ k < max(n, m)) β the number of cells in which the data had been preserved. The next k lines contain the data on the state of the table in the preserved cells. Each line is of the form "a b c", where a (1 β€ a β€ n) β the number of the table row, b (1 β€ b β€ m) β the number of the column, c β the value containing in the cell (1 or -1). They are numbered starting from 1. It is guaranteed that no two lines with same a and b values exist. The last line contains an integer p (2 β€ p β€ 109 + 7).
Output
Print the number of different tables that could conform to the preserved data modulo p.
Examples
Input
2 2
0
100
Output
2
Input
2 2
1
1 1 -1
100
Output
1 | instruction | 0 | 104,010 | 14 | 208,020 |
Tags: combinatorics
Correct Solution:
```
# METO Bot 0.9.9
n,m=map(int,input().split())
k=int(input())
A=[[] for i in range(max(n,m))]
for i in range(k):
a,b,c=map(int,input().split())
A[b-1 if n<m else a-1].append(c==-1)
p=int(input())
if n%2!=m%2:
print(0)
else:
r=k
for i in A:
if len(i)>=min(n,m):
if sum(i)%2:
r-=1
else:
print(0)
break
else:
print(pow(2,(n-1)*(m-1)-r,p))
``` | output | 1 | 104,010 | 14 | 208,021 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As it has been found out recently, all the Berland's current economical state can be described using a simple table n Γ m in size. n β the number of days in each Berland month, m β the number of months. Thus, a table cell corresponds to a day and a month of the Berland's year. Each cell will contain either 1, or -1, which means the state's gains in a particular month, on a particular day. 1 corresponds to profits, -1 corresponds to losses. It turned out important for successful development to analyze the data on the state of the economy of the previous year, however when the treasurers referred to the archives to retrieve the data, it turned out that the table had been substantially damaged. In some table cells the number values had faded and were impossible to be deciphered. It is known that the number of cells in which the data had been preserved is strictly less than max(n, m). However, there is additional information β the product of the numbers in each line and column equaled -1. Your task is to find out how many different tables may conform to the preserved data. As the answer to the task can be quite large, you have to find it modulo p.
Input
The first line contains integers n and m (1 β€ n, m β€ 1000). The second line contains the integer k (0 β€ k < max(n, m)) β the number of cells in which the data had been preserved. The next k lines contain the data on the state of the table in the preserved cells. Each line is of the form "a b c", where a (1 β€ a β€ n) β the number of the table row, b (1 β€ b β€ m) β the number of the column, c β the value containing in the cell (1 or -1). They are numbered starting from 1. It is guaranteed that no two lines with same a and b values exist. The last line contains an integer p (2 β€ p β€ 109 + 7).
Output
Print the number of different tables that could conform to the preserved data modulo p.
Examples
Input
2 2
0
100
Output
2
Input
2 2
1
1 1 -1
100
Output
1 | instruction | 0 | 104,011 | 14 | 208,022 |
Tags: combinatorics
Correct Solution:
```
import itertools
import math
n, m = [int(x) for x in input().split()]
if n%2 != m%2:
print(0)
else:
k = int(input())
S = [[] for i in range(max(n,m))]
for i in range(k):
a, b, c = [int(x) for x in input().split()]
if n<m:
S[b-1].append(c==-1)
else:
S[a-1].append(c==-1)
p = int(input())
restrictions = k
for string in S:
if len(string) >= min(n,m):
if sum(string)%2:
restrictions -= 1
else:
print(0)
break
else:
print(pow(2, (n-1)*(m-1) - restrictions, p))
``` | output | 1 | 104,011 | 14 | 208,023 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As it has been found out recently, all the Berland's current economical state can be described using a simple table n Γ m in size. n β the number of days in each Berland month, m β the number of months. Thus, a table cell corresponds to a day and a month of the Berland's year. Each cell will contain either 1, or -1, which means the state's gains in a particular month, on a particular day. 1 corresponds to profits, -1 corresponds to losses. It turned out important for successful development to analyze the data on the state of the economy of the previous year, however when the treasurers referred to the archives to retrieve the data, it turned out that the table had been substantially damaged. In some table cells the number values had faded and were impossible to be deciphered. It is known that the number of cells in which the data had been preserved is strictly less than max(n, m). However, there is additional information β the product of the numbers in each line and column equaled -1. Your task is to find out how many different tables may conform to the preserved data. As the answer to the task can be quite large, you have to find it modulo p.
Input
The first line contains integers n and m (1 β€ n, m β€ 1000). The second line contains the integer k (0 β€ k < max(n, m)) β the number of cells in which the data had been preserved. The next k lines contain the data on the state of the table in the preserved cells. Each line is of the form "a b c", where a (1 β€ a β€ n) β the number of the table row, b (1 β€ b β€ m) β the number of the column, c β the value containing in the cell (1 or -1). They are numbered starting from 1. It is guaranteed that no two lines with same a and b values exist. The last line contains an integer p (2 β€ p β€ 109 + 7).
Output
Print the number of different tables that could conform to the preserved data modulo p.
Examples
Input
2 2
0
100
Output
2
Input
2 2
1
1 1 -1
100
Output
1 | instruction | 0 | 104,012 | 14 | 208,024 |
Tags: combinatorics
Correct Solution:
```
n,m=map(int,input().split())
k=int(input())
A=[[] for i in range(max(n,m))]
for i in range(k):
a,b,c=map(int,input().split())
A[b-1 if n<m else a-1].append(c==-1)
p=int(input())
if n%2!=m%2:
print(0)
else:
r=k
for i in A:
if len(i)>=min(n,m):
if sum(i)%2:
r-=1
else:
print(0)
break
else:
print(pow(2,(n-1)*(m-1)-r,p))
``` | output | 1 | 104,012 | 14 | 208,025 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.