text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Anya loves to watch horror movies. In the best traditions of horror, she will be visited by m ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly t seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one candle, then this candle burns for exactly t seconds and then goes out and can no longer be used.
For each of the m ghosts Anya knows the time at which it comes: the i-th visit will happen wi seconds after midnight, all wi's are distinct. Each visit lasts exactly one second.
What is the minimum number of candles Anya should use so that during each visit, at least r candles are burning? Anya can start to light a candle at any time that is integer number of seconds from midnight, possibly, at the time before midnight. That means, she can start to light a candle integer number of seconds before midnight or integer number of seconds after a midnight, or in other words in any integer moment of time.
Input
The first line contains three integers m, t, r (1 ≤ m, t, r ≤ 300), representing the number of ghosts to visit Anya, the duration of a candle's burning and the minimum number of candles that should burn during each visit.
The next line contains m space-separated numbers wi (1 ≤ i ≤ m, 1 ≤ wi ≤ 300), the i-th of them repesents at what second after the midnight the i-th ghost will come. All wi's are distinct, they follow in the strictly increasing order.
Output
If it is possible to make at least r candles burn during each visit, then print the minimum number of candles that Anya needs to light for that.
If that is impossible, print - 1.
Examples
Input
1 8 3
10
Output
3
Input
2 10 1
5 8
Output
1
Input
1 1 3
10
Output
-1
Note
Anya can start lighting a candle in the same second with ghost visit. But this candle isn't counted as burning at this visit.
It takes exactly one second to light up a candle and only after that second this candle is considered burning; it means that if Anya starts lighting candle at moment x, candle is buring from second x + 1 to second x + t inclusively.
In the first sample test three candles are enough. For example, Anya can start lighting them at the 3-rd, 5-th and 7-th seconds after the midnight.
In the second sample test one candle is enough. For example, Anya can start lighting it one second before the midnight.
In the third sample test the answer is - 1, since during each second at most one candle can burn but Anya needs three candles to light up the room at the moment when the ghost comes.
Tags: constructive algorithms, greedy
Correct Solution:
```
m,t,r=input().split(' ')
m=int(m)
t=int(t)
r=int(r)
if t<r:
input()
need=-1
else:
candles=[]
need=r
ghosts=input().split(' ')
for i in range(r):
candles.append(t-i)
for i in range(len(ghosts)-1):
dead=[]
diff=int(ghosts[i+1])-int(ghosts[i])
for j in range(len(candles)):
candles[j]=max(candles[j]-diff,0)
if candles[j] is 0:
dead.append(candles[j])
for candle in dead:
candles.remove(0)
need+=r-len(candles)
for k in range(r-len(candles)):
candles.append(t-k)
print(need)
```
| 93,900 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anya loves to watch horror movies. In the best traditions of horror, she will be visited by m ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly t seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one candle, then this candle burns for exactly t seconds and then goes out and can no longer be used.
For each of the m ghosts Anya knows the time at which it comes: the i-th visit will happen wi seconds after midnight, all wi's are distinct. Each visit lasts exactly one second.
What is the minimum number of candles Anya should use so that during each visit, at least r candles are burning? Anya can start to light a candle at any time that is integer number of seconds from midnight, possibly, at the time before midnight. That means, she can start to light a candle integer number of seconds before midnight or integer number of seconds after a midnight, or in other words in any integer moment of time.
Input
The first line contains three integers m, t, r (1 ≤ m, t, r ≤ 300), representing the number of ghosts to visit Anya, the duration of a candle's burning and the minimum number of candles that should burn during each visit.
The next line contains m space-separated numbers wi (1 ≤ i ≤ m, 1 ≤ wi ≤ 300), the i-th of them repesents at what second after the midnight the i-th ghost will come. All wi's are distinct, they follow in the strictly increasing order.
Output
If it is possible to make at least r candles burn during each visit, then print the minimum number of candles that Anya needs to light for that.
If that is impossible, print - 1.
Examples
Input
1 8 3
10
Output
3
Input
2 10 1
5 8
Output
1
Input
1 1 3
10
Output
-1
Note
Anya can start lighting a candle in the same second with ghost visit. But this candle isn't counted as burning at this visit.
It takes exactly one second to light up a candle and only after that second this candle is considered burning; it means that if Anya starts lighting candle at moment x, candle is buring from second x + 1 to second x + t inclusively.
In the first sample test three candles are enough. For example, Anya can start lighting them at the 3-rd, 5-th and 7-th seconds after the midnight.
In the second sample test one candle is enough. For example, Anya can start lighting it one second before the midnight.
In the third sample test the answer is - 1, since during each second at most one candle can burn but Anya needs three candles to light up the room at the moment when the ghost comes.
Tags: constructive algorithms, greedy
Correct Solution:
```
import math
import sys
debug = False
if debug:
fin = open('input.txt', 'r')
fout = open('output.txt', 'w')
else:
fin = sys.stdin
fout = sys.stdout
s = fin.readline()
m, t, r = list(map(int, s.split()))
if r > t:
fout.write('-1')
exit()
s = fin.readline()
w = list(map(int, s.split()))
ans = r
ar = [w[0] - r + i for i in range(r)]
for i in range(1, m):
while ar and w[i] - ar[0] > t:
ar.pop(0)
ans += r - len(ar)
b = r - len(ar)
for j in range(b):
ar.append(w[i] - b + j)
fout.write(str(ans))
```
| 93,901 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anya loves to watch horror movies. In the best traditions of horror, she will be visited by m ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly t seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one candle, then this candle burns for exactly t seconds and then goes out and can no longer be used.
For each of the m ghosts Anya knows the time at which it comes: the i-th visit will happen wi seconds after midnight, all wi's are distinct. Each visit lasts exactly one second.
What is the minimum number of candles Anya should use so that during each visit, at least r candles are burning? Anya can start to light a candle at any time that is integer number of seconds from midnight, possibly, at the time before midnight. That means, she can start to light a candle integer number of seconds before midnight or integer number of seconds after a midnight, or in other words in any integer moment of time.
Input
The first line contains three integers m, t, r (1 ≤ m, t, r ≤ 300), representing the number of ghosts to visit Anya, the duration of a candle's burning and the minimum number of candles that should burn during each visit.
The next line contains m space-separated numbers wi (1 ≤ i ≤ m, 1 ≤ wi ≤ 300), the i-th of them repesents at what second after the midnight the i-th ghost will come. All wi's are distinct, they follow in the strictly increasing order.
Output
If it is possible to make at least r candles burn during each visit, then print the minimum number of candles that Anya needs to light for that.
If that is impossible, print - 1.
Examples
Input
1 8 3
10
Output
3
Input
2 10 1
5 8
Output
1
Input
1 1 3
10
Output
-1
Note
Anya can start lighting a candle in the same second with ghost visit. But this candle isn't counted as burning at this visit.
It takes exactly one second to light up a candle and only after that second this candle is considered burning; it means that if Anya starts lighting candle at moment x, candle is buring from second x + 1 to second x + t inclusively.
In the first sample test three candles are enough. For example, Anya can start lighting them at the 3-rd, 5-th and 7-th seconds after the midnight.
In the second sample test one candle is enough. For example, Anya can start lighting it one second before the midnight.
In the third sample test the answer is - 1, since during each second at most one candle can burn but Anya needs three candles to light up the room at the moment when the ghost comes.
Tags: constructive algorithms, greedy
Correct Solution:
```
# import itertools
# import bisect
# import math
from collections import defaultdict, Counter, deque
import os
import sys
from io import BytesIO, IOBase
# sys.setrecursionlimit(10 ** 5)
ii = lambda: int(input())
lmii = lambda: list(map(int, input().split()))
slmii = lambda: sorted(map(int, input().split()))
li = lambda: list(input())
mii = lambda: map(int, input().split())
msi = lambda: map(str, input().split())
def gcd(a, b):
if b == 0: return a
return gcd(b, a % b)
def lcm(a, b): return (a * b) // gcd(a, b)
def main():
# for _ in " " * int(input()):
m, t, r = mii()
w = lmii()
cnt = 0
if t < r:
print(-1)
else:
cul = []
for i in range(m):
n = 0
for j in cul:
if w[i] - j <= t:
n += 1
for j in range(r-n):
cul.append(w[i]-1-j)
cnt += 1
print(cnt)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
```
| 93,902 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anya loves to watch horror movies. In the best traditions of horror, she will be visited by m ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly t seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one candle, then this candle burns for exactly t seconds and then goes out and can no longer be used.
For each of the m ghosts Anya knows the time at which it comes: the i-th visit will happen wi seconds after midnight, all wi's are distinct. Each visit lasts exactly one second.
What is the minimum number of candles Anya should use so that during each visit, at least r candles are burning? Anya can start to light a candle at any time that is integer number of seconds from midnight, possibly, at the time before midnight. That means, she can start to light a candle integer number of seconds before midnight or integer number of seconds after a midnight, or in other words in any integer moment of time.
Input
The first line contains three integers m, t, r (1 ≤ m, t, r ≤ 300), representing the number of ghosts to visit Anya, the duration of a candle's burning and the minimum number of candles that should burn during each visit.
The next line contains m space-separated numbers wi (1 ≤ i ≤ m, 1 ≤ wi ≤ 300), the i-th of them repesents at what second after the midnight the i-th ghost will come. All wi's are distinct, they follow in the strictly increasing order.
Output
If it is possible to make at least r candles burn during each visit, then print the minimum number of candles that Anya needs to light for that.
If that is impossible, print - 1.
Examples
Input
1 8 3
10
Output
3
Input
2 10 1
5 8
Output
1
Input
1 1 3
10
Output
-1
Note
Anya can start lighting a candle in the same second with ghost visit. But this candle isn't counted as burning at this visit.
It takes exactly one second to light up a candle and only after that second this candle is considered burning; it means that if Anya starts lighting candle at moment x, candle is buring from second x + 1 to second x + t inclusively.
In the first sample test three candles are enough. For example, Anya can start lighting them at the 3-rd, 5-th and 7-th seconds after the midnight.
In the second sample test one candle is enough. For example, Anya can start lighting it one second before the midnight.
In the third sample test the answer is - 1, since during each second at most one candle can burn but Anya needs three candles to light up the room at the moment when the ghost comes.
Tags: constructive algorithms, greedy
Correct Solution:
```
a,b,c = map(int,input().split())
t=sorted(map(int,input().split()),reverse=True)
if c>b:
print('-1')
else:
q=[False]*600
for k in t:
k=k-b
for j in range(k,k+c-sum(q[i] for i in range(k,k+b))):
q[j]=True
print(sum(q))
```
| 93,903 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anya loves to watch horror movies. In the best traditions of horror, she will be visited by m ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly t seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one candle, then this candle burns for exactly t seconds and then goes out and can no longer be used.
For each of the m ghosts Anya knows the time at which it comes: the i-th visit will happen wi seconds after midnight, all wi's are distinct. Each visit lasts exactly one second.
What is the minimum number of candles Anya should use so that during each visit, at least r candles are burning? Anya can start to light a candle at any time that is integer number of seconds from midnight, possibly, at the time before midnight. That means, she can start to light a candle integer number of seconds before midnight or integer number of seconds after a midnight, or in other words in any integer moment of time.
Input
The first line contains three integers m, t, r (1 ≤ m, t, r ≤ 300), representing the number of ghosts to visit Anya, the duration of a candle's burning and the minimum number of candles that should burn during each visit.
The next line contains m space-separated numbers wi (1 ≤ i ≤ m, 1 ≤ wi ≤ 300), the i-th of them repesents at what second after the midnight the i-th ghost will come. All wi's are distinct, they follow in the strictly increasing order.
Output
If it is possible to make at least r candles burn during each visit, then print the minimum number of candles that Anya needs to light for that.
If that is impossible, print - 1.
Examples
Input
1 8 3
10
Output
3
Input
2 10 1
5 8
Output
1
Input
1 1 3
10
Output
-1
Note
Anya can start lighting a candle in the same second with ghost visit. But this candle isn't counted as burning at this visit.
It takes exactly one second to light up a candle and only after that second this candle is considered burning; it means that if Anya starts lighting candle at moment x, candle is buring from second x + 1 to second x + t inclusively.
In the first sample test three candles are enough. For example, Anya can start lighting them at the 3-rd, 5-th and 7-th seconds after the midnight.
In the second sample test one candle is enough. For example, Anya can start lighting it one second before the midnight.
In the third sample test the answer is - 1, since during each second at most one candle can burn but Anya needs three candles to light up the room at the moment when the ghost comes.
Tags: constructive algorithms, greedy
Correct Solution:
```
import sys
import math
m, t, r = map(int, input().split())
if r > t:
print(-1)
exit()
candles = []
gh = list(map(int, input().split()))
for i in range(m):
g = gh[i]
now_on = 0
for c in candles:
if g - c <= t:
now_on += 1
for k in range(r - now_on):
candles.append(g - 1 - k)
print(len(candles))
```
| 93,904 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anya loves to watch horror movies. In the best traditions of horror, she will be visited by m ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly t seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one candle, then this candle burns for exactly t seconds and then goes out and can no longer be used.
For each of the m ghosts Anya knows the time at which it comes: the i-th visit will happen wi seconds after midnight, all wi's are distinct. Each visit lasts exactly one second.
What is the minimum number of candles Anya should use so that during each visit, at least r candles are burning? Anya can start to light a candle at any time that is integer number of seconds from midnight, possibly, at the time before midnight. That means, she can start to light a candle integer number of seconds before midnight or integer number of seconds after a midnight, or in other words in any integer moment of time.
Input
The first line contains three integers m, t, r (1 ≤ m, t, r ≤ 300), representing the number of ghosts to visit Anya, the duration of a candle's burning and the minimum number of candles that should burn during each visit.
The next line contains m space-separated numbers wi (1 ≤ i ≤ m, 1 ≤ wi ≤ 300), the i-th of them repesents at what second after the midnight the i-th ghost will come. All wi's are distinct, they follow in the strictly increasing order.
Output
If it is possible to make at least r candles burn during each visit, then print the minimum number of candles that Anya needs to light for that.
If that is impossible, print - 1.
Examples
Input
1 8 3
10
Output
3
Input
2 10 1
5 8
Output
1
Input
1 1 3
10
Output
-1
Note
Anya can start lighting a candle in the same second with ghost visit. But this candle isn't counted as burning at this visit.
It takes exactly one second to light up a candle and only after that second this candle is considered burning; it means that if Anya starts lighting candle at moment x, candle is buring from second x + 1 to second x + t inclusively.
In the first sample test three candles are enough. For example, Anya can start lighting them at the 3-rd, 5-th and 7-th seconds after the midnight.
In the second sample test one candle is enough. For example, Anya can start lighting it one second before the midnight.
In the third sample test the answer is - 1, since during each second at most one candle can burn but Anya needs three candles to light up the room at the moment when the ghost comes.
Submitted Solution:
```
M,T,R = [int(x) for x in input().split()]
W = [int(x) for x in input().split()]
W.sort()
if T<R:
print(-1)
exit()
candle_cnt = 0
candles_num = [0 for i in range(601)]
for w in W:
for i in range(R):
if candles_num[w]<R:
for j in range(w-i,w-i+T):
candles_num[j] += 1
candle_cnt += 1
else:
break
print(candle_cnt)
```
Yes
| 93,905 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anya loves to watch horror movies. In the best traditions of horror, she will be visited by m ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly t seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one candle, then this candle burns for exactly t seconds and then goes out and can no longer be used.
For each of the m ghosts Anya knows the time at which it comes: the i-th visit will happen wi seconds after midnight, all wi's are distinct. Each visit lasts exactly one second.
What is the minimum number of candles Anya should use so that during each visit, at least r candles are burning? Anya can start to light a candle at any time that is integer number of seconds from midnight, possibly, at the time before midnight. That means, she can start to light a candle integer number of seconds before midnight or integer number of seconds after a midnight, or in other words in any integer moment of time.
Input
The first line contains three integers m, t, r (1 ≤ m, t, r ≤ 300), representing the number of ghosts to visit Anya, the duration of a candle's burning and the minimum number of candles that should burn during each visit.
The next line contains m space-separated numbers wi (1 ≤ i ≤ m, 1 ≤ wi ≤ 300), the i-th of them repesents at what second after the midnight the i-th ghost will come. All wi's are distinct, they follow in the strictly increasing order.
Output
If it is possible to make at least r candles burn during each visit, then print the minimum number of candles that Anya needs to light for that.
If that is impossible, print - 1.
Examples
Input
1 8 3
10
Output
3
Input
2 10 1
5 8
Output
1
Input
1 1 3
10
Output
-1
Note
Anya can start lighting a candle in the same second with ghost visit. But this candle isn't counted as burning at this visit.
It takes exactly one second to light up a candle and only after that second this candle is considered burning; it means that if Anya starts lighting candle at moment x, candle is buring from second x + 1 to second x + t inclusively.
In the first sample test three candles are enough. For example, Anya can start lighting them at the 3-rd, 5-th and 7-th seconds after the midnight.
In the second sample test one candle is enough. For example, Anya can start lighting it one second before the midnight.
In the third sample test the answer is - 1, since during each second at most one candle can burn but Anya needs three candles to light up the room at the moment when the ghost comes.
Submitted Solution:
```
m, t, r = map(int,input().split())
a = list(map(int,input().split()))
a.sort(reverse = True)
if r > t:
print(-1)
exit(0)
burn = [0] * 1000
for i in a:
l = i
l -= t
for j in range(l, l + r - sum(burn[k] for k in range(l, l + t))):
burn[j] = 1
print(sum(burn))
```
Yes
| 93,906 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anya loves to watch horror movies. In the best traditions of horror, she will be visited by m ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly t seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one candle, then this candle burns for exactly t seconds and then goes out and can no longer be used.
For each of the m ghosts Anya knows the time at which it comes: the i-th visit will happen wi seconds after midnight, all wi's are distinct. Each visit lasts exactly one second.
What is the minimum number of candles Anya should use so that during each visit, at least r candles are burning? Anya can start to light a candle at any time that is integer number of seconds from midnight, possibly, at the time before midnight. That means, she can start to light a candle integer number of seconds before midnight or integer number of seconds after a midnight, or in other words in any integer moment of time.
Input
The first line contains three integers m, t, r (1 ≤ m, t, r ≤ 300), representing the number of ghosts to visit Anya, the duration of a candle's burning and the minimum number of candles that should burn during each visit.
The next line contains m space-separated numbers wi (1 ≤ i ≤ m, 1 ≤ wi ≤ 300), the i-th of them repesents at what second after the midnight the i-th ghost will come. All wi's are distinct, they follow in the strictly increasing order.
Output
If it is possible to make at least r candles burn during each visit, then print the minimum number of candles that Anya needs to light for that.
If that is impossible, print - 1.
Examples
Input
1 8 3
10
Output
3
Input
2 10 1
5 8
Output
1
Input
1 1 3
10
Output
-1
Note
Anya can start lighting a candle in the same second with ghost visit. But this candle isn't counted as burning at this visit.
It takes exactly one second to light up a candle and only after that second this candle is considered burning; it means that if Anya starts lighting candle at moment x, candle is buring from second x + 1 to second x + t inclusively.
In the first sample test three candles are enough. For example, Anya can start lighting them at the 3-rd, 5-th and 7-th seconds after the midnight.
In the second sample test one candle is enough. For example, Anya can start lighting it one second before the midnight.
In the third sample test the answer is - 1, since during each second at most one candle can burn but Anya needs three candles to light up the room at the moment when the ghost comes.
Submitted Solution:
```
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
# from fractions import *
# from heapq import*
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz/'
M=998244353
EPS=1e-6
def Ceil(a,b): return a//b+int(a%b>0)
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
# vsInput()
m,t,need=value()
a=array()
have=[i+t-1 for i in range(a[0]-need+1,a[0]+1)]
# print(have)
for i in a:
ind=len(have)-bisect_left(have,i)
# print(i,ind,i-need+ind+1,have)
for j in range(i-need+ind+1,i+1):
have.append(j+t-1)
if(t<need): print(-1)
else: print(len(have))
# print(have)
```
Yes
| 93,907 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anya loves to watch horror movies. In the best traditions of horror, she will be visited by m ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly t seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one candle, then this candle burns for exactly t seconds and then goes out and can no longer be used.
For each of the m ghosts Anya knows the time at which it comes: the i-th visit will happen wi seconds after midnight, all wi's are distinct. Each visit lasts exactly one second.
What is the minimum number of candles Anya should use so that during each visit, at least r candles are burning? Anya can start to light a candle at any time that is integer number of seconds from midnight, possibly, at the time before midnight. That means, she can start to light a candle integer number of seconds before midnight or integer number of seconds after a midnight, or in other words in any integer moment of time.
Input
The first line contains three integers m, t, r (1 ≤ m, t, r ≤ 300), representing the number of ghosts to visit Anya, the duration of a candle's burning and the minimum number of candles that should burn during each visit.
The next line contains m space-separated numbers wi (1 ≤ i ≤ m, 1 ≤ wi ≤ 300), the i-th of them repesents at what second after the midnight the i-th ghost will come. All wi's are distinct, they follow in the strictly increasing order.
Output
If it is possible to make at least r candles burn during each visit, then print the minimum number of candles that Anya needs to light for that.
If that is impossible, print - 1.
Examples
Input
1 8 3
10
Output
3
Input
2 10 1
5 8
Output
1
Input
1 1 3
10
Output
-1
Note
Anya can start lighting a candle in the same second with ghost visit. But this candle isn't counted as burning at this visit.
It takes exactly one second to light up a candle and only after that second this candle is considered burning; it means that if Anya starts lighting candle at moment x, candle is buring from second x + 1 to second x + t inclusively.
In the first sample test three candles are enough. For example, Anya can start lighting them at the 3-rd, 5-th and 7-th seconds after the midnight.
In the second sample test one candle is enough. For example, Anya can start lighting it one second before the midnight.
In the third sample test the answer is - 1, since during each second at most one candle can burn but Anya needs three candles to light up the room at the moment when the ghost comes.
Submitted Solution:
```
#!/bin/python3
import os
import sys
from io import BytesIO, IOBase
import math
def main():
m, t, r = map(int, input().split())
w = list(map(int, input().split()))
if r > t:
print(-1)
else:
candles = []
ans = 0
for time in w:
while candles and candles[0] + t - 1 < time:
candles.pop(0)
requirement = r - len(candles)
for i in range(requirement):
candles.append(time - (requirement - 1) + i)
ans += 1
print(ans)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
def input(): return sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
```
Yes
| 93,908 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anya loves to watch horror movies. In the best traditions of horror, she will be visited by m ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly t seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one candle, then this candle burns for exactly t seconds and then goes out and can no longer be used.
For each of the m ghosts Anya knows the time at which it comes: the i-th visit will happen wi seconds after midnight, all wi's are distinct. Each visit lasts exactly one second.
What is the minimum number of candles Anya should use so that during each visit, at least r candles are burning? Anya can start to light a candle at any time that is integer number of seconds from midnight, possibly, at the time before midnight. That means, she can start to light a candle integer number of seconds before midnight or integer number of seconds after a midnight, or in other words in any integer moment of time.
Input
The first line contains three integers m, t, r (1 ≤ m, t, r ≤ 300), representing the number of ghosts to visit Anya, the duration of a candle's burning and the minimum number of candles that should burn during each visit.
The next line contains m space-separated numbers wi (1 ≤ i ≤ m, 1 ≤ wi ≤ 300), the i-th of them repesents at what second after the midnight the i-th ghost will come. All wi's are distinct, they follow in the strictly increasing order.
Output
If it is possible to make at least r candles burn during each visit, then print the minimum number of candles that Anya needs to light for that.
If that is impossible, print - 1.
Examples
Input
1 8 3
10
Output
3
Input
2 10 1
5 8
Output
1
Input
1 1 3
10
Output
-1
Note
Anya can start lighting a candle in the same second with ghost visit. But this candle isn't counted as burning at this visit.
It takes exactly one second to light up a candle and only after that second this candle is considered burning; it means that if Anya starts lighting candle at moment x, candle is buring from second x + 1 to second x + t inclusively.
In the first sample test three candles are enough. For example, Anya can start lighting them at the 3-rd, 5-th and 7-th seconds after the midnight.
In the second sample test one candle is enough. For example, Anya can start lighting it one second before the midnight.
In the third sample test the answer is - 1, since during each second at most one candle can burn but Anya needs three candles to light up the room at the moment when the ghost comes.
Submitted Solution:
```
def fun(m,t,r,ghost_time):
last_ghost = ghost_time[len(ghost_time)-1]
arr=[0]* last_ghost
sets = set()
x=0
i=0
dic={}
candles=0
g_arr=[0]*last_ghost
for i in range(last_ghost):
if i == ghost_time[x]-1:
g_arr[i]=i
x+=1
x=0
while i < last_ghost and x<m:
if i == ghost_time[x]-1:
j=0
y=i-1
while j < r:
arr[y]=y+t
y-=1
j+=1
i+=1
x+=1
continue
i+=1
i=0
x=0
start=0
while i < last_ghost:
if i!=0 and i == g_arr[i]:
y = i-r
candles+=r
start = y+t
i
if start <i:
return -1
i=start
continue
i+=1
# for i in range(last_ghost):
# if arr[i]==1 :
# dic[i]=i+t
# x=0
# last = 0
# while x < len(ghost_time):
# index = ghost_time[x]-1
# y=0
# for k in dic.keys():
# if dic[k] >= index:
# sets.add(k)
# y+=1
# if y == r:
# break
# x+=1
return candles
# def fun1(st):
# le = len(st)
# stack = [0]*le
# i=0
# x=0
# sh = 0
# h=0
# ans=list(st)
# while i < len(ans):
# if ans[i]=='#' :
# stack[i]=stack[i-1]
# i+=1
# continue
# if i > 0 and ans[i] == ans[i-1]:
# stack[i]=(stack[i-1]+1)
# else:
# stack[i] =0
# if i < len(ans)-1 and (ans[i] != ans[i+1]) or i == len(ans)-1:
# p=0
# if i < le and stack[i]==0:
# ans[i]=ans[i]
# elif i > 2 and stack[i] == 1 and stack[i-2] == 1:
# ans[i]='#'
# h=1
# sh=0
# i-=2
# elif stack[i] != 1:
# h=i
# x=i
# while stack[x-1]!=0:
# ans[x]='#'
# x-=1
# i = x-3
# i+=1
# return ''.join(c for c in ans if c!='#')
var1, var2,var3 = [int(x) for x in input().split()]
user_input = input().split(' ')
numbers = [int(x.strip()) for x in user_input]
# st = input()
# print(fun(st))
print(fun(var1,var2,var3,numbers))
# # st = input()
# var1, var2 = [int(x) for x in input().split()]
# # # fun(st,var1,var2)
# # # var2 = input()
# print(fun(var1,var2))
# ############################################################3###############################
# # user_input = input().split(' ')
# # numbers = [int(x.strip()) for x in user_input]
# # print(fun(numbers))
# ######################################################################################
```
No
| 93,909 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anya loves to watch horror movies. In the best traditions of horror, she will be visited by m ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly t seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one candle, then this candle burns for exactly t seconds and then goes out and can no longer be used.
For each of the m ghosts Anya knows the time at which it comes: the i-th visit will happen wi seconds after midnight, all wi's are distinct. Each visit lasts exactly one second.
What is the minimum number of candles Anya should use so that during each visit, at least r candles are burning? Anya can start to light a candle at any time that is integer number of seconds from midnight, possibly, at the time before midnight. That means, she can start to light a candle integer number of seconds before midnight or integer number of seconds after a midnight, or in other words in any integer moment of time.
Input
The first line contains three integers m, t, r (1 ≤ m, t, r ≤ 300), representing the number of ghosts to visit Anya, the duration of a candle's burning and the minimum number of candles that should burn during each visit.
The next line contains m space-separated numbers wi (1 ≤ i ≤ m, 1 ≤ wi ≤ 300), the i-th of them repesents at what second after the midnight the i-th ghost will come. All wi's are distinct, they follow in the strictly increasing order.
Output
If it is possible to make at least r candles burn during each visit, then print the minimum number of candles that Anya needs to light for that.
If that is impossible, print - 1.
Examples
Input
1 8 3
10
Output
3
Input
2 10 1
5 8
Output
1
Input
1 1 3
10
Output
-1
Note
Anya can start lighting a candle in the same second with ghost visit. But this candle isn't counted as burning at this visit.
It takes exactly one second to light up a candle and only after that second this candle is considered burning; it means that if Anya starts lighting candle at moment x, candle is buring from second x + 1 to second x + t inclusively.
In the first sample test three candles are enough. For example, Anya can start lighting them at the 3-rd, 5-th and 7-th seconds after the midnight.
In the second sample test one candle is enough. For example, Anya can start lighting it one second before the midnight.
In the third sample test the answer is - 1, since during each second at most one candle can burn but Anya needs three candles to light up the room at the moment when the ghost comes.
Submitted Solution:
```
__author__ = 'default'
def TaskC():
import sys
#fl = open('TaskC.txt','r')
m, t, r = list(map(int,input().split()))
rdl1 = list(map(int,input().split()))
used = 0
mas = [0]*r
if r+1 > t:
print(-1)
sys.exit()
for i in range(len(rdl1)):
if i == 0:
for j in range(len(mas)):
mas[j] = rdl1[0]-r+j+t
used += 1
else:
if rdl1[i]+1 < mas[0]:
pass
else:
for j in range(len(mas)):
if mas[j] <= rdl1[i]+1:
mas[j] = rdl1[i]-r+j+t
used += 1
else:
break
print(used)
TaskC()
```
No
| 93,910 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anya loves to watch horror movies. In the best traditions of horror, she will be visited by m ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly t seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one candle, then this candle burns for exactly t seconds and then goes out and can no longer be used.
For each of the m ghosts Anya knows the time at which it comes: the i-th visit will happen wi seconds after midnight, all wi's are distinct. Each visit lasts exactly one second.
What is the minimum number of candles Anya should use so that during each visit, at least r candles are burning? Anya can start to light a candle at any time that is integer number of seconds from midnight, possibly, at the time before midnight. That means, she can start to light a candle integer number of seconds before midnight or integer number of seconds after a midnight, or in other words in any integer moment of time.
Input
The first line contains three integers m, t, r (1 ≤ m, t, r ≤ 300), representing the number of ghosts to visit Anya, the duration of a candle's burning and the minimum number of candles that should burn during each visit.
The next line contains m space-separated numbers wi (1 ≤ i ≤ m, 1 ≤ wi ≤ 300), the i-th of them repesents at what second after the midnight the i-th ghost will come. All wi's are distinct, they follow in the strictly increasing order.
Output
If it is possible to make at least r candles burn during each visit, then print the minimum number of candles that Anya needs to light for that.
If that is impossible, print - 1.
Examples
Input
1 8 3
10
Output
3
Input
2 10 1
5 8
Output
1
Input
1 1 3
10
Output
-1
Note
Anya can start lighting a candle in the same second with ghost visit. But this candle isn't counted as burning at this visit.
It takes exactly one second to light up a candle and only after that second this candle is considered burning; it means that if Anya starts lighting candle at moment x, candle is buring from second x + 1 to second x + t inclusively.
In the first sample test three candles are enough. For example, Anya can start lighting them at the 3-rd, 5-th and 7-th seconds after the midnight.
In the second sample test one candle is enough. For example, Anya can start lighting it one second before the midnight.
In the third sample test the answer is - 1, since during each second at most one candle can burn but Anya needs three candles to light up the room at the moment when the ghost comes.
Submitted Solution:
```
raw=input().split()
time=input().split()
raw=[int(x) for x in raw]
time=[int(x) for x in time]
m=raw[0]
t=raw[1]
r=raw[2]
c=0
can=0
lt=None
if t<=r-1:
print("-1")
exit()
while c <m:
pt=time[c]
if c!=0:
de=pt-lt
if de>t:
can+=r
lt=pt
elif de >= t -(r-1)and de <=t:
lt=pt
te=r-1-(t-de)
if te > 0:
can+=te
else:
te*=-1
can+=te
else:
lt=pt
can+=r
c+=1
print(can)
```
No
| 93,911 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anya loves to watch horror movies. In the best traditions of horror, she will be visited by m ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly t seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one candle, then this candle burns for exactly t seconds and then goes out and can no longer be used.
For each of the m ghosts Anya knows the time at which it comes: the i-th visit will happen wi seconds after midnight, all wi's are distinct. Each visit lasts exactly one second.
What is the minimum number of candles Anya should use so that during each visit, at least r candles are burning? Anya can start to light a candle at any time that is integer number of seconds from midnight, possibly, at the time before midnight. That means, she can start to light a candle integer number of seconds before midnight or integer number of seconds after a midnight, or in other words in any integer moment of time.
Input
The first line contains three integers m, t, r (1 ≤ m, t, r ≤ 300), representing the number of ghosts to visit Anya, the duration of a candle's burning and the minimum number of candles that should burn during each visit.
The next line contains m space-separated numbers wi (1 ≤ i ≤ m, 1 ≤ wi ≤ 300), the i-th of them repesents at what second after the midnight the i-th ghost will come. All wi's are distinct, they follow in the strictly increasing order.
Output
If it is possible to make at least r candles burn during each visit, then print the minimum number of candles that Anya needs to light for that.
If that is impossible, print - 1.
Examples
Input
1 8 3
10
Output
3
Input
2 10 1
5 8
Output
1
Input
1 1 3
10
Output
-1
Note
Anya can start lighting a candle in the same second with ghost visit. But this candle isn't counted as burning at this visit.
It takes exactly one second to light up a candle and only after that second this candle is considered burning; it means that if Anya starts lighting candle at moment x, candle is buring from second x + 1 to second x + t inclusively.
In the first sample test three candles are enough. For example, Anya can start lighting them at the 3-rd, 5-th and 7-th seconds after the midnight.
In the second sample test one candle is enough. For example, Anya can start lighting it one second before the midnight.
In the third sample test the answer is - 1, since during each second at most one candle can burn but Anya needs three candles to light up the room at the moment when the ghost comes.
Submitted Solution:
```
m,t,r=map(int,input().split())
a=list(map(int,input().split()))
mini=r
ans=a[0]
start=a[0]-1
end=t
if t==1:
print(-1)
exit()
for i in range(1,len(a)):
if a[i]-start>t:
start=a[i]-1
mini+=r
elif a[i]-start==t:
mini+=r
start=a[i]
else:
pass
print(mini)
```
No
| 93,912 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After Vitaly was expelled from the university, he became interested in the graph theory.
Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once.
Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not necessarily connected, without parallel edges and loops. You need to find t — the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find w — the number of ways to add t edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges.
Two ways to add edges to the graph are considered equal if they have the same sets of added edges.
Since Vitaly does not study at the university, he asked you to help him with this task.
Input
The first line of the input contains two integers n and m (<image> — the number of vertices in the graph and the number of edges in the graph.
Next m lines contain the descriptions of the edges of the graph, one edge per line. Each edge is given by a pair of integers ai, bi (1 ≤ ai, bi ≤ n) — the vertices that are connected by the i-th edge. All numbers in the lines are separated by a single space.
It is guaranteed that the given graph doesn't contain any loops and parallel edges. The graph isn't necessarily connected.
Output
Print in the first line of the output two space-separated integers t and w — the minimum number of edges that should be added to the graph to form a simple cycle of an odd length consisting of more than one vertex where each vertex occurs at most once, and the number of ways to do this.
Examples
Input
4 4
1 2
1 3
4 2
4 3
Output
1 2
Input
3 3
1 2
2 3
3 1
Output
0 1
Input
3 0
Output
3 1
Note
The simple cycle is a cycle that doesn't contain any vertex twice.
Tags: combinatorics, dfs and similar, graphs, math
Correct Solution:
```
def connected_components(n, graph):
components, visited = [], [False] * n
def dfs(start):
component, stack = [], [start]
while stack:
start = stack[-1]
if visited[start]:
stack.pop()
continue
else:
visited[start] = True
component.append(start)
for i in graph[start]:
if not visited[i]:
stack.append(i)
return component
for i in range(n):
if not visited[i]:
components.append(dfs(i))
return components
# ------------------- fast io --------------------
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")
# ------------------- fast io --------------------
from math import gcd, ceil
def prod(a, mod=10**9+7):
ans = 1
for each in a:
ans = (ans * each) % mod
return ans
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
from collections import deque
def bfs(graph, n, alpha, used, color):
"""Breadth first search on a graph!"""
q = deque([alpha])
used[alpha] = True
z, o = 0, 0
while q:
v = q.popleft()
if color[v] == -1:
color[v] = 0
z += 1
for u in graph[v]:
if not used[u]:
used[u] = True
q.append(u)
if color[u] == color[v]:return False
if color[u] == -1:
if color[v] == 1:z+=1
else: o += 1
color[u] = (color[v] + 1) % 2
return (used, color, z, o)
def shortest_path(graph, alpha, omega):
"""Returns the shortest path between two vertices!"""
used, dist, parents = bfs(graph, alpha)
if not used[omega]:
return []
path = [omega]
v = omega
while parents[v] != -1:
path += [parents[v]]
v = parents[v]
return path[::-1]
for _ in range(int(input()) if not True else 1):
#n = int(input())
n, m = map(int, input().split())
#a, b = map(int, input().split())
#c, d = map(int, input().split())
#e, f = map(int, input().split())
graph = [[] for __ in range(n+1)]
ml = 0
for i in range(m):
x, y = map(int, input().split())
graph[x] += [y]
graph[y] += [x]
ml = max(ml, len(graph[x]), len(graph[y]))
if ml == 0:
print(3, (n*(n-1)*(n-2))//6)
continue
if ml == 1:
x=0
for i in graph:
if len(i) == 1:
x += 1
print(2, (x//2)*(n-2))
continue
# ans will be 1 if no odd cycle else 0
cn = connected_components(n+1, graph)
bipartite = True
ans = 0
used = [0]*(n+1)
color = [-1]*(n+1)
for i in range(1, len(cn)):
j = cn[i][0]
ooff = bfs(graph, n+1, j, used, color)
if not ooff:
bipartite = False
break
used, color, z, o = ooff
ans += (z*(z-1)) // 2 + (o*(o-1))//2
if not bipartite:
print(0, 1)
continue
# ans = 1
print(1, ans)
```
| 93,913 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After Vitaly was expelled from the university, he became interested in the graph theory.
Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once.
Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not necessarily connected, without parallel edges and loops. You need to find t — the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find w — the number of ways to add t edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges.
Two ways to add edges to the graph are considered equal if they have the same sets of added edges.
Since Vitaly does not study at the university, he asked you to help him with this task.
Input
The first line of the input contains two integers n and m (<image> — the number of vertices in the graph and the number of edges in the graph.
Next m lines contain the descriptions of the edges of the graph, one edge per line. Each edge is given by a pair of integers ai, bi (1 ≤ ai, bi ≤ n) — the vertices that are connected by the i-th edge. All numbers in the lines are separated by a single space.
It is guaranteed that the given graph doesn't contain any loops and parallel edges. The graph isn't necessarily connected.
Output
Print in the first line of the output two space-separated integers t and w — the minimum number of edges that should be added to the graph to form a simple cycle of an odd length consisting of more than one vertex where each vertex occurs at most once, and the number of ways to do this.
Examples
Input
4 4
1 2
1 3
4 2
4 3
Output
1 2
Input
3 3
1 2
2 3
3 1
Output
0 1
Input
3 0
Output
3 1
Note
The simple cycle is a cycle that doesn't contain any vertex twice.
Tags: combinatorics, dfs and similar, graphs, math
Correct Solution:
```
import sys
import threading
threading.stack_size(67108864)
sys.setrecursionlimit(100500)
def nc2(k):
return k * (k - 1) // 2
def solve():
def dfs(u):
comp[u] = n_comp
for v in g[u]:
if color[v] == 0:
color[v] = 3 - color[u]
dfs(v)
elif color[u] == color[v]:
return True
return False
def check(g, color, n):
for v in range(1, n + 1):
for u in g[v]:
if color[u] == color[v]:
return False
return True
n, m = map(int, input().split())
g = dict()
for i in range(1, n + 1):
g[i] = set()
for i in range(m):
a, b = map(int, input().split())
g[a].add(b)
g[b].add(a)
color = [0] * (n + 1)
comp = [0] * (n + 1)
n_comp = 0
for u in range(1, n + 1):
if color[u] == 0:
n_comp += 1
color[u] = 1
if dfs(u):
print(0, 1)
return
if not check(g, color, n):
print(0, 1)
return
counts = [0] * (n_comp + 1)
counts_1 = [0] * (n_comp + 1)
counts_2 = [0] * (n_comp + 1)
for i in range(1, n + 1):
counts[comp[i]] += 1
if color[i] == 1:
counts_1[comp[i]] += 1
else:
counts_2[comp[i]] += 1
c = max(counts)
if c == 1:
print(3, n * (n - 1) * (n - 2) // 6)
elif c == 2:
print(2, m * (n - 2))
elif c >= 3:
ans = 0
for i in range(1, n_comp + 1):
if counts[i] >= 3:
ans += nc2(counts_1[i]) + nc2(counts_2[i])
print(1, ans)
thread = threading.Thread(target=solve)
thread.start()
```
| 93,914 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After Vitaly was expelled from the university, he became interested in the graph theory.
Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once.
Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not necessarily connected, without parallel edges and loops. You need to find t — the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find w — the number of ways to add t edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges.
Two ways to add edges to the graph are considered equal if they have the same sets of added edges.
Since Vitaly does not study at the university, he asked you to help him with this task.
Input
The first line of the input contains two integers n and m (<image> — the number of vertices in the graph and the number of edges in the graph.
Next m lines contain the descriptions of the edges of the graph, one edge per line. Each edge is given by a pair of integers ai, bi (1 ≤ ai, bi ≤ n) — the vertices that are connected by the i-th edge. All numbers in the lines are separated by a single space.
It is guaranteed that the given graph doesn't contain any loops and parallel edges. The graph isn't necessarily connected.
Output
Print in the first line of the output two space-separated integers t and w — the minimum number of edges that should be added to the graph to form a simple cycle of an odd length consisting of more than one vertex where each vertex occurs at most once, and the number of ways to do this.
Examples
Input
4 4
1 2
1 3
4 2
4 3
Output
1 2
Input
3 3
1 2
2 3
3 1
Output
0 1
Input
3 0
Output
3 1
Note
The simple cycle is a cycle that doesn't contain any vertex twice.
Tags: combinatorics, dfs and similar, graphs, math
Correct Solution:
```
# 解説AC
# 二部グラフでないグラフの性質や,パスの長さを考察する
def main():
N, M = (int(i) for i in input().split())
par = [i for i in range(N)]
size = [1 for i in range(N)]
def find(x):
if par[x] == x:
return x
else:
par[x] = find(par[x])
size[x] = size[par[x]]
return par[x]
def same(x, y):
return find(x) == find(y)
def union(x, y):
x = find(x)
y = find(y)
if x == y:
return
if size[x] < size[y]:
x, y = y, x
size[x] += size[y]
par[y] = x
def get_size(x):
return size[find(x)]
G = [[] for _ in range(N)]
for _ in range(M):
a, b = (int(i) for i in input().split())
G[a-1].append(b-1)
G[b-1].append(a-1)
union(a-1, b-1)
S = [False]*4
for i in range(N):
S[min(3, get_size(i))] = True
if S[3]:
break
t = 0
if S[3]:
t = 1
elif S[2]:
t = 2
else:
t = 3
color = [-1]*N
def dfs(s):
stack = [s]
color[s] = 0
b = 1
w = 0
while stack:
v = stack.pop()
for u in G[v]:
if color[u] != -1:
if color[u] == color[v]:
return False, b*w
continue
color[u] = color[v] ^ 1
if color[u] == 0:
b += 1
else:
w += 1
stack.append(u)
return True, b*(b-1)//2 + w*(w-1)//2
is_bipartite, _ = dfs(0)
if is_bipartite:
w = 0
if t == 3:
w = N*(N-1)*(N-2)//3//2
elif t == 2:
used = [False]*N
for i in range(N):
if not used[find(i)] and get_size(i) == 2:
w += (N-2)
used[find(i)] = True
elif t == 1:
used = [False]*N
color = [-1]*N
for i in range(N):
if not used[find(i)] and get_size(i) >= 3:
_, ways = dfs(i)
w += ways
used[find(i)] = True
print(t, w)
else:
print(0, 1)
if __name__ == '__main__':
main()
```
| 93,915 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After Vitaly was expelled from the university, he became interested in the graph theory.
Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once.
Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not necessarily connected, without parallel edges and loops. You need to find t — the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find w — the number of ways to add t edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges.
Two ways to add edges to the graph are considered equal if they have the same sets of added edges.
Since Vitaly does not study at the university, he asked you to help him with this task.
Input
The first line of the input contains two integers n and m (<image> — the number of vertices in the graph and the number of edges in the graph.
Next m lines contain the descriptions of the edges of the graph, one edge per line. Each edge is given by a pair of integers ai, bi (1 ≤ ai, bi ≤ n) — the vertices that are connected by the i-th edge. All numbers in the lines are separated by a single space.
It is guaranteed that the given graph doesn't contain any loops and parallel edges. The graph isn't necessarily connected.
Output
Print in the first line of the output two space-separated integers t and w — the minimum number of edges that should be added to the graph to form a simple cycle of an odd length consisting of more than one vertex where each vertex occurs at most once, and the number of ways to do this.
Examples
Input
4 4
1 2
1 3
4 2
4 3
Output
1 2
Input
3 3
1 2
2 3
3 1
Output
0 1
Input
3 0
Output
3 1
Note
The simple cycle is a cycle that doesn't contain any vertex twice.
Tags: combinatorics, dfs and similar, graphs, math
Correct Solution:
```
"""
#If FastIO not needed, use 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
import time
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, Counter as dc
import math, string
start_time = time.time()
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())
def getMat(n):
return [getInts() for _ in range(n)]
MOD = 998244353
#MOD = 10**9+7
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
"""
Scenarios:
0) no edges, answer is (3,N choose 3)
1) already have an odd cycle: answer is (0,1)
2) no odd cycle, but a connected component of at least size 3: answer is (1,W), where W is the number of paths of length 2
number of paths of length 2 = sum(x*(x-1)//2) where x is the degree of each vertex
3) no odd cycle, no component of size 3 or more, some isolated edges: answer is (2,M*(N-2))
How to count odd cycles
"""
def solve():
N, M = getInts()
#case 0
if not M:
print(3,N*(N-1)*(N-2)//6)
return
graph = dd(set)
for m in range(M):
A, B = getInts()
A -= 1
B -= 1
graph[A].add(B)
graph[B].add(A)
parent = [-1]*N
levels = [-1]*N
edges = set()
global flag
flag = False
@bootstrap
def dfs(node,level):
global flag
global odds
global evens
levels[node] = level
if level: odds += 1
else: evens += 1
visited.add(node)
nodes.remove(node)
for neigh in graph[node]:
if neigh in visited and neigh != parent[node] and levels[neigh] == level:
flag = True
if neigh not in visited:
parent[neigh] = node
yield dfs(neigh,level^1)
yield
ans = 0
nodes = set(list(range(N)))
while nodes:
node = next(iter(nodes))
visited = set()
global odds
odds = 0
global evens
evens = 0
dfs(node,0)
ans += odds*(odds-1)//2 + evens*(evens-1)//2
if flag:
print(0,1)
return
if ans:
print(1,ans)
return
if edges:
print(1,len(edges))
return
print(2,M*(N-2))
return
#for _ in range(getInt()):
solve()
#solve()
#print(time.time()-start_time)
```
| 93,916 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After Vitaly was expelled from the university, he became interested in the graph theory.
Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once.
Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not necessarily connected, without parallel edges and loops. You need to find t — the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find w — the number of ways to add t edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges.
Two ways to add edges to the graph are considered equal if they have the same sets of added edges.
Since Vitaly does not study at the university, he asked you to help him with this task.
Input
The first line of the input contains two integers n and m (<image> — the number of vertices in the graph and the number of edges in the graph.
Next m lines contain the descriptions of the edges of the graph, one edge per line. Each edge is given by a pair of integers ai, bi (1 ≤ ai, bi ≤ n) — the vertices that are connected by the i-th edge. All numbers in the lines are separated by a single space.
It is guaranteed that the given graph doesn't contain any loops and parallel edges. The graph isn't necessarily connected.
Output
Print in the first line of the output two space-separated integers t and w — the minimum number of edges that should be added to the graph to form a simple cycle of an odd length consisting of more than one vertex where each vertex occurs at most once, and the number of ways to do this.
Examples
Input
4 4
1 2
1 3
4 2
4 3
Output
1 2
Input
3 3
1 2
2 3
3 1
Output
0 1
Input
3 0
Output
3 1
Note
The simple cycle is a cycle that doesn't contain any vertex twice.
Tags: combinatorics, dfs and similar, graphs, math
Correct Solution:
```
def main():
N, M = (int(i) for i in input().split())
par = [i for i in range(N)]
size = [1 for i in range(N)]
def find(x):
if par[x] == x:
return x
else:
par[x] = find(par[x])
size[x] = size[par[x]]
return par[x]
def same(x, y):
return find(x) == find(y)
def union(x, y):
x = find(x)
y = find(y)
if x == y:
return
if size[x] < size[y]:
x, y = y, x
size[x] += size[y]
par[y] = x
def get_size(x):
return size[find(x)]
G = [[] for _ in range(N)]
for _ in range(M):
a, b = (int(i) for i in input().split())
G[a-1].append(b-1)
G[b-1].append(a-1)
union(a-1, b-1)
S = [False]*4
for i in range(N):
S[min(3, get_size(i))] = True
if S[3]:
break
t = 0
if S[3]:
t = 1
elif S[2]:
t = 2
else:
t = 3
color = [-1]*N
def dfs(s):
stack = [s]
color[s] = 0
b = 1
w = 0
while stack:
v = stack.pop()
for u in G[v]:
if color[u] != -1:
if color[u] == color[v]:
return False, b*w
continue
color[u] = color[v] ^ 1
if color[u] == 0:
b += 1
else:
w += 1
stack.append(u)
return True, b*(b-1)//2 + w*(w-1)//2
is_bipartite, _ = dfs(0)
if is_bipartite:
w = 0
if t == 3:
w = N*(N-1)*(N-2)//3//2
elif t == 2:
used = [False]*N
for i in range(N):
if not used[find(i)] and get_size(i) == 2:
w += (N-2)
used[find(i)] = True
elif t == 1:
used = [False]*N
color = [-1]*N
for i in range(N):
if not used[find(i)] and get_size(i) >= 3:
_, ways = dfs(i)
w += ways
used[find(i)] = True
print(t, w)
else:
print(0, 1)
if __name__ == '__main__':
main()
```
| 93,917 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After Vitaly was expelled from the university, he became interested in the graph theory.
Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once.
Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not necessarily connected, without parallel edges and loops. You need to find t — the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find w — the number of ways to add t edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges.
Two ways to add edges to the graph are considered equal if they have the same sets of added edges.
Since Vitaly does not study at the university, he asked you to help him with this task.
Input
The first line of the input contains two integers n and m (<image> — the number of vertices in the graph and the number of edges in the graph.
Next m lines contain the descriptions of the edges of the graph, one edge per line. Each edge is given by a pair of integers ai, bi (1 ≤ ai, bi ≤ n) — the vertices that are connected by the i-th edge. All numbers in the lines are separated by a single space.
It is guaranteed that the given graph doesn't contain any loops and parallel edges. The graph isn't necessarily connected.
Output
Print in the first line of the output two space-separated integers t and w — the minimum number of edges that should be added to the graph to form a simple cycle of an odd length consisting of more than one vertex where each vertex occurs at most once, and the number of ways to do this.
Examples
Input
4 4
1 2
1 3
4 2
4 3
Output
1 2
Input
3 3
1 2
2 3
3 1
Output
0 1
Input
3 0
Output
3 1
Note
The simple cycle is a cycle that doesn't contain any vertex twice.
Tags: combinatorics, dfs and similar, graphs, math
Correct Solution:
```
n, m = [int(x) for x in input().split()]
E = {i:[] for i in range(n)}
for i in range(m):
u, v = [int(x)-1 for x in input().split()]
E[v].append(u)
E[u].append(v)
def dfs():
visited = [False for i in range(n)]
colour = [0 for i in range(n)]
ans = 0
for v in range(n):
if visited[v]: continue
stack = [(v, 0)]
part = [0, 0]
while stack:
node, c = stack.pop()
if not visited[node]:
part[c] += 1
visited[node] = True
colour[node] = c
stack.extend((u,c^1) for u in E[node])
elif c != colour[node]:
return (0, 1)
ans += (part[0]*(part[0] - 1) + part[1]*(part[1] - 1)) // 2
return (1, ans)
if m == 0:
print(3, n*(n-1)*(n-2)//6)
elif max(len(E[v]) for v in E) == 1:
print(2, m*(n-2))
else:
ans = dfs()
print(ans[0], ans[1])
```
| 93,918 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After Vitaly was expelled from the university, he became interested in the graph theory.
Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once.
Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not necessarily connected, without parallel edges and loops. You need to find t — the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find w — the number of ways to add t edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges.
Two ways to add edges to the graph are considered equal if they have the same sets of added edges.
Since Vitaly does not study at the university, he asked you to help him with this task.
Input
The first line of the input contains two integers n and m (<image> — the number of vertices in the graph and the number of edges in the graph.
Next m lines contain the descriptions of the edges of the graph, one edge per line. Each edge is given by a pair of integers ai, bi (1 ≤ ai, bi ≤ n) — the vertices that are connected by the i-th edge. All numbers in the lines are separated by a single space.
It is guaranteed that the given graph doesn't contain any loops and parallel edges. The graph isn't necessarily connected.
Output
Print in the first line of the output two space-separated integers t and w — the minimum number of edges that should be added to the graph to form a simple cycle of an odd length consisting of more than one vertex where each vertex occurs at most once, and the number of ways to do this.
Examples
Input
4 4
1 2
1 3
4 2
4 3
Output
1 2
Input
3 3
1 2
2 3
3 1
Output
0 1
Input
3 0
Output
3 1
Note
The simple cycle is a cycle that doesn't contain any vertex twice.
Tags: combinatorics, dfs and similar, graphs, math
Correct Solution:
```
def read_data():
n, m = map(int, input().split())
Es = [[] for v in range(n)]
for e in range(m):
a, b = map(int, input().split())
a -= 1
b -= 1
Es[a].append(b)
Es[b].append(a)
return n, m, Es
def solve(n, m, Es):
if m == 0:
return 3, n * (n - 1) * (n - 2) // 6
if max(map(len, Es)) == 1:
return 2, m * (n-2)
patterns = 0
color = [0] * n
for u in range(n):
if color[u]:
continue
color[u] = 1
stack = [u]
n_color = [1, 0]
while stack:
v = stack.pop()
prev_color = color[v]
for w in Es[v]:
current_color = color[w]
if current_color == prev_color:
return 0, 1
if current_color == 0:
color[w] = - prev_color
n_color[(prev_color + 1)//2] += 1
stack.append(w)
n_even = n_color[0]
n_odd = n_color[1]
patterns += n_even * (n_even - 1) // 2 + n_odd * (n_odd - 1) // 2
return 1, patterns
if __name__ == '__main__':
n, m, Es = read_data()
print(*solve(n, m, Es))
```
| 93,919 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After Vitaly was expelled from the university, he became interested in the graph theory.
Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once.
Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not necessarily connected, without parallel edges and loops. You need to find t — the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find w — the number of ways to add t edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges.
Two ways to add edges to the graph are considered equal if they have the same sets of added edges.
Since Vitaly does not study at the university, he asked you to help him with this task.
Input
The first line of the input contains two integers n and m (<image> — the number of vertices in the graph and the number of edges in the graph.
Next m lines contain the descriptions of the edges of the graph, one edge per line. Each edge is given by a pair of integers ai, bi (1 ≤ ai, bi ≤ n) — the vertices that are connected by the i-th edge. All numbers in the lines are separated by a single space.
It is guaranteed that the given graph doesn't contain any loops and parallel edges. The graph isn't necessarily connected.
Output
Print in the first line of the output two space-separated integers t and w — the minimum number of edges that should be added to the graph to form a simple cycle of an odd length consisting of more than one vertex where each vertex occurs at most once, and the number of ways to do this.
Examples
Input
4 4
1 2
1 3
4 2
4 3
Output
1 2
Input
3 3
1 2
2 3
3 1
Output
0 1
Input
3 0
Output
3 1
Note
The simple cycle is a cycle that doesn't contain any vertex twice.
Tags: combinatorics, dfs and similar, graphs, math
Correct Solution:
```
g = [[] for _ in range(100005)]
n, m = map(int, input().split(' '))
for i in range(m):
a, b = map(int, input().split(' '))
g[a].append(b)
g[b].append(a)
colour = [0] * 100005
v = [0] * 100005
cycle = False
two = True
twos = 0
ones = 0
ans = 0
for i in range(1, n+1):
cs = 0
c1 = 0
c2 = 0
if (not colour[i]):
q = [i]
colour[i] = 1
while q:
cs += 1
top = q.pop()
if colour[top] == 1:
c1 += 1
else: c2 += 1
for j in g[top]:
if colour[j] == colour[top]:
cycle = True
elif colour[j] == 0:
colour[j] = -colour[top]
q = [j] + q
if cs > 2:
two = False
ans += ((c1*(c1-1))//2 + (c2*(c2-1))//2)
if cs == 2:
twos += 1
if cs == 1:
ones += 1
if cycle:
print(0, 1)
quit()
if m == 0:
print(3, (n*(n-1)*(n-2)//6))
quit()
if two:
print(2, twos*ones + 4 * (twos * (twos - 1) // 2))
quit()
sumx = 0
for i in range(1, n+1):
ll = len(g[i])
sumx += ll * (ll-1) // 2
print(1, ans)
```
| 93,920 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After Vitaly was expelled from the university, he became interested in the graph theory.
Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once.
Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not necessarily connected, without parallel edges and loops. You need to find t — the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find w — the number of ways to add t edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges.
Two ways to add edges to the graph are considered equal if they have the same sets of added edges.
Since Vitaly does not study at the university, he asked you to help him with this task.
Input
The first line of the input contains two integers n and m (<image> — the number of vertices in the graph and the number of edges in the graph.
Next m lines contain the descriptions of the edges of the graph, one edge per line. Each edge is given by a pair of integers ai, bi (1 ≤ ai, bi ≤ n) — the vertices that are connected by the i-th edge. All numbers in the lines are separated by a single space.
It is guaranteed that the given graph doesn't contain any loops and parallel edges. The graph isn't necessarily connected.
Output
Print in the first line of the output two space-separated integers t and w — the minimum number of edges that should be added to the graph to form a simple cycle of an odd length consisting of more than one vertex where each vertex occurs at most once, and the number of ways to do this.
Examples
Input
4 4
1 2
1 3
4 2
4 3
Output
1 2
Input
3 3
1 2
2 3
3 1
Output
0 1
Input
3 0
Output
3 1
Note
The simple cycle is a cycle that doesn't contain any vertex twice.
Submitted Solution:
```
import sys
import threading
threading.stack_size(67108864)
sys.setrecursionlimit(100500)
def nc2(k):
return k * (k - 1) // 2
def solve():
def dfs(u):
comp[u] = n_comp
for v in g[u]:
if color[v] == 0:
color[v] = 3 - color[u]
dfs(v)
elif color[u] == color[v]:
return True
return False
n, m = map(int, input().split())
g = dict()
for i in range(1, n + 1):
g[i] = set()
for i in range(m):
a, b = map(int, input().split())
g[a].add(b)
g[b].add(a)
bad_graph = False
color = [0] * (n + 1)
comp = [0] * (n + 1)
n_comp = 0
for u in range(1, n + 1):
if color[u] == 0:
n_comp += 1
color[u] = 1
if dfs(u):
print(0, 1)
return
counts = [0] * (n_comp + 1)
counts_1 = [0] * (n_comp + 1)
counts_2 = [0] * (n_comp + 1)
for i in range(1, n + 1):
counts[comp[i]] += 1
if color[i] == 1:
counts_1[comp[i]] += 1
else:
counts_2[comp[i]] += 1
c = max(counts)
if c == 1:
print(3, n * (n - 1) * (n - 2) // 6)
elif c == 2:
print(2, m * (n - 2))
elif c >= 3:
ans = 0
for i in range(1, n_comp + 1):
if counts[i] >= 3:
ans += nc2(counts_1[i]) + nc2(counts_2[i])
print(1, ans)
thread = threading.Thread(target=solve)
thread.start()
```
No
| 93,921 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After Vitaly was expelled from the university, he became interested in the graph theory.
Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once.
Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not necessarily connected, without parallel edges and loops. You need to find t — the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find w — the number of ways to add t edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges.
Two ways to add edges to the graph are considered equal if they have the same sets of added edges.
Since Vitaly does not study at the university, he asked you to help him with this task.
Input
The first line of the input contains two integers n and m (<image> — the number of vertices in the graph and the number of edges in the graph.
Next m lines contain the descriptions of the edges of the graph, one edge per line. Each edge is given by a pair of integers ai, bi (1 ≤ ai, bi ≤ n) — the vertices that are connected by the i-th edge. All numbers in the lines are separated by a single space.
It is guaranteed that the given graph doesn't contain any loops and parallel edges. The graph isn't necessarily connected.
Output
Print in the first line of the output two space-separated integers t and w — the minimum number of edges that should be added to the graph to form a simple cycle of an odd length consisting of more than one vertex where each vertex occurs at most once, and the number of ways to do this.
Examples
Input
4 4
1 2
1 3
4 2
4 3
Output
1 2
Input
3 3
1 2
2 3
3 1
Output
0 1
Input
3 0
Output
3 1
Note
The simple cycle is a cycle that doesn't contain any vertex twice.
Submitted Solution:
```
__author__ = 'Andrey'
import sys
sys.setrecursionlimit(100500)
n, m = map(int, input().split())
g = dict()
for i in range(1, n + 1):
g[i] = set()
for i in range(m):
a, b = map(int, input().split())
g[a].add(b)
g[b].add(a)
bad_graph = False
color = [0] * (n + 1)
def dfs(u):
global bad_graph
for v in g[u]:
if color[v] == 0:
color[v] = 3 - color[u]
dfs(v)
elif color[u] == color[v]:
bad_graph = True
for u in range(1, n + 1):
if color[u] == 0:
color[u] = 1
dfs(u)
if bad_graph:
print(0, 1)
else:
nothing = 0
ans = -1
total = 0
set_1 = set()
set_2 = set()
for i in range(1, n + 1):
c = 0
c_1 = 0
if color[i] == 1:
for u in g[i]:
c += 1
if u in set_1:
c_1 += 1
set_1.add(u)
if color[i] == 2:
for u in g[i]:
c += 1
if u in set_2:
c_1 += 1
set_2.add(u)
if c == 0:
nothing += 1
if ans == 1:
if c >= 2:
total += c * (c - 1) // 2 - c_1 * (c_1 - 1) // 2
if ans == 2:
if c >= 2:
total = c * (c - 1) // 2 - c_1 * (c_1 - 1) // 2
ans = 1
if c == 1 and len(g[i]) == 1:
total += n - 2
if ans == -1:
if c >= 2:
ans = 1
total = c * (c - 1) // 2 - c_1 * (c_1 - 1) // 2
if c == 1 and len(g[i]) == 1:
ans = 2
total = n - 2
if nothing == n:
print(n * (n - 1) * (n - 2) // 6)
else:
print(ans, total)
```
No
| 93,922 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After Vitaly was expelled from the university, he became interested in the graph theory.
Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once.
Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not necessarily connected, without parallel edges and loops. You need to find t — the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find w — the number of ways to add t edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges.
Two ways to add edges to the graph are considered equal if they have the same sets of added edges.
Since Vitaly does not study at the university, he asked you to help him with this task.
Input
The first line of the input contains two integers n and m (<image> — the number of vertices in the graph and the number of edges in the graph.
Next m lines contain the descriptions of the edges of the graph, one edge per line. Each edge is given by a pair of integers ai, bi (1 ≤ ai, bi ≤ n) — the vertices that are connected by the i-th edge. All numbers in the lines are separated by a single space.
It is guaranteed that the given graph doesn't contain any loops and parallel edges. The graph isn't necessarily connected.
Output
Print in the first line of the output two space-separated integers t and w — the minimum number of edges that should be added to the graph to form a simple cycle of an odd length consisting of more than one vertex where each vertex occurs at most once, and the number of ways to do this.
Examples
Input
4 4
1 2
1 3
4 2
4 3
Output
1 2
Input
3 3
1 2
2 3
3 1
Output
0 1
Input
3 0
Output
3 1
Note
The simple cycle is a cycle that doesn't contain any vertex twice.
Submitted Solution:
```
import sys
import threading
sys.setrecursionlimit(100500)
def nc2(k):
return k * (k - 1) // 2
def solve():
def dfs(u):
comp[u] = n_comp
for v in g[u]:
if color[v] == 0:
color[v] = 3 - color[u]
dfs(v)
elif color[u] == color[v]:
bad_graph = True
n, m = map(int, input().split())
g = dict()
for i in range(1, n + 1):
g[i] = set()
for i in range(m):
a, b = map(int, input().split())
g[a].add(b)
g[b].add(a)
bad_graph = False
color = [0] * (n + 1)
comp = [0] * (n + 1)
n_comp = 0
for u in range(1, n + 1):
if color[u] == 0:
n_comp += 1
color[u] = 1
dfs(u)
if bad_graph:
print(0, 1)
else:
counts = [0] * (n_comp + 1)
counts_1 = [0] * (n_comp + 1)
counts_2 = [0] * (n_comp + 1)
for i in range(1, n + 1):
counts[comp[i]] += 1
if color[i] == 1:
counts_1[comp[i]] += 1
else:
counts_2[comp[i]] += 1
c = max(counts)
if c == 1:
print(3, n * (n - 1) * (n - 2) // 6)
elif c == 2:
print(2, counts.count(2) * (n - 2))
elif c >= 3:
ans = 0
for i in range(1, n_comp + 1):
if counts[i] >= 3:
ans += nc2(counts_1[i]) + nc2(counts_2[i])
print(1, ans)
thread = threading.Thread(target=solve)
thread.start()
```
No
| 93,923 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After Vitaly was expelled from the university, he became interested in the graph theory.
Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once.
Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not necessarily connected, without parallel edges and loops. You need to find t — the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find w — the number of ways to add t edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges.
Two ways to add edges to the graph are considered equal if they have the same sets of added edges.
Since Vitaly does not study at the university, he asked you to help him with this task.
Input
The first line of the input contains two integers n and m (<image> — the number of vertices in the graph and the number of edges in the graph.
Next m lines contain the descriptions of the edges of the graph, one edge per line. Each edge is given by a pair of integers ai, bi (1 ≤ ai, bi ≤ n) — the vertices that are connected by the i-th edge. All numbers in the lines are separated by a single space.
It is guaranteed that the given graph doesn't contain any loops and parallel edges. The graph isn't necessarily connected.
Output
Print in the first line of the output two space-separated integers t and w — the minimum number of edges that should be added to the graph to form a simple cycle of an odd length consisting of more than one vertex where each vertex occurs at most once, and the number of ways to do this.
Examples
Input
4 4
1 2
1 3
4 2
4 3
Output
1 2
Input
3 3
1 2
2 3
3 1
Output
0 1
Input
3 0
Output
3 1
Note
The simple cycle is a cycle that doesn't contain any vertex twice.
Submitted Solution:
```
__author__ = 'Andrey'
import sys
import threading
threading.stack_size(67108864)
sys.setrecursionlimit(10 ** 6)
def nc2(k):
return k * (k - 1) // 2
def dfs(u, n_comp, color, bad_graph, comp, g):
comp[u] = n_comp
for v in g[u]:
if color[v] == 0:
color[v] = 3 - color[u]
dfs(v, n_comp, color, bad_graph, comp, g)
elif color[u] == color[v]:
bad_graph = True
return comp, color, bad_graph
def solve():
# f = open("bipartite.in")
# n, m = map(int, f.readline().rstrip().split())
n, m = map(int, input().split())
g = dict()
for i in range(1, n + 1):
g[i] = set()
for i in range(m):
# a, b = map(int, f.readline().rstrip().split())
a, b = map(int, input().split())
g[a].add(b)
g[b].add(a)
bad_graph = False
color = [0] * (n + 1)
comp = [0] * (n + 1)
n_comp = 0
for u in range(1, n + 1):
if color[u] == 0:
n_comp += 1
color[u] = 1
comp, color, bad_graph = dfs(u, n_comp, color, bad_graph, comp, g)
if bad_graph:
print(0, 1)
else:
counts = [0] * (n_comp + 1)
counts_1 = [0] * (n_comp + 1)
counts_2 = [0] * (n_comp + 1)
for i in range(1, n + 1):
counts[comp[i]] += 1
if color[i] == 1:
counts_1[comp[i]] += 1
else:
counts_2[comp[i]] += 1
c = max(counts)
if c == 1:
print(3, n * (n - 1) * (n - 2) // 6)
elif c == 2:
print(2, counts.count(2) * (n - 2))
elif c >= 3:
ans = 0
for i in range(1, n_comp + 1):
if counts[i] >= 3:
ans += nc2(counts_1[i]) + nc2(counts_2[i])
print(1, ans)
thread = threading.Thread(target=solve)
thread.start()
```
No
| 93,924 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at least ai any pieces of information from the other computers. Doc can hack the computer only if he is right next to it.
The robot is assembled using modern technologies and can move along the line of computers in either of the two possible directions, but the change of direction requires a large amount of resources from Doc. Tell the minimum number of changes of direction, which the robot will have to make to collect all n parts of information if initially it is next to computer with number 1.
It is guaranteed that there exists at least one sequence of the robot's actions, which leads to the collection of all information. Initially Doc doesn't have any pieces of information.
Input
The first line contains number n (1 ≤ n ≤ 1000). The second line contains n non-negative integers a1, a2, ..., an (0 ≤ ai < n), separated by a space. It is guaranteed that there exists a way for robot to collect all pieces of the information.
Output
Print a single number — the minimum number of changes in direction that the robot will have to make in order to collect all n parts of information.
Examples
Input
3
0 2 0
Output
1
Input
5
4 2 3 0 1
Output
3
Input
7
0 3 1 0 5 2 6
Output
2
Note
In the first sample you can assemble all the pieces of information in the optimal manner by assembling first the piece of information in the first computer, then in the third one, then change direction and move to the second one, and then, having 2 pieces of information, collect the last piece.
In the second sample to collect all the pieces of information in the optimal manner, Doc can go to the fourth computer and get the piece of information, then go to the fifth computer with one piece and get another one, then go to the second computer in the same manner, then to the third one and finally, to the first one. Changes of direction will take place before moving from the fifth to the second computer, then from the second to the third computer, then from the third to the first computer.
In the third sample the optimal order of collecting parts from computers can look like that: 1->3->4->6->2->5->7.
Tags: greedy, implementation
Correct Solution:
```
n = int(input())
a = [int(x) for x in input().split()]
hacked = 0
pos = 0
changes = 0
right = True
while hacked < n:
if right:
r = range(pos, n)
else:
r = range(pos, -1, -1)
for i in r:
if a[i] <= hacked:
a[i] = n + 1
hacked += 1
pos = i
if hacked < n:
changes += 1
right = not right
print(changes)
```
| 93,925 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at least ai any pieces of information from the other computers. Doc can hack the computer only if he is right next to it.
The robot is assembled using modern technologies and can move along the line of computers in either of the two possible directions, but the change of direction requires a large amount of resources from Doc. Tell the minimum number of changes of direction, which the robot will have to make to collect all n parts of information if initially it is next to computer with number 1.
It is guaranteed that there exists at least one sequence of the robot's actions, which leads to the collection of all information. Initially Doc doesn't have any pieces of information.
Input
The first line contains number n (1 ≤ n ≤ 1000). The second line contains n non-negative integers a1, a2, ..., an (0 ≤ ai < n), separated by a space. It is guaranteed that there exists a way for robot to collect all pieces of the information.
Output
Print a single number — the minimum number of changes in direction that the robot will have to make in order to collect all n parts of information.
Examples
Input
3
0 2 0
Output
1
Input
5
4 2 3 0 1
Output
3
Input
7
0 3 1 0 5 2 6
Output
2
Note
In the first sample you can assemble all the pieces of information in the optimal manner by assembling first the piece of information in the first computer, then in the third one, then change direction and move to the second one, and then, having 2 pieces of information, collect the last piece.
In the second sample to collect all the pieces of information in the optimal manner, Doc can go to the fourth computer and get the piece of information, then go to the fifth computer with one piece and get another one, then go to the second computer in the same manner, then to the third one and finally, to the first one. Changes of direction will take place before moving from the fifth to the second computer, then from the second to the third computer, then from the third to the first computer.
In the third sample the optimal order of collecting parts from computers can look like that: 1->3->4->6->2->5->7.
Tags: greedy, implementation
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
sum = 0
ans = 0
f = True
while sum != n:
for i in range(n):
if a[i] <= sum:
a[i] = 100000000000000000000000
sum += 1
if sum == n:
f = False
break
if not f:
break
ans += 1
for i in range(n - 1, -1, -1):
if a[i] <= sum:
a[i] = 1000000000000000000000000000
sum += 1
if sum == n:
f = False
break
if not f:
break
ans += 1
print(ans)
```
| 93,926 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at least ai any pieces of information from the other computers. Doc can hack the computer only if he is right next to it.
The robot is assembled using modern technologies and can move along the line of computers in either of the two possible directions, but the change of direction requires a large amount of resources from Doc. Tell the minimum number of changes of direction, which the robot will have to make to collect all n parts of information if initially it is next to computer with number 1.
It is guaranteed that there exists at least one sequence of the robot's actions, which leads to the collection of all information. Initially Doc doesn't have any pieces of information.
Input
The first line contains number n (1 ≤ n ≤ 1000). The second line contains n non-negative integers a1, a2, ..., an (0 ≤ ai < n), separated by a space. It is guaranteed that there exists a way for robot to collect all pieces of the information.
Output
Print a single number — the minimum number of changes in direction that the robot will have to make in order to collect all n parts of information.
Examples
Input
3
0 2 0
Output
1
Input
5
4 2 3 0 1
Output
3
Input
7
0 3 1 0 5 2 6
Output
2
Note
In the first sample you can assemble all the pieces of information in the optimal manner by assembling first the piece of information in the first computer, then in the third one, then change direction and move to the second one, and then, having 2 pieces of information, collect the last piece.
In the second sample to collect all the pieces of information in the optimal manner, Doc can go to the fourth computer and get the piece of information, then go to the fifth computer with one piece and get another one, then go to the second computer in the same manner, then to the third one and finally, to the first one. Changes of direction will take place before moving from the fifth to the second computer, then from the second to the third computer, then from the third to the first computer.
In the third sample the optimal order of collecting parts from computers can look like that: 1->3->4->6->2->5->7.
Tags: greedy, implementation
Correct Solution:
```
from sys import stdin
live = True
if not live: stdin = open("data.in", "r")
n = int(stdin.readline().strip())
c = list(map(int, stdin.readline().strip().split()))
g = dir = 0
ans = -1
while g != n:
ans += 1
if dir == 0:
for it in range(n):
if c[it] <= g and c[it] != - 1:
g += 1
c[it] = -1
else:
for it in range(n - 1, -1, -1):
if c[it] <= g and c[it] != - 1:
g += 1
c[it] = -1
dir = 1 - dir
print(ans)
if not live: stdin.close()
```
| 93,927 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at least ai any pieces of information from the other computers. Doc can hack the computer only if he is right next to it.
The robot is assembled using modern technologies and can move along the line of computers in either of the two possible directions, but the change of direction requires a large amount of resources from Doc. Tell the minimum number of changes of direction, which the robot will have to make to collect all n parts of information if initially it is next to computer with number 1.
It is guaranteed that there exists at least one sequence of the robot's actions, which leads to the collection of all information. Initially Doc doesn't have any pieces of information.
Input
The first line contains number n (1 ≤ n ≤ 1000). The second line contains n non-negative integers a1, a2, ..., an (0 ≤ ai < n), separated by a space. It is guaranteed that there exists a way for robot to collect all pieces of the information.
Output
Print a single number — the minimum number of changes in direction that the robot will have to make in order to collect all n parts of information.
Examples
Input
3
0 2 0
Output
1
Input
5
4 2 3 0 1
Output
3
Input
7
0 3 1 0 5 2 6
Output
2
Note
In the first sample you can assemble all the pieces of information in the optimal manner by assembling first the piece of information in the first computer, then in the third one, then change direction and move to the second one, and then, having 2 pieces of information, collect the last piece.
In the second sample to collect all the pieces of information in the optimal manner, Doc can go to the fourth computer and get the piece of information, then go to the fifth computer with one piece and get another one, then go to the second computer in the same manner, then to the third one and finally, to the first one. Changes of direction will take place before moving from the fifth to the second computer, then from the second to the third computer, then from the third to the first computer.
In the third sample the optimal order of collecting parts from computers can look like that: 1->3->4->6->2->5->7.
Tags: greedy, implementation
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
visited = [False]*n
c = 0
cycles = 0
order = 1
while not all(visited):
for idx,i in enumerate(a[::order]):
if order == -1:
idx = n - idx - 1
if not visited[idx] and i <= c:
c += 1
visited[idx] = True
if all(visited):
break
order = 1 if order < 0 else -1
cycles += 1
print(cycles)
```
| 93,928 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at least ai any pieces of information from the other computers. Doc can hack the computer only if he is right next to it.
The robot is assembled using modern technologies and can move along the line of computers in either of the two possible directions, but the change of direction requires a large amount of resources from Doc. Tell the minimum number of changes of direction, which the robot will have to make to collect all n parts of information if initially it is next to computer with number 1.
It is guaranteed that there exists at least one sequence of the robot's actions, which leads to the collection of all information. Initially Doc doesn't have any pieces of information.
Input
The first line contains number n (1 ≤ n ≤ 1000). The second line contains n non-negative integers a1, a2, ..., an (0 ≤ ai < n), separated by a space. It is guaranteed that there exists a way for robot to collect all pieces of the information.
Output
Print a single number — the minimum number of changes in direction that the robot will have to make in order to collect all n parts of information.
Examples
Input
3
0 2 0
Output
1
Input
5
4 2 3 0 1
Output
3
Input
7
0 3 1 0 5 2 6
Output
2
Note
In the first sample you can assemble all the pieces of information in the optimal manner by assembling first the piece of information in the first computer, then in the third one, then change direction and move to the second one, and then, having 2 pieces of information, collect the last piece.
In the second sample to collect all the pieces of information in the optimal manner, Doc can go to the fourth computer and get the piece of information, then go to the fifth computer with one piece and get another one, then go to the second computer in the same manner, then to the third one and finally, to the first one. Changes of direction will take place before moving from the fifth to the second computer, then from the second to the third computer, then from the third to the first computer.
In the third sample the optimal order of collecting parts from computers can look like that: 1->3->4->6->2->5->7.
Tags: greedy, implementation
Correct Solution:
```
# 583B
# θ(n*log(n)) time
# θ(n) space
from queue import PriorityQueue
__author__ = 'artyom'
# SOLUTION
def main():
n = read()
a = read(3)
if n == 1:
return 0
ix = []
for i in range(n):
ix.append(i)
ix.sort(key=lambda x: a[x])
l = PriorityQueue()
r = PriorityQueue()
i = pos = eg = flag = count = 0
while eg < n:
while i < n and a[ix[i]] <= eg:
if ix[i] > pos:
r.put(ix[i])
elif ix[i] < pos:
l.put(-ix[i])
else:
eg += 1
i += 1
if flag:
if l.empty():
flag = 0
count += 1
pos = r.get()
else:
pos = -l.get()
else:
if r.empty():
flag = 1
count += 1
pos = -l.get()
else:
pos = r.get()
eg += 1
return count
# HELPERS
def read(mode=1, size=None):
# 0: String
# 1: Integer
# 2: List of strings
# 3: List of integers
# 4: Matrix of integers
if mode == 0: return input().strip()
if mode == 1: return int(input().strip())
if mode == 2: return input().strip().split()
if mode == 3: return list(map(int, input().strip().split()))
a = []
for _ in range(size):
a.append(read(3))
return a
def write(s="\n"):
if s is None: s = ''
if isinstance(s, tuple) or isinstance(s, list): s = ' '.join(map(str, s))
s = str(s)
print(s, end="\n")
write(main())
```
| 93,929 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at least ai any pieces of information from the other computers. Doc can hack the computer only if he is right next to it.
The robot is assembled using modern technologies and can move along the line of computers in either of the two possible directions, but the change of direction requires a large amount of resources from Doc. Tell the minimum number of changes of direction, which the robot will have to make to collect all n parts of information if initially it is next to computer with number 1.
It is guaranteed that there exists at least one sequence of the robot's actions, which leads to the collection of all information. Initially Doc doesn't have any pieces of information.
Input
The first line contains number n (1 ≤ n ≤ 1000). The second line contains n non-negative integers a1, a2, ..., an (0 ≤ ai < n), separated by a space. It is guaranteed that there exists a way for robot to collect all pieces of the information.
Output
Print a single number — the minimum number of changes in direction that the robot will have to make in order to collect all n parts of information.
Examples
Input
3
0 2 0
Output
1
Input
5
4 2 3 0 1
Output
3
Input
7
0 3 1 0 5 2 6
Output
2
Note
In the first sample you can assemble all the pieces of information in the optimal manner by assembling first the piece of information in the first computer, then in the third one, then change direction and move to the second one, and then, having 2 pieces of information, collect the last piece.
In the second sample to collect all the pieces of information in the optimal manner, Doc can go to the fourth computer and get the piece of information, then go to the fifth computer with one piece and get another one, then go to the second computer in the same manner, then to the third one and finally, to the first one. Changes of direction will take place before moving from the fifth to the second computer, then from the second to the third computer, then from the third to the first computer.
In the third sample the optimal order of collecting parts from computers can look like that: 1->3->4->6->2->5->7.
Tags: greedy, implementation
Correct Solution:
```
n = int(input())
arr = list(map(int,input().split()))
info = 0
num =0
count = -1
while num != n:
count += 1
for i in range(n):
if arr[i]<=info:
arr[i] = 2000
info += 1
num += 1
arr.reverse()
print(count)
```
| 93,930 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at least ai any pieces of information from the other computers. Doc can hack the computer only if he is right next to it.
The robot is assembled using modern technologies and can move along the line of computers in either of the two possible directions, but the change of direction requires a large amount of resources from Doc. Tell the minimum number of changes of direction, which the robot will have to make to collect all n parts of information if initially it is next to computer with number 1.
It is guaranteed that there exists at least one sequence of the robot's actions, which leads to the collection of all information. Initially Doc doesn't have any pieces of information.
Input
The first line contains number n (1 ≤ n ≤ 1000). The second line contains n non-negative integers a1, a2, ..., an (0 ≤ ai < n), separated by a space. It is guaranteed that there exists a way for robot to collect all pieces of the information.
Output
Print a single number — the minimum number of changes in direction that the robot will have to make in order to collect all n parts of information.
Examples
Input
3
0 2 0
Output
1
Input
5
4 2 3 0 1
Output
3
Input
7
0 3 1 0 5 2 6
Output
2
Note
In the first sample you can assemble all the pieces of information in the optimal manner by assembling first the piece of information in the first computer, then in the third one, then change direction and move to the second one, and then, having 2 pieces of information, collect the last piece.
In the second sample to collect all the pieces of information in the optimal manner, Doc can go to the fourth computer and get the piece of information, then go to the fifth computer with one piece and get another one, then go to the second computer in the same manner, then to the third one and finally, to the first one. Changes of direction will take place before moving from the fifth to the second computer, then from the second to the third computer, then from the third to the first computer.
In the third sample the optimal order of collecting parts from computers can look like that: 1->3->4->6->2->5->7.
Tags: greedy, implementation
Correct Solution:
```
n = int(input())
a = list(map(int,input().split()))
direct = 1
pos = 0
now = 0
res = 0
checked = [0] * n
count = 0
while now < n:
if count < 10:
#print(checked)
count += 1
if direct == 1:
good = 0
for i in range(pos, n):
if checked[i]: continue
if a[i] <= now:
checked[i] = 1
now += 1
pos = i
good = 1
break
if not good:
res += 1
direct = 0
if now == n:
break
if count < 10:
#print(now, direct)
count += 1
if direct == 0:
good = 0
for i in range(pos-1, -1, -1):
if checked[i]: continue
if a[i] <= now:
checked[i] = 1
now += 1
pos = i
good = 1
break
if not good:
direct = 1
res += 1
print(res)
```
| 93,931 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at least ai any pieces of information from the other computers. Doc can hack the computer only if he is right next to it.
The robot is assembled using modern technologies and can move along the line of computers in either of the two possible directions, but the change of direction requires a large amount of resources from Doc. Tell the minimum number of changes of direction, which the robot will have to make to collect all n parts of information if initially it is next to computer with number 1.
It is guaranteed that there exists at least one sequence of the robot's actions, which leads to the collection of all information. Initially Doc doesn't have any pieces of information.
Input
The first line contains number n (1 ≤ n ≤ 1000). The second line contains n non-negative integers a1, a2, ..., an (0 ≤ ai < n), separated by a space. It is guaranteed that there exists a way for robot to collect all pieces of the information.
Output
Print a single number — the minimum number of changes in direction that the robot will have to make in order to collect all n parts of information.
Examples
Input
3
0 2 0
Output
1
Input
5
4 2 3 0 1
Output
3
Input
7
0 3 1 0 5 2 6
Output
2
Note
In the first sample you can assemble all the pieces of information in the optimal manner by assembling first the piece of information in the first computer, then in the third one, then change direction and move to the second one, and then, having 2 pieces of information, collect the last piece.
In the second sample to collect all the pieces of information in the optimal manner, Doc can go to the fourth computer and get the piece of information, then go to the fifth computer with one piece and get another one, then go to the second computer in the same manner, then to the third one and finally, to the first one. Changes of direction will take place before moving from the fifth to the second computer, then from the second to the third computer, then from the third to the first computer.
In the third sample the optimal order of collecting parts from computers can look like that: 1->3->4->6->2->5->7.
Tags: greedy, implementation
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
cnt = 0
res = 0
while len(a):
b = []
for i in range(len(a)):
if a[i] <= cnt:
cnt += 1
else:
b.append(a[i])
a = b[::-1]
res += 1
print(res - 1)
```
| 93,932 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at least ai any pieces of information from the other computers. Doc can hack the computer only if he is right next to it.
The robot is assembled using modern technologies and can move along the line of computers in either of the two possible directions, but the change of direction requires a large amount of resources from Doc. Tell the minimum number of changes of direction, which the robot will have to make to collect all n parts of information if initially it is next to computer with number 1.
It is guaranteed that there exists at least one sequence of the robot's actions, which leads to the collection of all information. Initially Doc doesn't have any pieces of information.
Input
The first line contains number n (1 ≤ n ≤ 1000). The second line contains n non-negative integers a1, a2, ..., an (0 ≤ ai < n), separated by a space. It is guaranteed that there exists a way for robot to collect all pieces of the information.
Output
Print a single number — the minimum number of changes in direction that the robot will have to make in order to collect all n parts of information.
Examples
Input
3
0 2 0
Output
1
Input
5
4 2 3 0 1
Output
3
Input
7
0 3 1 0 5 2 6
Output
2
Note
In the first sample you can assemble all the pieces of information in the optimal manner by assembling first the piece of information in the first computer, then in the third one, then change direction and move to the second one, and then, having 2 pieces of information, collect the last piece.
In the second sample to collect all the pieces of information in the optimal manner, Doc can go to the fourth computer and get the piece of information, then go to the fifth computer with one piece and get another one, then go to the second computer in the same manner, then to the third one and finally, to the first one. Changes of direction will take place before moving from the fifth to the second computer, then from the second to the third computer, then from the third to the first computer.
In the third sample the optimal order of collecting parts from computers can look like that: 1->3->4->6->2->5->7.
Submitted Solution:
```
n=int(input())
a=list(map(int,input().split()))
info=0; i=0; di=0
while 1:
for i in range(n):
if a[i]==-69: continue
if a[i]<=info:
info+=1
a[i]=-69
if info==n: break
a.reverse()
di+=1
print(di)
```
Yes
| 93,933 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at least ai any pieces of information from the other computers. Doc can hack the computer only if he is right next to it.
The robot is assembled using modern technologies and can move along the line of computers in either of the two possible directions, but the change of direction requires a large amount of resources from Doc. Tell the minimum number of changes of direction, which the robot will have to make to collect all n parts of information if initially it is next to computer with number 1.
It is guaranteed that there exists at least one sequence of the robot's actions, which leads to the collection of all information. Initially Doc doesn't have any pieces of information.
Input
The first line contains number n (1 ≤ n ≤ 1000). The second line contains n non-negative integers a1, a2, ..., an (0 ≤ ai < n), separated by a space. It is guaranteed that there exists a way for robot to collect all pieces of the information.
Output
Print a single number — the minimum number of changes in direction that the robot will have to make in order to collect all n parts of information.
Examples
Input
3
0 2 0
Output
1
Input
5
4 2 3 0 1
Output
3
Input
7
0 3 1 0 5 2 6
Output
2
Note
In the first sample you can assemble all the pieces of information in the optimal manner by assembling first the piece of information in the first computer, then in the third one, then change direction and move to the second one, and then, having 2 pieces of information, collect the last piece.
In the second sample to collect all the pieces of information in the optimal manner, Doc can go to the fourth computer and get the piece of information, then go to the fifth computer with one piece and get another one, then go to the second computer in the same manner, then to the third one and finally, to the first one. Changes of direction will take place before moving from the fifth to the second computer, then from the second to the third computer, then from the third to the first computer.
In the third sample the optimal order of collecting parts from computers can look like that: 1->3->4->6->2->5->7.
Submitted Solution:
```
n = int(input())
list = [int(x) for x in input().split()]
count = 0 #answer
x = 0 #count level
i = 0 #index
while list!=[]:
count += 1
i = 0
while i < len(list):
if list[i] <= x:
del list[i]
x += 1
else:
i += 1
if list!=[]:
count += 1
i = len(list)-1
while i >= 0:
if list[i] <= x:
x += 1
del list[i]
i -= 1
count -= 1
print(count)
```
Yes
| 93,934 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at least ai any pieces of information from the other computers. Doc can hack the computer only if he is right next to it.
The robot is assembled using modern technologies and can move along the line of computers in either of the two possible directions, but the change of direction requires a large amount of resources from Doc. Tell the minimum number of changes of direction, which the robot will have to make to collect all n parts of information if initially it is next to computer with number 1.
It is guaranteed that there exists at least one sequence of the robot's actions, which leads to the collection of all information. Initially Doc doesn't have any pieces of information.
Input
The first line contains number n (1 ≤ n ≤ 1000). The second line contains n non-negative integers a1, a2, ..., an (0 ≤ ai < n), separated by a space. It is guaranteed that there exists a way for robot to collect all pieces of the information.
Output
Print a single number — the minimum number of changes in direction that the robot will have to make in order to collect all n parts of information.
Examples
Input
3
0 2 0
Output
1
Input
5
4 2 3 0 1
Output
3
Input
7
0 3 1 0 5 2 6
Output
2
Note
In the first sample you can assemble all the pieces of information in the optimal manner by assembling first the piece of information in the first computer, then in the third one, then change direction and move to the second one, and then, having 2 pieces of information, collect the last piece.
In the second sample to collect all the pieces of information in the optimal manner, Doc can go to the fourth computer and get the piece of information, then go to the fifth computer with one piece and get another one, then go to the second computer in the same manner, then to the third one and finally, to the first one. Changes of direction will take place before moving from the fifth to the second computer, then from the second to the third computer, then from the third to the first computer.
In the third sample the optimal order of collecting parts from computers can look like that: 1->3->4->6->2->5->7.
Submitted Solution:
```
n = int(input())
lst = [int(x) for x in input().split()]
power = 0
answer = 0
while power != len(lst):
for i in range(len(lst)):
if lst[i] <= power:
power += 1
lst[i] = float('inf')
if power == len(lst):
break
answer += 1
for i in range(len(lst)-1, -1, -1):
if lst[i] <= power:
power += 1
lst[i] = float('inf')
if power == len(lst):
break
answer += 1
print(answer)
```
Yes
| 93,935 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at least ai any pieces of information from the other computers. Doc can hack the computer only if he is right next to it.
The robot is assembled using modern technologies and can move along the line of computers in either of the two possible directions, but the change of direction requires a large amount of resources from Doc. Tell the minimum number of changes of direction, which the robot will have to make to collect all n parts of information if initially it is next to computer with number 1.
It is guaranteed that there exists at least one sequence of the robot's actions, which leads to the collection of all information. Initially Doc doesn't have any pieces of information.
Input
The first line contains number n (1 ≤ n ≤ 1000). The second line contains n non-negative integers a1, a2, ..., an (0 ≤ ai < n), separated by a space. It is guaranteed that there exists a way for robot to collect all pieces of the information.
Output
Print a single number — the minimum number of changes in direction that the robot will have to make in order to collect all n parts of information.
Examples
Input
3
0 2 0
Output
1
Input
5
4 2 3 0 1
Output
3
Input
7
0 3 1 0 5 2 6
Output
2
Note
In the first sample you can assemble all the pieces of information in the optimal manner by assembling first the piece of information in the first computer, then in the third one, then change direction and move to the second one, and then, having 2 pieces of information, collect the last piece.
In the second sample to collect all the pieces of information in the optimal manner, Doc can go to the fourth computer and get the piece of information, then go to the fifth computer with one piece and get another one, then go to the second computer in the same manner, then to the third one and finally, to the first one. Changes of direction will take place before moving from the fifth to the second computer, then from the second to the third computer, then from the third to the first computer.
In the third sample the optimal order of collecting parts from computers can look like that: 1->3->4->6->2->5->7.
Submitted Solution:
```
n=int(input())
s=list(map(int,input().split()))
c=[0]*n
i=0
o=1
p=-1
d=0
while(i!=n):
if(p+o<0) or (p+o>=n):
o*=-1
d+=1
p+=o
if(c[p]==0 and s[p]<=i):
c[p]=1
i+=1
print(d)
```
Yes
| 93,936 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at least ai any pieces of information from the other computers. Doc can hack the computer only if he is right next to it.
The robot is assembled using modern technologies and can move along the line of computers in either of the two possible directions, but the change of direction requires a large amount of resources from Doc. Tell the minimum number of changes of direction, which the robot will have to make to collect all n parts of information if initially it is next to computer with number 1.
It is guaranteed that there exists at least one sequence of the robot's actions, which leads to the collection of all information. Initially Doc doesn't have any pieces of information.
Input
The first line contains number n (1 ≤ n ≤ 1000). The second line contains n non-negative integers a1, a2, ..., an (0 ≤ ai < n), separated by a space. It is guaranteed that there exists a way for robot to collect all pieces of the information.
Output
Print a single number — the minimum number of changes in direction that the robot will have to make in order to collect all n parts of information.
Examples
Input
3
0 2 0
Output
1
Input
5
4 2 3 0 1
Output
3
Input
7
0 3 1 0 5 2 6
Output
2
Note
In the first sample you can assemble all the pieces of information in the optimal manner by assembling first the piece of information in the first computer, then in the third one, then change direction and move to the second one, and then, having 2 pieces of information, collect the last piece.
In the second sample to collect all the pieces of information in the optimal manner, Doc can go to the fourth computer and get the piece of information, then go to the fifth computer with one piece and get another one, then go to the second computer in the same manner, then to the third one and finally, to the first one. Changes of direction will take place before moving from the fifth to the second computer, then from the second to the third computer, then from the third to the first computer.
In the third sample the optimal order of collecting parts from computers can look like that: 1->3->4->6->2->5->7.
Submitted Solution:
```
n=int(input())
a=list(map(int,input().split()))
co=0
an=-1
while True:
if len(set(a))==1:
break
for i in range(n):
if a[i]<=co:
co+=1
a[i]=10**5
an+=1
if len(set(a))==1:
break
j=n-1
while j>=0:
if a[j]<=co:
co+=1
a[j]=10**5
j-=1
an+=1
print(an)
```
No
| 93,937 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at least ai any pieces of information from the other computers. Doc can hack the computer only if he is right next to it.
The robot is assembled using modern technologies and can move along the line of computers in either of the two possible directions, but the change of direction requires a large amount of resources from Doc. Tell the minimum number of changes of direction, which the robot will have to make to collect all n parts of information if initially it is next to computer with number 1.
It is guaranteed that there exists at least one sequence of the robot's actions, which leads to the collection of all information. Initially Doc doesn't have any pieces of information.
Input
The first line contains number n (1 ≤ n ≤ 1000). The second line contains n non-negative integers a1, a2, ..., an (0 ≤ ai < n), separated by a space. It is guaranteed that there exists a way for robot to collect all pieces of the information.
Output
Print a single number — the minimum number of changes in direction that the robot will have to make in order to collect all n parts of information.
Examples
Input
3
0 2 0
Output
1
Input
5
4 2 3 0 1
Output
3
Input
7
0 3 1 0 5 2 6
Output
2
Note
In the first sample you can assemble all the pieces of information in the optimal manner by assembling first the piece of information in the first computer, then in the third one, then change direction and move to the second one, and then, having 2 pieces of information, collect the last piece.
In the second sample to collect all the pieces of information in the optimal manner, Doc can go to the fourth computer and get the piece of information, then go to the fifth computer with one piece and get another one, then go to the second computer in the same manner, then to the third one and finally, to the first one. Changes of direction will take place before moving from the fifth to the second computer, then from the second to the third computer, then from the third to the first computer.
In the third sample the optimal order of collecting parts from computers can look like that: 1->3->4->6->2->5->7.
Submitted Solution:
```
#!/usr/bin/env python3
import copy
def solveLeft(elems, acum=0):
changed = False
for i in range(len(elems)):
if elems[i] is not None and elems[i] <= acum:
acum += 1
elems[i] = None
changed = True
if not changed:
return 0
return 1 + solveRight(elems, acum)
def solveRight(elems, acum=0):
changed = False
for i in reversed(range(len(elems))):
if elems[i] is not None and elems[i] <= acum:
acum += 1
elems[i] = None
changed = True
if not changed:
return 0
return 1 + solveLeft(elems, acum)
def solve(elems):
return min(solveLeft(copy.copy(elems)),
solveRight(copy.copy(elems))) - 1
if __name__ == '__main__':
n = int(input())
elems = list(map(int, input().split()))
print(solve(elems))
```
No
| 93,938 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at least ai any pieces of information from the other computers. Doc can hack the computer only if he is right next to it.
The robot is assembled using modern technologies and can move along the line of computers in either of the two possible directions, but the change of direction requires a large amount of resources from Doc. Tell the minimum number of changes of direction, which the robot will have to make to collect all n parts of information if initially it is next to computer with number 1.
It is guaranteed that there exists at least one sequence of the robot's actions, which leads to the collection of all information. Initially Doc doesn't have any pieces of information.
Input
The first line contains number n (1 ≤ n ≤ 1000). The second line contains n non-negative integers a1, a2, ..., an (0 ≤ ai < n), separated by a space. It is guaranteed that there exists a way for robot to collect all pieces of the information.
Output
Print a single number — the minimum number of changes in direction that the robot will have to make in order to collect all n parts of information.
Examples
Input
3
0 2 0
Output
1
Input
5
4 2 3 0 1
Output
3
Input
7
0 3 1 0 5 2 6
Output
2
Note
In the first sample you can assemble all the pieces of information in the optimal manner by assembling first the piece of information in the first computer, then in the third one, then change direction and move to the second one, and then, having 2 pieces of information, collect the last piece.
In the second sample to collect all the pieces of information in the optimal manner, Doc can go to the fourth computer and get the piece of information, then go to the fifth computer with one piece and get another one, then go to the second computer in the same manner, then to the third one and finally, to the first one. Changes of direction will take place before moving from the fifth to the second computer, then from the second to the third computer, then from the third to the first computer.
In the third sample the optimal order of collecting parts from computers can look like that: 1->3->4->6->2->5->7.
Submitted Solution:
```
#!/usr/bin/env python3.4
import time
COL, ROW, LEN = 1000, 1000, 26
matrix = [[0] * COL for i in range(ROW)]
arr = [0] * LEN
direction = ((0, -1), (-1, 0), (0, 1), (1, 0))
class Pair:
def __init__(self, x, y):
self.x = x
self.y = y
def timer(func, *pargs, **kargs):
start = time.time()
func(*pargs, **kargs)
return time.time() - start
def test(a):
answer = 0
for value in a:
if value >= 0:
answer += value
return answer
if __name__ == "__main__":
n = int(input())
arr = list(map(int, input().split()))
ans = -1
volume = 0
direct = 0;
while test(arr):
ans += 1
if direct == 0:
for ind, val in enumerate(arr):
if val <= volume and val != -1:
arr[ind] = -1
volume += 1
else:
for ind in range(len(arr), 0, -1):
if arr[val] <= volume and arr[val] != -1:
arr[ind] = -1
volume += 1
direct += 1
direct %= 2
print(ans)
```
No
| 93,939 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at least ai any pieces of information from the other computers. Doc can hack the computer only if he is right next to it.
The robot is assembled using modern technologies and can move along the line of computers in either of the two possible directions, but the change of direction requires a large amount of resources from Doc. Tell the minimum number of changes of direction, which the robot will have to make to collect all n parts of information if initially it is next to computer with number 1.
It is guaranteed that there exists at least one sequence of the robot's actions, which leads to the collection of all information. Initially Doc doesn't have any pieces of information.
Input
The first line contains number n (1 ≤ n ≤ 1000). The second line contains n non-negative integers a1, a2, ..., an (0 ≤ ai < n), separated by a space. It is guaranteed that there exists a way for robot to collect all pieces of the information.
Output
Print a single number — the minimum number of changes in direction that the robot will have to make in order to collect all n parts of information.
Examples
Input
3
0 2 0
Output
1
Input
5
4 2 3 0 1
Output
3
Input
7
0 3 1 0 5 2 6
Output
2
Note
In the first sample you can assemble all the pieces of information in the optimal manner by assembling first the piece of information in the first computer, then in the third one, then change direction and move to the second one, and then, having 2 pieces of information, collect the last piece.
In the second sample to collect all the pieces of information in the optimal manner, Doc can go to the fourth computer and get the piece of information, then go to the fifth computer with one piece and get another one, then go to the second computer in the same manner, then to the third one and finally, to the first one. Changes of direction will take place before moving from the fifth to the second computer, then from the second to the third computer, then from the third to the first computer.
In the third sample the optimal order of collecting parts from computers can look like that: 1->3->4->6->2->5->7.
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
used = [False for i in range(n)]
k = 0
for i in range(n):
flag = False
for j in range(n):
if a[j] <= k and used[j] == False:
used[j] = True
k += 1
for j in range(n):
if used[j] == False:
flag = True
if flag == False:
print(i + 1)
break
for j in range(n - 1, -1, -1):
if a[j] <= k and used[j] == False:
used[j] = True
k += 1
```
No
| 93,940 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) — the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≤ aj ≤ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≤ uj, vj ≤ n, uj ≠ vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1
Tags: constructive algorithms, data structures, graphs
Correct Solution:
```
f = lambda: map(int, input().split())
n, m = f()
p = []
for i in range(m):
a, b = f()
p.append((a, 1 - b, i))
p.sort()
k = j = 0
s = [0] * m
u, v = 1, 3
for a, b, i in p:
if not b:
k += j
s[i] = (j + 1, j + 2)
j += 1
elif k:
k -= 1
s[i] = (u, v)
if v - u - 2: u += 1
else: u, v = 1, v + 1
else:
print(-1)
exit(0)
for x, y in s: print(x, y)
```
| 93,941 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) — the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≤ aj ≤ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≤ uj, vj ≤ n, uj ≠ vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1
Tags: constructive algorithms, data structures, graphs
Correct Solution:
```
import sys
from operator import itemgetter
lines = sys.stdin.readlines()
n, m = map(int, lines[0].split(' '))
def build_edge(i, row):
parts = row.split(' ')
return (int(parts[0]), int(parts[1]), i)
def edge_key(a):
return (a[0], -a[1])
edges = [build_edge(i, row) for i, row in enumerate(lines[1:])]
edges = sorted(edges, key=edge_key)
x, y = 1, 2
vertex = 1
color = [0 for x in range(n)]
color[0] = 1 # root of tree
ans = []
for weight, used, index in edges:
if used == 1:
color[vertex] = 1
ans.append((0, vertex, index))
vertex += 1
else:
if color[x] != 1 or color[y] != 1:
print(-1)
exit(0)
ans.append((x,y,index))
x += 1
if x == y:
x = 1
y += 1
ans = sorted(ans, key=itemgetter(2))
for edge in ans:
print("%s %s" % (edge[0]+1, edge[1]+1))
```
| 93,942 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) — the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≤ aj ≤ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≤ uj, vj ≤ n, uj ≠ vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1
Tags: constructive algorithms, data structures, graphs
Correct Solution:
```
def read_data():
n, m = map(int, input().split())
ABs = []
for i in range(m):
a, b = map(int, input().split())
ABs.append((a, b))
return n, m, ABs
def solve(n, m, ABs):
edges = [(a, -b, i) for i, (a, b) in enumerate(ABs)]
edges.sort()
ans = [(0, 0) for i in range(m)]
v = 0
count = 0
s = 1
t = 2
for a, mb, i in edges:
count += 1
if mb == -1:
v += 1
ans[i] = (0, v)
else:
if t > v:
return False, []
ans[i] = (s, t)
if t == s + 1:
s = 1
t += 1
else:
s += 1
return True, ans
n, m, ABs = read_data()
res, ans = solve(n, m, ABs)
if res:
for i, j in ans:
print(i + 1, j + 1)
else:
print(-1)
```
| 93,943 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) — the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≤ aj ≤ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≤ uj, vj ≤ n, uj ≠ vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1
Tags: constructive algorithms, data structures, graphs
Correct Solution:
```
readInts=lambda: list(map(int, input().split()))
n,m=readInts()
edge=[]
for _ in range(m):
l,f=readInts()
if f==1:
f=-1
edge+=[(l,f,_)]
edge.sort()
ok=True
cnt=0;ret=[(0,0)]*m
u=2;v=3;t=2
for e in edge:
if e[1]==-1:
ret[e[2]]=(1,t)
cnt+=t-2
t+=1
elif cnt<=0:
ok=False
break
else:
ret[e[2]]=(u,v)
cnt-=1
u+=1
if u==v:
u=2
v+=1
if ok==False:
print(-1)
else:
for e in ret:
print(*e)
```
| 93,944 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) — the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≤ aj ≤ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≤ uj, vj ≤ n, uj ≠ vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1
Tags: constructive algorithms, data structures, graphs
Correct Solution:
```
def graph(e):
e = [(w, i, b) for i, (w, b) in enumerate(e)]
e.sort()
g = [None]*len(e)
mst = [(w, i) for w, i, b in e if b]
for n, (w, i) in enumerate(mst, 2):
g[i] = 1, n
cm = 0
available = []
for w, i, b in e:
if not b:
if not available:
cm += 1
if mst[cm][0] > w:
return None
available = [(u, cm+2) for u in range(2, cm+2)]
g[i] = available.pop()
return g
if __name__ == '__main__':
n, m = map(int, input().split())
e = []
for _ in range(m):
a, b = map(int, input().split())
e.append((a, b))
g = graph(e)
if g:
for u, v in g:
print("{} {}".format(u, v))
else:
print(-1)
```
| 93,945 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) — the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≤ aj ≤ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≤ uj, vj ≤ n, uj ≠ vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1
Tags: constructive algorithms, data structures, graphs
Correct Solution:
```
def main():
n, m = map(int, input().split())
tmp = ([], [])
for i in range(m):
a, b = input().split()
tmp[b == "1"].append((int(a), i))
for l in tmp:
l.sort()
additional, spanning = tmp
tmp = []
def concurrent_way():
for y, (ww, _) in enumerate(spanning, 2):
for x in range(2, y):
yield ww, x, y
for (w, e), (wmax, v1, v2) in zip(additional, concurrent_way()):
if w < wmax:
print("-1")
return
else:
tmp.append((e, v1, v2))
tmp.extend((n, 1, v) for v, (_, n) in enumerate(spanning, 2))
tmp.sort()
f = " ".join
print('\n'.join(f((str(j), str(k))) for _, j, k in tmp))
if __name__ == '__main__':
main()
```
| 93,946 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) — the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≤ aj ≤ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≤ uj, vj ≤ n, uj ≠ vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1
Tags: constructive algorithms, data structures, graphs
Correct Solution:
```
def parse(i):
t = input().split()
return int(t[0]), int(t[1]), i
n, m = [int(x) for x in input().split()]
list = [parse(i) for i in range(m)]
list.sort(key=lambda x: (x[0], -x[1]))
# print(list)
f = 0
t = 1
fakeFrom = 1
fakeTo = 2
graph = []
for i in range(m):
if list[i][1] == 1:
graph.append((f + 1, t + 1, list[i][2]))
t += 1
else:
graph.append((fakeFrom + 1, fakeTo + 1, list[i][2]))
if fakeTo >= t:
print(-1)
exit(0)
fakeFrom += 1
if fakeFrom == fakeTo:
fakeFrom = 1
fakeTo += 1
# if fakeTo >= t:
# print(-1)
# exit(0)
# print(graph)
graph.sort(key=lambda x: x[2])
for x in graph:
print(x[0], x[1])
```
| 93,947 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) — the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≤ aj ≤ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≤ uj, vj ≤ n, uj ≠ vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1
Tags: constructive algorithms, data structures, graphs
Correct Solution:
```
f = lambda: map(int, input().split())
n, m = f()
p = []
for i in range(m):
a, b = f()
p.append((a, 1 - b, i))
p.sort()
k = j = 0
s = [0] * m
u, v = 1, 3
for a, b, i in p:
if not b:
k += j
s[i] = (j + 1, j + 2)
j += 1
elif k:
k -= 1
s[i] = (u, v)
if v - u - 2: u += 1
else: u, v = 1, v + 1
else:
print(-1)
exit(0)
for x, y in s: print(x, y)
# Made By Mostafa_Khaled
```
| 93,948 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) — the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≤ aj ≤ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≤ uj, vj ≤ n, uj ≠ vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1
Submitted Solution:
```
n,m = map(int,input().split())
a = []
for i in range(m):
x,y = map(int,input().split())
a.append((x,y,i))
a.sort()
b,c,d = [object()]*m,2,[0]*(n+1)
for i in range(m):
if a[i][1]:
b[i]=(a[i][2],1,c)
d[c]=a[i][0]
c+=1
x,y,f = 2,3,0
for i in range(m):
if not a[i][1]:
if d[x]<= a[i][0] and d[y]<=a[i][0]:
b[i]=(a[i][2],x,y)
else:
f=1
break
x+=1
if x==y:
x=2
y+=1
if f:
print('-1')
else:
b.sort()
for _,i,j in b:
print(i,j)
```
Yes
| 93,949 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) — the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≤ aj ≤ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≤ uj, vj ≤ n, uj ≠ vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1
Submitted Solution:
```
__author__ = 'MoonBall'
import sys
import functools
# sys.stdin = open('data/D.in', 'r')
T = 1
def process():
N, M = list(map(int, input().split()))
e = []
for _ in range(M): e.append(list(map(int, input().split())) + [_])
e = sorted(e, key=functools.cmp_to_key(lambda x, y: y[1] - x[1] if x[0] == y[0] else x[0] - y[0]))
ans = [0] * M
# print(e)
i = 3
j = 1
has = 1
ok = True
for _e in e:
if _e[1] == 1:
has = has + 1
ans[_e[2]] = (has, has - 1)
else:
if has < i:
ok = False
else:
ans[_e[2]] = (i, j)
if j == i - 2:
i = i + 1
j = 1
else:
j = j + 1
if not ok:
print(-1)
else:
for u, v in ans: print(u, v)
for _ in range(T):
process()
```
Yes
| 93,950 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) — the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≤ aj ≤ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≤ uj, vj ≤ n, uj ≠ vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1
Submitted Solution:
```
import sys
from math import gcd,sqrt,ceil,log2
from collections import defaultdict,Counter,deque
from bisect import bisect_left,bisect_right
import math
sys.setrecursionlimit(2*10**5+10)
import heapq
from itertools import permutations
# input=sys.stdin.readline
# def print(x):
# sys.stdout.write(str(x)+"\n")
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
aa='abcdefghijklmnopqrstuvwxyz'
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")
# import sys
# import io, os
# input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def get_sum(bit,i):
s = 0
i+=1
while i>0:
s+=bit[i]
i-=i&(-i)
return s
def update(bit,n,i,v):
i+=1
while i<=n:
bit[i]+=v
i+=i&(-i)
def modInverse(b,m):
g = math.gcd(b, m)
if (g != 1):
return -1
else:
return pow(b, m - 2, m)
def primeFactors(n):
sa = []
# sa.add(n)
while n % 2 == 0:
sa.append(2)
n = n // 2
for i in range(3,int(math.sqrt(n))+1,2):
while n % i== 0:
sa.append(i)
n = n // i
# sa.add(n)
if n > 2:
sa.append(n)
return sa
def seive(n):
pri = [True]*(n+1)
p = 2
while p*p<=n:
if pri[p] == True:
for i in range(p*p,n+1,p):
pri[i] = False
p+=1
return pri
def check_prim(n):
if n<0:
return False
for i in range(2,int(sqrt(n))+1):
if n%i == 0:
return False
return True
def getZarr(string, z):
n = len(string)
# [L,R] make a window which matches
# with prefix of s
l, r, k = 0, 0, 0
for i in range(1, n):
# if i>R nothing matches so we will calculate.
# Z[i] using naive way.
if i > r:
l, r = i, i
# R-L = 0 in starting, so it will start
# checking from 0'th index. For example,
# for "ababab" and i = 1, the value of R
# remains 0 and Z[i] becomes 0. For string
# "aaaaaa" and i = 1, Z[i] and R become 5
while r < n and string[r - l] == string[r]:
r += 1
z[i] = r - l
r -= 1
else:
# k = i-L so k corresponds to number which
# matches in [L,R] interval.
k = i - l
# if Z[k] is less than remaining interval
# then Z[i] will be equal to Z[k].
# For example, str = "ababab", i = 3, R = 5
# and L = 2
if z[k] < r - i + 1:
z[i] = z[k]
# For example str = "aaaaaa" and i = 2,
# R is 5, L is 0
else:
# else start from R and check manually
l = i
while r < n and string[r - l] == string[r]:
r += 1
z[i] = r - l
r -= 1
def search(text, pattern):
# Create concatenated string "P$T"
concat = pattern + "$" + text
l = len(concat)
z = [0] * l
getZarr(concat, z)
ha = []
for i in range(l):
if z[i] == len(pattern):
ha.append(i - len(pattern) - 1)
return ha
# n,k = map(int,input().split())
# l = list(map(int,input().split()))
#
# n = int(input())
# l = list(map(int,input().split()))
#
# hash = defaultdict(list)
# la = []
#
# for i in range(n):
# la.append([l[i],i+1])
#
# la.sort(key = lambda x: (x[0],-x[1]))
# ans = []
# r = n
# flag = 0
# lo = []
# ha = [i for i in range(n,0,-1)]
# yo = []
# for a,b in la:
#
# if a == 1:
# ans.append([r,b])
# # hash[(1,1)].append([b,r])
# lo.append((r,b))
# ha.pop(0)
# yo.append([r,b])
# r-=1
#
# elif a == 2:
# # print(yo,lo)
# # print(hash[1,1])
# if lo == []:
# flag = 1
# break
# c,d = lo.pop(0)
# yo.pop(0)
# if b>=d:
# flag = 1
# break
# ans.append([c,b])
# yo.append([c,b])
#
#
#
# elif a == 3:
#
# if yo == []:
# flag = 1
# break
# c,d = yo.pop(0)
# if b>=d:
# flag = 1
# break
# if ha == []:
# flag = 1
# break
#
# ka = ha.pop(0)
#
# ans.append([ka,b])
# ans.append([ka,d])
# yo.append([ka,b])
#
# if flag:
# print(-1)
# else:
# print(len(ans))
# for a,b in ans:
# print(a,b)
def mergeIntervals(arr):
# Sorting based on the increasing order
# of the start intervals
arr.sort(key = lambda x: x[0])
# array to hold the merged intervals
m = []
s = -10000
max = -100000
for i in range(len(arr)):
a = arr[i]
if a[0] > max:
if i != 0:
m.append([s,max])
max = a[1]
s = a[0]
else:
if a[1] >= max:
max = a[1]
#'max' value gives the last point of
# that particular interval
# 's' gives the starting point of that interval
# 'm' array contains the list of all merged intervals
if max != -100000 and [s, max] not in m:
m.append([s, max])
return m
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
def ncr(n, r, p):
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den,
p - 2, p)) % p
def sol(n):
seti = set()
for i in range(1,int(sqrt(n))+1):
if n%i == 0:
seti.add(n//i)
seti.add(i)
return seti
def lcm(a,b):
return (a*b)//gcd(a,b)
#
# n,p = map(int,input().split())
#
# s = input()
#
# if n <=2:
# if n == 1:
# pass
# if n == 2:
# pass
# i = n-1
# idx = -1
# while i>=0:
# z = ord(s[i])-96
# k = chr(z+1+96)
# flag = 1
# if i-1>=0:
# if s[i-1]!=k:
# flag+=1
# else:
# flag+=1
# if i-2>=0:
# if s[i-2]!=k:
# flag+=1
# else:
# flag+=1
# if flag == 2:
# idx = i
# s[i] = k
# break
# if idx == -1:
# print('NO')
# exit()
# for i in range(idx+1,n):
# if
#
def moore_voting(l):
count1 = 0
count2 = 0
first = 10**18
second = 10**18
n = len(l)
for i in range(n):
if l[i] == first:
count1+=1
elif l[i] == second:
count2+=1
elif count1 == 0:
count1+=1
first = l[i]
elif count2 == 0:
count2+=1
second = l[i]
else:
count1-=1
count2-=1
for i in range(n):
if l[i] == first:
count1+=1
elif l[i] == second:
count2+=1
if count1>n//3:
return first
if count2>n//3:
return second
return -1
def find_parent(u,parent):
if u!=parent[u]:
parent[u] = find_parent(parent[u],parent)
return parent[u]
def dis_union(n):
par = [i for i in range(n+1)]
rank = [1]*(n+1)
k = int(input())
for i in range(k):
a,b = map(int,input().split())
z1,z2 = find_parent(a,par),find_parent(b,par)
if z1!=z2:
par[z1] = z2
rank[z2]+=rank[z1]
def dijkstra(n,tot,hash):
hea = [[0,n]]
dis = [10**18]*(tot+1)
dis[n] = 0
boo = defaultdict(bool)
check = defaultdict(int)
while hea:
a,b = heapq.heappop(hea)
if boo[b]:
continue
boo[b] = True
for i,w in hash[b]:
if b == 1:
c = 0
if (1,i,w) in nodes:
c = nodes[(1,i,w)]
del nodes[(1,i,w)]
if dis[b]+w<dis[i]:
dis[i] = dis[b]+w
check[i] = c
elif dis[b]+w == dis[i] and c == 0:
dis[i] = dis[b]+w
check[i] = c
else:
if dis[b]+w<=dis[i]:
dis[i] = dis[b]+w
check[i] = check[b]
heapq.heappush(hea,[dis[i],i])
return check
def power(x,y,p):
res = 1
x = x%p
if x == 0:
return 0
while y>0:
if (y&1) == 1:
res*=x
x = x*x
y = y>>1
return res
#
# n,m = map(int,input().split())
# hash = defaultdict(list)
# ans = set()
# cur = 2
# rest = []
# now = []
# ba = []
# ho = defaultdict(bool)
# for i in range(m):
# a,b = map(int,input().split())
# ba.append(a)
# if b == 1:
# ans.add((a,1,cur))
# now.append([a,1,cur])
# ho[(1,cur)] = True
# ho[(cur,1)] = True
# cur+=1
#
#
# else:
# rest.append(a)
# ha = n-1
#
#
# rest.sort()
# # print(now)
# inf = -10**18
# i = 0
# cur = 2
# while ha!=m:
# if rest == []:
# break
# yo = cur+1
# while yo<=n:
#
# x1,x2 =
#
#
#
# hash = defaultdict(list)
#
# for a,b,c in ans:
# hash[a].append((b,c))
# yo = []
# for a in ba:
# while hash[a]!=[]:
# c,d = hash[a].pop(0)
# yo.append((c,d))
#
# for a,b in yo:
# print(a,b)
n,m = map(int,input().split())
ans = set()
cur = 2
rest = []
now = []
ba = []
hash = defaultdict(int)
for i in range(m):
a,b = map(int,input().split())
now.append([a,b,i])
now.sort()
yo = [[0,0]]*(m)
for i in range(m):
a,b,x = now[i]
ba.append([x,a])
if b == 1:
hash[(1,cur)] = a
yo[x] = [1,cur]
cur+=1
else:
rest.append(a)
rest.sort()
ba.sort()
ha = n-1
to = 2
fro = 3
while ha!=m:
z = rest.pop(0)
a,b = to,fro
z1,z2 = hash[(1,to)],hash[(1,fro)]
if z<z1 or z<z2:
# print(z,a,b,z1,z2)
print(-1)
exit()
ans.add((z,a,b))
if rest == []:
break
to+=1
if to == fro:
fro+=1
to = 2
hash = defaultdict(list)
for a,b,c in ans:
hash[a].append((b,c))
# print(hash)
# print(ba)
for x,a in ba:
if yo[x] == [0,0]:
c,d = hash[a].pop(0)
yo[x] = c,d
for a,b in yo:
print(a,b)
```
Yes
| 93,951 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) — the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≤ aj ≤ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≤ uj, vj ≤ n, uj ≠ vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1
Submitted Solution:
```
n, m = map(int, input().split())
arr = []
for i in range(m):
a, b = map(int, input().split())
arr.append([a, -b, i + 1])
arr.sort()
ans = [[-1,-1] for i in range(m)]
ok = True
at = 2
last = 3
curr = 2
for i in range(m):
idx = arr[i][2] - 1
inc = arr[i][1]
if(inc):
ans[idx] = [1, curr]
curr += 1
else:
if(last < curr):
ans[idx] = [at, last]
at += 1
if(at == last):
last += 1
at = 2
else:
ok= False
# print(arr)
if(ok):
for i in ans:
print(*i)
else:
print(-1)
# print(*ans)
```
Yes
| 93,952 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) — the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≤ aj ≤ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≤ uj, vj ≤ n, uj ≠ vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1
Submitted Solution:
```
n,m = map(int,input().split())
a = []
for i in range(m):
x,y = map(int,input().split())
a.append((x,y,i))
a.sort()
b,c,d = [object()]*m,2,[0]*(n+1)
for i in range(m):
if a[i][1]:
b[i]=(a[i][2],1,c)
d[c]=a[i][0]
c+=1
x,y,f = 2,3,0
for i in range(m):
if not a[i][1]:
if d[x]<= a[i][0] and d[y]<=a[i][0]:
b[i]=(a[i][2],x,y)
else:
f=1
break
y+=1
if y>n:
x+=1
y=x+1
if f:
print('-1')
else:
b.sort()
for _,i,j in b:
print(i,j)
```
No
| 93,953 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) — the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≤ aj ≤ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≤ uj, vj ≤ n, uj ≠ vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1
Submitted Solution:
```
n,m = map(int, input().split())
l = []
for i in range(m):
a,b = map(int, input().split())
if b==1: b=0
else: b=1
l.append((a,b))
l2 = sorted(l)
gap = 3
num = 2
o = 2
d = {}
d2 = {}
min1 = {}
for i in range(m):
if l2[i] not in d:
d[l2[i]] = []
d2[l2[i]] = 0
if l2[i][1]==0:
if o>n:
print(-1)
exit()
min1[o]=l2[i][0]
d[l2[i]].append((1, o))
o += 1
continue
if num==gap:
num = 2
gap += 1
if l2[i][1]:
if gap in min1 and l2[i][0] < min1[gap]:
print(-1)
exit()
else:
min1[gap] = l2[i][0]
d[l2[i]].append((num, gap))
num += 1
for i in l:
a = d[i][d2[i]]
print(a[0], a[1])
d2[i] += 1
d = {}
```
No
| 93,954 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) — the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≤ aj ≤ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≤ uj, vj ≤ n, uj ≠ vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1
Submitted Solution:
```
n, m = map(int, input().split())
arr = []
for i in range(m):
a, b = map(int, input().split())
arr.append([a, -b, i+1])
arr.sort()
ok = True
for i in range(n-1):
if(arr[i][1] == 0):
ok = False
break
if(ok):
ans = [[-1, -1] for i in range(m)]
for i in range(1, n):
ans[arr[i - 1][2] - 1] = [i, i+1]
at = 1
sec = at + 2
for i in range(n-1, m):
ans[arr[i][2] - 1] = [at, sec]
sec += 1
if(sec == n+1):
at += 1
sec = at + 2
for i in ans:
print(*i)
else:
print(-1)
```
No
| 93,955 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) — the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≤ aj ≤ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≤ uj, vj ≤ n, uj ≠ vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1
Submitted Solution:
```
n,m = map(int, input().split())
l = []
for i in range(m):
a,b = map(int, input().split())
if b==1: b=0
else: b=1
l.append((a,b))
l2 = sorted(l)
t = 1
gap = 1
num = 1
d = {}
d2 = {}
for i in range(m):
if t==0 and l2[i][1]==0:
print(-1)
exit()
if l2[i][1]==1:
t = 0
if num+gap>n:
num = 1
gap += 1
if l2[i] not in d:
d[l2[i]] = []
d2[l2[i]] = 0
d[l2[i]].append((num, num+gap))
num += 1
for i in l:
a = d[i][d2[i]]
print(a[0], a[1])
d2[i] += 1
d = {}
```
No
| 93,956 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Johnny drives a truck and must deliver a package from his hometown to the district center. His hometown is located at point 0 on a number line, and the district center is located at the point d.
Johnny's truck has a gas tank that holds exactly n liters, and his tank is initially full. As he drives, the truck consumes exactly one liter per unit distance traveled. Moreover, there are m gas stations located at various points along the way to the district center. The i-th station is located at the point xi on the number line and sells an unlimited amount of fuel at a price of pi dollars per liter. Find the minimum cost Johnny must pay for fuel to successfully complete the delivery.
Input
The first line of input contains three space separated integers d, n, and m (1 ≤ n ≤ d ≤ 109, 1 ≤ m ≤ 200 000) — the total distance to the district center, the volume of the gas tank, and the number of gas stations, respectively.
Each of the next m lines contains two integers xi, pi (1 ≤ xi ≤ d - 1, 1 ≤ pi ≤ 106) — the position and cost of gas at the i-th gas station. It is guaranteed that the positions of the gas stations are distinct.
Output
Print a single integer — the minimum cost to complete the delivery. If there is no way to complete the delivery, print -1.
Examples
Input
10 4 4
3 5
5 8
6 3
8 4
Output
22
Input
16 5 2
8 2
5 1
Output
-1
Note
In the first sample, Johnny's truck holds 4 liters. He can drive 3 units to the first gas station, buy 2 liters of gas there (bringing the tank to 3 liters total), drive 3 more units to the third gas station, buy 4 liters there to fill up his tank, and then drive straight to the district center. His total cost is 2·5 + 4·3 = 22 dollars.
In the second sample, there is no way for Johnny to make it to the district center, as his tank cannot hold enough gas to take him from the latest gas station to the district center.
Tags: data structures, divide and conquer, greedy
Correct Solution:
```
destination, max_gas_tank_volume, gas_prices_number = map(int, input().split())
start_point = 0
gas_prices = {start_point:0}
for i in range(gas_prices_number):
coordinate, price = map(int, input().split())
gas_prices[coordinate] = price
points = sorted(gas_prices.keys(), reverse = True)
current_point = start_point
count = 0
gas_tank_volume = max_gas_tank_volume
reachable_points = []
while current_point != destination:
farthest_reachable_point = current_point + max_gas_tank_volume
while points and points[-1] <= farthest_reachable_point:
reachable_points.append(points.pop())
if reachable_points:
cheaper_reachable_points = sorted(filter(lambda point: gas_prices[point] < gas_prices[current_point], reachable_points))
next_point = cheaper_reachable_points[0] if cheaper_reachable_points else min(reachable_points, key = lambda point: gas_prices[point])
if farthest_reachable_point >= destination and (current_point == start_point or gas_prices[next_point] >= gas_prices[current_point]):
next_point = destination
else:
reachable_points = [point for point in reachable_points if point > next_point]
else:
if farthest_reachable_point >= destination:
next_point = destination
else:
count = -1
break
distantion = next_point - current_point
if next_point != destination and gas_prices[current_point] <= gas_prices[next_point]:
required_gas_volume = max_gas_tank_volume
else:
required_gas_volume = distantion
if required_gas_volume > gas_tank_volume:
count += (required_gas_volume - gas_tank_volume)*gas_prices[current_point]
gas_tank_volume = required_gas_volume
current_point = next_point
gas_tank_volume -= distantion
print(count)
```
| 93,957 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Johnny drives a truck and must deliver a package from his hometown to the district center. His hometown is located at point 0 on a number line, and the district center is located at the point d.
Johnny's truck has a gas tank that holds exactly n liters, and his tank is initially full. As he drives, the truck consumes exactly one liter per unit distance traveled. Moreover, there are m gas stations located at various points along the way to the district center. The i-th station is located at the point xi on the number line and sells an unlimited amount of fuel at a price of pi dollars per liter. Find the minimum cost Johnny must pay for fuel to successfully complete the delivery.
Input
The first line of input contains three space separated integers d, n, and m (1 ≤ n ≤ d ≤ 109, 1 ≤ m ≤ 200 000) — the total distance to the district center, the volume of the gas tank, and the number of gas stations, respectively.
Each of the next m lines contains two integers xi, pi (1 ≤ xi ≤ d - 1, 1 ≤ pi ≤ 106) — the position and cost of gas at the i-th gas station. It is guaranteed that the positions of the gas stations are distinct.
Output
Print a single integer — the minimum cost to complete the delivery. If there is no way to complete the delivery, print -1.
Examples
Input
10 4 4
3 5
5 8
6 3
8 4
Output
22
Input
16 5 2
8 2
5 1
Output
-1
Note
In the first sample, Johnny's truck holds 4 liters. He can drive 3 units to the first gas station, buy 2 liters of gas there (bringing the tank to 3 liters total), drive 3 more units to the third gas station, buy 4 liters there to fill up his tank, and then drive straight to the district center. His total cost is 2·5 + 4·3 = 22 dollars.
In the second sample, there is no way for Johnny to make it to the district center, as his tank cannot hold enough gas to take him from the latest gas station to the district center.
Submitted Solution:
```
destination, max_gas_tank_volume, gas_prices_number = map(int, input().split())
gas_prices = {}
for i in range(gas_prices_number):
coordinate, price = map(int, input().split())
gas_prices[coordinate] = price
points = sorted(gas_prices.keys(), reverse = True)
start_point = 0
current_point = start_point
count = 0
gas_tank_volume = max_gas_tank_volume
reachable_points = []
while current_point != destination:
farthest_reachable_point = current_point + max_gas_tank_volume
while points and points[-1] <= farthest_reachable_point:
reachable_points.append(points.pop())
if reachable_points:
next_point = min(reachable_points, key = lambda point: gas_prices[point])
if farthest_reachable_point >= destination and (current_point == start_point or gas_prices[next_point] >= gas_prices[current_point]):
next_point = destination
else:
reachable_points = [point for point in reachable_points if point > next_point]
else:
if farthest_reachable_point >= destination:
next_point = destination
else:
count = -1
break
distantion = next_point - current_point
if current_point != start_point and next_point != destination and gas_prices[current_point] < gas_prices[next_point]:
required_gas_volume = max_gas_tank_volume
else:
required_gas_volume = distantion
if required_gas_volume > gas_tank_volume:
count += (required_gas_volume - gas_tank_volume)*gas_prices[current_point]
gas_tank_volume = required_gas_volume
current_point = next_point
gas_tank_volume -= distantion
print(count)
```
No
| 93,958 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Johnny drives a truck and must deliver a package from his hometown to the district center. His hometown is located at point 0 on a number line, and the district center is located at the point d.
Johnny's truck has a gas tank that holds exactly n liters, and his tank is initially full. As he drives, the truck consumes exactly one liter per unit distance traveled. Moreover, there are m gas stations located at various points along the way to the district center. The i-th station is located at the point xi on the number line and sells an unlimited amount of fuel at a price of pi dollars per liter. Find the minimum cost Johnny must pay for fuel to successfully complete the delivery.
Input
The first line of input contains three space separated integers d, n, and m (1 ≤ n ≤ d ≤ 109, 1 ≤ m ≤ 200 000) — the total distance to the district center, the volume of the gas tank, and the number of gas stations, respectively.
Each of the next m lines contains two integers xi, pi (1 ≤ xi ≤ d - 1, 1 ≤ pi ≤ 106) — the position and cost of gas at the i-th gas station. It is guaranteed that the positions of the gas stations are distinct.
Output
Print a single integer — the minimum cost to complete the delivery. If there is no way to complete the delivery, print -1.
Examples
Input
10 4 4
3 5
5 8
6 3
8 4
Output
22
Input
16 5 2
8 2
5 1
Output
-1
Note
In the first sample, Johnny's truck holds 4 liters. He can drive 3 units to the first gas station, buy 2 liters of gas there (bringing the tank to 3 liters total), drive 3 more units to the third gas station, buy 4 liters there to fill up his tank, and then drive straight to the district center. His total cost is 2·5 + 4·3 = 22 dollars.
In the second sample, there is no way for Johnny to make it to the district center, as his tank cannot hold enough gas to take him from the latest gas station to the district center.
Submitted Solution:
```
destination, max_gas_tank_volume, gas_prices_number = map(int, input().split())
gas_prices = {}
for i in range(gas_prices_number):
coordinate, price = map(int, input().split())
gas_prices[coordinate] = price
points = sorted(gas_prices.keys(), reverse = True)
start_point = 0
current_point = start_point
count = 0
gas_tank_volume = max_gas_tank_volume
reachable_points = []
while current_point != destination:
farthest_reachable_point = current_point + max_gas_tank_volume
while points and points[-1] <= farthest_reachable_point:
reachable_points.append(points.pop())
if reachable_points:
next_point = min(reachable_points, key = lambda point: gas_prices[point])
if farthest_reachable_point >= destination and (current_point == start_point or gas_prices[next_point] >= gas_prices[current_point]):
next_point = destination
else:
reachable_points = [point for point in reachable_points if point > next_point]
else:
if farthest_reachable_point >= destination:
next_point = destination
else:
count = -1
break
distantion = next_point - current_point
if current_point != start_point and next_point != destination and gas_prices[current_point] <= gas_prices[next_point]:
required_gas_volume = max_gas_tank_volume
else:
required_gas_volume = distantion
if required_gas_volume > gas_tank_volume:
count += (required_gas_volume - gas_tank_volume)*gas_prices[current_point]
gas_tank_volume = required_gas_volume
current_point = next_point
gas_tank_volume -= distantion
print(count)
```
No
| 93,959 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Johnny drives a truck and must deliver a package from his hometown to the district center. His hometown is located at point 0 on a number line, and the district center is located at the point d.
Johnny's truck has a gas tank that holds exactly n liters, and his tank is initially full. As he drives, the truck consumes exactly one liter per unit distance traveled. Moreover, there are m gas stations located at various points along the way to the district center. The i-th station is located at the point xi on the number line and sells an unlimited amount of fuel at a price of pi dollars per liter. Find the minimum cost Johnny must pay for fuel to successfully complete the delivery.
Input
The first line of input contains three space separated integers d, n, and m (1 ≤ n ≤ d ≤ 109, 1 ≤ m ≤ 200 000) — the total distance to the district center, the volume of the gas tank, and the number of gas stations, respectively.
Each of the next m lines contains two integers xi, pi (1 ≤ xi ≤ d - 1, 1 ≤ pi ≤ 106) — the position and cost of gas at the i-th gas station. It is guaranteed that the positions of the gas stations are distinct.
Output
Print a single integer — the minimum cost to complete the delivery. If there is no way to complete the delivery, print -1.
Examples
Input
10 4 4
3 5
5 8
6 3
8 4
Output
22
Input
16 5 2
8 2
5 1
Output
-1
Note
In the first sample, Johnny's truck holds 4 liters. He can drive 3 units to the first gas station, buy 2 liters of gas there (bringing the tank to 3 liters total), drive 3 more units to the third gas station, buy 4 liters there to fill up his tank, and then drive straight to the district center. His total cost is 2·5 + 4·3 = 22 dollars.
In the second sample, there is no way for Johnny to make it to the district center, as his tank cannot hold enough gas to take him from the latest gas station to the district center.
Submitted Solution:
```
destination, max_gas_tank_volume, gas_prices_number = map(int, input().split())
gas_prices = {}
for i in range(gas_prices_number):
coordinate, price = map(int, input().split())
gas_prices[coordinate] = price
points = sorted(gas_prices.keys(), reverse = True)
start_point = 0
current_point = start_point
count = 0
gas_tank_volume = max_gas_tank_volume
reachable_points = []
while current_point != destination:
farthest_reachable_point = current_point + max_gas_tank_volume
while points and points[-1] <= farthest_reachable_point:
reachable_points.append(points.pop())
if reachable_points:
next_point = min(reachable_points, key = lambda point: gas_prices[point])
if farthest_reachable_point >= destination and (current_point == start_point or gas_prices[next_point] >= gas_prices[current_point]):
next_point = destination
else:
reachable_points = [point for point in reachable_points if point > next_point]
else:
if farthest_reachable_point >= destination:
next_point = destination
else:
count = -1
break
distation = next_point - current_point
if current_point != 0 and next_point != destination and gas_prices[current_point] < gas_prices[next_point]:
required_gas_volume = min(max_gas_tank_volume, destination - current_point)
else:
required_gas_volume = distation
if required_gas_volume > gas_tank_volume:
count += (required_gas_volume - gas_tank_volume)*gas_prices[current_point]
gas_tank_volume = required_gas_volume
current_point = next_point
gas_tank_volume -= distation
print(count)
```
No
| 93,960 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Johnny drives a truck and must deliver a package from his hometown to the district center. His hometown is located at point 0 on a number line, and the district center is located at the point d.
Johnny's truck has a gas tank that holds exactly n liters, and his tank is initially full. As he drives, the truck consumes exactly one liter per unit distance traveled. Moreover, there are m gas stations located at various points along the way to the district center. The i-th station is located at the point xi on the number line and sells an unlimited amount of fuel at a price of pi dollars per liter. Find the minimum cost Johnny must pay for fuel to successfully complete the delivery.
Input
The first line of input contains three space separated integers d, n, and m (1 ≤ n ≤ d ≤ 109, 1 ≤ m ≤ 200 000) — the total distance to the district center, the volume of the gas tank, and the number of gas stations, respectively.
Each of the next m lines contains two integers xi, pi (1 ≤ xi ≤ d - 1, 1 ≤ pi ≤ 106) — the position and cost of gas at the i-th gas station. It is guaranteed that the positions of the gas stations are distinct.
Output
Print a single integer — the minimum cost to complete the delivery. If there is no way to complete the delivery, print -1.
Examples
Input
10 4 4
3 5
5 8
6 3
8 4
Output
22
Input
16 5 2
8 2
5 1
Output
-1
Note
In the first sample, Johnny's truck holds 4 liters. He can drive 3 units to the first gas station, buy 2 liters of gas there (bringing the tank to 3 liters total), drive 3 more units to the third gas station, buy 4 liters there to fill up his tank, and then drive straight to the district center. His total cost is 2·5 + 4·3 = 22 dollars.
In the second sample, there is no way for Johnny to make it to the district center, as his tank cannot hold enough gas to take him from the latest gas station to the district center.
Submitted Solution:
```
destination, max_gas_tank_volume, gas_prices_number = map(int, input().split())
gas_prices = {}
for i in range(gas_prices_number):
coordinate, price = map(int, input().split())
gas_prices[coordinate] = price
gas_prices[destination] = 0
points = sorted(gas_prices.keys(), reverse = True)
current_point = 0
count = 0
gas_tank_volume = max_gas_tank_volume
reachable_points = []
while current_point != destination:
while points and points[-1] <= current_point + max_gas_tank_volume:
reachable_points.append(points.pop())
if not reachable_points:
count = -1
break
next_point = min(reachable_points, key = lambda point: gas_prices[point])
reachable_points = [point for point in reachable_points if point > next_point]
distation = next_point - current_point
if distation > gas_tank_volume:
count += (distation - gas_tank_volume)*gas_prices[current_point]
gas_tank_volume = distation
current_point = next_point
gas_tank_volume -= distation
print(count)
```
No
| 93,961 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Tags: data structures, geometry, math
Correct Solution:
```
n = int(input())
d = {}
d2 = {}
d3 = {}
ans = 0
for i in range(n):
x,y = map(int,input().split())
if (x,y) not in d:
d[(x,y)] = 0
d[(x,y)] += 1
if x not in d2:
d2[x] = 0
d2[x] += 1
if y not in d3:
d3[y] = 0
d3[y] += 1
for i in d2:
ans += d2[i]*(d2[i]-1)//2
for i in d3:
ans += d3[i]*(d3[i]-1)//2
for i in d:
ans -= d[i]*(d[i]-1)//2
print(ans)
```
| 93,962 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Tags: data structures, geometry, math
Correct Solution:
```
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def inc_val_of_dict(dictionary, key):
if key not in dictionary:
dictionary[key] = 0
dictionary[key] += 1
def main():
n = int(input())
p_ctr = dict()
x_ctr = dict()
y_ctr = dict()
for _ in range(n):
x, y = map(int, input().split())
inc_val_of_dict(p_ctr, (x, y))
inc_val_of_dict(x_ctr, x)
inc_val_of_dict(y_ctr, y)
answer = 0
for (x, y), num in p_ctr.items():
answer += num * (x_ctr[x] + y_ctr[y] - p_ctr[(x, y)] - 1)
answer //= 2
print(answer)
if __name__ == '__main__':
main()
```
| 93,963 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Tags: data structures, geometry, math
Correct Solution:
```
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
def summa_maksonchik_top_potomu_chto_pishet_cod_na_scretche(n_maksonchik_top_potomu_chto_pishet_cod_na_scretche):
ans_maksonchik_top_potomu_chto_pishet_cod_na_scretche = 0
while n_maksonchik_top_potomu_chto_pishet_cod_na_scretche > 0:
ans_maksonchik_top_potomu_chto_pishet_cod_na_scretche += n_maksonchik_top_potomu_chto_pishet_cod_na_scretche
n_maksonchik_top_potomu_chto_pishet_cod_na_scretche -= 1
return ans_maksonchik_top_potomu_chto_pishet_cod_na_scretche
import sys
n_maksonchik_top_potomu_chto_pishet_cod_na_scretche = int(sys.stdin.readline())
a_maksonchik_top_potomu_chto_pishet_cod_na_scretche = []
ans_maksonchik_top_potomu_chto_pishet_cod_na_scretche = 0
for i_maksonchik_top_potomu_chto_pishet_cod_na_scretche in range(n_maksonchik_top_potomu_chto_pishet_cod_na_scretche):
a_maksonchik_top_potomu_chto_pishet_cod_na_scretche.append(tuple(map(int, sys.stdin.readline().split())))
b_maksonchik_top_potomu_chto_pishet_cod_na_scretche = {}
x_maksonchik_top_potomu_chto_pishet_cod_na_scretche = {}
for i_maksonchik_top_potomu_chto_pishet_cod_na_scretche in a_maksonchik_top_potomu_chto_pishet_cod_na_scretche:
if i_maksonchik_top_potomu_chto_pishet_cod_na_scretche [0] not in x_maksonchik_top_potomu_chto_pishet_cod_na_scretche :
x_maksonchik_top_potomu_chto_pishet_cod_na_scretche[i_maksonchik_top_potomu_chto_pishet_cod_na_scretche[0]] = [1, 0]
b_maksonchik_top_potomu_chto_pishet_cod_na_scretche[i_maksonchik_top_potomu_chto_pishet_cod_na_scretche] = 1
else:
if i_maksonchik_top_potomu_chto_pishet_cod_na_scretche not in b_maksonchik_top_potomu_chto_pishet_cod_na_scretche:
b_maksonchik_top_potomu_chto_pishet_cod_na_scretche[i_maksonchik_top_potomu_chto_pishet_cod_na_scretche] = 1
else:
b_maksonchik_top_potomu_chto_pishet_cod_na_scretche[i_maksonchik_top_potomu_chto_pishet_cod_na_scretche] += 1
x_maksonchik_top_potomu_chto_pishet_cod_na_scretche[i_maksonchik_top_potomu_chto_pishet_cod_na_scretche[0]][0] += 1
x_maksonchik_top_potomu_chto_pishet_cod_na_scretche[i_maksonchik_top_potomu_chto_pishet_cod_na_scretche[0]][1] += x_maksonchik_top_potomu_chto_pishet_cod_na_scretche[i_maksonchik_top_potomu_chto_pishet_cod_na_scretche[0]][0]-1
for i_maksonchik_top_potomu_chto_pishet_cod_na_scretche in x_maksonchik_top_potomu_chto_pishet_cod_na_scretche.values():
ans_maksonchik_top_potomu_chto_pishet_cod_na_scretche += i_maksonchik_top_potomu_chto_pishet_cod_na_scretche[1]
y_maksonchik_top_potomu_chto_pishet_cod_na_scretche = {}
for i_maksonchik_top_potomu_chto_pishet_cod_na_scretche in a_maksonchik_top_potomu_chto_pishet_cod_na_scretche:
if i_maksonchik_top_potomu_chto_pishet_cod_na_scretche[1] not in y_maksonchik_top_potomu_chto_pishet_cod_na_scretche:
y_maksonchik_top_potomu_chto_pishet_cod_na_scretche[i_maksonchik_top_potomu_chto_pishet_cod_na_scretche[1]] = [1, 0]
else:
y_maksonchik_top_potomu_chto_pishet_cod_na_scretche[i_maksonchik_top_potomu_chto_pishet_cod_na_scretche[1]][0] += 1
y_maksonchik_top_potomu_chto_pishet_cod_na_scretche[i_maksonchik_top_potomu_chto_pishet_cod_na_scretche[1]][1] += y_maksonchik_top_potomu_chto_pishet_cod_na_scretche[i_maksonchik_top_potomu_chto_pishet_cod_na_scretche[1]][0]-1
for i_maksonchik_top_potomu_chto_pishet_cod_na_scretche in y_maksonchik_top_potomu_chto_pishet_cod_na_scretche.values():
ans_maksonchik_top_potomu_chto_pishet_cod_na_scretche += i_maksonchik_top_potomu_chto_pishet_cod_na_scretche[1]
for i_maksonchik_top_potomu_chto_pishet_cod_na_scretche in b_maksonchik_top_potomu_chto_pishet_cod_na_scretche.values():
if i_maksonchik_top_potomu_chto_pishet_cod_na_scretche > 1:
ans_maksonchik_top_potomu_chto_pishet_cod_na_scretche -= summa_maksonchik_top_potomu_chto_pishet_cod_na_scretche(i_maksonchik_top_potomu_chto_pishet_cod_na_scretche-1)
print(ans_maksonchik_top_potomu_chto_pishet_cod_na_scretche)
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
#maksonchiktoppotomuchtopishetcodnascretche
```
| 93,964 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Tags: data structures, geometry, math
Correct Solution:
```
n=int(input())
a =0
b =0
s1 = {}
s2 = {}
s3 = {}
for i in range(n):
a,b = map(int, input().split())
s1[a]=s1.get(a,0)+1
s2[b]=s2.get(b,0)+1
tmp = (a,b)
s3[tmp] = s3.get(tmp,0)+1
sum=0
for i in s1.values():
sum+=(i-1)*(i)//2
for i in s2.values():
sum+=(i-1)*(i)//2
for i in s3.values():
sum-=(i-1)*(i)//2
print(sum)
```
| 93,965 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Tags: data structures, geometry, math
Correct Solution:
```
n=int(input())
d1={}
d2={}
same={}
for i in range(n):
a,b=map(int,input().split())
if a in d1.keys():
d1[a]+=1
else:
d1[a]=1
if b in d2.keys():
d2[b]+=1
else:
d2[b]=1
#print(a,b)
if (a,b) in same.keys():
same[(a,b)]+=1
else:
same[(a,b)]=1
#print(d1,d2,same)
ans=0
for i in d1.keys():
if d1[i]>1:
ans+=(d1[i]*(d1[i]-1))//2
for i in d2.keys():
if d2[i]>1:
ans+=(d2[i]*(d2[i]-1))//2
#print(ans)
for i in same.keys():
if same[i]>1:
ans-=(same[i]*(same[i]-1))//2
print(ans)
```
| 93,966 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Tags: data structures, geometry, math
Correct Solution:
```
from collections import defaultdict
n=int(input())
dic,dicx,dicy=defaultdict(int),defaultdict(int),defaultdict(int)
ans=0
for _ in range(n):
x,y=input().split()
x,y=int(x),int(y)
ans += (dicx[x]+dicy[y]-dic[(x,y)])
dicx[x]+=1
dicy[y]+=1
dic[(x,y)]+=1
print(ans)
```
| 93,967 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Tags: data structures, geometry, math
Correct Solution:
```
# link: https://codeforces.com/contest/651/problem/C
import heapq
import os, 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")
from math import ceil
mod = 10 ** 9 + 7
# number of test cases
for _ in range(1):
n = int(input()) # number of watchmen
memo_x = {}
memo_y = {}
memo_xy = {}
pairs = 0
for i in range(n):
x,y = map(int, input().split())
if x not in memo_x: memo_x[x] = 1
else: memo_x[x] += 1
if y not in memo_y: memo_y[y] = 1
else: memo_y[y] += 1
if (x,y) not in memo_xy: memo_xy[(x,y)] = 1
else: memo_xy[(x,y)] += 1
for key, value in memo_x.items():
pairs += (value * (value-1)) // 2
for key, value in memo_y.items():
pairs += (value * (value-1)) // 2
for key, value in memo_xy.items():
pairs -= (value * (value-1)) // 2
print(pairs)
```
| 93,968 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Tags: data structures, geometry, math
Correct Solution:
```
from sys import stdout, stdin, setrecursionlimit
from io import BytesIO, IOBase
from collections import *
from itertools import *
# from random import *
from bisect import *
from string import *
from queue import *
from heapq import *
from math import *
from re import *
from os import *
####################################---fast-input-output----#########################################
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 = read(self._fd, max(fstat(self._fd).st_size, 8192))
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 = read(self._fd, max(fstat(self._fd).st_size, 8192))
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:
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")
stdin, stdout = IOWrapper(stdin), IOWrapper(stdout)
graph, mod, szzz = {}, 10**9 + 7, lambda: sorted(zzz())
def getStr(): return input()
def getInt(): return int(input())
def listStr(): return list(input())
def getStrs(): return input().split()
def isInt(s): return '0' <= s[0] <= '9'
def input(): return stdin.readline().strip()
def zzz(): return [int(i) for i in input().split()]
def output(answer, end='\n'): stdout.write(str(answer) + end)
def lcd(xnum1, xnum2): return (xnum1 * xnum2 // gcd(xnum1, xnum2))
dx = [-1, 1, 0, 0, 1, -1, 1, -1]
dy = [0, 0, 1, -1, 1, -1, -1, 1]
daysInMounth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
#################################################---Some Rule For Me To Follow---#################################
"""
--instants of Reading problem continuously try to understand them.
--If you Know some-one , Then you probably don't know him !
--Try & again try
"""
##################################################---START-CODING---###############################################
num = getInt()
X=[]
Y=[]
XY=[]
for _ in range(num):
x,y=zzz()
X.append(x)
Y.append(y)
XY.append((x,y))
new1= Counter(X)
new2= Counter(Y)
new3=Counter(XY)
ans = 0
for i in new1:
ans+=(new1[i]*(new1[i]-1))//2
for j in new2:
ans+=(new2[j]*(new2[j]-1))//2
for k in new3:
ans-=(new3[k]*(new3[k]-1))//2
print(ans)
```
| 93,969 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Submitted Solution:
```
import math
def nCr(n,r):
if n<r:
return 0
return math.factorial(n) // ((math.factorial(r) * math.factorial(n-r)))
n = int(input())
dict_x ={}
dict_y = {}
dict_x_y = {}
ans = 0
for i in range(n):
x,y = map(int,input().split())
ans += (dict_x.get(x,0)+dict_y.get(y,0) - dict_x_y.get((x,y),0))
dict_x[x] = dict_x.get(x,0)+1
dict_y[y] = dict_y.get(y,0)+1
dict_x_y[(x,y)] = dict_x_y.get((x,y),0)+1
print(ans)
# print(dict_x)
# print(dict_y)
# print(dict_x_y)
```
Yes
| 93,970 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Submitted Solution:
```
n=int(input())
x=[]
y=[]
res=0
for i in range(n):
m,k=(int(z) for z in input().split())
x+=[[m,k]]
y+=[[k,m]]
x.sort()
y.sort()
cur1=x[0][0]
cur2=x[0][1]
count1=1
count2=1
sum1=0
sum2=0
i=1
while i<n:
e=x[i][0]
f=x[i][1]
if e==cur1:
count1+=1
if f==cur2:
count2+=1
else:
cur2=f
sum2+=count2*(count2-1)//2
count2=1
else:
cur1=e
cur2=f
sum1+=count1*(count1-1)//2
count1=1
sum2+=count2*(count2-1)//2
count2=1
i+=1
i=1
sum1+=count1*(count1-1)//2
sum2+=count2*(count2-1)//2
count=1
sum3=0
cur1=y[0][0]
while i<n:
e=y[i][0]
if e==cur1:
count+=1
else:
cur1=e
sum3+=count*(count-1)//2
count=1
i+=1
sum3+=count*(count-1)//2
print(sum1-sum2+sum3)
```
Yes
| 93,971 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Submitted Solution:
```
import math,sys
from collections import Counter, defaultdict, deque
from sys import stdin, stdout
input = stdin.readline
lili=lambda:list(map(int,sys.stdin.readlines()))
li = lambda:list(map(int,input().split()))
#for deque append(),pop(),appendleft(),popleft(),count()
I=lambda:int(input())
S=lambda:input().strip()
n=I()
a=[]
b=[]
for i in range(0,n):
k=li()
a.append(k)
b.append(k[::-1])
a.sort()
b.sort()
temp=a[0][0]
c=1
s=0
for i in range(1,n):
if(a[i][0]==temp):
c+=1
else:
s=s+(c*(c-1))//2
c=1
temp=a[i][0]
s=s+(c*(c-1))//2
c=1
temp=b[0][0]
for i in range(1,n):
if(b[i][0]==temp):
c+=1
else:
s=s+(c*(c-1))//2
c=1
temp=b[i][0]
s=s+(c*(c-1))//2
temp=a[0][0]
temp1=a[0][1]
c=1
d=0
for i in range(1,n):
if(a[i][0]==temp and a[i][1]==temp1):
c+=1
else:
d=d+((c)*(c-1))//2
temp=a[i][0]
temp1=a[i][1]
c=1
d=d+((c)*(c-1))//2
print(s-d)
```
Yes
| 93,972 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Submitted Solution:
```
if __name__=='__main__':
n = int(input())
gx,gy,c= {},{},0
tup = {}
for i in range(n):
x,y= map(int,input().split(' '))
if x in gx and y not in gy:
c += gx[x]
gx[x]+=1
gy[y]=1
tup[(x,y)]=1
elif x not in gx and y in gy:
c += gy[y]
gy[y]+=1
gx[x]=1
tup[(x,y)]=1
elif x not in gx and y not in gy:
gx[x],gy[y],tup[(x,y)]=1,1,1
elif x in gx and y in gy:
if (x,y) in tup:
c+=gx[x]+gy[y]-tup[(x,y)] #common
tup[(x,y)]+=1
else:
c+=gx[x]+gy[y]
tup[(x,y)]=1
gx[x]+=1
gy[y]+=1
#print(gx,gy)
print(c)
```
Yes
| 93,973 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Submitted Solution:
```
n=int(input())
a=[]
for i in range(n):
x,y=map(int,input().split())
a.append([x,y])
c,d=0,0
p,q,r={},{},{}
for i in range(n):
c=a[i][0]
d=a[i][1]
if c in p:
p[c]+=1
else:
p[c]=1
if d in q:
q[d]+=1
else:
q[d]=1
if (c,d) in r:
r[(c,d)]+=1
else:
r[(c,d)]=1
count=0
for i in p.values():
count+=(i*(i-1))//2
for i in q.values():
count+=(i*(i-1))//2
for i in r.values():
count+=(i*(i-1))//2
print(count)
```
No
| 93,974 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Submitted Solution:
```
n = int(input())
dic ={}
X={}
Y={}
for _ in range(n):
tup = tuple(map(int,input().split()))
if tup in dic:
dic[tup]+=1
else:
dic[tup]=1
if tup[0] in X:
X[tup[0]]+=1
else:
X[tup[0]]=1
if tup[1] in Y:
Y[tup[1]]+=1
else:
Y[tup[1]]=1
final = 0
for i in X:
final+= ((X[i])*(X[i]-1))//2
for i in Y:
final+= ((Y[i])*(Y[i]-1))//2
for i in dic:
if dic[i]>1:
if X[i[0]]>dic[i] and Y[i[1]]>dic[i]:
final+= -(((dic[i])*(dic[i]-1))//2)
if n==1000:
for i in X:
if i!=4250:
print(i)
print(final)
```
No
| 93,975 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Submitted Solution:
```
n = int(input())
dic ={}
X={}
Y={}
for _ in range(n):
tup = tuple(map(int,input().split()))
if tup in dic:
dic[tup]+=1
else:
dic[tup]=1
if tup[0] in X:
X[tup[0]]+=1
else:
X[tup[0]]=1
if tup[1] in Y:
Y[tup[1]]+=1
else:
Y[tup[1]]=1
final = 0
for i in X:
final+= ((X[i])*(X[i]-1))//2
for i in Y:
final+= ((Y[i])*(Y[i]-1))//2
for i in dic:
if dic[i]>1:
if X[i[0]]>dic[i] and Y[i[1]]>dic[i]:
final+= -(((dic[i])*(dic[i]-1))//2)
if n==1000:
for i in dic:
if dic[i]>1:
print(i)
print(final)
```
No
| 93,976 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Submitted Solution:
```
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 8 10:55:25 2020
@author: Nada Adel
"""
import os
import sys
from atexit import register
from io import BytesIO
n = int(input())
line=''
x={}
y={}
pairs={}
for i in range(n):
line=input()
line=line.split()
if int(line[0]) not in x:
x[int(line[0])]=1
else:
x[int(line[0])]+=1
if int(line[1]) not in y:
y[int(line[1])]=1
else:
y[int(line[1])]+=1
if (int(line[0]),int(line[1])) not in pairs:
pairs[(int(line[0]),int(line[1]))]=1
else:
pairs[(int(line[0]),int(line[1]))]+=1
sumX=0
sumY=0
sumPairs=0
for key,value in x.items():
if value!=1:
sumX+=value*(value-1)/2.0
for key,value in y.items():
if value!=1:
sumY+=value*(value-1)/2.0
for key,value in pairs.items():
if value!=1:
sumPairs+=value*(value-1)/2.0
print(sumX+sumY-sumPairs)
```
No
| 93,977 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the i-th person is equal to ai.
Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
Input
The first line of the input contains two integers n and h (1 ≤ n ≤ 1000, 1 ≤ h ≤ 1000) — the number of friends and the height of the fence, respectively.
The second line contains n integers ai (1 ≤ ai ≤ 2h), the i-th of them is equal to the height of the i-th person.
Output
Print a single integer — the minimum possible valid width of the road.
Examples
Input
3 7
4 5 14
Output
4
Input
6 1
1 1 1 1 1 1
Output
6
Input
6 5
7 6 8 9 10 5
Output
11
Note
In the first sample, only person number 3 must bend down, so the required width is equal to 1 + 1 + 2 = 4.
In the second sample, all friends are short enough and no one has to bend, so the width 1 + 1 + 1 + 1 + 1 + 1 = 6 is enough.
In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2 + 2 + 2 + 2 + 2 + 1 = 11.
Tags: implementation
Correct Solution:
```
n,h=map(int,input().split())
print(sum([2 if int(i)>h else 1 for i in input().split() ]))
```
| 93,978 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the i-th person is equal to ai.
Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
Input
The first line of the input contains two integers n and h (1 ≤ n ≤ 1000, 1 ≤ h ≤ 1000) — the number of friends and the height of the fence, respectively.
The second line contains n integers ai (1 ≤ ai ≤ 2h), the i-th of them is equal to the height of the i-th person.
Output
Print a single integer — the minimum possible valid width of the road.
Examples
Input
3 7
4 5 14
Output
4
Input
6 1
1 1 1 1 1 1
Output
6
Input
6 5
7 6 8 9 10 5
Output
11
Note
In the first sample, only person number 3 must bend down, so the required width is equal to 1 + 1 + 2 = 4.
In the second sample, all friends are short enough and no one has to bend, so the width 1 + 1 + 1 + 1 + 1 + 1 = 6 is enough.
In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2 + 2 + 2 + 2 + 2 + 1 = 11.
Tags: implementation
Correct Solution:
```
w = 0
n, h = map(int, input().split())
a = [int(x) for x in input().split()]
for i in range(n):
if(a[i] > h):
w += 2
else:
w += 1
print(w)
```
| 93,979 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the i-th person is equal to ai.
Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
Input
The first line of the input contains two integers n and h (1 ≤ n ≤ 1000, 1 ≤ h ≤ 1000) — the number of friends and the height of the fence, respectively.
The second line contains n integers ai (1 ≤ ai ≤ 2h), the i-th of them is equal to the height of the i-th person.
Output
Print a single integer — the minimum possible valid width of the road.
Examples
Input
3 7
4 5 14
Output
4
Input
6 1
1 1 1 1 1 1
Output
6
Input
6 5
7 6 8 9 10 5
Output
11
Note
In the first sample, only person number 3 must bend down, so the required width is equal to 1 + 1 + 2 = 4.
In the second sample, all friends are short enough and no one has to bend, so the width 1 + 1 + 1 + 1 + 1 + 1 = 6 is enough.
In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2 + 2 + 2 + 2 + 2 + 1 = 11.
Tags: implementation
Correct Solution:
```
n=input()
m=input()
a=[]
b=[]
a=n.split(' ')
b=m.split(' ')
j=int(a[0])
l=int(a[1])
ans=j
for i in range(len(b)):
if int(b[i])>l:
ans+=1
print(ans)
```
| 93,980 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the i-th person is equal to ai.
Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
Input
The first line of the input contains two integers n and h (1 ≤ n ≤ 1000, 1 ≤ h ≤ 1000) — the number of friends and the height of the fence, respectively.
The second line contains n integers ai (1 ≤ ai ≤ 2h), the i-th of them is equal to the height of the i-th person.
Output
Print a single integer — the minimum possible valid width of the road.
Examples
Input
3 7
4 5 14
Output
4
Input
6 1
1 1 1 1 1 1
Output
6
Input
6 5
7 6 8 9 10 5
Output
11
Note
In the first sample, only person number 3 must bend down, so the required width is equal to 1 + 1 + 2 = 4.
In the second sample, all friends are short enough and no one has to bend, so the width 1 + 1 + 1 + 1 + 1 + 1 = 6 is enough.
In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2 + 2 + 2 + 2 + 2 + 1 = 11.
Tags: implementation
Correct Solution:
```
n , h = input().split()
n = int(n)
h = int(h)
ans = 0
for i in input().split():
if int(i ) > h :
ans +=2
else:
ans +=1
print(ans)
```
| 93,981 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the i-th person is equal to ai.
Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
Input
The first line of the input contains two integers n and h (1 ≤ n ≤ 1000, 1 ≤ h ≤ 1000) — the number of friends and the height of the fence, respectively.
The second line contains n integers ai (1 ≤ ai ≤ 2h), the i-th of them is equal to the height of the i-th person.
Output
Print a single integer — the minimum possible valid width of the road.
Examples
Input
3 7
4 5 14
Output
4
Input
6 1
1 1 1 1 1 1
Output
6
Input
6 5
7 6 8 9 10 5
Output
11
Note
In the first sample, only person number 3 must bend down, so the required width is equal to 1 + 1 + 2 = 4.
In the second sample, all friends are short enough and no one has to bend, so the width 1 + 1 + 1 + 1 + 1 + 1 = 6 is enough.
In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2 + 2 + 2 + 2 + 2 + 1 = 11.
Tags: implementation
Correct Solution:
```
n, h = map(int, input().split())
v = list(map(int, input().split()))
s = 0
for i in range(0,n):
if v[i]>h:
s+=2
else:
s+=1
print(s)
```
| 93,982 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the i-th person is equal to ai.
Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
Input
The first line of the input contains two integers n and h (1 ≤ n ≤ 1000, 1 ≤ h ≤ 1000) — the number of friends and the height of the fence, respectively.
The second line contains n integers ai (1 ≤ ai ≤ 2h), the i-th of them is equal to the height of the i-th person.
Output
Print a single integer — the minimum possible valid width of the road.
Examples
Input
3 7
4 5 14
Output
4
Input
6 1
1 1 1 1 1 1
Output
6
Input
6 5
7 6 8 9 10 5
Output
11
Note
In the first sample, only person number 3 must bend down, so the required width is equal to 1 + 1 + 2 = 4.
In the second sample, all friends are short enough and no one has to bend, so the width 1 + 1 + 1 + 1 + 1 + 1 = 6 is enough.
In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2 + 2 + 2 + 2 + 2 + 1 = 11.
Tags: implementation
Correct Solution:
```
n,h=map(int,input().split())
l=list(map(int,input().split()))
a=0
for i in range(n):
if l[i]>h:
a=a+2
else:
a=a+1
print(a)
```
| 93,983 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the i-th person is equal to ai.
Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
Input
The first line of the input contains two integers n and h (1 ≤ n ≤ 1000, 1 ≤ h ≤ 1000) — the number of friends and the height of the fence, respectively.
The second line contains n integers ai (1 ≤ ai ≤ 2h), the i-th of them is equal to the height of the i-th person.
Output
Print a single integer — the minimum possible valid width of the road.
Examples
Input
3 7
4 5 14
Output
4
Input
6 1
1 1 1 1 1 1
Output
6
Input
6 5
7 6 8 9 10 5
Output
11
Note
In the first sample, only person number 3 must bend down, so the required width is equal to 1 + 1 + 2 = 4.
In the second sample, all friends are short enough and no one has to bend, so the width 1 + 1 + 1 + 1 + 1 + 1 = 6 is enough.
In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2 + 2 + 2 + 2 + 2 + 1 = 11.
Tags: implementation
Correct Solution:
```
s =input().split()
t = input().split()
p=0
for i in range(0,int(s[0])):
if(int(t[i])<=int(s[1])):
p=p+1
if(int(t[i])>int(s[1])):
p=p+2
print(p)
```
| 93,984 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the i-th person is equal to ai.
Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
Input
The first line of the input contains two integers n and h (1 ≤ n ≤ 1000, 1 ≤ h ≤ 1000) — the number of friends and the height of the fence, respectively.
The second line contains n integers ai (1 ≤ ai ≤ 2h), the i-th of them is equal to the height of the i-th person.
Output
Print a single integer — the minimum possible valid width of the road.
Examples
Input
3 7
4 5 14
Output
4
Input
6 1
1 1 1 1 1 1
Output
6
Input
6 5
7 6 8 9 10 5
Output
11
Note
In the first sample, only person number 3 must bend down, so the required width is equal to 1 + 1 + 2 = 4.
In the second sample, all friends are short enough and no one has to bend, so the width 1 + 1 + 1 + 1 + 1 + 1 = 6 is enough.
In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2 + 2 + 2 + 2 + 2 + 1 = 11.
Tags: implementation
Correct Solution:
```
n, h = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
w = 0
for x in a:
if x > h:
w += 2
continue
w += 1
print(w)
```
| 93,985 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the i-th person is equal to ai.
Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
Input
The first line of the input contains two integers n and h (1 ≤ n ≤ 1000, 1 ≤ h ≤ 1000) — the number of friends and the height of the fence, respectively.
The second line contains n integers ai (1 ≤ ai ≤ 2h), the i-th of them is equal to the height of the i-th person.
Output
Print a single integer — the minimum possible valid width of the road.
Examples
Input
3 7
4 5 14
Output
4
Input
6 1
1 1 1 1 1 1
Output
6
Input
6 5
7 6 8 9 10 5
Output
11
Note
In the first sample, only person number 3 must bend down, so the required width is equal to 1 + 1 + 2 = 4.
In the second sample, all friends are short enough and no one has to bend, so the width 1 + 1 + 1 + 1 + 1 + 1 = 6 is enough.
In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2 + 2 + 2 + 2 + 2 + 1 = 11.
Submitted Solution:
```
nh=input().split()
valuse=input().split()
counter=0
for x in range(int(nh[0])):
if int(valuse[x])>int(nh[1]):
counter+=2
else: counter+=1
print(counter)
```
Yes
| 93,986 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the i-th person is equal to ai.
Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
Input
The first line of the input contains two integers n and h (1 ≤ n ≤ 1000, 1 ≤ h ≤ 1000) — the number of friends and the height of the fence, respectively.
The second line contains n integers ai (1 ≤ ai ≤ 2h), the i-th of them is equal to the height of the i-th person.
Output
Print a single integer — the minimum possible valid width of the road.
Examples
Input
3 7
4 5 14
Output
4
Input
6 1
1 1 1 1 1 1
Output
6
Input
6 5
7 6 8 9 10 5
Output
11
Note
In the first sample, only person number 3 must bend down, so the required width is equal to 1 + 1 + 2 = 4.
In the second sample, all friends are short enough and no one has to bend, so the width 1 + 1 + 1 + 1 + 1 + 1 = 6 is enough.
In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2 + 2 + 2 + 2 + 2 + 1 = 11.
Submitted Solution:
```
a ,b= input().split(' ')
a=int(a)
b=int(b)
ar = list(map(int, input().strip().split(' ')))
sum=0
i=0
while a!=i:
if ar[i]>b:
sum+=2
else:
sum+=1
i+=1
print(sum)
```
Yes
| 93,987 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the i-th person is equal to ai.
Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
Input
The first line of the input contains two integers n and h (1 ≤ n ≤ 1000, 1 ≤ h ≤ 1000) — the number of friends and the height of the fence, respectively.
The second line contains n integers ai (1 ≤ ai ≤ 2h), the i-th of them is equal to the height of the i-th person.
Output
Print a single integer — the minimum possible valid width of the road.
Examples
Input
3 7
4 5 14
Output
4
Input
6 1
1 1 1 1 1 1
Output
6
Input
6 5
7 6 8 9 10 5
Output
11
Note
In the first sample, only person number 3 must bend down, so the required width is equal to 1 + 1 + 2 = 4.
In the second sample, all friends are short enough and no one has to bend, so the width 1 + 1 + 1 + 1 + 1 + 1 = 6 is enough.
In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2 + 2 + 2 + 2 + 2 + 1 = 11.
Submitted Solution:
```
Line1=input("")
Line2=input("")
Parameter=list(map(int, Line1.split(' ')))
h=Parameter[1] # Height of the fence
N=Parameter[0] # Number of people
Array=list(map(int, Line2.split(' ')))
min_width=0
for itr in range(0, N):
if Array[itr]>h:
min_width+=2
elif Array[itr]<=h:
min_width+=1
print(min_width)
```
Yes
| 93,988 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the i-th person is equal to ai.
Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
Input
The first line of the input contains two integers n and h (1 ≤ n ≤ 1000, 1 ≤ h ≤ 1000) — the number of friends and the height of the fence, respectively.
The second line contains n integers ai (1 ≤ ai ≤ 2h), the i-th of them is equal to the height of the i-th person.
Output
Print a single integer — the minimum possible valid width of the road.
Examples
Input
3 7
4 5 14
Output
4
Input
6 1
1 1 1 1 1 1
Output
6
Input
6 5
7 6 8 9 10 5
Output
11
Note
In the first sample, only person number 3 must bend down, so the required width is equal to 1 + 1 + 2 = 4.
In the second sample, all friends are short enough and no one has to bend, so the width 1 + 1 + 1 + 1 + 1 + 1 = 6 is enough.
In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2 + 2 + 2 + 2 + 2 + 1 = 11.
Submitted Solution:
```
n, h = [int(i) for i in input().split()]
high = [int(i) for i in input().split()]
y = 0
for x in high :
if x > h:
y += 2
else:
y += 1
print(y)
```
Yes
| 93,989 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the i-th person is equal to ai.
Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
Input
The first line of the input contains two integers n and h (1 ≤ n ≤ 1000, 1 ≤ h ≤ 1000) — the number of friends and the height of the fence, respectively.
The second line contains n integers ai (1 ≤ ai ≤ 2h), the i-th of them is equal to the height of the i-th person.
Output
Print a single integer — the minimum possible valid width of the road.
Examples
Input
3 7
4 5 14
Output
4
Input
6 1
1 1 1 1 1 1
Output
6
Input
6 5
7 6 8 9 10 5
Output
11
Note
In the first sample, only person number 3 must bend down, so the required width is equal to 1 + 1 + 2 = 4.
In the second sample, all friends are short enough and no one has to bend, so the width 1 + 1 + 1 + 1 + 1 + 1 = 6 is enough.
In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2 + 2 + 2 + 2 + 2 + 1 = 11.
Submitted Solution:
```
l1=list(map(int,input().split()))
l2=list(map(int,input().split()))
l2=l2[0:l1[0]]
s=0
for a in l2:
s+=1
if a>l2[1]:
s+=1
print(s)
```
No
| 93,990 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the i-th person is equal to ai.
Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
Input
The first line of the input contains two integers n and h (1 ≤ n ≤ 1000, 1 ≤ h ≤ 1000) — the number of friends and the height of the fence, respectively.
The second line contains n integers ai (1 ≤ ai ≤ 2h), the i-th of them is equal to the height of the i-th person.
Output
Print a single integer — the minimum possible valid width of the road.
Examples
Input
3 7
4 5 14
Output
4
Input
6 1
1 1 1 1 1 1
Output
6
Input
6 5
7 6 8 9 10 5
Output
11
Note
In the first sample, only person number 3 must bend down, so the required width is equal to 1 + 1 + 2 = 4.
In the second sample, all friends are short enough and no one has to bend, so the width 1 + 1 + 1 + 1 + 1 + 1 = 6 is enough.
In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2 + 2 + 2 + 2 + 2 + 1 = 11.
Submitted Solution:
```
n = 0
x = []
h = 0
ans = 0
ans = n
for i in range(len(x)):
if(x[i] > h):
ans = ans + 1
print(ans)
```
No
| 93,991 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the i-th person is equal to ai.
Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
Input
The first line of the input contains two integers n and h (1 ≤ n ≤ 1000, 1 ≤ h ≤ 1000) — the number of friends and the height of the fence, respectively.
The second line contains n integers ai (1 ≤ ai ≤ 2h), the i-th of them is equal to the height of the i-th person.
Output
Print a single integer — the minimum possible valid width of the road.
Examples
Input
3 7
4 5 14
Output
4
Input
6 1
1 1 1 1 1 1
Output
6
Input
6 5
7 6 8 9 10 5
Output
11
Note
In the first sample, only person number 3 must bend down, so the required width is equal to 1 + 1 + 2 = 4.
In the second sample, all friends are short enough and no one has to bend, so the width 1 + 1 + 1 + 1 + 1 + 1 = 6 is enough.
In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2 + 2 + 2 + 2 + 2 + 1 = 11.
Submitted Solution:
```
n,h = map(int,input().split())
c = 0
b = 0
l = list(map(int,input().split()))
for i in l:
if i <= h:
c += 1
elif i > b:
b += 2
print(b+c)
```
No
| 93,992 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the i-th person is equal to ai.
Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
Input
The first line of the input contains two integers n and h (1 ≤ n ≤ 1000, 1 ≤ h ≤ 1000) — the number of friends and the height of the fence, respectively.
The second line contains n integers ai (1 ≤ ai ≤ 2h), the i-th of them is equal to the height of the i-th person.
Output
Print a single integer — the minimum possible valid width of the road.
Examples
Input
3 7
4 5 14
Output
4
Input
6 1
1 1 1 1 1 1
Output
6
Input
6 5
7 6 8 9 10 5
Output
11
Note
In the first sample, only person number 3 must bend down, so the required width is equal to 1 + 1 + 2 = 4.
In the second sample, all friends are short enough and no one has to bend, so the width 1 + 1 + 1 + 1 + 1 + 1 = 6 is enough.
In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2 + 2 + 2 + 2 + 2 + 1 = 11.
Submitted Solution:
```
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 15 15:36:21 2020
@author: 86198
"""
n,h=map(int,input().split());x=0
listi=[int(i)for i in input().split()]
for i in listi:
if i<h:
x=x+1
else:
x=x+2
print(x)
```
No
| 93,993 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allowed to break the sticks or use their partial length. Anne has perfectly solved this task, now she is asking Johnny to do the same.
The boy answered that he would cope with it without any difficulty. However, after a while he found out that different tricky things can occur. It can happen that it is impossible to construct a triangle of a positive area, but it is possible to construct a degenerate triangle. It can be so, that it is impossible to construct a degenerate triangle even. As Johnny is very lazy, he does not want to consider such a big amount of cases, he asks you to help him.
Input
The first line of the input contains four space-separated positive integer numbers not exceeding 100 — lengthes of the sticks.
Output
Output TRIANGLE if it is possible to construct a non-degenerate triangle. Output SEGMENT if the first case cannot take place and it is possible to construct a degenerate triangle. Output IMPOSSIBLE if it is impossible to construct any triangle. Remember that you are to use three sticks. It is not allowed to break the sticks or use their partial length.
Examples
Input
4 2 1 3
Output
TRIANGLE
Input
7 2 2 4
Output
SEGMENT
Input
3 5 9 1
Output
IMPOSSIBLE
Tags: brute force, geometry
Correct Solution:
```
ints,answer = list(reversed(sorted(list(map(int, input().split(' ')))))), "IMPOSSIBLE"
if ints[0] < ints[1] + ints[2]:
#0 did work
answer = "TRIANGLE"
elif ints[0] == ints[1] + ints[2]:
#segment only a triangle is better.
answer = "SEGMENT"
if ints[1] < ints[2] + ints[3]:
#1 did work
answer = "TRIANGLE"
else:
# a triangle or segment is needed.
if ints[1] < ints[2] + ints[3]:
#1 did work
answer = "TRIANGLE"
elif ints[1] == ints[2] + ints[3]:
answer = "SEGMENT"
print(answer)
```
| 93,994 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allowed to break the sticks or use their partial length. Anne has perfectly solved this task, now she is asking Johnny to do the same.
The boy answered that he would cope with it without any difficulty. However, after a while he found out that different tricky things can occur. It can happen that it is impossible to construct a triangle of a positive area, but it is possible to construct a degenerate triangle. It can be so, that it is impossible to construct a degenerate triangle even. As Johnny is very lazy, he does not want to consider such a big amount of cases, he asks you to help him.
Input
The first line of the input contains four space-separated positive integer numbers not exceeding 100 — lengthes of the sticks.
Output
Output TRIANGLE if it is possible to construct a non-degenerate triangle. Output SEGMENT if the first case cannot take place and it is possible to construct a degenerate triangle. Output IMPOSSIBLE if it is impossible to construct any triangle. Remember that you are to use three sticks. It is not allowed to break the sticks or use their partial length.
Examples
Input
4 2 1 3
Output
TRIANGLE
Input
7 2 2 4
Output
SEGMENT
Input
3 5 9 1
Output
IMPOSSIBLE
Tags: brute force, geometry
Correct Solution:
```
def task():
a,b,c,d = input().split()
a,b,c,d = [int(a),int(b),int(c),int(d)]
if (a+b>c and a+c>b and c+b>a) or (d+a>b and d+b>a and a+b>d) or (a+c>d and c+d>a and d+a>c) or (b+c>d and b+d>c and d+c>b):
return("TRIANGLE")
elif a+b==c or a+d==c or d+b==c or a+c==d or a+b==d or c+b==d or c+b==a or c+d==a or d+b==a or a+c==b or a+d==b or c+d==b:
return("SEGMENT")
else:
return("IMPOSSIBLE")
print(task())
```
| 93,995 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allowed to break the sticks or use their partial length. Anne has perfectly solved this task, now she is asking Johnny to do the same.
The boy answered that he would cope with it without any difficulty. However, after a while he found out that different tricky things can occur. It can happen that it is impossible to construct a triangle of a positive area, but it is possible to construct a degenerate triangle. It can be so, that it is impossible to construct a degenerate triangle even. As Johnny is very lazy, he does not want to consider such a big amount of cases, he asks you to help him.
Input
The first line of the input contains four space-separated positive integer numbers not exceeding 100 — lengthes of the sticks.
Output
Output TRIANGLE if it is possible to construct a non-degenerate triangle. Output SEGMENT if the first case cannot take place and it is possible to construct a degenerate triangle. Output IMPOSSIBLE if it is impossible to construct any triangle. Remember that you are to use three sticks. It is not allowed to break the sticks or use their partial length.
Examples
Input
4 2 1 3
Output
TRIANGLE
Input
7 2 2 4
Output
SEGMENT
Input
3 5 9 1
Output
IMPOSSIBLE
Tags: brute force, geometry
Correct Solution:
```
arr = list(map(int, input().strip().split()))
arr.sort()
a, b, c, d = arr
if a+b < c:
if b+c > d:
print('TRIANGLE')
elif b+c == d:
print('SEGMENT')
else:
print('IMPOSSIBLE')
elif a+b == c:
if b+c > d:
print('TRIANGLE')
else:
print('SEGMENT')
else:
print('TRIANGLE')
```
| 93,996 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allowed to break the sticks or use their partial length. Anne has perfectly solved this task, now she is asking Johnny to do the same.
The boy answered that he would cope with it without any difficulty. However, after a while he found out that different tricky things can occur. It can happen that it is impossible to construct a triangle of a positive area, but it is possible to construct a degenerate triangle. It can be so, that it is impossible to construct a degenerate triangle even. As Johnny is very lazy, he does not want to consider such a big amount of cases, he asks you to help him.
Input
The first line of the input contains four space-separated positive integer numbers not exceeding 100 — lengthes of the sticks.
Output
Output TRIANGLE if it is possible to construct a non-degenerate triangle. Output SEGMENT if the first case cannot take place and it is possible to construct a degenerate triangle. Output IMPOSSIBLE if it is impossible to construct any triangle. Remember that you are to use three sticks. It is not allowed to break the sticks or use their partial length.
Examples
Input
4 2 1 3
Output
TRIANGLE
Input
7 2 2 4
Output
SEGMENT
Input
3 5 9 1
Output
IMPOSSIBLE
Tags: brute force, geometry
Correct Solution:
```
a=list(map(int,input().split()))
a.sort()
if a[0]+a[1]>a[2]:
print("TRIANGLE")
elif a[1]+a[2]>a[3]:
print("TRIANGLE")
elif a[0]+a[1]==a[2] or a[1]+a[2]==a[3]:
print("SEGMENT")
else:
print("IMPOSSIBLE")
```
| 93,997 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allowed to break the sticks or use their partial length. Anne has perfectly solved this task, now she is asking Johnny to do the same.
The boy answered that he would cope with it without any difficulty. However, after a while he found out that different tricky things can occur. It can happen that it is impossible to construct a triangle of a positive area, but it is possible to construct a degenerate triangle. It can be so, that it is impossible to construct a degenerate triangle even. As Johnny is very lazy, he does not want to consider such a big amount of cases, he asks you to help him.
Input
The first line of the input contains four space-separated positive integer numbers not exceeding 100 — lengthes of the sticks.
Output
Output TRIANGLE if it is possible to construct a non-degenerate triangle. Output SEGMENT if the first case cannot take place and it is possible to construct a degenerate triangle. Output IMPOSSIBLE if it is impossible to construct any triangle. Remember that you are to use three sticks. It is not allowed to break the sticks or use their partial length.
Examples
Input
4 2 1 3
Output
TRIANGLE
Input
7 2 2 4
Output
SEGMENT
Input
3 5 9 1
Output
IMPOSSIBLE
Tags: brute force, geometry
Correct Solution:
```
x,y,z,w=map(int,input().split())
arr=[]
arr.append(x)
arr.append(y)
arr.append(z)
arr.append(w)
arr.sort()
# print(arr)
if (arr[0]+arr[1]>arr[2]) or (arr[0]+arr[1]>arr[3]) or (arr[1]+arr[2]>arr[3]):
print("TRIANGLE")
elif (arr[0]+arr[1]==arr[2]) or (arr[0]+arr[1]==arr[3]) or (arr[1]+arr[2]==arr[3]):
print("SEGMENT")
else:
print("IMPOSSIBLE")
```
| 93,998 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allowed to break the sticks or use their partial length. Anne has perfectly solved this task, now she is asking Johnny to do the same.
The boy answered that he would cope with it without any difficulty. However, after a while he found out that different tricky things can occur. It can happen that it is impossible to construct a triangle of a positive area, but it is possible to construct a degenerate triangle. It can be so, that it is impossible to construct a degenerate triangle even. As Johnny is very lazy, he does not want to consider such a big amount of cases, he asks you to help him.
Input
The first line of the input contains four space-separated positive integer numbers not exceeding 100 — lengthes of the sticks.
Output
Output TRIANGLE if it is possible to construct a non-degenerate triangle. Output SEGMENT if the first case cannot take place and it is possible to construct a degenerate triangle. Output IMPOSSIBLE if it is impossible to construct any triangle. Remember that you are to use three sticks. It is not allowed to break the sticks or use their partial length.
Examples
Input
4 2 1 3
Output
TRIANGLE
Input
7 2 2 4
Output
SEGMENT
Input
3 5 9 1
Output
IMPOSSIBLE
Tags: brute force, geometry
Correct Solution:
```
l = list(map(int, input().split()))
m = l[0]
l.sort()
if ((l[0]+l[1])>l[2]) or ((l[1]+l[2])>l[3]):
print('TRIANGLE')
elif ((l[0]+l[1]) == l[2]) or ((l[1]+l[2]) == l[3]):
print('SEGMENT')
else:
print('IMPOSSIBLE')
```
| 93,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.