message stringlengths 2 23.4k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 129 108k | cluster float64 6 6 | __index_level_0__ int64 258 216k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.
The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:
1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.
2. The i-th element of the array is subtracted from the result of the previous step modulo 256.
3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.
You are given the text printed using this method. Restore the array used to produce this text.
Input
The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.
Output
Output the initial array, which was used to produce text, one integer per line.
Examples
Input
Hello, World!
Output
238
108
112
0
64
194
48
26
244
168
24
16
162
Note
Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b. | instruction | 0 | 26,691 | 6 | 53,382 |
Tags: implementation
Correct Solution:
```
'''''''''''
Author : code_marshal
Method : strings
'''''''''''
x, f = input(), 0
for i in x:
h = bin(ord(i))[2:]; h = ('0' * (8 - len(h)) + h)[::-1]
print ((f - int(h, 2)) % 256)
f = int(h, 2)
``` | output | 1 | 26,691 | 6 | 53,383 |
Provide tags and a correct Python 3 solution for this coding contest problem.
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.
The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:
1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.
2. The i-th element of the array is subtracted from the result of the previous step modulo 256.
3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.
You are given the text printed using this method. Restore the array used to produce this text.
Input
The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.
Output
Output the initial array, which was used to produce text, one integer per line.
Examples
Input
Hello, World!
Output
238
108
112
0
64
194
48
26
244
168
24
16
162
Note
Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b. | instruction | 0 | 26,692 | 6 | 53,384 |
Tags: implementation
Correct Solution:
```
old=0
for c in input():
s=bin(ord(c))[2:][::-1]
now=int(s+"0"*(8-len(s)),2)
print((old-now)%256)
old=now
``` | output | 1 | 26,692 | 6 | 53,385 |
Provide tags and a correct Python 3 solution for this coding contest problem.
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.
The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:
1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.
2. The i-th element of the array is subtracted from the result of the previous step modulo 256.
3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.
You are given the text printed using this method. Restore the array used to produce this text.
Input
The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.
Output
Output the initial array, which was used to produce text, one integer per line.
Examples
Input
Hello, World!
Output
238
108
112
0
64
194
48
26
244
168
24
16
162
Note
Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b. | instruction | 0 | 26,693 | 6 | 53,386 |
Tags: implementation
Correct Solution:
```
s = input()
A = []
A.append(0)
for i in s:
codigo = ord(i)
sCodigo = bin(codigo).lstrip("0b")
sCodigo = sCodigo.rjust(8, '0')
sCodigo = sCodigo[::-1]
x = int(sCodigo, 2)
A.append(x)
size = len(s)
for i in range(0, size):
print((A[i] - A[i + 1]) % 256)
``` | output | 1 | 26,693 | 6 | 53,387 |
Provide tags and a correct Python 3 solution for this coding contest problem.
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.
The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:
1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.
2. The i-th element of the array is subtracted from the result of the previous step modulo 256.
3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.
You are given the text printed using this method. Restore the array used to produce this text.
Input
The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.
Output
Output the initial array, which was used to produce text, one integer per line.
Examples
Input
Hello, World!
Output
238
108
112
0
64
194
48
26
244
168
24
16
162
Note
Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b. | instruction | 0 | 26,694 | 6 | 53,388 |
Tags: implementation
Correct Solution:
```
def sum_pow(n):
mem = [1]
for i in range(8):
mem.append((n * mem[i]))
return mem
mem ,pre= sum_pow(2),0
for i in input():
asc, sum, c= ord(i), 0, 7
while (asc != 0):
sum += (asc % 2) * mem[c]
asc //= 2
c -= 1
print((pre - sum) % 256)
pre = sum
``` | output | 1 | 26,694 | 6 | 53,389 |
Provide tags and a correct Python 3 solution for this coding contest problem.
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.
The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:
1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.
2. The i-th element of the array is subtracted from the result of the previous step modulo 256.
3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.
You are given the text printed using this method. Restore the array used to produce this text.
Input
The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.
Output
Output the initial array, which was used to produce text, one integer per line.
Examples
Input
Hello, World!
Output
238
108
112
0
64
194
48
26
244
168
24
16
162
Note
Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b. | instruction | 0 | 26,695 | 6 | 53,390 |
Tags: implementation
Correct Solution:
```
s = input()
f = 0
for i in range(len(s)):
asc = ord(s[i])
bi = format(asc, "08b")
bi = bi[::-1]
sasc = int(bi, 2)
res = (f - sasc) % 256
f = sasc
print(res)
``` | output | 1 | 26,695 | 6 | 53,391 |
Provide tags and a correct Python 3 solution for this coding contest problem.
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.
The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:
1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.
2. The i-th element of the array is subtracted from the result of the previous step modulo 256.
3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.
You are given the text printed using this method. Restore the array used to produce this text.
Input
The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.
Output
Output the initial array, which was used to produce text, one integer per line.
Examples
Input
Hello, World!
Output
238
108
112
0
64
194
48
26
244
168
24
16
162
Note
Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b. | instruction | 0 | 26,696 | 6 | 53,392 |
Tags: implementation
Correct Solution:
```
def obin(a):
a = ord(a)
text = bin(a)[bin(a).find('1'):]
ntext = '0'*(8-len(text))+text
return ntext
def rev(a):
return a[-1::-1]
def revascii(char):
return int(rev(obin(char)),base=2)
text = input()
for i in range(len(text)):
if i == 0:
lastele = 0
else:
lastele = revascii(text[i-1])
print((lastele-revascii(text[i]))%256)
``` | output | 1 | 26,696 | 6 | 53,393 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.
The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:
1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.
2. The i-th element of the array is subtracted from the result of the previous step modulo 256.
3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.
You are given the text printed using this method. Restore the array used to produce this text.
Input
The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.
Output
Output the initial array, which was used to produce text, one integer per line.
Examples
Input
Hello, World!
Output
238
108
112
0
64
194
48
26
244
168
24
16
162
Note
Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b.
Submitted Solution:
```
k = 0
word = input()
for i in word:
asci = ord(i)
s1 = int(bin(asci)[2:].rjust(8, '0')[::-1], base=2)
s2 = (k - s1) % 256
k = s1
print(s2)
``` | instruction | 0 | 26,697 | 6 | 53,394 |
Yes | output | 1 | 26,697 | 6 | 53,395 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.
The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:
1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.
2. The i-th element of the array is subtracted from the result of the previous step modulo 256.
3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.
You are given the text printed using this method. Restore the array used to produce this text.
Input
The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.
Output
Output the initial array, which was used to produce text, one integer per line.
Examples
Input
Hello, World!
Output
238
108
112
0
64
194
48
26
244
168
24
16
162
Note
Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b.
Submitted Solution:
```
a = input()
l = len(a)
b = []
k = 0
for i in range(l):
p = bin(ord(a[i]))[2:]
q = len(p)
while q<8:
p="0"+p
q+=1
p = p[::-1]
p = int(p,2)
x = (k-p)%256
b.append(x)
k = p
for i in b:
print(i)
``` | instruction | 0 | 26,698 | 6 | 53,396 |
Yes | output | 1 | 26,698 | 6 | 53,397 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.
The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:
1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.
2. The i-th element of the array is subtracted from the result of the previous step modulo 256.
3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.
You are given the text printed using this method. Restore the array used to produce this text.
Input
The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.
Output
Output the initial array, which was used to produce text, one integer per line.
Examples
Input
Hello, World!
Output
238
108
112
0
64
194
48
26
244
168
24
16
162
Note
Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b.
Submitted Solution:
```
import sys
import math
stra=str(input())
scar=[ord(stra[int(i)]) for i in range(len(stra))]
val=[]
k,ans,kaa=0,0,0
for i in range(len(scar)):
s=""
while(scar[i]!=0):
s+=str(scar[i]&1)
scar[i]>>=1
if(len(s)<8):
s+="0"*(8-len(s))
kaa=int(s,2)
#print(kaa)
val.append(kaa)
ans=(k - val[-1]) % 256
print((k-val[-1])%256)
k=int(s,2)
#print("k=",k)
``` | instruction | 0 | 26,699 | 6 | 53,398 |
Yes | output | 1 | 26,699 | 6 | 53,399 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.
The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:
1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.
2. The i-th element of the array is subtracted from the result of the previous step modulo 256.
3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.
You are given the text printed using this method. Restore the array used to produce this text.
Input
The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.
Output
Output the initial array, which was used to produce text, one integer per line.
Examples
Input
Hello, World!
Output
238
108
112
0
64
194
48
26
244
168
24
16
162
Note
Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b.
Submitted Solution:
```
def f(x):
a = bin(x)[2:]
b = '0' * (8 - len(a)) + a
return int(b[::-1], 2)
rev = [0] * 260
for i in range(257):
rev[i] = f(i)
x = input()
k = [0]
for i in x:
k.append(ord(i))
for i in range(len(x)):
print((f(k[i]) - f(k[i+1]))%256)
``` | instruction | 0 | 26,700 | 6 | 53,400 |
Yes | output | 1 | 26,700 | 6 | 53,401 |
Provide tags and a correct Python 3 solution for this coding contest problem.
While exploring the old caves, researchers found a book, or more precisely, a stash of mixed pages from a book. Luckily, all of the original pages are present and each page contains its number. Therefore, the researchers can reconstruct the book.
After taking a deeper look into the contents of these pages, linguists think that this may be some kind of dictionary. What's interesting is that this ancient civilization used an alphabet which is a subset of the English alphabet, however, the order of these letters in the alphabet is not like the one in the English language.
Given the contents of pages that researchers have found, your task is to reconstruct the alphabet of this ancient civilization using the provided pages from the dictionary.
Input
First-line contains two integers: n and k (1 β€ n, k β€ 10^3) β the number of pages that scientists have found and the number of words present at each page. Following n groups contain a line with a single integer p_i (0 β€ n < 10^3) β the number of i-th page, as well as k lines, each line containing one of the strings (up to 100 characters) written on the page numbered p_i.
Output
Output a string representing the reconstructed alphabet of this ancient civilization. If the book found is not a dictionary, output "IMPOSSIBLE" without quotes. In case there are multiple solutions, output any of them.
Example
Input
3 3
2
b
b
bbac
0
a
aca
acba
1
ab
c
ccb
Output
acb | instruction | 0 | 26,716 | 6 | 53,432 |
Tags: graphs, sortings
Correct Solution:
```
import os
import io
from collections import deque, defaultdict
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def li():return [int(i) for i in input().rstrip().split()]
def st():return str(input().rstrip())[2:-1]
def val():return int(input().rstrip())
# def li():return [int(i) for i in input().rstrip().split()]
# def st():return str(input())
# def val():return int(input())
#Input Reading
n,k = li()
pages = []
abc = set()
for _ in range(n):
p = val()
page = []
for i in range(k):
word = st()
page.append(word)
abc |= set(page[-1])
pages.append((p,page))
pages.sort(key = lambda x: x[0])
words = []
for _,page in pages:
words.extend(page)
if n == k == 1:
print(''.join(abc))
exit()
def match(w1,w2):
for i in range(min(len(w1), len(w2))):
if w1[i] == w2[i]:
continue
else:
return (w1[i],w2[i])
if len(w1) > len(w2):
print("IMPOSSIBLE")
exit()
#Reading the graph and its indegrees
g = defaultdict(set)
indeg = defaultdict(int)
for i in range(len(words) - 1):
out = match(words[i], words[i+1])
if out is not None:
c1,c2 = out
if c2 not in g[c1]:
g[c1].add(c2)
indeg[c2] += 1
#Topsort things
ts = []
zero = deque()
for u in g:
if indeg[u] == 0:
zero.append(u)
while len(ts) != len(abc):
if len(zero) == 0:
print("IMPOSSIBLE")
exit()
u = zero.popleft()
ts.append(u)
for v in g[u]:
indeg[v] -= 1
if indeg[v] == 0:
zero.append(v)
print("".join(ts))
``` | output | 1 | 26,716 | 6 | 53,433 |
Provide tags and a correct Python 3 solution for this coding contest problem.
While exploring the old caves, researchers found a book, or more precisely, a stash of mixed pages from a book. Luckily, all of the original pages are present and each page contains its number. Therefore, the researchers can reconstruct the book.
After taking a deeper look into the contents of these pages, linguists think that this may be some kind of dictionary. What's interesting is that this ancient civilization used an alphabet which is a subset of the English alphabet, however, the order of these letters in the alphabet is not like the one in the English language.
Given the contents of pages that researchers have found, your task is to reconstruct the alphabet of this ancient civilization using the provided pages from the dictionary.
Input
First-line contains two integers: n and k (1 β€ n, k β€ 10^3) β the number of pages that scientists have found and the number of words present at each page. Following n groups contain a line with a single integer p_i (0 β€ n < 10^3) β the number of i-th page, as well as k lines, each line containing one of the strings (up to 100 characters) written on the page numbered p_i.
Output
Output a string representing the reconstructed alphabet of this ancient civilization. If the book found is not a dictionary, output "IMPOSSIBLE" without quotes. In case there are multiple solutions, output any of them.
Example
Input
3 3
2
b
b
bbac
0
a
aca
acba
1
ab
c
ccb
Output
acb | instruction | 0 | 26,717 | 6 | 53,434 |
Tags: graphs, sortings
Correct Solution:
```
from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop
import math
from collections import *
from functools import reduce,cmp_to_key,lru_cache
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
# import sys
# input = sys.stdin.readline
M = mod = 10**9 + 7
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)
def li():return [int(i) for i in input().rstrip().split()]
def st():return str(input().rstrip())[2:-1]
def val():return int(input().rstrip())
def li2():return [str(i)[2:-1] for i in input().rstrip().split()]
def li3():return [int(i) for i in st()]
graph = defaultdict(set)
n, k = li()
l = []
allwords = set()
for i in range(n):
p = val()
l1 = []
for j in range(k):l1.append(st())
allwords |= set(l1[-1])
l.append([p, l1[:]])
l.sort(key = lambda x:x[0])
l = [i[1] for i in l]
if n == k == 1:
print(''.join(set(l[0][0])))
exit()
ingraph = defaultdict(int)
def match(a, b):
for j in range(min(len(a), len(b))):
if a[j] == b[j]:continue
elif b[j] in graph[a[j]]:return
else:
graph[a[j]].add(b[j])
ingraph[b[j]] += 1
return
if len(a) > len(b):
print('IMPOSSIBLE')
exit()
finl = []
for i in l:finl.extend(i)
l = finl
# for i in l:print(i)
for i in range(1, len(l)):
match(l[i - 1], l[i])
# print(graph)
# print(ingraph)
if min([ingraph[j] for j in graph]) != 0:
print('IMPOSSIBLE')
exit()
ans = ''
d = deque()
for j in graph:
if ingraph[j] == 0:
d.append(j)
while d:
node = d.popleft()
ans += node
for j in graph[node]:
ingraph[j] -= 1
if not ingraph[j]:d.append(j)
if len(ans) != len(allwords):
print('IMPOSSIBLE')
exit()
print(ans)
``` | output | 1 | 26,717 | 6 | 53,435 |
Provide tags and a correct Python 3 solution for this coding contest problem.
While exploring the old caves, researchers found a book, or more precisely, a stash of mixed pages from a book. Luckily, all of the original pages are present and each page contains its number. Therefore, the researchers can reconstruct the book.
After taking a deeper look into the contents of these pages, linguists think that this may be some kind of dictionary. What's interesting is that this ancient civilization used an alphabet which is a subset of the English alphabet, however, the order of these letters in the alphabet is not like the one in the English language.
Given the contents of pages that researchers have found, your task is to reconstruct the alphabet of this ancient civilization using the provided pages from the dictionary.
Input
First-line contains two integers: n and k (1 β€ n, k β€ 10^3) β the number of pages that scientists have found and the number of words present at each page. Following n groups contain a line with a single integer p_i (0 β€ n < 10^3) β the number of i-th page, as well as k lines, each line containing one of the strings (up to 100 characters) written on the page numbered p_i.
Output
Output a string representing the reconstructed alphabet of this ancient civilization. If the book found is not a dictionary, output "IMPOSSIBLE" without quotes. In case there are multiple solutions, output any of them.
Example
Input
3 3
2
b
b
bbac
0
a
aca
acba
1
ab
c
ccb
Output
acb | instruction | 0 | 26,718 | 6 | 53,436 |
Tags: graphs, sortings
Correct Solution:
```
import os
import io
from collections import deque, defaultdict
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def li():return [int(i) for i in input().rstrip().split()]
def st():return str(input().rstrip())[2:-1]
def val():return int(input().rstrip())
# def li():return [int(i) for i in input().rstrip().split()]
# def st():return str(input())
# def val():return int(input())
#Input Reading
n,k = li()
words = [""] * n * k
indeg = {}
for i in range(n):
p = val()
page = []
for j in range(k):
word = st()
words[p*k+j] = word
for c in word:
indeg[c] = 0
def match(w1,w2):
for i in range(min(len(w1), len(w2))):
if w1[i] == w2[i]:
continue
else:
return (w1[i],w2[i])
if len(w1) > len(w2):
print("IMPOSSIBLE")
exit()
#Reading the graph and its indegrees
g = defaultdict(set)
for i in range(len(words) - 1):
out = match(words[i], words[i+1])
if out is not None:
c1,c2 = out
if c2 not in g[c1]:
g[c1].add(c2)
indeg[c2] += 1
#Topsort things
ts = []
zero = deque()
for u in indeg:
if indeg[u] == 0:
zero.append(u)
while len(ts) != len(indeg):
if len(zero) == 0:
print("IMPOSSIBLE")
exit()
u = zero.popleft()
ts.append(u)
for v in g[u]:
indeg[v] -= 1
if indeg[v] == 0:
zero.append(v)
print("".join(ts))
``` | output | 1 | 26,718 | 6 | 53,437 |
Provide tags and a correct Python 3 solution for this coding contest problem.
While exploring the old caves, researchers found a book, or more precisely, a stash of mixed pages from a book. Luckily, all of the original pages are present and each page contains its number. Therefore, the researchers can reconstruct the book.
After taking a deeper look into the contents of these pages, linguists think that this may be some kind of dictionary. What's interesting is that this ancient civilization used an alphabet which is a subset of the English alphabet, however, the order of these letters in the alphabet is not like the one in the English language.
Given the contents of pages that researchers have found, your task is to reconstruct the alphabet of this ancient civilization using the provided pages from the dictionary.
Input
First-line contains two integers: n and k (1 β€ n, k β€ 10^3) β the number of pages that scientists have found and the number of words present at each page. Following n groups contain a line with a single integer p_i (0 β€ n < 10^3) β the number of i-th page, as well as k lines, each line containing one of the strings (up to 100 characters) written on the page numbered p_i.
Output
Output a string representing the reconstructed alphabet of this ancient civilization. If the book found is not a dictionary, output "IMPOSSIBLE" without quotes. In case there are multiple solutions, output any of them.
Example
Input
3 3
2
b
b
bbac
0
a
aca
acba
1
ab
c
ccb
Output
acb | instruction | 0 | 26,719 | 6 | 53,438 |
Tags: graphs, sortings
Correct Solution:
```
import os
import io
from collections import deque, defaultdict
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def li():return [int(i) for i in input().rstrip().split()]
def st():return str(input().rstrip())[2:-1]
def val():return int(input().rstrip())
# def li():return [int(i) for i in input().rstrip().split()]
# def st():return str(input())
# def val():return int(input())
#Input Reading
n,k = li()
words = [""] * n * k
abc = set()
for i in range(n):
p = val()
page = []
for j in range(k):
word = st()
words[p*k+j] = word
abc |= set(word)
def match(w1,w2):
for i in range(min(len(w1), len(w2))):
if w1[i] == w2[i]:
continue
else:
return (w1[i],w2[i])
if len(w1) > len(w2):
print("IMPOSSIBLE")
exit()
#Reading the graph and its indegrees
g = {c: set() for c in abc}
indeg = {c: 0 for c in abc}
for i in range(len(words) - 1):
out = match(words[i], words[i+1])
if out is not None:
c1,c2 = out
if c2 not in g[c1]:
g[c1].add(c2)
indeg[c2] += 1
#Topsort things
ts = []
zero = deque()
for u in g:
if indeg[u] == 0:
zero.append(u)
while len(ts) != len(abc):
if len(zero) == 0:
print("IMPOSSIBLE")
exit()
u = zero.popleft()
ts.append(u)
for v in g[u]:
indeg[v] -= 1
if indeg[v] == 0:
zero.append(v)
print("".join(ts))
``` | output | 1 | 26,719 | 6 | 53,439 |
Provide tags and a correct Python 3 solution for this coding contest problem.
While exploring the old caves, researchers found a book, or more precisely, a stash of mixed pages from a book. Luckily, all of the original pages are present and each page contains its number. Therefore, the researchers can reconstruct the book.
After taking a deeper look into the contents of these pages, linguists think that this may be some kind of dictionary. What's interesting is that this ancient civilization used an alphabet which is a subset of the English alphabet, however, the order of these letters in the alphabet is not like the one in the English language.
Given the contents of pages that researchers have found, your task is to reconstruct the alphabet of this ancient civilization using the provided pages from the dictionary.
Input
First-line contains two integers: n and k (1 β€ n, k β€ 10^3) β the number of pages that scientists have found and the number of words present at each page. Following n groups contain a line with a single integer p_i (0 β€ n < 10^3) β the number of i-th page, as well as k lines, each line containing one of the strings (up to 100 characters) written on the page numbered p_i.
Output
Output a string representing the reconstructed alphabet of this ancient civilization. If the book found is not a dictionary, output "IMPOSSIBLE" without quotes. In case there are multiple solutions, output any of them.
Example
Input
3 3
2
b
b
bbac
0
a
aca
acba
1
ab
c
ccb
Output
acb | instruction | 0 | 26,720 | 6 | 53,440 |
Tags: graphs, sortings
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline()
# ------------------------------
def RL(): return map(int, sys.stdin.readline().split())
def RLL(): return list(map(int, sys.stdin.readline().split()))
def N(): return int(input())
def print_list(l):
print(' '.join(map(str,l)))
# sys.setrecursionlimit(100000)
# from heapq import *
# from collections import deque as dq
# from math import ceil,floor,sqrt,pow,gcd,log
# import bisect as bs
# from collections import Counter
from collections import defaultdict as dc
# from functools import lru_cache
n,k = RL()
dic = [[] for _ in range(1000)]
for _ in range(n):
page = N()
for _ in range(k):
dic[page].append(input().strip())
dic = [word for page in dic for word in page]
nw = len(dic)
# print(dic)
ingress = dc(int)
edges = dc(list)
chars = set()
chars|=set(dic[0])
F = True
for i in range(1,nw):
a,b = dic[i-1],dic[i]
if len(chars)<26: chars|=set(b)
flag = False
for i,j in zip(a,b):
if i!=j:
ingress[j]+=1
edges[i].append(j)
flag = True
break
if not flag and len(b)<len(a):
F = False
break
if not F:
print('IMPOSSIBLE')
else:
# print(edges)
res = ''
now = []
for c in chars:
ingress[c] = max(0,ingress[c])
if ingress[c]==0:
now.append(c)
# print(ingress)
while now:
a = now.pop()
res+=a
for b in edges[a]:
ingress[b]-=1
if ingress[b]==0:
now.append(b)
if len(res)==len(chars):
print(res)
else:
print('IMPOSSIBLE')
``` | output | 1 | 26,720 | 6 | 53,441 |
Provide tags and a correct Python 3 solution for this coding contest problem.
While exploring the old caves, researchers found a book, or more precisely, a stash of mixed pages from a book. Luckily, all of the original pages are present and each page contains its number. Therefore, the researchers can reconstruct the book.
After taking a deeper look into the contents of these pages, linguists think that this may be some kind of dictionary. What's interesting is that this ancient civilization used an alphabet which is a subset of the English alphabet, however, the order of these letters in the alphabet is not like the one in the English language.
Given the contents of pages that researchers have found, your task is to reconstruct the alphabet of this ancient civilization using the provided pages from the dictionary.
Input
First-line contains two integers: n and k (1 β€ n, k β€ 10^3) β the number of pages that scientists have found and the number of words present at each page. Following n groups contain a line with a single integer p_i (0 β€ n < 10^3) β the number of i-th page, as well as k lines, each line containing one of the strings (up to 100 characters) written on the page numbered p_i.
Output
Output a string representing the reconstructed alphabet of this ancient civilization. If the book found is not a dictionary, output "IMPOSSIBLE" without quotes. In case there are multiple solutions, output any of them.
Example
Input
3 3
2
b
b
bbac
0
a
aca
acba
1
ab
c
ccb
Output
acb | instruction | 0 | 26,721 | 6 | 53,442 |
Tags: graphs, sortings
Correct Solution:
```
# ------------------- 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
for _ in range(int(input()) if not True else 1):
#n = int(input())
n, k = map(int, input().split())
#a, b = map(int, input().split())
#c, d = map(int, input().split())
#a = list(map(int, input().split()))
#b = list(map(int, input().split()))
#s = input()
di = {}
present = [False]*26
for i in range(n):
page = int(input())
di[page] = []
for __ in range(k):
s = input()
for i in s:
present[ord(i)-97] = True
di[page] += [s]
words = []
for u in sorted(k for k in di):
words += di[u]
graph = [set() for i in range(26)]
pos = True
for i in range(1, len(words)):
j = 0
while j < min(len(words[i]), len(words[i-1])):
if words[i][j] == words[i-1][j]:
j += 1
continue
l1, l2 = ord(words[i-1][j]) - 97, ord(words[i][j]) - 97
if l1 in graph[l2]:
pos = False
break
graph[l1].add(l2)
break
if len(words[i-1]) > len(words[i]) and words[i-1][:len(words[i])] == words[i]:
print("IMPOSSIBLE")
quit()
if not pos:break
if not pos:
print("IMPOSSIBLE")
quit()
graph = [list(k) for k in graph]
edges = [i for i in range(26) if present[i]]
order = []
vis = [False]*26
while True:
lo = len(order)
for e in edges:
if not graph[e] and e not in order:
order += [e]
vis[e] = True
for i in range(26):
for j in order:
if j in graph[i]:
graph[i].remove(j)
if lo == len(order):break
order = order[::-1]
if not order:
print("IMPOSSIBLE")
quit()
pos = True
for i in range(26):
for j in graph[i]:
if order.index(i) > order.index(j):
pos = False
break
if not pos:break
if not pos:print("IMPOSSIBLE")
else:
print("".join(chr(97+k) for k in order))
``` | output | 1 | 26,721 | 6 | 53,443 |
Provide tags and a correct Python 3 solution for this coding contest problem.
While exploring the old caves, researchers found a book, or more precisely, a stash of mixed pages from a book. Luckily, all of the original pages are present and each page contains its number. Therefore, the researchers can reconstruct the book.
After taking a deeper look into the contents of these pages, linguists think that this may be some kind of dictionary. What's interesting is that this ancient civilization used an alphabet which is a subset of the English alphabet, however, the order of these letters in the alphabet is not like the one in the English language.
Given the contents of pages that researchers have found, your task is to reconstruct the alphabet of this ancient civilization using the provided pages from the dictionary.
Input
First-line contains two integers: n and k (1 β€ n, k β€ 10^3) β the number of pages that scientists have found and the number of words present at each page. Following n groups contain a line with a single integer p_i (0 β€ n < 10^3) β the number of i-th page, as well as k lines, each line containing one of the strings (up to 100 characters) written on the page numbered p_i.
Output
Output a string representing the reconstructed alphabet of this ancient civilization. If the book found is not a dictionary, output "IMPOSSIBLE" without quotes. In case there are multiple solutions, output any of them.
Example
Input
3 3
2
b
b
bbac
0
a
aca
acba
1
ab
c
ccb
Output
acb | instruction | 0 | 26,722 | 6 | 53,444 |
Tags: graphs, sortings
Correct Solution:
```
from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop
import math
from collections import *
from functools import reduce,cmp_to_key,lru_cache
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline;M = mod = 10**9 + 7
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)
def li():return [int(i) for i in input().rstrip().split()]
def st():return str(input().rstrip())[2:-1]
def val():return int(input().rstrip())
def li2():return [str(i)[2:-1] for i in input().rstrip().split()]
def li3():return [int(i) for i in st()]
graph = defaultdict(set);n, k = li();l = [];allwords = set()
for i in range(n):
p = val();l1 = []
for j in range(k):l1.append(st())
allwords |= set(l1[-1]);l.append([p, l1[:]])
l.sort(key = lambda x:x[0]);l = [i[1] for i in l]
if n == k == 1:print(''.join(set(l[0][0])));exit()
ingraph = defaultdict(int)
def match(a, b):
for j in range(min(len(a), len(b))):
if a[j] == b[j]:continue
elif b[j] in graph[a[j]]:return
else:graph[a[j]].add(b[j]);ingraph[b[j]] += 1;return
if len(a) > len(b):print('IMPOSSIBLE');exit()
finl = []
for i in l:finl.extend(i)
l = finl
for i in range(1, len(l)):match(l[i - 1], l[i])
if min([ingraph[j] for j in graph]) != 0:print('IMPOSSIBLE');exit()
ans = '';d = deque()
for j in graph:
if ingraph[j] == 0:d.append(j)
while d:
node = d.popleft();ans += node
for j in graph[node]:
ingraph[j] -= 1
if not ingraph[j]:d.append(j)
if len(ans) != len(allwords):print('IMPOSSIBLE');exit()
print(ans)
``` | output | 1 | 26,722 | 6 | 53,445 |
Provide tags and a correct Python 3 solution for this coding contest problem.
While exploring the old caves, researchers found a book, or more precisely, a stash of mixed pages from a book. Luckily, all of the original pages are present and each page contains its number. Therefore, the researchers can reconstruct the book.
After taking a deeper look into the contents of these pages, linguists think that this may be some kind of dictionary. What's interesting is that this ancient civilization used an alphabet which is a subset of the English alphabet, however, the order of these letters in the alphabet is not like the one in the English language.
Given the contents of pages that researchers have found, your task is to reconstruct the alphabet of this ancient civilization using the provided pages from the dictionary.
Input
First-line contains two integers: n and k (1 β€ n, k β€ 10^3) β the number of pages that scientists have found and the number of words present at each page. Following n groups contain a line with a single integer p_i (0 β€ n < 10^3) β the number of i-th page, as well as k lines, each line containing one of the strings (up to 100 characters) written on the page numbered p_i.
Output
Output a string representing the reconstructed alphabet of this ancient civilization. If the book found is not a dictionary, output "IMPOSSIBLE" without quotes. In case there are multiple solutions, output any of them.
Example
Input
3 3
2
b
b
bbac
0
a
aca
acba
1
ab
c
ccb
Output
acb | instruction | 0 | 26,723 | 6 | 53,446 |
Tags: graphs, sortings
Correct Solution:
```
# from collections import deque
import io
# input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline # η₯ε₯εΏ«θ―»οΌζ ζ³θΏθ‘θ°θ―
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)
def input(): return sys.stdin.readline().rstrip("\r\n")
n, m = map(int, input().split())
# d = {}
inc = {
# chr(97+i):0 for i in range(26)
}
l = [None for i in range(n*m)]
for i in range(n):
t = int(input())
# tmp = []
for j in range(m):
# tmp.append(input())
ipt = input()
l[t*m+j] = ipt
if len(inc)==26:continue
for q in ipt:
inc.setdefault(q, 0)
# d[t] = tmp
# l = []
# for i in range(n):
# for j in d[i]:
# l.append(j)
d = {}
# f = l[0][0]
def ae(u, v):
t = d.setdefault(u, set())
if v not in t:
t.add(v)
inc[v] = inc.get(v, 0) + 1
for p, i in enumerate(l[1:]):
for j in range(min(len(l[p]), len(i))):
if l[p][j] != i[j]:
# if len(l[p])-1 != j:
# ae(l[p][j],i[j])
ae(i[j], l[p][j])
break
if len(i)-1==j and len(l[p])-1 > j:
print("IMPOSSIBLE")
exit(0)
ans = []
dq = []
# dq = deque()
ptr = 0
ninc = {}
for k, v in inc.items():
if v == 0:
dq.append(k)
else:
ninc[k] = v
# if ctr>1:
# print("IMPOSSIBLE")
# exit(0)
inc = ninc
while ptr != len(dq):
fst = dq[ptr]
ans.append(fst)
for i in d.get(fst, []):
inc[i] -= 1
if inc[i] == 0:
dq.append(i)
inc.pop(i)
# if ctr>1:
# print("IMPOSSIBLE")
# exit(0)
ptr += 1
if len(inc):
print("IMPOSSIBLE")
exit(0)
print(*reversed(ans), sep='')
``` | output | 1 | 26,723 | 6 | 53,447 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
While exploring the old caves, researchers found a book, or more precisely, a stash of mixed pages from a book. Luckily, all of the original pages are present and each page contains its number. Therefore, the researchers can reconstruct the book.
After taking a deeper look into the contents of these pages, linguists think that this may be some kind of dictionary. What's interesting is that this ancient civilization used an alphabet which is a subset of the English alphabet, however, the order of these letters in the alphabet is not like the one in the English language.
Given the contents of pages that researchers have found, your task is to reconstruct the alphabet of this ancient civilization using the provided pages from the dictionary.
Input
First-line contains two integers: n and k (1 β€ n, k β€ 10^3) β the number of pages that scientists have found and the number of words present at each page. Following n groups contain a line with a single integer p_i (0 β€ n < 10^3) β the number of i-th page, as well as k lines, each line containing one of the strings (up to 100 characters) written on the page numbered p_i.
Output
Output a string representing the reconstructed alphabet of this ancient civilization. If the book found is not a dictionary, output "IMPOSSIBLE" without quotes. In case there are multiple solutions, output any of them.
Example
Input
3 3
2
b
b
bbac
0
a
aca
acba
1
ab
c
ccb
Output
acb
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline()
# ------------------------------
def RL(): return map(int, sys.stdin.readline().split())
def RLL(): return list(map(int, sys.stdin.readline().split()))
def N(): return int(input())
def print_list(l):
print(' '.join(map(str,l)))
# sys.setrecursionlimit(100000)
# from heapq import *
# from collections import deque as dq
# from math import ceil,floor,sqrt,pow,gcd,log
# import bisect as bs
# from collections import Counter
from collections import defaultdict as dc
# from functools import lru_cache
n,k = RL()
dic = [[] for _ in range(1000)]
for _ in range(n):
page = N()
for _ in range(k):
dic[page].append(input().strip())
dic = [word for page in dic for word in page]
nw = len(dic)
# print(dic)
ingress = dc(int)
edges = dc(list)
chars = set()
chars|=set(dic[0])
for i in range(1,nw):
a,b = dic[i-1],dic[i]
if len(chars)<26: chars|=set(b)
for i,j in zip(a,b):
if i!=j:
ingress[j]+=1
edges[i].append(j)
break
# print(edges)
res = ''
now = []
for c in chars:
ingress[c] = max(0,ingress[c])
if ingress[c]==0:
now.append(c)
while now:
a = now.pop()
res+=a
for b in edges[a]:
ingress[b]-=1
if ingress[b]==0:
now.append(b)
if len(res)==len(chars):
print(res)
else:
print('IMPOSSIBLE')
``` | instruction | 0 | 26,724 | 6 | 53,448 |
No | output | 1 | 26,724 | 6 | 53,449 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
While exploring the old caves, researchers found a book, or more precisely, a stash of mixed pages from a book. Luckily, all of the original pages are present and each page contains its number. Therefore, the researchers can reconstruct the book.
After taking a deeper look into the contents of these pages, linguists think that this may be some kind of dictionary. What's interesting is that this ancient civilization used an alphabet which is a subset of the English alphabet, however, the order of these letters in the alphabet is not like the one in the English language.
Given the contents of pages that researchers have found, your task is to reconstruct the alphabet of this ancient civilization using the provided pages from the dictionary.
Input
First-line contains two integers: n and k (1 β€ n, k β€ 10^3) β the number of pages that scientists have found and the number of words present at each page. Following n groups contain a line with a single integer p_i (0 β€ n < 10^3) β the number of i-th page, as well as k lines, each line containing one of the strings (up to 100 characters) written on the page numbered p_i.
Output
Output a string representing the reconstructed alphabet of this ancient civilization. If the book found is not a dictionary, output "IMPOSSIBLE" without quotes. In case there are multiple solutions, output any of them.
Example
Input
3 3
2
b
b
bbac
0
a
aca
acba
1
ab
c
ccb
Output
acb
Submitted Solution:
```
from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop,heapify
import math
from collections import *
from functools import reduce,cmp_to_key
import sys
input = sys.stdin.readline
from itertools import accumulate
from functools import lru_cache
M = mod = 998244353
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)
def li():return [int(i) for i in input().rstrip('\n').split()]
def st():return input().rstrip('\n')
def val():return int(input().rstrip('\n'))
def li2():return [i for i in input().rstrip('\n')]
def li3():return [int(i) for i in input().rstrip('\n')]
graph = defaultdict(set)
n, k = li()
l = []
allwords = set()
for i in range(n):
p = val()
l1 = []
for j in range(k):l1.append(st())
# print(p, l1)
allwords |= set(l1[-1])
l.append([p, l1[:]])
l.sort()
l = [i[1] for i in l]
# print(l)
ingraph = defaultdict(int)
def match(a, b):
for j in range(min(len(a), len(b))):
if a[j] == b[j] or b[j] in graph[a[j]]:continue
else:
graph[a[j]].add(b[j])
ingraph[b[j]] += 1
return
# print(l)
finl = []
for i in l:finl.extend(i)
l = finl
# for i in l:
# print(i)
# print()
# print(l)
for i in range(1, len(l)):
match(l[i - 1], l[i])
# print(graph)
# print(ingraph)
if min([ingraph[j] for j in graph]) != 0:
print('IMPOSSIBLE')
exit()
ans = ''
d = deque()
for j in graph:
if ingraph[j] == 0:
d.append(j)
# print(d)
while d:
node = d.popleft()
ans += node
for j in graph[node]:
ingraph[j] -= 1
if not ingraph[j]:d.append(j)
if len(ans) != len(allwords):
print('IMPOSSIBLE')
exit()
print(ans)
``` | instruction | 0 | 26,725 | 6 | 53,450 |
No | output | 1 | 26,725 | 6 | 53,451 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
While exploring the old caves, researchers found a book, or more precisely, a stash of mixed pages from a book. Luckily, all of the original pages are present and each page contains its number. Therefore, the researchers can reconstruct the book.
After taking a deeper look into the contents of these pages, linguists think that this may be some kind of dictionary. What's interesting is that this ancient civilization used an alphabet which is a subset of the English alphabet, however, the order of these letters in the alphabet is not like the one in the English language.
Given the contents of pages that researchers have found, your task is to reconstruct the alphabet of this ancient civilization using the provided pages from the dictionary.
Input
First-line contains two integers: n and k (1 β€ n, k β€ 10^3) β the number of pages that scientists have found and the number of words present at each page. Following n groups contain a line with a single integer p_i (0 β€ n < 10^3) β the number of i-th page, as well as k lines, each line containing one of the strings (up to 100 characters) written on the page numbered p_i.
Output
Output a string representing the reconstructed alphabet of this ancient civilization. If the book found is not a dictionary, output "IMPOSSIBLE" without quotes. In case there are multiple solutions, output any of them.
Example
Input
3 3
2
b
b
bbac
0
a
aca
acba
1
ab
c
ccb
Output
acb
Submitted Solution:
```
from collections import deque
import io,os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline # η₯ε₯εΏ«θ―»οΌζ ζ³θΏθ‘θ°θ―
n,m = map(int,input().split())
d = {}
inc = {}
for i in range(n):
t = int(input())
tmp = []
for j in range(m):
tmp.append(input())
for q in tmp[-1]:
inc.setdefault(q,0)
d[t] = tmp
l = []
for i in range(n):
for j in d[i]:
l.append(j)
d = {}
# f = l[0][0]
def ae(u,v):
t = d.setdefault(u,set())
if v not in t:
t.add(v)
inc[v] = inc.get(v,0) + 1
for p,i in enumerate(l[1:]):
for j in range(min(len(l[p]),len(i))):
if l[p][j]!=i[j]:
if len(l[p])!=j-1:
# ae(l[p][j],i[j])
ae(i[j],l[p][j])
break
ans = []
dq = []
# dq = deque()
ptr = 0
ctr = 0
ninc = {}
for k,v in inc.items():
if v==0:
dq.append(k)
ctr+=1
else:
ninc[k] = v
# if ctr>1:
# print("IMPOSSIBLE")
# exit(0)
inc = ninc
while ptr != len(dq):
fst = dq[ptr]
ans.append(fst)
ctr = 0
for i in d.get(fst,[]):
inc[i]-=1
if inc[i]==0:
dq.append(i)
inc.pop(i)
ctr += 1
# if ctr>1:
# print("IMPOSSIBLE")
# exit(0)
ptr+=1
if len(inc):
print("IMPOSSIBLE")
exit(0)
print(*reversed(ans),sep='')
``` | instruction | 0 | 26,726 | 6 | 53,452 |
No | output | 1 | 26,726 | 6 | 53,453 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
While exploring the old caves, researchers found a book, or more precisely, a stash of mixed pages from a book. Luckily, all of the original pages are present and each page contains its number. Therefore, the researchers can reconstruct the book.
After taking a deeper look into the contents of these pages, linguists think that this may be some kind of dictionary. What's interesting is that this ancient civilization used an alphabet which is a subset of the English alphabet, however, the order of these letters in the alphabet is not like the one in the English language.
Given the contents of pages that researchers have found, your task is to reconstruct the alphabet of this ancient civilization using the provided pages from the dictionary.
Input
First-line contains two integers: n and k (1 β€ n, k β€ 10^3) β the number of pages that scientists have found and the number of words present at each page. Following n groups contain a line with a single integer p_i (0 β€ n < 10^3) β the number of i-th page, as well as k lines, each line containing one of the strings (up to 100 characters) written on the page numbered p_i.
Output
Output a string representing the reconstructed alphabet of this ancient civilization. If the book found is not a dictionary, output "IMPOSSIBLE" without quotes. In case there are multiple solutions, output any of them.
Example
Input
3 3
2
b
b
bbac
0
a
aca
acba
1
ab
c
ccb
Output
acb
Submitted Solution:
```
from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop,heapify
import math
from collections import *
from functools import reduce,cmp_to_key
import sys
input = sys.stdin.readline
from itertools import accumulate
from functools import lru_cache
M = mod = 998244353
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)
def li():return [int(i) for i in input().rstrip('\n').split()]
def st():return input().rstrip('\n')
def val():return int(input().rstrip('\n'))
def li2():return [i for i in input().rstrip('\n')]
def li3():return [int(i) for i in input().rstrip('\n')]
graph = defaultdict(set)
n, k = li()
l = []
for i in range(n):
p = val()
l1 = []
for j in range(k):l1.append(st())
# print(p, l1)
l.append([p, l1[:]])
l.sort()
l = [i[1] for i in l]
# print(l)
ingraph = defaultdict(int)
def match(a, b):
for j in range(min(len(a), len(b))):
if a[j] == b[j] or b[j] in graph[a[j]]:continue
else:
graph[a[j]].add(b[j])
ingraph[b[j]] += 1
return
# print(l)
finl = []
for i in l:finl.extend(i)
l = finl
# for i in l:
# print(i)
# print()
# print(l)
for i in range(1, len(l)):
match(l[i - 1], l[i])
if min([ingraph[j] for j in graph]) != 0:
print('IMPOSSIBLE')
exit()
ans = ''
d = deque()
for j in graph:
if ingraph[j] == 0:
d.append(j)
# print(d)
while d:
node = d.popleft()
ans += node
for j in graph[node]:
ingraph[j] -= 1
if not ingraph[j]:d.append(j)
for i in list(graph) + list(ingraph):
if i not in ans:
print('IMPOSSIBLE')
exit()
print(ans)
``` | instruction | 0 | 26,727 | 6 | 53,454 |
No | output | 1 | 26,727 | 6 | 53,455 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players.
Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move.
Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him.
Input
The first line contains two integers, n and k (1 β€ n β€ 105; 1 β€ k β€ 109).
Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters.
Output
If the player who moves first wins, print "First", otherwise print "Second" (without the quotes).
Examples
Input
2 3
a
b
Output
First
Input
3 1
a
b
c
Output
First
Input
1 2
ab
Output
Second | instruction | 0 | 26,884 | 6 | 53,768 |
Tags: dfs and similar, dp, games, implementation, strings, trees
Correct Solution:
```
"""
Codeforces Contest 260 Div 1 Problem B
Author : chaotic_iak
Language: Python 3.3.4
"""
def main():
n,k = read()
s = set()
for i in range(n): s.add(read(0))
s = list(s)
s.sort()
s = treeify(s)
res = solve(s)
if res == 0: # neither: second player win
print("Second")
if res == 1: # odd: first player win if k is odd
print("First" if k % 2 else "Second")
if res == 2: # even: second player win
print("Second")
if res == 3: # both: first player win
print("First")
def treeify(s):
res = [[] for _ in range(26)]
for i in s:
if i: res[ord(i[0]) - 97].append(i[1:])
fin = []
for i in range(26):
if res[i]: fin.append(treeify(res[i]))
return fin
def solve(s, parity=2):
for i in range(len(s)):
if isinstance(s[i], list): s[i] = solve(s[i], 3-parity)
if not s: return parity # no possible move: current parity
if 0 in s: return 3 # any neither: both
if 1 in s and 2 in s: return 3 # any odd and any even: both
if 1 in s: return 1 # any odd: odd
if 2 in s: return 2 # any even: even
return 0 # all both: neither
################################### NON-SOLUTION STUFF BELOW
def read(mode=2):
# 0: String
# 1: List of strings
# 2: List of integers
inputs = input().strip()
if mode == 0: return inputs
if mode == 1: return inputs.split()
if mode == 2: return map(int, inputs.split())
def write(s="\n"):
if isinstance(s, list): s = " ".join(map(str, s))
s = str(s)
print(s, end="")
main()
``` | output | 1 | 26,884 | 6 | 53,769 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players.
Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move.
Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him.
Input
The first line contains two integers, n and k (1 β€ n β€ 105; 1 β€ k β€ 109).
Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters.
Output
If the player who moves first wins, print "First", otherwise print "Second" (without the quotes).
Examples
Input
2 3
a
b
Output
First
Input
3 1
a
b
c
Output
First
Input
1 2
ab
Output
Second | instruction | 0 | 26,885 | 6 | 53,770 |
Tags: dfs and similar, dp, games, implementation, strings, trees
Correct Solution:
```
class TrieNode(object):
def __init__(self, char: str):
self.char = char
self.children = []
self.word_finished = False
self.counter = 1
def add(root, word):
node = root
node.counter+=1
for char in word:
found_in_child = False
for child in node.children:
if child.char == char:
child.counter += 1
node = child
found_in_child = True
break
if not found_in_child:
new_node = TrieNode(char)
node.children.append(new_node)
node = new_node
node.word_finished = True
def win(node):
if node.children==[]:
return False
for child in node.children:
if not win(child):
return True
return False
def loss(node):
if node.children == []:
return True
for child in node.children:
if not loss(child):
return True
return False
root=TrieNode("")
n,k=map(int,input().split())
for j in range(n):
add(root,input())
win=win(root)
loss=loss(root)
if not win:
print("Second")
else:
if loss:
print("First")
else:
if k%2:
print("First")
else:
print("Second")
``` | output | 1 | 26,885 | 6 | 53,771 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players.
Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move.
Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him.
Input
The first line contains two integers, n and k (1 β€ n β€ 105; 1 β€ k β€ 109).
Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters.
Output
If the player who moves first wins, print "First", otherwise print "Second" (without the quotes).
Examples
Input
2 3
a
b
Output
First
Input
3 1
a
b
c
Output
First
Input
1 2
ab
Output
Second | instruction | 0 | 26,886 | 6 | 53,772 |
Tags: dfs and similar, dp, games, implementation, strings, trees
Correct Solution:
```
# ------------------- fast io --------------------
import os
import sys
sys.setrecursionlimit(10**5)
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 --------------------
class Trie:
class Node:
def __init__(self, char: str = "*"):
self.char = char
self.children = []
self.word_finished = False
self.counter = 1
def __init__(self):
self.root = Trie.Node()
def add(self, word: str):
node = self.root
for char in word:
found_in_child = False
for child in node.children:
if child.char == char:
child.counter += 1
node = child
found_in_child = True
break
if not found_in_child:
new_node = Trie.Node(char)
node.children.append(new_node)
node = new_node
node.word_finished = True
def query(self, prefix, root=None):
if not root: root = self.root
node = root
if not root.children:
return 0
for char in prefix:
char_not_found = True
for child in node.children:
if child.char == char:
char_not_found = False
node = child
break
if char_not_found:
return 0
return node
n, k = map(int, input().split())
tr = Trie()
for _ in range(n):
tr.add(input())
def can_win(node):
if not node.children:
return False
for child in node.children:
if not can_win(child):
return True
return False
def can_lose(node):
if not node.children:
return True
for child in node.children:
if not can_lose(child):
return True
return False
pos = can_win(tr.root)
pos2 = can_lose(tr.root)
if pos and pos2:
print("First")
elif not pos:
print("Second")
else:
print("First" if k % 2 else "Second")
``` | output | 1 | 26,886 | 6 | 53,773 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players.
Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move.
Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him.
Input
The first line contains two integers, n and k (1 β€ n β€ 105; 1 β€ k β€ 109).
Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters.
Output
If the player who moves first wins, print "First", otherwise print "Second" (without the quotes).
Examples
Input
2 3
a
b
Output
First
Input
3 1
a
b
c
Output
First
Input
1 2
ab
Output
Second | instruction | 0 | 26,887 | 6 | 53,774 |
Tags: dfs and similar, dp, games, implementation, strings, trees
Correct Solution:
```
from sys import stdin, setrecursionlimit
setrecursionlimit(200000)
n, k = [int(i) for i in stdin.readline().split()]
tree = {}
for i in range(n):
_str = stdin.readline().strip()
cur = tree
for i in _str:
if not i in cur:
cur[i] = {}
cur = cur[i]
def forced(tree):
if not tree:
return (False, True)
else:
winner = False
loser = False
for leaf in tree:
a, b = forced(tree[leaf])
if not a:
winner = True
if not b:
loser = True
return (winner, loser)
a, b = forced(tree)
first = 'First'
second = 'Second'
if a == 1 and b == 1:
print(first)
elif a == 0:
print(second)
else:
if k % 2 != 0:
print(first)
else:
print(second)
``` | output | 1 | 26,887 | 6 | 53,775 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players.
Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move.
Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him.
Input
The first line contains two integers, n and k (1 β€ n β€ 105; 1 β€ k β€ 109).
Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters.
Output
If the player who moves first wins, print "First", otherwise print "Second" (without the quotes).
Examples
Input
2 3
a
b
Output
First
Input
3 1
a
b
c
Output
First
Input
1 2
ab
Output
Second | instruction | 0 | 26,889 | 6 | 53,778 |
Tags: dfs and similar, dp, games, implementation, strings, trees
Correct Solution:
```
def forced(tree):
if not tree:
return (False, True)
else:
winner = False
loser = False
for leaf in tree:
a, b = forced(tree[leaf])
if not a:
winner = True
if not b:
loser = True
return (winner, loser)
def print_res(a, b, k):
first = 'First'
second = 'Second'
if a == 1 and b == 1:
print(first)
elif a == 0:
print(second)
else:
if k % 2 != 0:
print(first)
else:
print(second)
def main():
n, k = [int(i) for i in input().split()]
tree = {}
for i in range(n):
_str = input().strip()
cur = tree
for i in _str:
if not i in cur:
cur[i] = {}
cur = cur[i]
a, b = forced(tree)
print_res(a, b, k)
if __name__ == '__main__':
main()
``` | output | 1 | 26,889 | 6 | 53,779 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players.
Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move.
Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him.
Input
The first line contains two integers, n and k (1 β€ n β€ 105; 1 β€ k β€ 109).
Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters.
Output
If the player who moves first wins, print "First", otherwise print "Second" (without the quotes).
Examples
Input
2 3
a
b
Output
First
Input
3 1
a
b
c
Output
First
Input
1 2
ab
Output
Second | instruction | 0 | 26,890 | 6 | 53,780 |
Tags: dfs and similar, dp, games, implementation, strings, trees
Correct Solution:
```
from sys import stdin, setrecursionlimit
setrecursionlimit(200000)
n, k = [int(i) for i in stdin.readline().split()]
tree = {}
for i in range(n):
_str = stdin.readline().strip()
cur = tree
for i in _str:
if not i in cur:
cur[i] = {}
cur = cur[i]
def forced(tree):
if not tree:
return (False, True)
else:
winner = False
loser = False
for leaf in tree:
a, b = forced(tree[leaf])
if not a:
winner = True
if not b:
loser = True
return (winner, loser)
a, b = forced(tree)
def print_res(a, b, k):
first = 'First'
second = 'Second'
if a == 1 and b == 1:
print(first)
elif a == 0:
print(second)
else:
if k % 2 != 0:
print(first)
else:
print(second)
print_res(a, b, k)
``` | output | 1 | 26,890 | 6 | 53,781 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library.
Some long and uninteresting story was removed...
The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large version of a letter x is denoted by x'. BSCII encoding, which is used everywhere in Bookland, is made in that way so that large letters are presented in the order of the numbers they are denoted by, and small letters are presented in the order of the numbers they are denoted by, but all large letters are before all small letters. For example, the following conditions hold: 2 < 3, 2' < 3', 3' < 2.
A word x1, x2, ..., xa is not lexicographically greater than y1, y2, ..., yb if one of the two following conditions holds:
* a β€ b and x1 = y1, ..., xa = ya, i.e. the first word is the prefix of the second word;
* there is a position 1 β€ j β€ min(a, b), such that x1 = y1, ..., xj - 1 = yj - 1 and xj < yj, i.e. at the first position where the words differ the first word has a smaller letter than the second word has.
For example, the word "3' 7 5" is before the word "2 4' 6" in lexicographical order. It is said that sequence of words is in lexicographical order if each word is not lexicographically greater than the next word in the sequence.
Denis has a sequence of words consisting of small letters only. He wants to change some letters to large (let's call this process a capitalization) in such a way that the sequence of words is in lexicographical order. However, he soon realized that for some reason he can't change a single letter in a single word. He only can choose a letter and change all of its occurrences in all words to large letters. He can perform this operation any number of times with arbitrary letters of Bookland's alphabet.
Help Denis to choose which letters he needs to capitalize (make large) in order to make the sequence of words lexicographically ordered, or determine that it is impossible.
Note that some words can be equal.
Input
The first line contains two integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 100 000) β the number of words and the number of letters in Bookland's alphabet, respectively. The letters of Bookland's alphabet are denoted by integers from 1 to m.
Each of the next n lines contains a description of one word in format li, si, 1, si, 2, ..., si, li (1 β€ li β€ 100 000, 1 β€ si, j β€ m), where li is the length of the word, and si, j is the sequence of letters in the word. The words are given in the order Denis has them in the sequence.
It is guaranteed that the total length of all words is not greater than 100 000.
Output
In the first line print "Yes" (without quotes), if it is possible to capitalize some set of letters in such a way that the sequence of words becomes lexicographically ordered. Otherwise, print "No" (without quotes).
If the required is possible, in the second line print k β the number of letters Denis has to capitalize (make large), and in the third line print k distinct integers β these letters. Note that you don't need to minimize the value k.
You can print the letters in any order. If there are multiple answers, print any of them.
Examples
Input
4 3
1 2
1 1
3 1 3 2
2 1 1
Output
Yes
2
2 3
Input
6 5
2 1 2
2 1 2
3 1 2 3
2 1 5
2 4 4
2 4 4
Output
Yes
0
Input
4 3
4 3 2 2 1
3 1 1 3
3 2 3 3
2 3 1
Output
No
Note
In the first example after Denis makes letters 2 and 3 large, the sequence looks like the following:
* 2'
* 1
* 1 3' 2'
* 1 1
The condition 2' < 1 holds, so the first word is not lexicographically larger than the second word. The second word is the prefix of the third word, so the are in lexicographical order. As the first letters of the third and the fourth words are the same, and 3' < 1, then the third word is not lexicographically larger than the fourth word.
In the second example the words are in lexicographical order from the beginning, so Denis can do nothing.
In the third example there is no set of letters such that if Denis capitalizes them, the sequence becomes lexicographically ordered. | instruction | 0 | 27,081 | 6 | 54,162 |
Tags: 2-sat, dfs and similar, graphs, implementation
Correct Solution:
```
from collections import defaultdict, deque
def main():
n,m = map(int, input().split())
cap = [None]*(m+1)
same_cap = defaultdict(list)
q = deque()
def apply_cap(a, c):
if cap[a] is not None:
return cap[a] == c
q.append((a,c))
while q:
b = q.pop()
if b[1] == c:
if cap[b[0]] is None:
cap[b[0]] = c
q.extend(same_cap[b[0]])
same_cap[b[0]] = []
elif cap[b[0]]!=c:
return False
return True
def same(a,b):
same_cap[b].append((a,True))
same_cap[a].append((b,False))
if cap[a] == False:
return apply_cap(b, False)
if cap[b] == True:
return apply_cap(a, True)
return True
def process(p,c):
lp = p[0]
lc = c[0]
for i in range(1, min(lp,lc)+1):
if p[i]>c[i]:
return apply_cap(p[i], True) and apply_cap(c[i], False)
if p[i]<c[i]:
return same(p[i], c[i])
return lp<=lc
p = list(map(int, input().split()))
for i in range(n-1):
c = list(map(int, input().split()))
if not process(p, c):
print ('No')
break
p = c
else:
print ('Yes')
res = []
for i,b in enumerate(cap):
if b:
res.append(i)
print(len(res))
print(' '.join(map(str,res)))
main()
``` | output | 1 | 27,081 | 6 | 54,163 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library.
Some long and uninteresting story was removed...
The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large version of a letter x is denoted by x'. BSCII encoding, which is used everywhere in Bookland, is made in that way so that large letters are presented in the order of the numbers they are denoted by, and small letters are presented in the order of the numbers they are denoted by, but all large letters are before all small letters. For example, the following conditions hold: 2 < 3, 2' < 3', 3' < 2.
A word x1, x2, ..., xa is not lexicographically greater than y1, y2, ..., yb if one of the two following conditions holds:
* a β€ b and x1 = y1, ..., xa = ya, i.e. the first word is the prefix of the second word;
* there is a position 1 β€ j β€ min(a, b), such that x1 = y1, ..., xj - 1 = yj - 1 and xj < yj, i.e. at the first position where the words differ the first word has a smaller letter than the second word has.
For example, the word "3' 7 5" is before the word "2 4' 6" in lexicographical order. It is said that sequence of words is in lexicographical order if each word is not lexicographically greater than the next word in the sequence.
Denis has a sequence of words consisting of small letters only. He wants to change some letters to large (let's call this process a capitalization) in such a way that the sequence of words is in lexicographical order. However, he soon realized that for some reason he can't change a single letter in a single word. He only can choose a letter and change all of its occurrences in all words to large letters. He can perform this operation any number of times with arbitrary letters of Bookland's alphabet.
Help Denis to choose which letters he needs to capitalize (make large) in order to make the sequence of words lexicographically ordered, or determine that it is impossible.
Note that some words can be equal.
Input
The first line contains two integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 100 000) β the number of words and the number of letters in Bookland's alphabet, respectively. The letters of Bookland's alphabet are denoted by integers from 1 to m.
Each of the next n lines contains a description of one word in format li, si, 1, si, 2, ..., si, li (1 β€ li β€ 100 000, 1 β€ si, j β€ m), where li is the length of the word, and si, j is the sequence of letters in the word. The words are given in the order Denis has them in the sequence.
It is guaranteed that the total length of all words is not greater than 100 000.
Output
In the first line print "Yes" (without quotes), if it is possible to capitalize some set of letters in such a way that the sequence of words becomes lexicographically ordered. Otherwise, print "No" (without quotes).
If the required is possible, in the second line print k β the number of letters Denis has to capitalize (make large), and in the third line print k distinct integers β these letters. Note that you don't need to minimize the value k.
You can print the letters in any order. If there are multiple answers, print any of them.
Examples
Input
4 3
1 2
1 1
3 1 3 2
2 1 1
Output
Yes
2
2 3
Input
6 5
2 1 2
2 1 2
3 1 2 3
2 1 5
2 4 4
2 4 4
Output
Yes
0
Input
4 3
4 3 2 2 1
3 1 1 3
3 2 3 3
2 3 1
Output
No
Note
In the first example after Denis makes letters 2 and 3 large, the sequence looks like the following:
* 2'
* 1
* 1 3' 2'
* 1 1
The condition 2' < 1 holds, so the first word is not lexicographically larger than the second word. The second word is the prefix of the third word, so the are in lexicographical order. As the first letters of the third and the fourth words are the same, and 3' < 1, then the third word is not lexicographically larger than the fourth word.
In the second example the words are in lexicographical order from the beginning, so Denis can do nothing.
In the third example there is no set of letters such that if Denis capitalizes them, the sequence becomes lexicographically ordered. | instruction | 0 | 27,082 | 6 | 54,164 |
Tags: 2-sat, dfs and similar, graphs, implementation
Correct Solution:
```
# -*- coding: utf-8 -*-
import math
import collections
import bisect
import heapq
import time
import random
import itertools
"""
created by shhuan at 2017/10/18 16:22
"""
M, N = map(int, input().split())
words = []
for i in range(M):
words.append([int(x) for x in input().split()][1:])
# all elements in C should be capitalized
C = set()
# E[u][v] means if we capitalize u, we must capitalize v
E = collections.defaultdict(list)
for i in range(M-1):
w1 = words[i]
w2 = words[i+1]
if len(w1) > len(w2) and w1[:len(w2)] == w2:
print('No')
exit(0)
for j in range(min(len(w1), len(w2))):
if w1[j] < w2[j]:
E[w2[j]].append(w1[j])
break
elif w1[j] > w2[j]:
C.add(w1[j])
break
# add all letters should be capitalized based on E
A = {u for u in C}
while A:
B = set(itertools.chain.from_iterable([E[u] for u in A]))
A = B - C
C |= B
# check
for i in range(M-1):
w1 = words[i]
w2 = words[i+1]
for j in range(min(len(w1), len(w2))):
a, b = w1[j], w2[j]
d = [a in C, b in C]
if a < b:
if d == [False, True]:
print('No')
exit(0)
break
elif a > b:
if d != [True, False]:
print('No')
exit(0)
break
print('Yes')
print(len(C))
if C:
print(" ".join(map(str, sorted(C))))
# Made By Mostafa_Khaled
``` | output | 1 | 27,082 | 6 | 54,165 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library.
Some long and uninteresting story was removed...
The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large version of a letter x is denoted by x'. BSCII encoding, which is used everywhere in Bookland, is made in that way so that large letters are presented in the order of the numbers they are denoted by, and small letters are presented in the order of the numbers they are denoted by, but all large letters are before all small letters. For example, the following conditions hold: 2 < 3, 2' < 3', 3' < 2.
A word x1, x2, ..., xa is not lexicographically greater than y1, y2, ..., yb if one of the two following conditions holds:
* a β€ b and x1 = y1, ..., xa = ya, i.e. the first word is the prefix of the second word;
* there is a position 1 β€ j β€ min(a, b), such that x1 = y1, ..., xj - 1 = yj - 1 and xj < yj, i.e. at the first position where the words differ the first word has a smaller letter than the second word has.
For example, the word "3' 7 5" is before the word "2 4' 6" in lexicographical order. It is said that sequence of words is in lexicographical order if each word is not lexicographically greater than the next word in the sequence.
Denis has a sequence of words consisting of small letters only. He wants to change some letters to large (let's call this process a capitalization) in such a way that the sequence of words is in lexicographical order. However, he soon realized that for some reason he can't change a single letter in a single word. He only can choose a letter and change all of its occurrences in all words to large letters. He can perform this operation any number of times with arbitrary letters of Bookland's alphabet.
Help Denis to choose which letters he needs to capitalize (make large) in order to make the sequence of words lexicographically ordered, or determine that it is impossible.
Note that some words can be equal.
Input
The first line contains two integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 100 000) β the number of words and the number of letters in Bookland's alphabet, respectively. The letters of Bookland's alphabet are denoted by integers from 1 to m.
Each of the next n lines contains a description of one word in format li, si, 1, si, 2, ..., si, li (1 β€ li β€ 100 000, 1 β€ si, j β€ m), where li is the length of the word, and si, j is the sequence of letters in the word. The words are given in the order Denis has them in the sequence.
It is guaranteed that the total length of all words is not greater than 100 000.
Output
In the first line print "Yes" (without quotes), if it is possible to capitalize some set of letters in such a way that the sequence of words becomes lexicographically ordered. Otherwise, print "No" (without quotes).
If the required is possible, in the second line print k β the number of letters Denis has to capitalize (make large), and in the third line print k distinct integers β these letters. Note that you don't need to minimize the value k.
You can print the letters in any order. If there are multiple answers, print any of them.
Examples
Input
4 3
1 2
1 1
3 1 3 2
2 1 1
Output
Yes
2
2 3
Input
6 5
2 1 2
2 1 2
3 1 2 3
2 1 5
2 4 4
2 4 4
Output
Yes
0
Input
4 3
4 3 2 2 1
3 1 1 3
3 2 3 3
2 3 1
Output
No
Note
In the first example after Denis makes letters 2 and 3 large, the sequence looks like the following:
* 2'
* 1
* 1 3' 2'
* 1 1
The condition 2' < 1 holds, so the first word is not lexicographically larger than the second word. The second word is the prefix of the third word, so the are in lexicographical order. As the first letters of the third and the fourth words are the same, and 3' < 1, then the third word is not lexicographically larger than the fourth word.
In the second example the words are in lexicographical order from the beginning, so Denis can do nothing.
In the third example there is no set of letters such that if Denis capitalizes them, the sequence becomes lexicographically ordered. | instruction | 0 | 27,083 | 6 | 54,166 |
Tags: 2-sat, dfs and similar, graphs, implementation
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=2**51, func=lambda a, b: a & b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] < key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
n,m=map(int,input().split())
l=[]
for i in range(n):
l.append(list(map(int,input().split())))
c=[0]*(m+1)
ans=[]
f=0
graph=defaultdict(list)
for i in range(n-1):
for j in range(1,int(l[i][0])+1):
if j==int(l[i+1][0]) and int(l[i+1][0])<int(l[i][0]):
if c[l[i+1][j]]>c[l[i][j]]:
if c[l[i][j]] == 0:
c[l[i][j]] = 1
break
else:
f = 1
break
if l[i][j] >=l[i + 1][j] and c[l[i][j]] <= c[l[i + 1][j]]:
if c[l[i][j]] == 0:
c[l[i][j]] = 1
break
else:
f = 1
break
else:
graph[l[i + 1][j]].append(l[i][j])
break
elif c[l[i+1][j]]>c[l[i][j]]:
if c[l[i][j]] == 0:
c[l[i][j]] = 1
break
else:
f = 1
break
elif l[i][j]>l[i+1][j] and c[l[i][j]]<=c[l[i+1][j]]:
if c[l[i][j]]==0:
c[l[i][j]]=1
break
else:
f=1
break
elif l[i][j]<l[i+1][j] or c[l[i][j]]>c[l[i+1][j]]:
graph[l[i+1][j]].append(l[i][j])
break
if f==1:
break
if f==1:
print("No")
sys.exit(0)
f=0
visited=[False]*(m+1)
def dfs(v,t):
stack=[]
stack.append((v,t))
while(len(stack)>0):
v,t=stack.pop()
c[v] = max(t, c[v])
visited[v] = True
for i in graph[v]:
c[i]=max(c[i],c[v])
if visited[i]==False:
stack.append((i,c[v]))
for i in range(1,m+1):
if visited[i]==False and c[i]==1:
dfs(i,c[i])
for i in range(1,m+1):
if c[i]==1:
ans.append(i)
for i in range(n-1):
for j in range(1,int(l[i][0])+1):
if j == int(l[i + 1][0]) and int(l[i+1][0])<int(l[i][0]):
if c[l[i+1][j]]>c[l[i][j]]:
f=1
break
if l[i][j] >=l[i + 1][j] and c[l[i][j]] <= c[l[i + 1][j]]:
f=1
break
else:
break
if c[l[i + 1][j]] > c[l[i][j]]:
f = 1
break
elif l[i][j]>l[i+1][j] and c[l[i][j]]<=c[l[i+1][j]]:
f=1
break
elif l[i][j] < l[i + 1][j] or c[l[i][j]]>c[l[i+1][j]]:
break
if f==1:
print("No")
else:
print("Yes")
print(len(ans))
print(*ans)
``` | output | 1 | 27,083 | 6 | 54,167 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library.
Some long and uninteresting story was removed...
The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large version of a letter x is denoted by x'. BSCII encoding, which is used everywhere in Bookland, is made in that way so that large letters are presented in the order of the numbers they are denoted by, and small letters are presented in the order of the numbers they are denoted by, but all large letters are before all small letters. For example, the following conditions hold: 2 < 3, 2' < 3', 3' < 2.
A word x1, x2, ..., xa is not lexicographically greater than y1, y2, ..., yb if one of the two following conditions holds:
* a β€ b and x1 = y1, ..., xa = ya, i.e. the first word is the prefix of the second word;
* there is a position 1 β€ j β€ min(a, b), such that x1 = y1, ..., xj - 1 = yj - 1 and xj < yj, i.e. at the first position where the words differ the first word has a smaller letter than the second word has.
For example, the word "3' 7 5" is before the word "2 4' 6" in lexicographical order. It is said that sequence of words is in lexicographical order if each word is not lexicographically greater than the next word in the sequence.
Denis has a sequence of words consisting of small letters only. He wants to change some letters to large (let's call this process a capitalization) in such a way that the sequence of words is in lexicographical order. However, he soon realized that for some reason he can't change a single letter in a single word. He only can choose a letter and change all of its occurrences in all words to large letters. He can perform this operation any number of times with arbitrary letters of Bookland's alphabet.
Help Denis to choose which letters he needs to capitalize (make large) in order to make the sequence of words lexicographically ordered, or determine that it is impossible.
Note that some words can be equal.
Input
The first line contains two integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 100 000) β the number of words and the number of letters in Bookland's alphabet, respectively. The letters of Bookland's alphabet are denoted by integers from 1 to m.
Each of the next n lines contains a description of one word in format li, si, 1, si, 2, ..., si, li (1 β€ li β€ 100 000, 1 β€ si, j β€ m), where li is the length of the word, and si, j is the sequence of letters in the word. The words are given in the order Denis has them in the sequence.
It is guaranteed that the total length of all words is not greater than 100 000.
Output
In the first line print "Yes" (without quotes), if it is possible to capitalize some set of letters in such a way that the sequence of words becomes lexicographically ordered. Otherwise, print "No" (without quotes).
If the required is possible, in the second line print k β the number of letters Denis has to capitalize (make large), and in the third line print k distinct integers β these letters. Note that you don't need to minimize the value k.
You can print the letters in any order. If there are multiple answers, print any of them.
Examples
Input
4 3
1 2
1 1
3 1 3 2
2 1 1
Output
Yes
2
2 3
Input
6 5
2 1 2
2 1 2
3 1 2 3
2 1 5
2 4 4
2 4 4
Output
Yes
0
Input
4 3
4 3 2 2 1
3 1 1 3
3 2 3 3
2 3 1
Output
No
Note
In the first example after Denis makes letters 2 and 3 large, the sequence looks like the following:
* 2'
* 1
* 1 3' 2'
* 1 1
The condition 2' < 1 holds, so the first word is not lexicographically larger than the second word. The second word is the prefix of the third word, so the are in lexicographical order. As the first letters of the third and the fourth words are the same, and 3' < 1, then the third word is not lexicographically larger than the fourth word.
In the second example the words are in lexicographical order from the beginning, so Denis can do nothing.
In the third example there is no set of letters such that if Denis capitalizes them, the sequence becomes lexicographically ordered.
Submitted Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=2**51, func=lambda a, b: a & b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] < key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
n,m=map(int,input().split())
l=[]
for i in range(n):
l.append(list(map(int,input().split())))
c=[0]*(m+1)
ans=[]
f=0
graph=defaultdict(list)
for i in range(n-1):
for j in range(1,int(l[i][0])+1):
if j==int(l[i+1][0]) and int(l[i+1][0])<int(l[i][0]):
if c[l[i+1][j]]>c[l[i][j]]:
if c[l[i][j]] == 0:
c[l[i][j]] = 1
break
else:
f = 1
break
if l[i][j] >=l[i + 1][j] and c[l[i][j]] <= c[l[i + 1][j]]:
if c[l[i][j]] == 0:
c[l[i][j]] = 1
break
else:
f = 1
break
else:
graph[l[i + 1][j]].append(l[i][j])
break
elif c[l[i+1][j]]>c[l[i][j]]:
if c[l[i][j]] == 0:
c[l[i][j]] = 1
break
else:
f = 1
break
elif l[i][j]>l[i+1][j] and c[l[i][j]]<=c[l[i+1][j]]:
if c[l[i][j]]==0:
c[l[i][j]]=1
break
else:
f=1
break
elif l[i][j]<l[i+1][j] or c[l[i][j]]>c[l[i+1][j]]:
graph[l[i+1][j]].append(l[i][j])
break
if f==1:
break
if f==1:
print("No")
sys.exit(0)
f=0
visited=[False]*(m+1)
def dfs(v,t):
stack=[]
stack.append((v,t))
while(len(stack)>0):
v,t=stack.pop()
c[v] = max(t, c[v])
visited[v] = True
for i in graph[v]:
c[i]=max(c[i],c[v])
if visited[i]==False:
stack.append((i,c[v]))
for i in range(1,m+1):
if visited[i]==False and c[i]==1:
dfs(i,c[i])
for i in range(1,m+1):
if c[i]==1:
ans.append(i)
for i in range(n-1):
for j in range(1,int(l[i][0])+1):
if j == int(l[i + 1][0]):
if l[i][j] > l[i + 1][j] and c[l[i][j]] <= c[l[i + 1][j]]:
f=1
break
else:
break
if c[l[i + 1][j]] > c[l[i][j]]:
f = 1
break
elif l[i][j]>l[i+1][j] and c[l[i][j]]<=c[l[i+1][j]]:
f=1
break
elif l[i][j] < l[i + 1][j] or c[l[i][j]]>c[l[i+1][j]]:
break
if f==1:
print("No")
else:
print("Yes")
print(len(ans))
print(*ans)
``` | instruction | 0 | 27,084 | 6 | 54,168 |
No | output | 1 | 27,084 | 6 | 54,169 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library.
Some long and uninteresting story was removed...
The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large version of a letter x is denoted by x'. BSCII encoding, which is used everywhere in Bookland, is made in that way so that large letters are presented in the order of the numbers they are denoted by, and small letters are presented in the order of the numbers they are denoted by, but all large letters are before all small letters. For example, the following conditions hold: 2 < 3, 2' < 3', 3' < 2.
A word x1, x2, ..., xa is not lexicographically greater than y1, y2, ..., yb if one of the two following conditions holds:
* a β€ b and x1 = y1, ..., xa = ya, i.e. the first word is the prefix of the second word;
* there is a position 1 β€ j β€ min(a, b), such that x1 = y1, ..., xj - 1 = yj - 1 and xj < yj, i.e. at the first position where the words differ the first word has a smaller letter than the second word has.
For example, the word "3' 7 5" is before the word "2 4' 6" in lexicographical order. It is said that sequence of words is in lexicographical order if each word is not lexicographically greater than the next word in the sequence.
Denis has a sequence of words consisting of small letters only. He wants to change some letters to large (let's call this process a capitalization) in such a way that the sequence of words is in lexicographical order. However, he soon realized that for some reason he can't change a single letter in a single word. He only can choose a letter and change all of its occurrences in all words to large letters. He can perform this operation any number of times with arbitrary letters of Bookland's alphabet.
Help Denis to choose which letters he needs to capitalize (make large) in order to make the sequence of words lexicographically ordered, or determine that it is impossible.
Note that some words can be equal.
Input
The first line contains two integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 100 000) β the number of words and the number of letters in Bookland's alphabet, respectively. The letters of Bookland's alphabet are denoted by integers from 1 to m.
Each of the next n lines contains a description of one word in format li, si, 1, si, 2, ..., si, li (1 β€ li β€ 100 000, 1 β€ si, j β€ m), where li is the length of the word, and si, j is the sequence of letters in the word. The words are given in the order Denis has them in the sequence.
It is guaranteed that the total length of all words is not greater than 100 000.
Output
In the first line print "Yes" (without quotes), if it is possible to capitalize some set of letters in such a way that the sequence of words becomes lexicographically ordered. Otherwise, print "No" (without quotes).
If the required is possible, in the second line print k β the number of letters Denis has to capitalize (make large), and in the third line print k distinct integers β these letters. Note that you don't need to minimize the value k.
You can print the letters in any order. If there are multiple answers, print any of them.
Examples
Input
4 3
1 2
1 1
3 1 3 2
2 1 1
Output
Yes
2
2 3
Input
6 5
2 1 2
2 1 2
3 1 2 3
2 1 5
2 4 4
2 4 4
Output
Yes
0
Input
4 3
4 3 2 2 1
3 1 1 3
3 2 3 3
2 3 1
Output
No
Note
In the first example after Denis makes letters 2 and 3 large, the sequence looks like the following:
* 2'
* 1
* 1 3' 2'
* 1 1
The condition 2' < 1 holds, so the first word is not lexicographically larger than the second word. The second word is the prefix of the third word, so the are in lexicographical order. As the first letters of the third and the fourth words are the same, and 3' < 1, then the third word is not lexicographically larger than the fourth word.
In the second example the words are in lexicographical order from the beginning, so Denis can do nothing.
In the third example there is no set of letters such that if Denis capitalizes them, the sequence becomes lexicographically ordered.
Submitted Solution:
```
from collections import defaultdict, deque
def main():
n,m = map(int, input().split())
cap = [None]*(m+1)
same_cap = defaultdict(list)
q = deque()
def apply_cap(a, c):
if cap[a] is not None:
return cap[a] == c
q.append(a)
while q:
b = q.pop()
if cap[b] is None:
cap[b] = c
q.extend(same_cap[b])
same_cap[b] = []
elif cap[b]!=c:
return False
return True
def same(a,b):
if cap[a] is None and cap[b] is None:
same_cap[b].append(a)
return True
elif cap[a] is None:
apply_cap(b, cap[a])
cap[a] = cap[b]
return True
elif cap[b] is None:
apply_cap(a, cap[b])
cap[b] = cap[a]
return True
else:
return cap[a] == cap[b]
def process(p,c):
lp = p[0]
lc = c[0]
for i in range(1, min(lp,lc)+1):
if p[i]>c[i]:
return apply_cap(p[i], True) and apply_cap(c[i], False)
if p[i]<c[i]:
return same(p[i], c[i])
return lp<=lc
p = list(map(int, input().split()))
for i in range(n-1):
c = list(map(int, input().split()))
if not process(p, c):
print ('No')
break
p = c
else:
print ('Yes')
res = []
for i,b in enumerate(cap):
if b:
res.append(i)
print(len(res))
print(' '.join(map(str,res)))
main()
``` | instruction | 0 | 27,085 | 6 | 54,170 |
No | output | 1 | 27,085 | 6 | 54,171 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library.
Some long and uninteresting story was removed...
The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large version of a letter x is denoted by x'. BSCII encoding, which is used everywhere in Bookland, is made in that way so that large letters are presented in the order of the numbers they are denoted by, and small letters are presented in the order of the numbers they are denoted by, but all large letters are before all small letters. For example, the following conditions hold: 2 < 3, 2' < 3', 3' < 2.
A word x1, x2, ..., xa is not lexicographically greater than y1, y2, ..., yb if one of the two following conditions holds:
* a β€ b and x1 = y1, ..., xa = ya, i.e. the first word is the prefix of the second word;
* there is a position 1 β€ j β€ min(a, b), such that x1 = y1, ..., xj - 1 = yj - 1 and xj < yj, i.e. at the first position where the words differ the first word has a smaller letter than the second word has.
For example, the word "3' 7 5" is before the word "2 4' 6" in lexicographical order. It is said that sequence of words is in lexicographical order if each word is not lexicographically greater than the next word in the sequence.
Denis has a sequence of words consisting of small letters only. He wants to change some letters to large (let's call this process a capitalization) in such a way that the sequence of words is in lexicographical order. However, he soon realized that for some reason he can't change a single letter in a single word. He only can choose a letter and change all of its occurrences in all words to large letters. He can perform this operation any number of times with arbitrary letters of Bookland's alphabet.
Help Denis to choose which letters he needs to capitalize (make large) in order to make the sequence of words lexicographically ordered, or determine that it is impossible.
Note that some words can be equal.
Input
The first line contains two integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 100 000) β the number of words and the number of letters in Bookland's alphabet, respectively. The letters of Bookland's alphabet are denoted by integers from 1 to m.
Each of the next n lines contains a description of one word in format li, si, 1, si, 2, ..., si, li (1 β€ li β€ 100 000, 1 β€ si, j β€ m), where li is the length of the word, and si, j is the sequence of letters in the word. The words are given in the order Denis has them in the sequence.
It is guaranteed that the total length of all words is not greater than 100 000.
Output
In the first line print "Yes" (without quotes), if it is possible to capitalize some set of letters in such a way that the sequence of words becomes lexicographically ordered. Otherwise, print "No" (without quotes).
If the required is possible, in the second line print k β the number of letters Denis has to capitalize (make large), and in the third line print k distinct integers β these letters. Note that you don't need to minimize the value k.
You can print the letters in any order. If there are multiple answers, print any of them.
Examples
Input
4 3
1 2
1 1
3 1 3 2
2 1 1
Output
Yes
2
2 3
Input
6 5
2 1 2
2 1 2
3 1 2 3
2 1 5
2 4 4
2 4 4
Output
Yes
0
Input
4 3
4 3 2 2 1
3 1 1 3
3 2 3 3
2 3 1
Output
No
Note
In the first example after Denis makes letters 2 and 3 large, the sequence looks like the following:
* 2'
* 1
* 1 3' 2'
* 1 1
The condition 2' < 1 holds, so the first word is not lexicographically larger than the second word. The second word is the prefix of the third word, so the are in lexicographical order. As the first letters of the third and the fourth words are the same, and 3' < 1, then the third word is not lexicographically larger than the fourth word.
In the second example the words are in lexicographical order from the beginning, so Denis can do nothing.
In the third example there is no set of letters such that if Denis capitalizes them, the sequence becomes lexicographically ordered.
Submitted Solution:
```
from collections import defaultdict, deque
def main():
n,m = map(int, input().split())
cap = [None]*(m+1)
same_cap = defaultdict(list)
q = deque()
def apply_cap(a, c):
if cap[a] is not None:
return cap[a] == c
q.append(a)
while q:
b = q.pop()
if cap[b] is None:
cap[b] = c
q.extend(same_cap[b])
same_cap[b] = []
elif cap[b]!=c:
return False
return True
def same(a,b):
if cap[a] is None and cap[b] is None:
same_cap[a].append(b)
same_cap[b].append(a)
return True
elif cap[a] is None:
apply_cap(b, cap[a])
cap[a] = cap[b]
return True
elif cap[b] is None:
apply_cap(a, cap[b])
cap[b] = cap[a]
return True
else:
return cap[a] == cap[b]
def process(p,c):
lp = p[0]
lc = c[0]
for i in range(1, min(lp,lc)+1):
if p[i]>c[i]:
return apply_cap(p[i], True) and apply_cap(c[i], False)
if p[i]<c[i]:
return same(p[i], c[i])
return lp<=lc
p = list(map(int, input().split()))
for i in range(n-1):
c = list(map(int, input().split()))
if not process(p, c):
print ('No')
break
p = c
else:
print ('Yes')
res = []
for i,b in enumerate(cap):
if b:
res.append(i)
print(len(res))
print(' '.join(map(str,res)))
main()
``` | instruction | 0 | 27,086 | 6 | 54,172 |
No | output | 1 | 27,086 | 6 | 54,173 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library.
Some long and uninteresting story was removed...
The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large version of a letter x is denoted by x'. BSCII encoding, which is used everywhere in Bookland, is made in that way so that large letters are presented in the order of the numbers they are denoted by, and small letters are presented in the order of the numbers they are denoted by, but all large letters are before all small letters. For example, the following conditions hold: 2 < 3, 2' < 3', 3' < 2.
A word x1, x2, ..., xa is not lexicographically greater than y1, y2, ..., yb if one of the two following conditions holds:
* a β€ b and x1 = y1, ..., xa = ya, i.e. the first word is the prefix of the second word;
* there is a position 1 β€ j β€ min(a, b), such that x1 = y1, ..., xj - 1 = yj - 1 and xj < yj, i.e. at the first position where the words differ the first word has a smaller letter than the second word has.
For example, the word "3' 7 5" is before the word "2 4' 6" in lexicographical order. It is said that sequence of words is in lexicographical order if each word is not lexicographically greater than the next word in the sequence.
Denis has a sequence of words consisting of small letters only. He wants to change some letters to large (let's call this process a capitalization) in such a way that the sequence of words is in lexicographical order. However, he soon realized that for some reason he can't change a single letter in a single word. He only can choose a letter and change all of its occurrences in all words to large letters. He can perform this operation any number of times with arbitrary letters of Bookland's alphabet.
Help Denis to choose which letters he needs to capitalize (make large) in order to make the sequence of words lexicographically ordered, or determine that it is impossible.
Note that some words can be equal.
Input
The first line contains two integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 100 000) β the number of words and the number of letters in Bookland's alphabet, respectively. The letters of Bookland's alphabet are denoted by integers from 1 to m.
Each of the next n lines contains a description of one word in format li, si, 1, si, 2, ..., si, li (1 β€ li β€ 100 000, 1 β€ si, j β€ m), where li is the length of the word, and si, j is the sequence of letters in the word. The words are given in the order Denis has them in the sequence.
It is guaranteed that the total length of all words is not greater than 100 000.
Output
In the first line print "Yes" (without quotes), if it is possible to capitalize some set of letters in such a way that the sequence of words becomes lexicographically ordered. Otherwise, print "No" (without quotes).
If the required is possible, in the second line print k β the number of letters Denis has to capitalize (make large), and in the third line print k distinct integers β these letters. Note that you don't need to minimize the value k.
You can print the letters in any order. If there are multiple answers, print any of them.
Examples
Input
4 3
1 2
1 1
3 1 3 2
2 1 1
Output
Yes
2
2 3
Input
6 5
2 1 2
2 1 2
3 1 2 3
2 1 5
2 4 4
2 4 4
Output
Yes
0
Input
4 3
4 3 2 2 1
3 1 1 3
3 2 3 3
2 3 1
Output
No
Note
In the first example after Denis makes letters 2 and 3 large, the sequence looks like the following:
* 2'
* 1
* 1 3' 2'
* 1 1
The condition 2' < 1 holds, so the first word is not lexicographically larger than the second word. The second word is the prefix of the third word, so the are in lexicographical order. As the first letters of the third and the fourth words are the same, and 3' < 1, then the third word is not lexicographically larger than the fourth word.
In the second example the words are in lexicographical order from the beginning, so Denis can do nothing.
In the third example there is no set of letters such that if Denis capitalizes them, the sequence becomes lexicographically ordered.
Submitted Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=2**51, func=lambda a, b: a & b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] < key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
n,m=map(int,input().split())
l=[]
for i in range(n):
l.append(list(map(int,input().split())))
c=defaultdict(int)
ans=[]
f=0
while(sum(c)!=10):
su=0
for i in range(10):
su+=c[i]
f=0
for i in range(n-1):
for j in range(1,int(l[i][0])+1):
if j==int(l[i+1][0]):
if c[l[i+1][j]]>c[l[i][j]]:
if c[l[i][j]] == 0:
ans.append(l[i][j])
c[l[i][j]] = 1
break
else:
f = 1
break
if l[i][j] > l[i + 1][j] and c[l[i][j]] <= c[l[i + 1][j]]:
if c[l[i][j]] == 0:
ans.append(l[i][j])
c[l[i][j]] = 1
break
else:
f = 1
break
else:
break
elif c[l[i+1][j]]>c[l[i][j]]:
if c[l[i][j]] == 0:
ans.append(l[i][j])
c[l[i][j]] = 1
break
else:
f = 1
break
elif l[i][j]>l[i+1][j] and c[l[i][j]]<=c[l[i+1][j]]:
if c[l[i][j]]==0:
ans.append(l[i][j])
c[l[i][j]]=1
break
else:
f=1
break
elif l[i][j]<l[i+1][j] or c[l[i][j]]>c[l[i+1][j]]:
break
if f==1:
break
if f==1:
break
su1 = 0
for i in range(10):
su1 += c[i]
if su==su1:
break
if f==1:
print("No")
sys.exit(0)
f=0
for i in range(n-1):
for j in range(1,int(l[i][0])+1):
if j == int(l[i + 1][0]):
if l[i][j] > l[i + 1][j] and c[l[i][j]] <= c[l[i + 1][j]]:
f=1
break
else:
break
if c[l[i + 1][j]] > c[l[i][j]]:
f = 1
break
elif l[i][j]>l[i+1][j] and c[l[i][j]]<=c[l[i+1][j]]:
f=1
break
elif l[i][j] < l[i + 1][j] or c[l[i][j]]>c[l[i+1][j]]:
break
if f==1:
print("No")
else:
print("Yes")
print(len(ans))
print(*ans)
``` | instruction | 0 | 27,087 | 6 | 54,174 |
No | output | 1 | 27,087 | 6 | 54,175 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string β concatenation of letters, which correspond to the stages.
There are n stages available. The rocket must contain exactly k of them. Stages in the rocket should be ordered by their weight. So, after the stage with some letter can go only stage with a letter, which is at least two positions after in the alphabet (skipping one letter in between, or even more). For example, after letter 'c' can't go letters 'a', 'b', 'c' and 'd', but can go letters 'e', 'f', ..., 'z'.
For the rocket to fly as far as possible, its weight should be minimal. The weight of the rocket is equal to the sum of the weights of its stages. The weight of the stage is the number of its letter in the alphabet. For example, the stage 'a 'weighs one ton,' b 'weighs two tons, and' z' β 26 tons.
Build the rocket with the minimal weight or determine, that it is impossible to build a rocket at all. Each stage can be used at most once.
Input
The first line of input contains two integers β n and k (1 β€ k β€ n β€ 50) β the number of available stages and the number of stages to use in the rocket.
The second line contains string s, which consists of exactly n lowercase Latin letters. Each letter defines a new stage, which can be used to build the rocket. Each stage can be used at most once.
Output
Print a single integer β the minimal total weight of the rocket or -1, if it is impossible to build the rocket at all.
Examples
Input
5 3
xyabd
Output
29
Input
7 4
problem
Output
34
Input
2 2
ab
Output
-1
Input
12 1
abaabbaaabbb
Output
1
Note
In the first example, the following rockets satisfy the condition:
* "adx" (weight is 1+4+24=29);
* "ady" (weight is 1+4+25=30);
* "bdx" (weight is 2+4+24=30);
* "bdy" (weight is 2+4+25=31).
Rocket "adx" has the minimal weight, so the answer is 29.
In the second example, target rocket is "belo". Its weight is 2+5+12+15=34.
In the third example, n=k=2, so the rocket must have both stages: 'a' and 'b'. This rocket doesn't satisfy the condition, because these letters are adjacent in the alphabet. Answer is -1. | instruction | 0 | 27,381 | 6 | 54,762 |
Tags: greedy, implementation, sortings
Correct Solution:
```
n,k=map(int,input().split())
s=input()
nl=[ chr(ord('a')+i) for i in range(26) ]
vall=[ 0 for i in range(0,26) ]
for i in s:
vall[ord(i)-ord('a')]+=1
j=0
ans=0
flag=0
while j<26 :
if vall[ord(nl[j])-ord('a')]>0 :
vall[ord(nl[j])-ord('a')]-=1
ans+=j+1
j+=2
flag+=1
if flag==k :
break
else:
j+=1
continue
if(flag==k):
print(ans)
else:
print("-1")
``` | output | 1 | 27,381 | 6 | 54,763 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string β concatenation of letters, which correspond to the stages.
There are n stages available. The rocket must contain exactly k of them. Stages in the rocket should be ordered by their weight. So, after the stage with some letter can go only stage with a letter, which is at least two positions after in the alphabet (skipping one letter in between, or even more). For example, after letter 'c' can't go letters 'a', 'b', 'c' and 'd', but can go letters 'e', 'f', ..., 'z'.
For the rocket to fly as far as possible, its weight should be minimal. The weight of the rocket is equal to the sum of the weights of its stages. The weight of the stage is the number of its letter in the alphabet. For example, the stage 'a 'weighs one ton,' b 'weighs two tons, and' z' β 26 tons.
Build the rocket with the minimal weight or determine, that it is impossible to build a rocket at all. Each stage can be used at most once.
Input
The first line of input contains two integers β n and k (1 β€ k β€ n β€ 50) β the number of available stages and the number of stages to use in the rocket.
The second line contains string s, which consists of exactly n lowercase Latin letters. Each letter defines a new stage, which can be used to build the rocket. Each stage can be used at most once.
Output
Print a single integer β the minimal total weight of the rocket or -1, if it is impossible to build the rocket at all.
Examples
Input
5 3
xyabd
Output
29
Input
7 4
problem
Output
34
Input
2 2
ab
Output
-1
Input
12 1
abaabbaaabbb
Output
1
Note
In the first example, the following rockets satisfy the condition:
* "adx" (weight is 1+4+24=29);
* "ady" (weight is 1+4+25=30);
* "bdx" (weight is 2+4+24=30);
* "bdy" (weight is 2+4+25=31).
Rocket "adx" has the minimal weight, so the answer is 29.
In the second example, target rocket is "belo". Its weight is 2+5+12+15=34.
In the third example, n=k=2, so the rocket must have both stages: 'a' and 'b'. This rocket doesn't satisfy the condition, because these letters are adjacent in the alphabet. Answer is -1. | instruction | 0 | 27,382 | 6 | 54,764 |
Tags: greedy, implementation, sortings
Correct Solution:
```
n,k=map(int,input().split())
s=input()
s=list(s)
s.sort()
ans=0
i=0
l=set()
cur=None
if(n==1 and k==1):
print(ord(s[0])-96)
elif(n==1 and k>1):
print(-1)
else:
while(i<n and k>0):
cur=s[i]
if(s[i] not in l):
ans+=ord(s[i])-96
l.add(s[i])
i+=1
k-=1
else:
i+=1
while(i<n and s[i]==chr(ord(cur)+1)):
i+=1
if(k>0):
print(-1)
else:
print(ans)
``` | output | 1 | 27,382 | 6 | 54,765 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string β concatenation of letters, which correspond to the stages.
There are n stages available. The rocket must contain exactly k of them. Stages in the rocket should be ordered by their weight. So, after the stage with some letter can go only stage with a letter, which is at least two positions after in the alphabet (skipping one letter in between, or even more). For example, after letter 'c' can't go letters 'a', 'b', 'c' and 'd', but can go letters 'e', 'f', ..., 'z'.
For the rocket to fly as far as possible, its weight should be minimal. The weight of the rocket is equal to the sum of the weights of its stages. The weight of the stage is the number of its letter in the alphabet. For example, the stage 'a 'weighs one ton,' b 'weighs two tons, and' z' β 26 tons.
Build the rocket with the minimal weight or determine, that it is impossible to build a rocket at all. Each stage can be used at most once.
Input
The first line of input contains two integers β n and k (1 β€ k β€ n β€ 50) β the number of available stages and the number of stages to use in the rocket.
The second line contains string s, which consists of exactly n lowercase Latin letters. Each letter defines a new stage, which can be used to build the rocket. Each stage can be used at most once.
Output
Print a single integer β the minimal total weight of the rocket or -1, if it is impossible to build the rocket at all.
Examples
Input
5 3
xyabd
Output
29
Input
7 4
problem
Output
34
Input
2 2
ab
Output
-1
Input
12 1
abaabbaaabbb
Output
1
Note
In the first example, the following rockets satisfy the condition:
* "adx" (weight is 1+4+24=29);
* "ady" (weight is 1+4+25=30);
* "bdx" (weight is 2+4+24=30);
* "bdy" (weight is 2+4+25=31).
Rocket "adx" has the minimal weight, so the answer is 29.
In the second example, target rocket is "belo". Its weight is 2+5+12+15=34.
In the third example, n=k=2, so the rocket must have both stages: 'a' and 'b'. This rocket doesn't satisfy the condition, because these letters are adjacent in the alphabet. Answer is -1. | instruction | 0 | 27,383 | 6 | 54,766 |
Tags: greedy, implementation, sortings
Correct Solution:
```
n, k = list(map(int, input().split()))
s = sorted(input())
su, i, e = ord(s[0]) - 96, 1, s[0]
while i < n:
if k <= 1:
break
if (ord(s[i]) - 96) - (ord(e) - 96) >= 2:
su += (ord(s[i]) - 96)
e, k = s[i], k - 1
i += 1
print(su if k <= 1 else -1)
``` | output | 1 | 27,383 | 6 | 54,767 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string β concatenation of letters, which correspond to the stages.
There are n stages available. The rocket must contain exactly k of them. Stages in the rocket should be ordered by their weight. So, after the stage with some letter can go only stage with a letter, which is at least two positions after in the alphabet (skipping one letter in between, or even more). For example, after letter 'c' can't go letters 'a', 'b', 'c' and 'd', but can go letters 'e', 'f', ..., 'z'.
For the rocket to fly as far as possible, its weight should be minimal. The weight of the rocket is equal to the sum of the weights of its stages. The weight of the stage is the number of its letter in the alphabet. For example, the stage 'a 'weighs one ton,' b 'weighs two tons, and' z' β 26 tons.
Build the rocket with the minimal weight or determine, that it is impossible to build a rocket at all. Each stage can be used at most once.
Input
The first line of input contains two integers β n and k (1 β€ k β€ n β€ 50) β the number of available stages and the number of stages to use in the rocket.
The second line contains string s, which consists of exactly n lowercase Latin letters. Each letter defines a new stage, which can be used to build the rocket. Each stage can be used at most once.
Output
Print a single integer β the minimal total weight of the rocket or -1, if it is impossible to build the rocket at all.
Examples
Input
5 3
xyabd
Output
29
Input
7 4
problem
Output
34
Input
2 2
ab
Output
-1
Input
12 1
abaabbaaabbb
Output
1
Note
In the first example, the following rockets satisfy the condition:
* "adx" (weight is 1+4+24=29);
* "ady" (weight is 1+4+25=30);
* "bdx" (weight is 2+4+24=30);
* "bdy" (weight is 2+4+25=31).
Rocket "adx" has the minimal weight, so the answer is 29.
In the second example, target rocket is "belo". Its weight is 2+5+12+15=34.
In the third example, n=k=2, so the rocket must have both stages: 'a' and 'b'. This rocket doesn't satisfy the condition, because these letters are adjacent in the alphabet. Answer is -1. | instruction | 0 | 27,384 | 6 | 54,768 |
Tags: greedy, implementation, sortings
Correct Solution:
```
n , k = [int(x) for x in input().split()]
MAXV = 999999999999999999999
s = input()
s = list(set(s))
n = len(s)
s.sort()
res = MAXV
cur = 0
st = 0
fin = st + 1
cur = ord(s[st]) - ord("a") + 1
taken = [s[st]]
while len(taken) < k and fin < n:
if ord(s[fin]) - ord(taken[-1]) > 1:
cur += ord(s[fin]) - ord("a") + 1
taken.append(s[fin])
fin += 1
if len(taken) == k:
print(cur)
else:
print(-1)
``` | output | 1 | 27,384 | 6 | 54,769 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string β concatenation of letters, which correspond to the stages.
There are n stages available. The rocket must contain exactly k of them. Stages in the rocket should be ordered by their weight. So, after the stage with some letter can go only stage with a letter, which is at least two positions after in the alphabet (skipping one letter in between, or even more). For example, after letter 'c' can't go letters 'a', 'b', 'c' and 'd', but can go letters 'e', 'f', ..., 'z'.
For the rocket to fly as far as possible, its weight should be minimal. The weight of the rocket is equal to the sum of the weights of its stages. The weight of the stage is the number of its letter in the alphabet. For example, the stage 'a 'weighs one ton,' b 'weighs two tons, and' z' β 26 tons.
Build the rocket with the minimal weight or determine, that it is impossible to build a rocket at all. Each stage can be used at most once.
Input
The first line of input contains two integers β n and k (1 β€ k β€ n β€ 50) β the number of available stages and the number of stages to use in the rocket.
The second line contains string s, which consists of exactly n lowercase Latin letters. Each letter defines a new stage, which can be used to build the rocket. Each stage can be used at most once.
Output
Print a single integer β the minimal total weight of the rocket or -1, if it is impossible to build the rocket at all.
Examples
Input
5 3
xyabd
Output
29
Input
7 4
problem
Output
34
Input
2 2
ab
Output
-1
Input
12 1
abaabbaaabbb
Output
1
Note
In the first example, the following rockets satisfy the condition:
* "adx" (weight is 1+4+24=29);
* "ady" (weight is 1+4+25=30);
* "bdx" (weight is 2+4+24=30);
* "bdy" (weight is 2+4+25=31).
Rocket "adx" has the minimal weight, so the answer is 29.
In the second example, target rocket is "belo". Its weight is 2+5+12+15=34.
In the third example, n=k=2, so the rocket must have both stages: 'a' and 'b'. This rocket doesn't satisfy the condition, because these letters are adjacent in the alphabet. Answer is -1. | instruction | 0 | 27,385 | 6 | 54,770 |
Tags: greedy, implementation, sortings
Correct Solution:
```
num = input()
num = num.split()
n = int(num[0])
x = int(num[1])
ip = input()
myDict = {}
ch = 'a'
for i in range(1,27):
myDict.update({ch:i})
ch = chr(ord(ch) + 1)
myList = []
for c in ip:
myList.append([c,myDict[c]])
myList.sort(key = lambda x: x[1])
sum = 0
prev = myList[0][1]
sum += prev
count = 1
done = False
if count!= x:
for i in range(1,n):
#print("LOOP" + str(i))
if prev + 1 == myList[i][1] or prev == myList[i][1]:
#print("PASS" + str(myList[i][1]))
pass
else:
#print("ELSE" + str(myList[i][1]))
count += 1
sum += myList[i][1]
prev = myList[i][1]
if count == x:
done = True
print(sum)
break
elif count == x:
if not done:
print(sum)
if count != x:
print(-1)
``` | output | 1 | 27,385 | 6 | 54,771 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string β concatenation of letters, which correspond to the stages.
There are n stages available. The rocket must contain exactly k of them. Stages in the rocket should be ordered by their weight. So, after the stage with some letter can go only stage with a letter, which is at least two positions after in the alphabet (skipping one letter in between, or even more). For example, after letter 'c' can't go letters 'a', 'b', 'c' and 'd', but can go letters 'e', 'f', ..., 'z'.
For the rocket to fly as far as possible, its weight should be minimal. The weight of the rocket is equal to the sum of the weights of its stages. The weight of the stage is the number of its letter in the alphabet. For example, the stage 'a 'weighs one ton,' b 'weighs two tons, and' z' β 26 tons.
Build the rocket with the minimal weight or determine, that it is impossible to build a rocket at all. Each stage can be used at most once.
Input
The first line of input contains two integers β n and k (1 β€ k β€ n β€ 50) β the number of available stages and the number of stages to use in the rocket.
The second line contains string s, which consists of exactly n lowercase Latin letters. Each letter defines a new stage, which can be used to build the rocket. Each stage can be used at most once.
Output
Print a single integer β the minimal total weight of the rocket or -1, if it is impossible to build the rocket at all.
Examples
Input
5 3
xyabd
Output
29
Input
7 4
problem
Output
34
Input
2 2
ab
Output
-1
Input
12 1
abaabbaaabbb
Output
1
Note
In the first example, the following rockets satisfy the condition:
* "adx" (weight is 1+4+24=29);
* "ady" (weight is 1+4+25=30);
* "bdx" (weight is 2+4+24=30);
* "bdy" (weight is 2+4+25=31).
Rocket "adx" has the minimal weight, so the answer is 29.
In the second example, target rocket is "belo". Its weight is 2+5+12+15=34.
In the third example, n=k=2, so the rocket must have both stages: 'a' and 'b'. This rocket doesn't satisfy the condition, because these letters are adjacent in the alphabet. Answer is -1. | instruction | 0 | 27,386 | 6 | 54,772 |
Tags: greedy, implementation, sortings
Correct Solution:
```
# cook your dish here
# from math import *
#for _ in range(int(input().strip())):
n,k = map(int,input().split())
s = input()
s = ''.join(sorted(s))
k-=1
prev = s[0]
ans = ord(s[0]) - ord('a') + 1
for i in range(n):
if k==0:
break
if ord(s[i]) - ord(prev) > 1 :
k-=1
ans+= ( ord(s[i]) - ord('a') + 1)
prev = s[i]
if k:
ans = -1
print(ans)
``` | output | 1 | 27,386 | 6 | 54,773 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string β concatenation of letters, which correspond to the stages.
There are n stages available. The rocket must contain exactly k of them. Stages in the rocket should be ordered by their weight. So, after the stage with some letter can go only stage with a letter, which is at least two positions after in the alphabet (skipping one letter in between, or even more). For example, after letter 'c' can't go letters 'a', 'b', 'c' and 'd', but can go letters 'e', 'f', ..., 'z'.
For the rocket to fly as far as possible, its weight should be minimal. The weight of the rocket is equal to the sum of the weights of its stages. The weight of the stage is the number of its letter in the alphabet. For example, the stage 'a 'weighs one ton,' b 'weighs two tons, and' z' β 26 tons.
Build the rocket with the minimal weight or determine, that it is impossible to build a rocket at all. Each stage can be used at most once.
Input
The first line of input contains two integers β n and k (1 β€ k β€ n β€ 50) β the number of available stages and the number of stages to use in the rocket.
The second line contains string s, which consists of exactly n lowercase Latin letters. Each letter defines a new stage, which can be used to build the rocket. Each stage can be used at most once.
Output
Print a single integer β the minimal total weight of the rocket or -1, if it is impossible to build the rocket at all.
Examples
Input
5 3
xyabd
Output
29
Input
7 4
problem
Output
34
Input
2 2
ab
Output
-1
Input
12 1
abaabbaaabbb
Output
1
Note
In the first example, the following rockets satisfy the condition:
* "adx" (weight is 1+4+24=29);
* "ady" (weight is 1+4+25=30);
* "bdx" (weight is 2+4+24=30);
* "bdy" (weight is 2+4+25=31).
Rocket "adx" has the minimal weight, so the answer is 29.
In the second example, target rocket is "belo". Its weight is 2+5+12+15=34.
In the third example, n=k=2, so the rocket must have both stages: 'a' and 'b'. This rocket doesn't satisfy the condition, because these letters are adjacent in the alphabet. Answer is -1. | instruction | 0 | 27,387 | 6 | 54,774 |
Tags: greedy, implementation, sortings
Correct Solution:
```
n,k = list(map(int,input().split()))
data = sorted(list(input()))
data = list(map(lambda x:ord(x)-ord('a')+1,data))
result = 0
used = 0
idx =0
prev = -2
# print(data)
for d in data:
if d > prev+1:
result+= d
prev = d
used += 1
if used == k:
break
if used < k:
print(-1)
else:
print(result)
``` | output | 1 | 27,387 | 6 | 54,775 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string β concatenation of letters, which correspond to the stages.
There are n stages available. The rocket must contain exactly k of them. Stages in the rocket should be ordered by their weight. So, after the stage with some letter can go only stage with a letter, which is at least two positions after in the alphabet (skipping one letter in between, or even more). For example, after letter 'c' can't go letters 'a', 'b', 'c' and 'd', but can go letters 'e', 'f', ..., 'z'.
For the rocket to fly as far as possible, its weight should be minimal. The weight of the rocket is equal to the sum of the weights of its stages. The weight of the stage is the number of its letter in the alphabet. For example, the stage 'a 'weighs one ton,' b 'weighs two tons, and' z' β 26 tons.
Build the rocket with the minimal weight or determine, that it is impossible to build a rocket at all. Each stage can be used at most once.
Input
The first line of input contains two integers β n and k (1 β€ k β€ n β€ 50) β the number of available stages and the number of stages to use in the rocket.
The second line contains string s, which consists of exactly n lowercase Latin letters. Each letter defines a new stage, which can be used to build the rocket. Each stage can be used at most once.
Output
Print a single integer β the minimal total weight of the rocket or -1, if it is impossible to build the rocket at all.
Examples
Input
5 3
xyabd
Output
29
Input
7 4
problem
Output
34
Input
2 2
ab
Output
-1
Input
12 1
abaabbaaabbb
Output
1
Note
In the first example, the following rockets satisfy the condition:
* "adx" (weight is 1+4+24=29);
* "ady" (weight is 1+4+25=30);
* "bdx" (weight is 2+4+24=30);
* "bdy" (weight is 2+4+25=31).
Rocket "adx" has the minimal weight, so the answer is 29.
In the second example, target rocket is "belo". Its weight is 2+5+12+15=34.
In the third example, n=k=2, so the rocket must have both stages: 'a' and 'b'. This rocket doesn't satisfy the condition, because these letters are adjacent in the alphabet. Answer is -1. | instruction | 0 | 27,388 | 6 | 54,776 |
Tags: greedy, implementation, sortings
Correct Solution:
```
import math as ma
from sys import exit
from decimal import Decimal as dec
def li():
return list(map(int , input().split()))
# https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/
def modInverse(a , m):
m0 = m
y = 0
x = 1
if (m == 1):
return 0
while (a > 1):
q = a // m
t = m
m = a % m
a = t
t = y
y = x - q * y
x = t
if (x < 0):
x = x + m0
return x
def num():
return map(int , input().split())
def nu():
return int(input())
def find_gcd(x , y):
while (y):
x , y = y , x % y
return x
mi=1000000000
n,k=num()
s=input()
f=[0]*26
for i in range(n):
a=ord(s[i])-97
f[a]+=1
ss=0
pp=0
ind=0
#print(f)
for i in range(26):
if(f[i]==0):
continue
ss=i+1
pp=1
ind=i+2
while(pp<k and ind<26):
#print(ind,pp)
if(f[ind]==0):
ind+=1
else:
ss+=ind+1
pp+=1
ind+=2
#print("Entered",pp)
#print(pp)
if(pp==k):
mi=min(ss,mi)
if(mi==1000000000):
print(-1)
else:
print(mi)
``` | output | 1 | 27,388 | 6 | 54,777 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string β concatenation of letters, which correspond to the stages.
There are n stages available. The rocket must contain exactly k of them. Stages in the rocket should be ordered by their weight. So, after the stage with some letter can go only stage with a letter, which is at least two positions after in the alphabet (skipping one letter in between, or even more). For example, after letter 'c' can't go letters 'a', 'b', 'c' and 'd', but can go letters 'e', 'f', ..., 'z'.
For the rocket to fly as far as possible, its weight should be minimal. The weight of the rocket is equal to the sum of the weights of its stages. The weight of the stage is the number of its letter in the alphabet. For example, the stage 'a 'weighs one ton,' b 'weighs two tons, and' z' β 26 tons.
Build the rocket with the minimal weight or determine, that it is impossible to build a rocket at all. Each stage can be used at most once.
Input
The first line of input contains two integers β n and k (1 β€ k β€ n β€ 50) β the number of available stages and the number of stages to use in the rocket.
The second line contains string s, which consists of exactly n lowercase Latin letters. Each letter defines a new stage, which can be used to build the rocket. Each stage can be used at most once.
Output
Print a single integer β the minimal total weight of the rocket or -1, if it is impossible to build the rocket at all.
Examples
Input
5 3
xyabd
Output
29
Input
7 4
problem
Output
34
Input
2 2
ab
Output
-1
Input
12 1
abaabbaaabbb
Output
1
Note
In the first example, the following rockets satisfy the condition:
* "adx" (weight is 1+4+24=29);
* "ady" (weight is 1+4+25=30);
* "bdx" (weight is 2+4+24=30);
* "bdy" (weight is 2+4+25=31).
Rocket "adx" has the minimal weight, so the answer is 29.
In the second example, target rocket is "belo". Its weight is 2+5+12+15=34.
In the third example, n=k=2, so the rocket must have both stages: 'a' and 'b'. This rocket doesn't satisfy the condition, because these letters are adjacent in the alphabet. Answer is -1.
Submitted Solution:
```
n,k=[*map(int,input().split())]
st=sorted(input())
li=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
newli=[]
for i in st:
newli.append(li.index(i)+1)
if k==1:
print(newli[0])
quit()
else:
addvalue=newli[0]
addtime=1
cursor1=0
cursor2=1
while addtime<k:
try:
newli[cursor2]
except:
print(-1)
quit()
if newli[cursor2]-newli[cursor1]<=1:
cursor2+=1
else:
addvalue+=newli[cursor2]
cursor1=cursor2
cursor2+=1
addtime+=1
print(addvalue)
``` | instruction | 0 | 27,389 | 6 | 54,778 |
Yes | output | 1 | 27,389 | 6 | 54,779 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string β concatenation of letters, which correspond to the stages.
There are n stages available. The rocket must contain exactly k of them. Stages in the rocket should be ordered by their weight. So, after the stage with some letter can go only stage with a letter, which is at least two positions after in the alphabet (skipping one letter in between, or even more). For example, after letter 'c' can't go letters 'a', 'b', 'c' and 'd', but can go letters 'e', 'f', ..., 'z'.
For the rocket to fly as far as possible, its weight should be minimal. The weight of the rocket is equal to the sum of the weights of its stages. The weight of the stage is the number of its letter in the alphabet. For example, the stage 'a 'weighs one ton,' b 'weighs two tons, and' z' β 26 tons.
Build the rocket with the minimal weight or determine, that it is impossible to build a rocket at all. Each stage can be used at most once.
Input
The first line of input contains two integers β n and k (1 β€ k β€ n β€ 50) β the number of available stages and the number of stages to use in the rocket.
The second line contains string s, which consists of exactly n lowercase Latin letters. Each letter defines a new stage, which can be used to build the rocket. Each stage can be used at most once.
Output
Print a single integer β the minimal total weight of the rocket or -1, if it is impossible to build the rocket at all.
Examples
Input
5 3
xyabd
Output
29
Input
7 4
problem
Output
34
Input
2 2
ab
Output
-1
Input
12 1
abaabbaaabbb
Output
1
Note
In the first example, the following rockets satisfy the condition:
* "adx" (weight is 1+4+24=29);
* "ady" (weight is 1+4+25=30);
* "bdx" (weight is 2+4+24=30);
* "bdy" (weight is 2+4+25=31).
Rocket "adx" has the minimal weight, so the answer is 29.
In the second example, target rocket is "belo". Its weight is 2+5+12+15=34.
In the third example, n=k=2, so the rocket must have both stages: 'a' and 'b'. This rocket doesn't satisfy the condition, because these letters are adjacent in the alphabet. Answer is -1.
Submitted Solution:
```
from sys import stdin
def func(arr):
return sum(list(map(lambda x:ord(x)-96,arr)))
n,k=map(int,stdin.readline().split())
s=stdin.readline().strip()
ans=[]
s=sorted(s)
for i in range(n-k+1):
arr=[s[i]]
total=ord(s[i])-ord('a')+1
count=1
m=i
j=m+1
while(j<n and count<k):
if ord(s[j])-ord(s[m])>=2:
arr.append(s[j])
count+=1
total+=(ord(s[j])+1-ord('a'))
m=j
j=m+1
else:
j+=1
if len(arr)==k:
ans.append(total)
else:
pass
if len(ans)==0:
print(-1)
else:
print(min(ans))
``` | instruction | 0 | 27,390 | 6 | 54,780 |
Yes | output | 1 | 27,390 | 6 | 54,781 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string β concatenation of letters, which correspond to the stages.
There are n stages available. The rocket must contain exactly k of them. Stages in the rocket should be ordered by their weight. So, after the stage with some letter can go only stage with a letter, which is at least two positions after in the alphabet (skipping one letter in between, or even more). For example, after letter 'c' can't go letters 'a', 'b', 'c' and 'd', but can go letters 'e', 'f', ..., 'z'.
For the rocket to fly as far as possible, its weight should be minimal. The weight of the rocket is equal to the sum of the weights of its stages. The weight of the stage is the number of its letter in the alphabet. For example, the stage 'a 'weighs one ton,' b 'weighs two tons, and' z' β 26 tons.
Build the rocket with the minimal weight or determine, that it is impossible to build a rocket at all. Each stage can be used at most once.
Input
The first line of input contains two integers β n and k (1 β€ k β€ n β€ 50) β the number of available stages and the number of stages to use in the rocket.
The second line contains string s, which consists of exactly n lowercase Latin letters. Each letter defines a new stage, which can be used to build the rocket. Each stage can be used at most once.
Output
Print a single integer β the minimal total weight of the rocket or -1, if it is impossible to build the rocket at all.
Examples
Input
5 3
xyabd
Output
29
Input
7 4
problem
Output
34
Input
2 2
ab
Output
-1
Input
12 1
abaabbaaabbb
Output
1
Note
In the first example, the following rockets satisfy the condition:
* "adx" (weight is 1+4+24=29);
* "ady" (weight is 1+4+25=30);
* "bdx" (weight is 2+4+24=30);
* "bdy" (weight is 2+4+25=31).
Rocket "adx" has the minimal weight, so the answer is 29.
In the second example, target rocket is "belo". Its weight is 2+5+12+15=34.
In the third example, n=k=2, so the rocket must have both stages: 'a' and 'b'. This rocket doesn't satisfy the condition, because these letters are adjacent in the alphabet. Answer is -1.
Submitted Solution:
```
n, k = map(int, input().split())
a = sorted(list(set(input())))
cnt = 0
m = 0
flag = True
for i in range(len(a)):
if cnt == k:
break
if i - 1 >= 0 and flag:
if a[i-1] == chr(ord(a[i])-1):
flag = False
continue
m += ord(a[i]) - ord('a') + 1
cnt += 1
flag = True
if cnt < k:
print(-1)
else:
print(m)
``` | instruction | 0 | 27,391 | 6 | 54,782 |
Yes | output | 1 | 27,391 | 6 | 54,783 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string β concatenation of letters, which correspond to the stages.
There are n stages available. The rocket must contain exactly k of them. Stages in the rocket should be ordered by their weight. So, after the stage with some letter can go only stage with a letter, which is at least two positions after in the alphabet (skipping one letter in between, or even more). For example, after letter 'c' can't go letters 'a', 'b', 'c' and 'd', but can go letters 'e', 'f', ..., 'z'.
For the rocket to fly as far as possible, its weight should be minimal. The weight of the rocket is equal to the sum of the weights of its stages. The weight of the stage is the number of its letter in the alphabet. For example, the stage 'a 'weighs one ton,' b 'weighs two tons, and' z' β 26 tons.
Build the rocket with the minimal weight or determine, that it is impossible to build a rocket at all. Each stage can be used at most once.
Input
The first line of input contains two integers β n and k (1 β€ k β€ n β€ 50) β the number of available stages and the number of stages to use in the rocket.
The second line contains string s, which consists of exactly n lowercase Latin letters. Each letter defines a new stage, which can be used to build the rocket. Each stage can be used at most once.
Output
Print a single integer β the minimal total weight of the rocket or -1, if it is impossible to build the rocket at all.
Examples
Input
5 3
xyabd
Output
29
Input
7 4
problem
Output
34
Input
2 2
ab
Output
-1
Input
12 1
abaabbaaabbb
Output
1
Note
In the first example, the following rockets satisfy the condition:
* "adx" (weight is 1+4+24=29);
* "ady" (weight is 1+4+25=30);
* "bdx" (weight is 2+4+24=30);
* "bdy" (weight is 2+4+25=31).
Rocket "adx" has the minimal weight, so the answer is 29.
In the second example, target rocket is "belo". Its weight is 2+5+12+15=34.
In the third example, n=k=2, so the rocket must have both stages: 'a' and 'b'. This rocket doesn't satisfy the condition, because these letters are adjacent in the alphabet. Answer is -1.
Submitted Solution:
```
n,k=(int(i) for i in input().split())
l=sorted(list(input()))
c=1
c1=l[0]
w=ord(l[0])-96
if(k==1):
print(w)
else:
for i in range(1,n):
if(c==k):
break
else:
if((ord(l[i])-ord(c1))>=2):
w+=ord(l[i])-96
c1=l[i]
c+=1
if(c<k):
print(-1)
else:
print(w)
``` | instruction | 0 | 27,392 | 6 | 54,784 |
Yes | output | 1 | 27,392 | 6 | 54,785 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string β concatenation of letters, which correspond to the stages.
There are n stages available. The rocket must contain exactly k of them. Stages in the rocket should be ordered by their weight. So, after the stage with some letter can go only stage with a letter, which is at least two positions after in the alphabet (skipping one letter in between, or even more). For example, after letter 'c' can't go letters 'a', 'b', 'c' and 'd', but can go letters 'e', 'f', ..., 'z'.
For the rocket to fly as far as possible, its weight should be minimal. The weight of the rocket is equal to the sum of the weights of its stages. The weight of the stage is the number of its letter in the alphabet. For example, the stage 'a 'weighs one ton,' b 'weighs two tons, and' z' β 26 tons.
Build the rocket with the minimal weight or determine, that it is impossible to build a rocket at all. Each stage can be used at most once.
Input
The first line of input contains two integers β n and k (1 β€ k β€ n β€ 50) β the number of available stages and the number of stages to use in the rocket.
The second line contains string s, which consists of exactly n lowercase Latin letters. Each letter defines a new stage, which can be used to build the rocket. Each stage can be used at most once.
Output
Print a single integer β the minimal total weight of the rocket or -1, if it is impossible to build the rocket at all.
Examples
Input
5 3
xyabd
Output
29
Input
7 4
problem
Output
34
Input
2 2
ab
Output
-1
Input
12 1
abaabbaaabbb
Output
1
Note
In the first example, the following rockets satisfy the condition:
* "adx" (weight is 1+4+24=29);
* "ady" (weight is 1+4+25=30);
* "bdx" (weight is 2+4+24=30);
* "bdy" (weight is 2+4+25=31).
Rocket "adx" has the minimal weight, so the answer is 29.
In the second example, target rocket is "belo". Its weight is 2+5+12+15=34.
In the third example, n=k=2, so the rocket must have both stages: 'a' and 'b'. This rocket doesn't satisfy the condition, because these letters are adjacent in the alphabet. Answer is -1.
Submitted Solution:
```
n, k = map(int, input().split())
s = input()
res = 0
sch = 0
s = sorted(s)
s2 = 'abcdefghijklmnopqrstuvwxyz'
sch = 0
i = 0
if len(s) == 0:
print(-1)
exit(0)
while True:
if sch < k and i < len(s) - 1:
if i != 0:
if s2.index(s[i]) - 1 != s2.index(s[i - 1]) and s2.index(s[i]) != s2.index(s[i - 1]):
res += s2.index(s[i]) + 1
sch += 1
else:
res += s2.index(s[i]) + 1
sch += 1
i += 1
else:
if sch < k:
print(-1)
exit(0)
else:
print(res)
exit(0)
print(-1)
``` | instruction | 0 | 27,393 | 6 | 54,786 |
No | output | 1 | 27,393 | 6 | 54,787 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string β concatenation of letters, which correspond to the stages.
There are n stages available. The rocket must contain exactly k of them. Stages in the rocket should be ordered by their weight. So, after the stage with some letter can go only stage with a letter, which is at least two positions after in the alphabet (skipping one letter in between, or even more). For example, after letter 'c' can't go letters 'a', 'b', 'c' and 'd', but can go letters 'e', 'f', ..., 'z'.
For the rocket to fly as far as possible, its weight should be minimal. The weight of the rocket is equal to the sum of the weights of its stages. The weight of the stage is the number of its letter in the alphabet. For example, the stage 'a 'weighs one ton,' b 'weighs two tons, and' z' β 26 tons.
Build the rocket with the minimal weight or determine, that it is impossible to build a rocket at all. Each stage can be used at most once.
Input
The first line of input contains two integers β n and k (1 β€ k β€ n β€ 50) β the number of available stages and the number of stages to use in the rocket.
The second line contains string s, which consists of exactly n lowercase Latin letters. Each letter defines a new stage, which can be used to build the rocket. Each stage can be used at most once.
Output
Print a single integer β the minimal total weight of the rocket or -1, if it is impossible to build the rocket at all.
Examples
Input
5 3
xyabd
Output
29
Input
7 4
problem
Output
34
Input
2 2
ab
Output
-1
Input
12 1
abaabbaaabbb
Output
1
Note
In the first example, the following rockets satisfy the condition:
* "adx" (weight is 1+4+24=29);
* "ady" (weight is 1+4+25=30);
* "bdx" (weight is 2+4+24=30);
* "bdy" (weight is 2+4+25=31).
Rocket "adx" has the minimal weight, so the answer is 29.
In the second example, target rocket is "belo". Its weight is 2+5+12+15=34.
In the third example, n=k=2, so the rocket must have both stages: 'a' and 'b'. This rocket doesn't satisfy the condition, because these letters are adjacent in the alphabet. Answer is -1.
Submitted Solution:
```
x,y=map(int,input().split());
s=input();
s=list(s);
s.sort();print(s);
d=dict();
for i in range(97,123):
d[chr(i)] =i-96;
sum=0;t=-1;c=0;w=0;
for i in s:
print(i,s);
if (d[i] - t >=2) :
c+=1;
sum+=d[i];
t=d[i];
if (c==y):
w=1;
break;
else :
continue ;
if (w==1):
print(sum);
else :
print("-1");
``` | instruction | 0 | 27,394 | 6 | 54,788 |
No | output | 1 | 27,394 | 6 | 54,789 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string β concatenation of letters, which correspond to the stages.
There are n stages available. The rocket must contain exactly k of them. Stages in the rocket should be ordered by their weight. So, after the stage with some letter can go only stage with a letter, which is at least two positions after in the alphabet (skipping one letter in between, or even more). For example, after letter 'c' can't go letters 'a', 'b', 'c' and 'd', but can go letters 'e', 'f', ..., 'z'.
For the rocket to fly as far as possible, its weight should be minimal. The weight of the rocket is equal to the sum of the weights of its stages. The weight of the stage is the number of its letter in the alphabet. For example, the stage 'a 'weighs one ton,' b 'weighs two tons, and' z' β 26 tons.
Build the rocket with the minimal weight or determine, that it is impossible to build a rocket at all. Each stage can be used at most once.
Input
The first line of input contains two integers β n and k (1 β€ k β€ n β€ 50) β the number of available stages and the number of stages to use in the rocket.
The second line contains string s, which consists of exactly n lowercase Latin letters. Each letter defines a new stage, which can be used to build the rocket. Each stage can be used at most once.
Output
Print a single integer β the minimal total weight of the rocket or -1, if it is impossible to build the rocket at all.
Examples
Input
5 3
xyabd
Output
29
Input
7 4
problem
Output
34
Input
2 2
ab
Output
-1
Input
12 1
abaabbaaabbb
Output
1
Note
In the first example, the following rockets satisfy the condition:
* "adx" (weight is 1+4+24=29);
* "ady" (weight is 1+4+25=30);
* "bdx" (weight is 2+4+24=30);
* "bdy" (weight is 2+4+25=31).
Rocket "adx" has the minimal weight, so the answer is 29.
In the second example, target rocket is "belo". Its weight is 2+5+12+15=34.
In the third example, n=k=2, so the rocket must have both stages: 'a' and 'b'. This rocket doesn't satisfy the condition, because these letters are adjacent in the alphabet. Answer is -1.
Submitted Solution:
```
n, k = map(int, input().split())
string = list(input())
string.sort()
sum = 0
pre = 0
j = -1
for i in range(k):
j+= 1
letter = string[j]
while ord(letter) <= pre+1 and j < len(string)-1:
j += 1
letter = string[j]
if j < len(string):
letter = string[j]
if j >= len(string):
break
if ord(letter) > pre+1:
sum += ord(letter)-96
pre = ord(letter)
if j >= len(string):
print(-1)
else:
print(sum)
``` | instruction | 0 | 27,395 | 6 | 54,790 |
No | output | 1 | 27,395 | 6 | 54,791 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.