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.
Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning.
Mahmoud knows that the i-th word can be sent with cost ai. For each word in his message, Mahmoud can either replace it with another word of the same meaning or leave it as it is. Can you help Mahmoud determine the minimum cost of sending the message?
The cost of sending the message is the sum of the costs of sending every word in it.
Input
The first line of input contains integers n, k and m (1 β€ k β€ n β€ 105, 1 β€ m β€ 105) β the number of words in their language, the number of groups of words, and the number of words in Mahmoud's message respectively.
The second line contains n strings consisting of lowercase English letters of length not exceeding 20 which represent the words. It's guaranteed that the words are distinct.
The third line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) where ai is the cost of sending the i-th word.
The next k lines describe the groups of words of same meaning. The next k lines each start with an integer x (1 β€ x β€ n) which means that there are x words in this group, followed by x integers which represent the indices of words in this group. It's guaranteed that each word appears in exactly one group.
The next line contains m space-separated words which represent Mahmoud's message. Each of these words appears in the list of language's words.
Output
The only line should contain the minimum cost to send the message after replacing some words (maybe none) with some words of the same meaning.
Examples
Input
5 4 4
i loser am the second
100 1 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
107
Input
5 4 4
i loser am the second
100 20 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
116
Note
In the first sample, Mahmoud should replace the word "second" with the word "loser" because it has less cost so the cost will be 100+1+5+1=107.
In the second sample, Mahmoud shouldn't do any replacement so the cost will be 100+1+5+10=116. | instruction | 0 | 79,666 | 6 | 159,332 |
Tags: dsu, greedy, implementation
Correct Solution:
```
def main():
nkm=input()
nkm=nkm.split()
n = int(nkm[0])
k = int(nkm[1])
m = int(nkm[2])
words = input()
words = words.split()
costs= input()
costs = costs.split()
groups = list()
dic = dict()
for i in range(k):
member = input()
member = member.split()
group = list()
for j in range(int(member[0])):
index = int(member[j+1])
dic[words[index-1]] = i
group.append(int(costs[index-1]))
group.sort()
groups.append(group)
send = input()
send = send.split()
ans = 0
for w in send:
ans+=groups[dic[w]][0]
print (ans)
if __name__ =='__main__':
main()
``` | output | 1 | 79,666 | 6 | 159,333 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning.
Mahmoud knows that the i-th word can be sent with cost ai. For each word in his message, Mahmoud can either replace it with another word of the same meaning or leave it as it is. Can you help Mahmoud determine the minimum cost of sending the message?
The cost of sending the message is the sum of the costs of sending every word in it.
Input
The first line of input contains integers n, k and m (1 β€ k β€ n β€ 105, 1 β€ m β€ 105) β the number of words in their language, the number of groups of words, and the number of words in Mahmoud's message respectively.
The second line contains n strings consisting of lowercase English letters of length not exceeding 20 which represent the words. It's guaranteed that the words are distinct.
The third line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) where ai is the cost of sending the i-th word.
The next k lines describe the groups of words of same meaning. The next k lines each start with an integer x (1 β€ x β€ n) which means that there are x words in this group, followed by x integers which represent the indices of words in this group. It's guaranteed that each word appears in exactly one group.
The next line contains m space-separated words which represent Mahmoud's message. Each of these words appears in the list of language's words.
Output
The only line should contain the minimum cost to send the message after replacing some words (maybe none) with some words of the same meaning.
Examples
Input
5 4 4
i loser am the second
100 1 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
107
Input
5 4 4
i loser am the second
100 20 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
116
Note
In the first sample, Mahmoud should replace the word "second" with the word "loser" because it has less cost so the cost will be 100+1+5+1=107.
In the second sample, Mahmoud shouldn't do any replacement so the cost will be 100+1+5+10=116. | instruction | 0 | 79,667 | 6 | 159,334 |
Tags: dsu, greedy, implementation
Correct Solution:
```
#!/usr/bin/python3.6
# -*- coding: utf-8 -*-
# @Time : 2020/11/1 3:40 PM
# @Author : Songtao Li
def init(n):
father = [i for i in range(n)]
return father
def find_father(x):
if father[x] == x:
return x
else:
father[x] = find_father(father[x])
return father[x]
def merge(i, j):
a, b = find_father(i), find_father(j)
if weights[a] <= weights[b]:
father[b] = a
else:
father[a] = b
if __name__ == "__main__":
n, k, m = map(int, input().split())
# initialize
father = init(n)
words = input().split()
words_weights = dict(zip(words, father))
weights = list(map(int, input().split()))
# merge
for _ in range(k):
indexes = list(map(lambda x: int(x) - 1, input().split()[1:]))
indexes_start = indexes[:-1]
indexes_end = indexes[1:]
for start, end in zip(indexes_start, indexes_end):
merge(start, end)
secret_string = input().split()
# find
res = [weights[find_father(words_weights[word])] for word in secret_string]
print(sum(res))
``` | output | 1 | 79,667 | 6 | 159,335 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning.
Mahmoud knows that the i-th word can be sent with cost ai. For each word in his message, Mahmoud can either replace it with another word of the same meaning or leave it as it is. Can you help Mahmoud determine the minimum cost of sending the message?
The cost of sending the message is the sum of the costs of sending every word in it.
Input
The first line of input contains integers n, k and m (1 β€ k β€ n β€ 105, 1 β€ m β€ 105) β the number of words in their language, the number of groups of words, and the number of words in Mahmoud's message respectively.
The second line contains n strings consisting of lowercase English letters of length not exceeding 20 which represent the words. It's guaranteed that the words are distinct.
The third line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) where ai is the cost of sending the i-th word.
The next k lines describe the groups of words of same meaning. The next k lines each start with an integer x (1 β€ x β€ n) which means that there are x words in this group, followed by x integers which represent the indices of words in this group. It's guaranteed that each word appears in exactly one group.
The next line contains m space-separated words which represent Mahmoud's message. Each of these words appears in the list of language's words.
Output
The only line should contain the minimum cost to send the message after replacing some words (maybe none) with some words of the same meaning.
Examples
Input
5 4 4
i loser am the second
100 1 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
107
Input
5 4 4
i loser am the second
100 20 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
116
Note
In the first sample, Mahmoud should replace the word "second" with the word "loser" because it has less cost so the cost will be 100+1+5+1=107.
In the second sample, Mahmoud shouldn't do any replacement so the cost will be 100+1+5+10=116. | instruction | 0 | 79,668 | 6 | 159,336 |
Tags: dsu, greedy, implementation
Correct Solution:
```
# https://codeforces.com/problemset/problem/959/B
class DSU:
def __init__(self,n):
self.n = n
self.comps = n
self.parent = [i for i in range(n)]
def FIND(self,x):
if x!=self.parent[x]:
self.parent[x] = self.FIND(self.parent[x])
return self.parent[x]
def UNION(self,x,y):
xRoot = self.FIND(x)
yRoot = self.FIND(y)
if xRoot != yRoot:
self.comps-=1
if costs[xRoot] <= costs[yRoot]:
self.parent[yRoot] = xRoot
else:
self.parent[xRoot] = yRoot
return 1
return 0
n,k,m = map(int,input().split())
words = {val:ind for ind,val in enumerate(input().split())}
costs = [int(x) for x in input().split()]
dsu = DSU(n)
ans = 0
while k:
arr = [int(x)-1 for x in input().split()][1:]
first = arr[0]
for item in arr[1:]:
dsu.UNION(first,item)
k-=1
sentence = input().split()
for word in sentence:
ind = words[word]
ans += costs[dsu.FIND(ind)]
print(ans)
``` | output | 1 | 79,668 | 6 | 159,337 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning.
Mahmoud knows that the i-th word can be sent with cost ai. For each word in his message, Mahmoud can either replace it with another word of the same meaning or leave it as it is. Can you help Mahmoud determine the minimum cost of sending the message?
The cost of sending the message is the sum of the costs of sending every word in it.
Input
The first line of input contains integers n, k and m (1 β€ k β€ n β€ 105, 1 β€ m β€ 105) β the number of words in their language, the number of groups of words, and the number of words in Mahmoud's message respectively.
The second line contains n strings consisting of lowercase English letters of length not exceeding 20 which represent the words. It's guaranteed that the words are distinct.
The third line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) where ai is the cost of sending the i-th word.
The next k lines describe the groups of words of same meaning. The next k lines each start with an integer x (1 β€ x β€ n) which means that there are x words in this group, followed by x integers which represent the indices of words in this group. It's guaranteed that each word appears in exactly one group.
The next line contains m space-separated words which represent Mahmoud's message. Each of these words appears in the list of language's words.
Output
The only line should contain the minimum cost to send the message after replacing some words (maybe none) with some words of the same meaning.
Examples
Input
5 4 4
i loser am the second
100 1 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
107
Input
5 4 4
i loser am the second
100 20 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
116
Note
In the first sample, Mahmoud should replace the word "second" with the word "loser" because it has less cost so the cost will be 100+1+5+1=107.
In the second sample, Mahmoud shouldn't do any replacement so the cost will be 100+1+5+10=116. | instruction | 0 | 79,669 | 6 | 159,338 |
Tags: dsu, greedy, implementation
Correct Solution:
```
arr = list(map(int,input().split(" ")))
n,k,m = arr[0],arr[1],arr[2]
word = list(input().split(" "))
cost = list(map(int,input().split(" ")))
dic = {}
for i in range(k):
tmp = list(map(int,input().split(" ")))
if tmp[0] == 1:
dic[word[tmp[1]-1]] = cost[tmp[1]-1]
else:
mincost = min(cost[tmp[1]-1],cost[tmp[2]-1])
for j in range(3,tmp[0]+1):
mincost = min(mincost,cost[tmp[j]-1])
for p in range(1,tmp[0]+1):
dic[word[tmp[p]-1]] = mincost
message = list(input().split(" "))
res = 0
for wordn in message:
res += dic[wordn]
print(res)
``` | output | 1 | 79,669 | 6 | 159,339 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning.
Mahmoud knows that the i-th word can be sent with cost ai. For each word in his message, Mahmoud can either replace it with another word of the same meaning or leave it as it is. Can you help Mahmoud determine the minimum cost of sending the message?
The cost of sending the message is the sum of the costs of sending every word in it.
Input
The first line of input contains integers n, k and m (1 β€ k β€ n β€ 105, 1 β€ m β€ 105) β the number of words in their language, the number of groups of words, and the number of words in Mahmoud's message respectively.
The second line contains n strings consisting of lowercase English letters of length not exceeding 20 which represent the words. It's guaranteed that the words are distinct.
The third line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) where ai is the cost of sending the i-th word.
The next k lines describe the groups of words of same meaning. The next k lines each start with an integer x (1 β€ x β€ n) which means that there are x words in this group, followed by x integers which represent the indices of words in this group. It's guaranteed that each word appears in exactly one group.
The next line contains m space-separated words which represent Mahmoud's message. Each of these words appears in the list of language's words.
Output
The only line should contain the minimum cost to send the message after replacing some words (maybe none) with some words of the same meaning.
Examples
Input
5 4 4
i loser am the second
100 1 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
107
Input
5 4 4
i loser am the second
100 20 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
116
Note
In the first sample, Mahmoud should replace the word "second" with the word "loser" because it has less cost so the cost will be 100+1+5+1=107.
In the second sample, Mahmoud shouldn't do any replacement so the cost will be 100+1+5+10=116. | instruction | 0 | 79,670 | 6 | 159,340 |
Tags: dsu, greedy, implementation
Correct Solution:
```
n, k, m = [int(i) for i in input().split()]
origwordarr = input().split()
costarr = [int(i) for i in input().split()]
for i in range(k):
group = [int(i) for i in input().split()]
if group[0] == 1:
continue
minindex = min((i-1 for i in group[1:]), key=lambda l: costarr[l]) # i-1 for i in group ???wtf??
for j in group[1:]:
costarr[j-1] = costarr[minindex]
costdict = dict(zip(origwordarr, costarr))
destwordarr = input().split()
print(sum(costdict[i] for i in destwordarr))
``` | output | 1 | 79,670 | 6 | 159,341 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning.
Mahmoud knows that the i-th word can be sent with cost ai. For each word in his message, Mahmoud can either replace it with another word of the same meaning or leave it as it is. Can you help Mahmoud determine the minimum cost of sending the message?
The cost of sending the message is the sum of the costs of sending every word in it.
Input
The first line of input contains integers n, k and m (1 β€ k β€ n β€ 105, 1 β€ m β€ 105) β the number of words in their language, the number of groups of words, and the number of words in Mahmoud's message respectively.
The second line contains n strings consisting of lowercase English letters of length not exceeding 20 which represent the words. It's guaranteed that the words are distinct.
The third line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) where ai is the cost of sending the i-th word.
The next k lines describe the groups of words of same meaning. The next k lines each start with an integer x (1 β€ x β€ n) which means that there are x words in this group, followed by x integers which represent the indices of words in this group. It's guaranteed that each word appears in exactly one group.
The next line contains m space-separated words which represent Mahmoud's message. Each of these words appears in the list of language's words.
Output
The only line should contain the minimum cost to send the message after replacing some words (maybe none) with some words of the same meaning.
Examples
Input
5 4 4
i loser am the second
100 1 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
107
Input
5 4 4
i loser am the second
100 20 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
116
Note
In the first sample, Mahmoud should replace the word "second" with the word "loser" because it has less cost so the cost will be 100+1+5+1=107.
In the second sample, Mahmoud shouldn't do any replacement so the cost will be 100+1+5+10=116. | instruction | 0 | 79,671 | 6 | 159,342 |
Tags: dsu, greedy, implementation
Correct Solution:
```
s = input().split()
n,k,m = int(s[0]), int(s[1]),int(s[2])
s=input().split()
d=dict()
for i in range(len(s)):
d[s[i]]=i+1
priceold=input().split()
price=['ZERONUM'] + list(map(int, priceold))
for i in range(k):
sold=input().split()
s=list(map(int,sold))
minimalpoint=price[s[1]]
for j in range(2,len(s)):
minimalpoint=min(minimalpoint, price[s[j]])
for j in range(1,len(s)):
price[s[j]]=minimalpoint
count=0
words=input().split()
for i in range(m):
number=d[words[i]]
count+=price[number]
print(count)
``` | output | 1 | 79,671 | 6 | 159,343 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning.
Mahmoud knows that the i-th word can be sent with cost ai. For each word in his message, Mahmoud can either replace it with another word of the same meaning or leave it as it is. Can you help Mahmoud determine the minimum cost of sending the message?
The cost of sending the message is the sum of the costs of sending every word in it.
Input
The first line of input contains integers n, k and m (1 β€ k β€ n β€ 105, 1 β€ m β€ 105) β the number of words in their language, the number of groups of words, and the number of words in Mahmoud's message respectively.
The second line contains n strings consisting of lowercase English letters of length not exceeding 20 which represent the words. It's guaranteed that the words are distinct.
The third line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) where ai is the cost of sending the i-th word.
The next k lines describe the groups of words of same meaning. The next k lines each start with an integer x (1 β€ x β€ n) which means that there are x words in this group, followed by x integers which represent the indices of words in this group. It's guaranteed that each word appears in exactly one group.
The next line contains m space-separated words which represent Mahmoud's message. Each of these words appears in the list of language's words.
Output
The only line should contain the minimum cost to send the message after replacing some words (maybe none) with some words of the same meaning.
Examples
Input
5 4 4
i loser am the second
100 1 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
107
Input
5 4 4
i loser am the second
100 20 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
116
Note
In the first sample, Mahmoud should replace the word "second" with the word "loser" because it has less cost so the cost will be 100+1+5+1=107.
In the second sample, Mahmoud shouldn't do any replacement so the cost will be 100+1+5+10=116. | instruction | 0 | 79,672 | 6 | 159,344 |
Tags: dsu, greedy, implementation
Correct Solution:
```
def main():
n, k, m = map(int, input().split())
words = ['Zero'] + input().split()
cost = dict(zip(words, [0] + [int(i) for i in input().split()]))
for i in range(k):
size, *group = map(int, input().split())
l = [cost[words[i]] for i in group]
mincost = min(l)
for i in group:
cost[words[i]] = mincost
message = input().split()
ans = sum([cost[w] for w in message])
print(ans)
if __name__ == "__main__":
main()
``` | output | 1 | 79,672 | 6 | 159,345 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning.
Mahmoud knows that the i-th word can be sent with cost ai. For each word in his message, Mahmoud can either replace it with another word of the same meaning or leave it as it is. Can you help Mahmoud determine the minimum cost of sending the message?
The cost of sending the message is the sum of the costs of sending every word in it.
Input
The first line of input contains integers n, k and m (1 β€ k β€ n β€ 105, 1 β€ m β€ 105) β the number of words in their language, the number of groups of words, and the number of words in Mahmoud's message respectively.
The second line contains n strings consisting of lowercase English letters of length not exceeding 20 which represent the words. It's guaranteed that the words are distinct.
The third line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) where ai is the cost of sending the i-th word.
The next k lines describe the groups of words of same meaning. The next k lines each start with an integer x (1 β€ x β€ n) which means that there are x words in this group, followed by x integers which represent the indices of words in this group. It's guaranteed that each word appears in exactly one group.
The next line contains m space-separated words which represent Mahmoud's message. Each of these words appears in the list of language's words.
Output
The only line should contain the minimum cost to send the message after replacing some words (maybe none) with some words of the same meaning.
Examples
Input
5 4 4
i loser am the second
100 1 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
107
Input
5 4 4
i loser am the second
100 20 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
116
Note
In the first sample, Mahmoud should replace the word "second" with the word "loser" because it has less cost so the cost will be 100+1+5+1=107.
In the second sample, Mahmoud shouldn't do any replacement so the cost will be 100+1+5+10=116.
Submitted Solution:
```
import sys
n,k,m = list(map(int,input().split()))
words = {}
arr = list(map(str,input().split()))
values = list(map(int,input().split()))
for i in range(n):
words[arr[i]] = values[i]
d,f = {},{}
new = {}
for i in range(k):
piko = list(map(int,input().split()))
piko = piko[1::]
d[i] = []
f[i] = 0
temp = sys.maxsize
for j in piko:
d[i].append(arr[j-1])
temp = min(temp,values[j-1])
new[arr[j-1]] = i
f[i] = temp
l = list(map(str,input().split()))
ans = 0
# print(new)
for i in l:
ans+=f[new[i]]
print(ans)
``` | instruction | 0 | 79,673 | 6 | 159,346 |
Yes | output | 1 | 79,673 | 6 | 159,347 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning.
Mahmoud knows that the i-th word can be sent with cost ai. For each word in his message, Mahmoud can either replace it with another word of the same meaning or leave it as it is. Can you help Mahmoud determine the minimum cost of sending the message?
The cost of sending the message is the sum of the costs of sending every word in it.
Input
The first line of input contains integers n, k and m (1 β€ k β€ n β€ 105, 1 β€ m β€ 105) β the number of words in their language, the number of groups of words, and the number of words in Mahmoud's message respectively.
The second line contains n strings consisting of lowercase English letters of length not exceeding 20 which represent the words. It's guaranteed that the words are distinct.
The third line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) where ai is the cost of sending the i-th word.
The next k lines describe the groups of words of same meaning. The next k lines each start with an integer x (1 β€ x β€ n) which means that there are x words in this group, followed by x integers which represent the indices of words in this group. It's guaranteed that each word appears in exactly one group.
The next line contains m space-separated words which represent Mahmoud's message. Each of these words appears in the list of language's words.
Output
The only line should contain the minimum cost to send the message after replacing some words (maybe none) with some words of the same meaning.
Examples
Input
5 4 4
i loser am the second
100 1 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
107
Input
5 4 4
i loser am the second
100 20 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
116
Note
In the first sample, Mahmoud should replace the word "second" with the word "loser" because it has less cost so the cost will be 100+1+5+1=107.
In the second sample, Mahmoud shouldn't do any replacement so the cost will be 100+1+5+10=116.
Submitted Solution:
```
n,ki,m=map(int,input().split())
k=input().split()
l=list(map(int,input().split()))
ind=range(1,n+1)
d1=dict(zip(k,l))
d2={}
for _ in range(ki):
d=list(map(int,input().split()))
if len(d)>2:
f=[]
for i in d[1:]:
f.append([k[i-1],l[i-1]])
f.sort(key=lambda x:x[-1])
for i in f[1:]:
d2[i[0]]=f[0][0]
else:
d2[k[d[1]-1]]=k[d[1]-1]
#print(d2)
#print(d1)
send=input().split()
cost=0
for i in send:
try:
cost+=d1[d2[i]]
except:
cost+=d1[i]
print(cost)
``` | instruction | 0 | 79,674 | 6 | 159,348 |
Yes | output | 1 | 79,674 | 6 | 159,349 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning.
Mahmoud knows that the i-th word can be sent with cost ai. For each word in his message, Mahmoud can either replace it with another word of the same meaning or leave it as it is. Can you help Mahmoud determine the minimum cost of sending the message?
The cost of sending the message is the sum of the costs of sending every word in it.
Input
The first line of input contains integers n, k and m (1 β€ k β€ n β€ 105, 1 β€ m β€ 105) β the number of words in their language, the number of groups of words, and the number of words in Mahmoud's message respectively.
The second line contains n strings consisting of lowercase English letters of length not exceeding 20 which represent the words. It's guaranteed that the words are distinct.
The third line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) where ai is the cost of sending the i-th word.
The next k lines describe the groups of words of same meaning. The next k lines each start with an integer x (1 β€ x β€ n) which means that there are x words in this group, followed by x integers which represent the indices of words in this group. It's guaranteed that each word appears in exactly one group.
The next line contains m space-separated words which represent Mahmoud's message. Each of these words appears in the list of language's words.
Output
The only line should contain the minimum cost to send the message after replacing some words (maybe none) with some words of the same meaning.
Examples
Input
5 4 4
i loser am the second
100 1 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
107
Input
5 4 4
i loser am the second
100 20 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
116
Note
In the first sample, Mahmoud should replace the word "second" with the word "loser" because it has less cost so the cost will be 100+1+5+1=107.
In the second sample, Mahmoud shouldn't do any replacement so the cost will be 100+1+5+10=116.
Submitted Solution:
```
# -*- coding: utf - 8 -*-
"""""""""""""""""""""""""""""""""""""""""""""
| author: mr.math - Hakimov Rahimjon |
| e-mail: mr.math0777@gmail.com |
| created: 04.05.2018 03:20 |
"""""""""""""""""""""""""""""""""""""""""""""
# inp = open("input.txt", "r"); input = inp.readline; out = open("output.txt", "w"); print = out.write
TN = 1
# ===========================================
def solution():
n, k, m = map(int, input().split())
sl = input().split()
d_sl = {sl[i]: i+1 for i in range(n)}
a = [-1]+list(map(int, input().split()))
ans = 0
m_x = max(a)
min_s = [m_x]*(n+1)
for i in range(k):
s = list(map(int, input().split()))
x = m_x
sx = s[1:]
for j in sx:
if a[j] < x: x = a[j]
for j in sx:
min_s[j] = x
st = input().split()
for i in st:
ans += min_s[d_sl[i]]
print(ans)
# ===========================================
while TN != 0:
solution()
TN -= 1
# ===========================================
# inp.close()
# out.close()
``` | instruction | 0 | 79,675 | 6 | 159,350 |
Yes | output | 1 | 79,675 | 6 | 159,351 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning.
Mahmoud knows that the i-th word can be sent with cost ai. For each word in his message, Mahmoud can either replace it with another word of the same meaning or leave it as it is. Can you help Mahmoud determine the minimum cost of sending the message?
The cost of sending the message is the sum of the costs of sending every word in it.
Input
The first line of input contains integers n, k and m (1 β€ k β€ n β€ 105, 1 β€ m β€ 105) β the number of words in their language, the number of groups of words, and the number of words in Mahmoud's message respectively.
The second line contains n strings consisting of lowercase English letters of length not exceeding 20 which represent the words. It's guaranteed that the words are distinct.
The third line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) where ai is the cost of sending the i-th word.
The next k lines describe the groups of words of same meaning. The next k lines each start with an integer x (1 β€ x β€ n) which means that there are x words in this group, followed by x integers which represent the indices of words in this group. It's guaranteed that each word appears in exactly one group.
The next line contains m space-separated words which represent Mahmoud's message. Each of these words appears in the list of language's words.
Output
The only line should contain the minimum cost to send the message after replacing some words (maybe none) with some words of the same meaning.
Examples
Input
5 4 4
i loser am the second
100 1 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
107
Input
5 4 4
i loser am the second
100 20 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
116
Note
In the first sample, Mahmoud should replace the word "second" with the word "loser" because it has less cost so the cost will be 100+1+5+1=107.
In the second sample, Mahmoud shouldn't do any replacement so the cost will be 100+1+5+10=116.
Submitted Solution:
```
ip = lambda: input().split()
rd = lambda: map(int, ip())
n, k, m = rd()
a = ip()
b = list(rd())
d = dict(zip(a, b))
for _ in range(k):
x = list(rd())[1:]
m = min(b[i - 1] for i in x)
for i in x:
d[a[i - 1]] = m
print(sum(map(lambda x: d[x], ip())))
``` | instruction | 0 | 79,676 | 6 | 159,352 |
Yes | output | 1 | 79,676 | 6 | 159,353 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning.
Mahmoud knows that the i-th word can be sent with cost ai. For each word in his message, Mahmoud can either replace it with another word of the same meaning or leave it as it is. Can you help Mahmoud determine the minimum cost of sending the message?
The cost of sending the message is the sum of the costs of sending every word in it.
Input
The first line of input contains integers n, k and m (1 β€ k β€ n β€ 105, 1 β€ m β€ 105) β the number of words in their language, the number of groups of words, and the number of words in Mahmoud's message respectively.
The second line contains n strings consisting of lowercase English letters of length not exceeding 20 which represent the words. It's guaranteed that the words are distinct.
The third line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) where ai is the cost of sending the i-th word.
The next k lines describe the groups of words of same meaning. The next k lines each start with an integer x (1 β€ x β€ n) which means that there are x words in this group, followed by x integers which represent the indices of words in this group. It's guaranteed that each word appears in exactly one group.
The next line contains m space-separated words which represent Mahmoud's message. Each of these words appears in the list of language's words.
Output
The only line should contain the minimum cost to send the message after replacing some words (maybe none) with some words of the same meaning.
Examples
Input
5 4 4
i loser am the second
100 1 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
107
Input
5 4 4
i loser am the second
100 20 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
116
Note
In the first sample, Mahmoud should replace the word "second" with the word "loser" because it has less cost so the cost will be 100+1+5+1=107.
In the second sample, Mahmoud shouldn't do any replacement so the cost will be 100+1+5+10=116.
Submitted Solution:
```
from sys import stdin, stdout
import math,sys,heapq
from itertools import permutations, combinations
from collections import defaultdict,deque,OrderedDict
from os import path
import random
import bisect as bi
def yes():print('YES')
def no():print('NO')
if (path.exists('input.txt')):
#------------------Sublime--------------------------------------#
sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
def I():return (int(input()))
def In():return(map(int,input().split()))
else:
#------------------PYPY FAst I/o--------------------------------#
def I():return (int(stdin.readline()))
def In():return(map(int,stdin.readline().split()))
#sys.setrecursionlimit(1500)
def dict(a):
d={}
for x in a:
if d.get(x,-1)!=-1:
d[x]+=1
else:
d[x]=1
return d
def find_gt(a, x):
'Find leftmost value greater than x'
i = bi.bisect_left(a, x)
if i != len(a):
return i
else:
return -1
def main():
try:
n,k,m=In()
T=list(input().split())
cost=list(In())
d={}
for x in range(k):
temp=list(In())
zara=[]
co=1e8
for t in range(1,temp[0]+1):
zara.append(T[temp[t]-1])
co=min(cost[temp[t]-1],co)
for t in zara:
d[t]=co
M=list(input().split())
ans=0
for x in M:
ans+=d[x]
print(ans)
except:
pass
M = 998244353
P = 1000000007
if __name__ == '__main__':
#for _ in range(I()):main()
for _ in range(1):main()
``` | instruction | 0 | 79,677 | 6 | 159,354 |
No | output | 1 | 79,677 | 6 | 159,355 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning.
Mahmoud knows that the i-th word can be sent with cost ai. For each word in his message, Mahmoud can either replace it with another word of the same meaning or leave it as it is. Can you help Mahmoud determine the minimum cost of sending the message?
The cost of sending the message is the sum of the costs of sending every word in it.
Input
The first line of input contains integers n, k and m (1 β€ k β€ n β€ 105, 1 β€ m β€ 105) β the number of words in their language, the number of groups of words, and the number of words in Mahmoud's message respectively.
The second line contains n strings consisting of lowercase English letters of length not exceeding 20 which represent the words. It's guaranteed that the words are distinct.
The third line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) where ai is the cost of sending the i-th word.
The next k lines describe the groups of words of same meaning. The next k lines each start with an integer x (1 β€ x β€ n) which means that there are x words in this group, followed by x integers which represent the indices of words in this group. It's guaranteed that each word appears in exactly one group.
The next line contains m space-separated words which represent Mahmoud's message. Each of these words appears in the list of language's words.
Output
The only line should contain the minimum cost to send the message after replacing some words (maybe none) with some words of the same meaning.
Examples
Input
5 4 4
i loser am the second
100 1 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
107
Input
5 4 4
i loser am the second
100 20 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
116
Note
In the first sample, Mahmoud should replace the word "second" with the word "loser" because it has less cost so the cost will be 100+1+5+1=107.
In the second sample, Mahmoud shouldn't do any replacement so the cost will be 100+1+5+10=116.
Submitted Solution:
```
n,k,m=map(int,input().split())
meh=input()
meh=meh.split()
cost=list(map(int,input().split()))
for i in range(k):
change=list(map(int,input().split()))
if change[0]>1:
mins=cost[change[1]]
for j in change[2:]:
if cost[j-1]<mins:
mins=cost[j-1]
for j in change[2:]:
cost[j-1]=mins
ehab=input()
ehab=ehab.split()
# index=[i for i in range(n) if meh[i] in ehab]
ans=0
for i in range(m):
ans+=cost[meh.index(ehab[i])]
print(ans)
``` | instruction | 0 | 79,678 | 6 | 159,356 |
No | output | 1 | 79,678 | 6 | 159,357 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning.
Mahmoud knows that the i-th word can be sent with cost ai. For each word in his message, Mahmoud can either replace it with another word of the same meaning or leave it as it is. Can you help Mahmoud determine the minimum cost of sending the message?
The cost of sending the message is the sum of the costs of sending every word in it.
Input
The first line of input contains integers n, k and m (1 β€ k β€ n β€ 105, 1 β€ m β€ 105) β the number of words in their language, the number of groups of words, and the number of words in Mahmoud's message respectively.
The second line contains n strings consisting of lowercase English letters of length not exceeding 20 which represent the words. It's guaranteed that the words are distinct.
The third line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) where ai is the cost of sending the i-th word.
The next k lines describe the groups of words of same meaning. The next k lines each start with an integer x (1 β€ x β€ n) which means that there are x words in this group, followed by x integers which represent the indices of words in this group. It's guaranteed that each word appears in exactly one group.
The next line contains m space-separated words which represent Mahmoud's message. Each of these words appears in the list of language's words.
Output
The only line should contain the minimum cost to send the message after replacing some words (maybe none) with some words of the same meaning.
Examples
Input
5 4 4
i loser am the second
100 1 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
107
Input
5 4 4
i loser am the second
100 20 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
116
Note
In the first sample, Mahmoud should replace the word "second" with the word "loser" because it has less cost so the cost will be 100+1+5+1=107.
In the second sample, Mahmoud shouldn't do any replacement so the cost will be 100+1+5+10=116.
Submitted Solution:
```
n, m, k = map(int, input().split())
palavras = input().split()
indice_palavra = {}
for i in range(len(palavras)):
indice_palavra[palavras[i]] = i
pesos = list(map(int, input().split()))
group = {}
for i in range(k):
a = list(map(int, input().split()))
if a[0] == 1:
group[a[1]-1] = pesos[a[1]-1]
else:
val = sorted([pesos[i-1] for i in a[1:]])[0]
print(val)
for i in a[1:]:
group[i-1] = val
frase = input().split()
soma = 0
for palavra in frase:
soma += group[indice_palavra[palavra]]
print(soma)
``` | instruction | 0 | 79,679 | 6 | 159,358 |
No | output | 1 | 79,679 | 6 | 159,359 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning.
Mahmoud knows that the i-th word can be sent with cost ai. For each word in his message, Mahmoud can either replace it with another word of the same meaning or leave it as it is. Can you help Mahmoud determine the minimum cost of sending the message?
The cost of sending the message is the sum of the costs of sending every word in it.
Input
The first line of input contains integers n, k and m (1 β€ k β€ n β€ 105, 1 β€ m β€ 105) β the number of words in their language, the number of groups of words, and the number of words in Mahmoud's message respectively.
The second line contains n strings consisting of lowercase English letters of length not exceeding 20 which represent the words. It's guaranteed that the words are distinct.
The third line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) where ai is the cost of sending the i-th word.
The next k lines describe the groups of words of same meaning. The next k lines each start with an integer x (1 β€ x β€ n) which means that there are x words in this group, followed by x integers which represent the indices of words in this group. It's guaranteed that each word appears in exactly one group.
The next line contains m space-separated words which represent Mahmoud's message. Each of these words appears in the list of language's words.
Output
The only line should contain the minimum cost to send the message after replacing some words (maybe none) with some words of the same meaning.
Examples
Input
5 4 4
i loser am the second
100 1 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
107
Input
5 4 4
i loser am the second
100 20 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
116
Note
In the first sample, Mahmoud should replace the word "second" with the word "loser" because it has less cost so the cost will be 100+1+5+1=107.
In the second sample, Mahmoud shouldn't do any replacement so the cost will be 100+1+5+10=116.
Submitted Solution:
```
n, k, m = map(int,input().strip().split())
words = list(input().strip().split())
cost = list(map(int,input().strip().split()))
i = 1
se = {}
minset = {}
while i <= k:
group = list(map(int,input().strip().split()))
minv = 100000000
for j in range(1,len(group)):
curword = words[group[j]-1]
currcost = cost[group[j]-1]
if currcost < minv:
minv = currcost
se[curword] = i
minset[i] = minv
i+=1
msg = list(input().strip().split())
sum = 0
i = 0
while i < len(msg):
curgp = se[msg[i]]
sum += minset[curgp]
i += 1
print(sum)
``` | instruction | 0 | 79,680 | 6 | 159,360 |
No | output | 1 | 79,680 | 6 | 159,361 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have obtained the Izua Japanese dictionary, which is the official language of Izua, and the Izua alphabet (list of letters). There are N types of letters in the Izua alphabet. The order of the words that appear in the Izua Japanese dictionary is in the alphabetical order of Izua.
Looking at the dictionary, I found that every word in the dictionary is N letters and contains N kinds of letters one by one. Upon further investigation, I found that the dictionary contained all possible arrangements of the N characters.
From this discovery, you can see what number a word appears in the dictionary. Use this knowledge to surprise people in Izua. First, arrange the N types of letters one by one in alphabetical order. Next, ask them to repeat the operation of changing the order of any two characters R times. You can guess the number of the finished word in the Izua Japanese dictionary. In preparation for that, create a program that finds the location of words in the Japanese dictionary. However, the first word in alphabetical order is the 0th word.
input
The input consists of multiple datasets. The end of the input is indicated by a single zero line. Each dataset is given in the following format.
N
R
s1 t1
s2 t2
::
sR tR
The first line is given the number of characters that make up the alphabet N (1 β€ N β€ 100000), and the second line is given the number of times R (0 β€ R β€ 50) to have the characters replaced. The following R line is given the set of character positions to be swapped. si and ti (1 β€ si <ti β€ N) represent the i-th swapping of the si and ti characters counting from the beginning. si and ti are separated by a single space.
The number of datasets does not exceed 100.
output
For each data set, the number indicating the number of the word obtained at the end of the replacement in the Japanese dictionary is output on one line. However, the value to be output can be very large, so instead output the remainder divided by 1,000,000,007.
Example
Input
3
2
1 2
2 3
4
2
2 3
2 4
0
Output
3
4
Submitted Solution:
```
class BIT:
def __init__(self,size):
self.bit = [0 for i in range(size+1)]
def update(self,idx,v):
while idx <= len(self.bit)-1:
self.bit[idx] += v
idx += idx & (-idx)
def sum(self,idx):
res = 0
while idx > 0:
res += self.bit[idx]
idx -= idx & (-idx)
return res
MOD_V = 1000000007
while 1:
N = int(input())
if N == 0:break
dp = [0 for i in range(N+1)]
dp[0] = 1
bit = BIT(N)
izua=[i for i in range(N+1)]
for i in range(1,N+1):
if dp[i] == 0:
dp[i] = (dp[i-1]*i) % MOD_V
R = int(input())
for i in range(R):#swap
s,t = list(map(int,input().split()))
w = izua[t]
izua[t] = izua[s]
izua[s] = w
res = 0
for i in range(N,0,-1):
res += (bit.sum(izua[i])*dp[N-i]) % MOD_V
bit.update(izua[i],1)
print (res%MOD_V)
``` | instruction | 0 | 79,853 | 6 | 159,706 |
No | output | 1 | 79,853 | 6 | 159,707 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have obtained the Izua Japanese dictionary, which is the official language of Izua, and the Izua alphabet (list of letters). There are N types of letters in the Izua alphabet. The order of the words that appear in the Izua Japanese dictionary is in the alphabetical order of Izua.
Looking at the dictionary, I found that every word in the dictionary is N letters and contains N kinds of letters one by one. Upon further investigation, I found that the dictionary contained all possible arrangements of the N characters.
From this discovery, you can see what number a word appears in the dictionary. Use this knowledge to surprise people in Izua. First, arrange the N types of letters one by one in alphabetical order. Next, ask them to repeat the operation of changing the order of any two characters R times. You can guess the number of the finished word in the Izua Japanese dictionary. In preparation for that, create a program that finds the location of words in the Japanese dictionary. However, the first word in alphabetical order is the 0th word.
input
The input consists of multiple datasets. The end of the input is indicated by a single zero line. Each dataset is given in the following format.
N
R
s1 t1
s2 t2
::
sR tR
The first line is given the number of characters that make up the alphabet N (1 β€ N β€ 100000), and the second line is given the number of times R (0 β€ R β€ 50) to have the characters replaced. The following R line is given the set of character positions to be swapped. si and ti (1 β€ si <ti β€ N) represent the i-th swapping of the si and ti characters counting from the beginning. si and ti are separated by a single space.
The number of datasets does not exceed 100.
output
For each data set, the number indicating the number of the word obtained at the end of the replacement in the Japanese dictionary is output on one line. However, the value to be output can be very large, so instead output the remainder divided by 1,000,000,007.
Example
Input
3
2
1 2
2 3
4
2
2 3
2 4
0
Output
3
4
Submitted Solution:
```
class BIT:
def __init__(self,size):
self.bit = [0 for i in range(size+1)]
def update(self,idx,v):
while idx <= len(self.bit)-1:
self.bit[idx] += v
idx += idx & (-idx)
def sum(self,idx):
res = 0
while idx > 0:
res += self.bit[idx]
idx -= idx & (-idx)
return res
MOD_V = 1000000007
while 1:
try:
N = int(input())
if N == 0:break
dp = [0 for i in range(N+1)]
dp[0] = 1
bit = BIT(N)
izua=[i for i in range(N+1)]
for i in range(1,N+1):
if dp[i] == 0:
dp[i] = (dp[i-1]*i) % MOD_V
R = int(input())
for i in range(R):#swap
s,t = list(map(int,input().split()))
w = izua[t]
izua[t] = izua[s]
izua[s] = w
res = 0
for i in range(N,0,-1):
res += (bit.sum(izua[i])*dp[N-i]) % MOD_V
bit.update(izua[i],1)
print (res%MOD_V)
except:
pass
``` | instruction | 0 | 79,854 | 6 | 159,708 |
No | output | 1 | 79,854 | 6 | 159,709 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrey received a postcard from Irina. It contained only the words "Hello, Andrey!", and a strange string consisting of lowercase Latin letters, snowflakes and candy canes. Andrey thought that this string is an encrypted message, and decided to decrypt it.
Andrey noticed that snowflakes and candy canes always stand after the letters, so he supposed that the message was encrypted as follows. Candy cane means that the letter before it can be removed, or can be left. A snowflake means that the letter before it can be removed, left, or repeated several times.
For example, consider the following string:
<image>
This string can encode the message Β«happynewyearΒ». For this, candy canes and snowflakes should be used as follows:
* candy cane 1: remove the letter w,
* snowflake 1: repeat the letter p twice,
* candy cane 2: leave the letter n,
* snowflake 2: remove the letter w,
* snowflake 3: leave the letter e.
<image>
Please note that the same string can encode different messages. For example, the string above can encode Β«hayewyarΒ», Β«happpppynewwwwwyearΒ», and other messages.
Andrey knows that messages from Irina usually have a length of k letters. Help him to find out if a given string can encode a message of k letters, and if so, give an example of such a message.
Input
The first line contains the string received in the postcard. The string consists only of lowercase Latin letters, as well as the characters Β«*Β» and Β«?Β», meaning snowflake and candy cone, respectively. These characters can only appear immediately after the letter. The length of the string does not exceed 200.
The second line contains an integer number k (1 β€ k β€ 200), the required message length.
Output
Print any message of length k that the given string can encode, or Β«ImpossibleΒ» if such a message does not exist.
Examples
Input
hw?ap*yn?eww*ye*ar
12
Output
happynewyear
Input
ab?a
2
Output
aa
Input
ab?a
3
Output
aba
Input
ababb
5
Output
ababb
Input
ab?a
1
Output
Impossible | instruction | 0 | 79,957 | 6 | 159,914 |
Tags: constructive algorithms, implementation
Correct Solution:
```
s = input()
sn = ""
a = int(input())
soma = 0
for i in s:
if i != '?' and i != '*':
soma+=1
# print(soma)
soma -=a
for i in s:
# flag = False
if i == '?':
if soma >0:
# flag = True
# sn +='0'
sn = sn[0:-1]
soma -=1
if i == '*':
if soma < 0:
sn += sn[-1]*abs(soma)
soma = 0
elif soma > 0:
sn = sn[0:-1]
soma-=1
# if not flag:
sn += i
if soma != 0:
print("Impossible")
else:
for i in sn:
if i != '?' and i != '*':
print(i, end='')
print()
# print(sn)
``` | output | 1 | 79,957 | 6 | 159,915 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrey received a postcard from Irina. It contained only the words "Hello, Andrey!", and a strange string consisting of lowercase Latin letters, snowflakes and candy canes. Andrey thought that this string is an encrypted message, and decided to decrypt it.
Andrey noticed that snowflakes and candy canes always stand after the letters, so he supposed that the message was encrypted as follows. Candy cane means that the letter before it can be removed, or can be left. A snowflake means that the letter before it can be removed, left, or repeated several times.
For example, consider the following string:
<image>
This string can encode the message Β«happynewyearΒ». For this, candy canes and snowflakes should be used as follows:
* candy cane 1: remove the letter w,
* snowflake 1: repeat the letter p twice,
* candy cane 2: leave the letter n,
* snowflake 2: remove the letter w,
* snowflake 3: leave the letter e.
<image>
Please note that the same string can encode different messages. For example, the string above can encode Β«hayewyarΒ», Β«happpppynewwwwwyearΒ», and other messages.
Andrey knows that messages from Irina usually have a length of k letters. Help him to find out if a given string can encode a message of k letters, and if so, give an example of such a message.
Input
The first line contains the string received in the postcard. The string consists only of lowercase Latin letters, as well as the characters Β«*Β» and Β«?Β», meaning snowflake and candy cone, respectively. These characters can only appear immediately after the letter. The length of the string does not exceed 200.
The second line contains an integer number k (1 β€ k β€ 200), the required message length.
Output
Print any message of length k that the given string can encode, or Β«ImpossibleΒ» if such a message does not exist.
Examples
Input
hw?ap*yn?eww*ye*ar
12
Output
happynewyear
Input
ab?a
2
Output
aa
Input
ab?a
3
Output
aba
Input
ababb
5
Output
ababb
Input
ab?a
1
Output
Impossible | instruction | 0 | 79,958 | 6 | 159,916 |
Tags: constructive algorithms, implementation
Correct Solution:
```
s=input()
k=int(input())
c=0
t1=0
t2=0
for i in range(0,len(s)):
if(s[i]!='*' and s[i]!='?'):
c=c+1
elif(s[i]=='*'):
t2=t2+1
else:
t1=t1+1
if(c!=k):
if(c<k and t2==0):
print('Impossible')
elif(c>k and c-t2-t1>k):
print('Impossible')
else:
if(c<k):
S=''
temp=0
for i in range(0,len(s)):
if(s[i]!='*' and s[i]!='?'):
S=S+s[i]
if(s[i]=='*' and temp==0):
S=S+S[-1]*(k-c)
temp=1
print(S)
else:
diff=c-k
S=''
for i in range(0,len(s)):
if(s[i]!='*' and s[i]!='?'):
S=S+s[i]
else:
if(diff>0):
S=S[:len(S)-1]
diff=diff-1
print(S)
else:
S=''
for i in range(0,len(s)):
if(s[i]!='*' and s[i]!='?'):
S=S+s[i]
print(S)
``` | output | 1 | 79,958 | 6 | 159,917 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrey received a postcard from Irina. It contained only the words "Hello, Andrey!", and a strange string consisting of lowercase Latin letters, snowflakes and candy canes. Andrey thought that this string is an encrypted message, and decided to decrypt it.
Andrey noticed that snowflakes and candy canes always stand after the letters, so he supposed that the message was encrypted as follows. Candy cane means that the letter before it can be removed, or can be left. A snowflake means that the letter before it can be removed, left, or repeated several times.
For example, consider the following string:
<image>
This string can encode the message Β«happynewyearΒ». For this, candy canes and snowflakes should be used as follows:
* candy cane 1: remove the letter w,
* snowflake 1: repeat the letter p twice,
* candy cane 2: leave the letter n,
* snowflake 2: remove the letter w,
* snowflake 3: leave the letter e.
<image>
Please note that the same string can encode different messages. For example, the string above can encode Β«hayewyarΒ», Β«happpppynewwwwwyearΒ», and other messages.
Andrey knows that messages from Irina usually have a length of k letters. Help him to find out if a given string can encode a message of k letters, and if so, give an example of such a message.
Input
The first line contains the string received in the postcard. The string consists only of lowercase Latin letters, as well as the characters Β«*Β» and Β«?Β», meaning snowflake and candy cone, respectively. These characters can only appear immediately after the letter. The length of the string does not exceed 200.
The second line contains an integer number k (1 β€ k β€ 200), the required message length.
Output
Print any message of length k that the given string can encode, or Β«ImpossibleΒ» if such a message does not exist.
Examples
Input
hw?ap*yn?eww*ye*ar
12
Output
happynewyear
Input
ab?a
2
Output
aa
Input
ab?a
3
Output
aba
Input
ababb
5
Output
ababb
Input
ab?a
1
Output
Impossible | instruction | 0 | 79,959 | 6 | 159,918 |
Tags: constructive algorithms, implementation
Correct Solution:
```
s=input()
k=int(input())
n=len(s)-s.count('?')-s.count("*")
if n<k:
if not "*" in s:
print("Impossible")
else:
x=s.index("*")
f=k-n
s=s[:x]+s[x-1]*f+s[x:]
while '*' in s:
s=s[:s.index("*")]+s[s.index("*")+1:]
while "?" in s:
s=s[:s.index("?")]+s[s.index("?")+1:]
print(s)
elif n>k:
f=n-k
if s.count("?")+s.count("*")<f:
print("Impossible")
else:
b=s.count("?")
for i in range(min(f,b)):
s=s[:s.index("?")-1]+s[s.index("?")+1:]
for i in range(f-min(f,b)):
s=s[:s.index("*")-1]+s[s.index("*")+1:]
while '*' in s:
s=s[:s.index("*")]+s[s.index("*")+1:]
while "?" in s:
s=s[:s.index("?")]+s[s.index("?")+1:]
print(s)
else:
while '*' in s:
s=s[:s.index("*")]+s[s.index("*")+1:]
while "?" in s:
s=s[:s.index("?")]+s[s.index("?")+1:]
print(s)
``` | output | 1 | 79,959 | 6 | 159,919 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrey received a postcard from Irina. It contained only the words "Hello, Andrey!", and a strange string consisting of lowercase Latin letters, snowflakes and candy canes. Andrey thought that this string is an encrypted message, and decided to decrypt it.
Andrey noticed that snowflakes and candy canes always stand after the letters, so he supposed that the message was encrypted as follows. Candy cane means that the letter before it can be removed, or can be left. A snowflake means that the letter before it can be removed, left, or repeated several times.
For example, consider the following string:
<image>
This string can encode the message Β«happynewyearΒ». For this, candy canes and snowflakes should be used as follows:
* candy cane 1: remove the letter w,
* snowflake 1: repeat the letter p twice,
* candy cane 2: leave the letter n,
* snowflake 2: remove the letter w,
* snowflake 3: leave the letter e.
<image>
Please note that the same string can encode different messages. For example, the string above can encode Β«hayewyarΒ», Β«happpppynewwwwwyearΒ», and other messages.
Andrey knows that messages from Irina usually have a length of k letters. Help him to find out if a given string can encode a message of k letters, and if so, give an example of such a message.
Input
The first line contains the string received in the postcard. The string consists only of lowercase Latin letters, as well as the characters Β«*Β» and Β«?Β», meaning snowflake and candy cone, respectively. These characters can only appear immediately after the letter. The length of the string does not exceed 200.
The second line contains an integer number k (1 β€ k β€ 200), the required message length.
Output
Print any message of length k that the given string can encode, or Β«ImpossibleΒ» if such a message does not exist.
Examples
Input
hw?ap*yn?eww*ye*ar
12
Output
happynewyear
Input
ab?a
2
Output
aa
Input
ab?a
3
Output
aba
Input
ababb
5
Output
ababb
Input
ab?a
1
Output
Impossible | instruction | 0 | 79,960 | 6 | 159,920 |
Tags: constructive algorithms, implementation
Correct Solution:
```
s = input()
k = int(input())
rem = k - (len(s) - sum(map(lambda x : not x.isalpha(), s)) * 2)
if rem < 0 :
print('Impossible')
exit(0)
res = []
for ch in s :
if ch.isalpha() :
res.append(ch)
elif ch == '?':
if rem == 0:
res.pop()
else :
rem -= 1
elif ch == '*':
if rem :
res += res[-1] * (rem - 1)
rem = 0
else :
res.pop()
if rem != 0 :
print('Impossible')
else :
print(''.join(res))
``` | output | 1 | 79,960 | 6 | 159,921 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrey received a postcard from Irina. It contained only the words "Hello, Andrey!", and a strange string consisting of lowercase Latin letters, snowflakes and candy canes. Andrey thought that this string is an encrypted message, and decided to decrypt it.
Andrey noticed that snowflakes and candy canes always stand after the letters, so he supposed that the message was encrypted as follows. Candy cane means that the letter before it can be removed, or can be left. A snowflake means that the letter before it can be removed, left, or repeated several times.
For example, consider the following string:
<image>
This string can encode the message Β«happynewyearΒ». For this, candy canes and snowflakes should be used as follows:
* candy cane 1: remove the letter w,
* snowflake 1: repeat the letter p twice,
* candy cane 2: leave the letter n,
* snowflake 2: remove the letter w,
* snowflake 3: leave the letter e.
<image>
Please note that the same string can encode different messages. For example, the string above can encode Β«hayewyarΒ», Β«happpppynewwwwwyearΒ», and other messages.
Andrey knows that messages from Irina usually have a length of k letters. Help him to find out if a given string can encode a message of k letters, and if so, give an example of such a message.
Input
The first line contains the string received in the postcard. The string consists only of lowercase Latin letters, as well as the characters Β«*Β» and Β«?Β», meaning snowflake and candy cone, respectively. These characters can only appear immediately after the letter. The length of the string does not exceed 200.
The second line contains an integer number k (1 β€ k β€ 200), the required message length.
Output
Print any message of length k that the given string can encode, or Β«ImpossibleΒ» if such a message does not exist.
Examples
Input
hw?ap*yn?eww*ye*ar
12
Output
happynewyear
Input
ab?a
2
Output
aa
Input
ab?a
3
Output
aba
Input
ababb
5
Output
ababb
Input
ab?a
1
Output
Impossible | instruction | 0 | 79,961 | 6 | 159,922 |
Tags: constructive algorithms, implementation
Correct Solution:
```
s = input()
k = int(input())
ch7 = s.count("?") # Π»Π΅Π΄Π΅Π½Π΅Ρ, ΡΠ΄Π°Π»ΠΈΡΡ
ch8 = s.count("*") # ΡΠ½Π΅ΠΆΠΈΠ½ΠΊΠ°, ΠΏΠΎΠ²ΡΠΎΡΠΈΡΡ
ch = "*?"
if len(s)-ch7-ch8 > k:
if len(s)-ch7-ch8-ch7-ch8 > k:
print("Impossible")
else:
cou = len(s)-ch7-ch8 - k
while cou > 0:
ind = s.find("?")
if ind == -1:
break
s = s[:ind-1] + s[ind+1:]
cou -= 1
while cou > 0:
ind = s.find("*")
if ind == -1:
break
s = s[:ind-1] + s[ind+1:]
cou -= 1
s = s.replace("*", "")
s = s.replace("?", "")
print(s)
elif len(s)-ch7-ch8 < k:
if ch8 == 0:
print("Impossible")
else:
cou = k - (len(s) - ch7 - ch8)
ind = s.find("*")
s = s[:ind] + s[ind-1]*cou + s[ind+1:]
s = s.replace("*", "")
s = s.replace("?", "")
print(s)
else:
s = s.replace("*", "")
s = s.replace("?", "")
print(s)
``` | output | 1 | 79,961 | 6 | 159,923 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrey received a postcard from Irina. It contained only the words "Hello, Andrey!", and a strange string consisting of lowercase Latin letters, snowflakes and candy canes. Andrey thought that this string is an encrypted message, and decided to decrypt it.
Andrey noticed that snowflakes and candy canes always stand after the letters, so he supposed that the message was encrypted as follows. Candy cane means that the letter before it can be removed, or can be left. A snowflake means that the letter before it can be removed, left, or repeated several times.
For example, consider the following string:
<image>
This string can encode the message Β«happynewyearΒ». For this, candy canes and snowflakes should be used as follows:
* candy cane 1: remove the letter w,
* snowflake 1: repeat the letter p twice,
* candy cane 2: leave the letter n,
* snowflake 2: remove the letter w,
* snowflake 3: leave the letter e.
<image>
Please note that the same string can encode different messages. For example, the string above can encode Β«hayewyarΒ», Β«happpppynewwwwwyearΒ», and other messages.
Andrey knows that messages from Irina usually have a length of k letters. Help him to find out if a given string can encode a message of k letters, and if so, give an example of such a message.
Input
The first line contains the string received in the postcard. The string consists only of lowercase Latin letters, as well as the characters Β«*Β» and Β«?Β», meaning snowflake and candy cone, respectively. These characters can only appear immediately after the letter. The length of the string does not exceed 200.
The second line contains an integer number k (1 β€ k β€ 200), the required message length.
Output
Print any message of length k that the given string can encode, or Β«ImpossibleΒ» if such a message does not exist.
Examples
Input
hw?ap*yn?eww*ye*ar
12
Output
happynewyear
Input
ab?a
2
Output
aa
Input
ab?a
3
Output
aba
Input
ababb
5
Output
ababb
Input
ab?a
1
Output
Impossible | instruction | 0 | 79,962 | 6 | 159,924 |
Tags: constructive algorithms, implementation
Correct Solution:
```
s = list(str(input()))
k = int(input())
letters = len(s) - s.count("*") - s.count("?")
if k == letters:
while "*" in s:
s.remove("*")
while "?" in s:
s.remove("?")
print("".join(s))
elif k > letters:
if "*" in s:
while "?" in s:
s.remove("?")
while s.count("*") > 1:
s.remove("*")
specialLetter = s[s.index("*") - 1]
s[s.index("*")] = specialLetter * (k-letters)
print("".join(s))
else:
print("Impossible")
else:
if s.count("*") + s.count("?") >= (letters-k):
while s.count("*") + s.count("?") > (letters-k):
if "*" in s:
s.remove("*")
else:
s.remove("?")
stringBuilder = ""
while len(s) > 0:
if len(s) == 1:
stringBuilder += s[0]
s.remove(s[0])
elif s[1] == "*" or s[1] == "?":
s.remove(s[0])
s.remove(s[0])
else:
stringBuilder += s[0]
s.remove(s[0])
print(stringBuilder)
else:
print("Impossible")
"""alphabet = list("abcdefghijklmnopqrstuvwxyz")
possibleValues = [0]; newPossibleValues = []
for i in range(0, len(s)-1):
if s[i] in alphabet:
if s[i+1] == "*":
elif s[i+1] == "?":
for k in possibleValues:
is k.isdigit()
else:
for j in possibleValues:
if j.isdigit():
newPossibleValues.append(j+1)
else:
"""
``` | output | 1 | 79,962 | 6 | 159,925 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrey received a postcard from Irina. It contained only the words "Hello, Andrey!", and a strange string consisting of lowercase Latin letters, snowflakes and candy canes. Andrey thought that this string is an encrypted message, and decided to decrypt it.
Andrey noticed that snowflakes and candy canes always stand after the letters, so he supposed that the message was encrypted as follows. Candy cane means that the letter before it can be removed, or can be left. A snowflake means that the letter before it can be removed, left, or repeated several times.
For example, consider the following string:
<image>
This string can encode the message Β«happynewyearΒ». For this, candy canes and snowflakes should be used as follows:
* candy cane 1: remove the letter w,
* snowflake 1: repeat the letter p twice,
* candy cane 2: leave the letter n,
* snowflake 2: remove the letter w,
* snowflake 3: leave the letter e.
<image>
Please note that the same string can encode different messages. For example, the string above can encode Β«hayewyarΒ», Β«happpppynewwwwwyearΒ», and other messages.
Andrey knows that messages from Irina usually have a length of k letters. Help him to find out if a given string can encode a message of k letters, and if so, give an example of such a message.
Input
The first line contains the string received in the postcard. The string consists only of lowercase Latin letters, as well as the characters Β«*Β» and Β«?Β», meaning snowflake and candy cone, respectively. These characters can only appear immediately after the letter. The length of the string does not exceed 200.
The second line contains an integer number k (1 β€ k β€ 200), the required message length.
Output
Print any message of length k that the given string can encode, or Β«ImpossibleΒ» if such a message does not exist.
Examples
Input
hw?ap*yn?eww*ye*ar
12
Output
happynewyear
Input
ab?a
2
Output
aa
Input
ab?a
3
Output
aba
Input
ababb
5
Output
ababb
Input
ab?a
1
Output
Impossible | instruction | 0 | 79,963 | 6 | 159,926 |
Tags: constructive algorithms, implementation
Correct Solution:
```
from sys import stdin, stdout
from math import *
from heapq import *
from collections import *
def main():
s=stdin.readline().rstrip('\n')
n=int(stdin.readline())
res=[]
lens=0
for c in s:
if (('a'<=c) and (c<='z')):
lens=lens+1
i=len(s)
while (i>0):
i=i-1
c=s[i]
if (('a'<=c) and (c<='z')):
res.append(c)
if (c=='?'):
if (lens<=n):
continue
else:
i=i-1
lens=lens-1
continue
if (c=='*'):
if (lens<=n):
while (lens<n):
lens=lens+1
res.append(s[i-1])
continue
else:
i=i-1
lens=lens-1
continue
res.reverse()
if (len(res)!=n):
stdout.write("Impossible")
return 0
stdout.write("".join([str(c) for c in res]))
return 0
if __name__ == "__main__":
main()
``` | output | 1 | 79,963 | 6 | 159,927 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrey received a postcard from Irina. It contained only the words "Hello, Andrey!", and a strange string consisting of lowercase Latin letters, snowflakes and candy canes. Andrey thought that this string is an encrypted message, and decided to decrypt it.
Andrey noticed that snowflakes and candy canes always stand after the letters, so he supposed that the message was encrypted as follows. Candy cane means that the letter before it can be removed, or can be left. A snowflake means that the letter before it can be removed, left, or repeated several times.
For example, consider the following string:
<image>
This string can encode the message Β«happynewyearΒ». For this, candy canes and snowflakes should be used as follows:
* candy cane 1: remove the letter w,
* snowflake 1: repeat the letter p twice,
* candy cane 2: leave the letter n,
* snowflake 2: remove the letter w,
* snowflake 3: leave the letter e.
<image>
Please note that the same string can encode different messages. For example, the string above can encode Β«hayewyarΒ», Β«happpppynewwwwwyearΒ», and other messages.
Andrey knows that messages from Irina usually have a length of k letters. Help him to find out if a given string can encode a message of k letters, and if so, give an example of such a message.
Input
The first line contains the string received in the postcard. The string consists only of lowercase Latin letters, as well as the characters Β«*Β» and Β«?Β», meaning snowflake and candy cone, respectively. These characters can only appear immediately after the letter. The length of the string does not exceed 200.
The second line contains an integer number k (1 β€ k β€ 200), the required message length.
Output
Print any message of length k that the given string can encode, or Β«ImpossibleΒ» if such a message does not exist.
Examples
Input
hw?ap*yn?eww*ye*ar
12
Output
happynewyear
Input
ab?a
2
Output
aa
Input
ab?a
3
Output
aba
Input
ababb
5
Output
ababb
Input
ab?a
1
Output
Impossible | instruction | 0 | 79,964 | 6 | 159,928 |
Tags: constructive algorithms, implementation
Correct Solution:
```
x=input()
b=eval(input())
i=0
candys=0
stars=0
while i <len(x):
if x[i]=='?':
candys+=1
i+=1
elif x[i]=='*':
stars+=1
i+=1
else:
i+=1
string=len(x)-candys-stars
i=0
a=''
while i <len(x):
if string==b:
if x[i]!='?' and x[i]!='*':
a+=x[i]
i+=1
else:
i+=1
elif string>b:
while i<len(x)-1 and string>b:
if x[i+1]=='?' or x[i+1]=='*':
i+=2
string-=1
else:
a+=x[i]
i+=1
if i ==len(x)-1:
a+=x[i]
i+=1
elif string<b:
if x[i]=='*':
c=b-int(string)
a+=c*x[i-1]
i+=1
string+=c
elif x[i]=='?':
i+=1
else:
a+=x[i]
i+=1
if len(a)==b:
print(a)
else:
print('Impossible')
``` | output | 1 | 79,964 | 6 | 159,929 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andrey received a postcard from Irina. It contained only the words "Hello, Andrey!", and a strange string consisting of lowercase Latin letters, snowflakes and candy canes. Andrey thought that this string is an encrypted message, and decided to decrypt it.
Andrey noticed that snowflakes and candy canes always stand after the letters, so he supposed that the message was encrypted as follows. Candy cane means that the letter before it can be removed, or can be left. A snowflake means that the letter before it can be removed, left, or repeated several times.
For example, consider the following string:
<image>
This string can encode the message Β«happynewyearΒ». For this, candy canes and snowflakes should be used as follows:
* candy cane 1: remove the letter w,
* snowflake 1: repeat the letter p twice,
* candy cane 2: leave the letter n,
* snowflake 2: remove the letter w,
* snowflake 3: leave the letter e.
<image>
Please note that the same string can encode different messages. For example, the string above can encode Β«hayewyarΒ», Β«happpppynewwwwwyearΒ», and other messages.
Andrey knows that messages from Irina usually have a length of k letters. Help him to find out if a given string can encode a message of k letters, and if so, give an example of such a message.
Input
The first line contains the string received in the postcard. The string consists only of lowercase Latin letters, as well as the characters Β«*Β» and Β«?Β», meaning snowflake and candy cone, respectively. These characters can only appear immediately after the letter. The length of the string does not exceed 200.
The second line contains an integer number k (1 β€ k β€ 200), the required message length.
Output
Print any message of length k that the given string can encode, or Β«ImpossibleΒ» if such a message does not exist.
Examples
Input
hw?ap*yn?eww*ye*ar
12
Output
happynewyear
Input
ab?a
2
Output
aa
Input
ab?a
3
Output
aba
Input
ababb
5
Output
ababb
Input
ab?a
1
Output
Impossible
Submitted Solution:
```
n = input()
k = int(input())
a,c,s = 0,0,0
ans = ''
for i in range(len(n)):
if n[i] == '?':c+=1
elif n[i] == '*':s+=1
else:a+=1
if (a - c - s > k) or (a < k and s == 0) : print('Impossible'); exit(0)
if a < k and s != 0:
err = 0
for i in range(len(n)):
if n[i] == '*' and not err and len(ans):
ans += ans[len(ans)-1]*(k-a)
err = 1
elif 97 <= ord(n[i]) <= 122: ans+=n[i]
else: continue
else:
err = a-k
for i in range(len(n)):
if n[i] in ['?','*'] and err and len(ans):
ans = ans[:len(ans)-1]
err -= 1
elif 97 <= ord(n[i]) <= 122: ans += n[i]
else: continue
if len(ans) != k:print('Impossible')
else:print(ans)
``` | instruction | 0 | 79,965 | 6 | 159,930 |
Yes | output | 1 | 79,965 | 6 | 159,931 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andrey received a postcard from Irina. It contained only the words "Hello, Andrey!", and a strange string consisting of lowercase Latin letters, snowflakes and candy canes. Andrey thought that this string is an encrypted message, and decided to decrypt it.
Andrey noticed that snowflakes and candy canes always stand after the letters, so he supposed that the message was encrypted as follows. Candy cane means that the letter before it can be removed, or can be left. A snowflake means that the letter before it can be removed, left, or repeated several times.
For example, consider the following string:
<image>
This string can encode the message Β«happynewyearΒ». For this, candy canes and snowflakes should be used as follows:
* candy cane 1: remove the letter w,
* snowflake 1: repeat the letter p twice,
* candy cane 2: leave the letter n,
* snowflake 2: remove the letter w,
* snowflake 3: leave the letter e.
<image>
Please note that the same string can encode different messages. For example, the string above can encode Β«hayewyarΒ», Β«happpppynewwwwwyearΒ», and other messages.
Andrey knows that messages from Irina usually have a length of k letters. Help him to find out if a given string can encode a message of k letters, and if so, give an example of such a message.
Input
The first line contains the string received in the postcard. The string consists only of lowercase Latin letters, as well as the characters Β«*Β» and Β«?Β», meaning snowflake and candy cone, respectively. These characters can only appear immediately after the letter. The length of the string does not exceed 200.
The second line contains an integer number k (1 β€ k β€ 200), the required message length.
Output
Print any message of length k that the given string can encode, or Β«ImpossibleΒ» if such a message does not exist.
Examples
Input
hw?ap*yn?eww*ye*ar
12
Output
happynewyear
Input
ab?a
2
Output
aa
Input
ab?a
3
Output
aba
Input
ababb
5
Output
ababb
Input
ab?a
1
Output
Impossible
Submitted Solution:
```
a = input()
k = int(input())
ml = 0
for i in a:
if i == '?' or i == '*':
ml -= 1
else:
ml += 1
if k < ml:
print('Impossible')
import sys
sys.exit(0)
dl = k - ml
t = ''
n = len(a)
for i in range(n):
if i + 1 < n and a[i + 1] == '?':
if dl <= 0: continue
t += a[i]
dl -= 1
continue
if i + 1 < n and a[i + 1] == '*':
if dl <= 0: continue
while dl > 0:
t += a[i]
dl -= 1
continue
if a[i] not in '?*':
t += a[i]
if len(t) == k:
print(t)
else:
print('Impossible')
``` | instruction | 0 | 79,966 | 6 | 159,932 |
Yes | output | 1 | 79,966 | 6 | 159,933 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andrey received a postcard from Irina. It contained only the words "Hello, Andrey!", and a strange string consisting of lowercase Latin letters, snowflakes and candy canes. Andrey thought that this string is an encrypted message, and decided to decrypt it.
Andrey noticed that snowflakes and candy canes always stand after the letters, so he supposed that the message was encrypted as follows. Candy cane means that the letter before it can be removed, or can be left. A snowflake means that the letter before it can be removed, left, or repeated several times.
For example, consider the following string:
<image>
This string can encode the message Β«happynewyearΒ». For this, candy canes and snowflakes should be used as follows:
* candy cane 1: remove the letter w,
* snowflake 1: repeat the letter p twice,
* candy cane 2: leave the letter n,
* snowflake 2: remove the letter w,
* snowflake 3: leave the letter e.
<image>
Please note that the same string can encode different messages. For example, the string above can encode Β«hayewyarΒ», Β«happpppynewwwwwyearΒ», and other messages.
Andrey knows that messages from Irina usually have a length of k letters. Help him to find out if a given string can encode a message of k letters, and if so, give an example of such a message.
Input
The first line contains the string received in the postcard. The string consists only of lowercase Latin letters, as well as the characters Β«*Β» and Β«?Β», meaning snowflake and candy cone, respectively. These characters can only appear immediately after the letter. The length of the string does not exceed 200.
The second line contains an integer number k (1 β€ k β€ 200), the required message length.
Output
Print any message of length k that the given string can encode, or Β«ImpossibleΒ» if such a message does not exist.
Examples
Input
hw?ap*yn?eww*ye*ar
12
Output
happynewyear
Input
ab?a
2
Output
aa
Input
ab?a
3
Output
aba
Input
ababb
5
Output
ababb
Input
ab?a
1
Output
Impossible
Submitted Solution:
```
s=input()
k=int(input())
if '*' in s:
c=''
j=-1
i=1
while i<len(s):
if s[i]=='?' or ( s[i]=='*' and j!=-1):
s=s[:i-1]+s[i+1:]
elif s[i]=='*' :
j=i-1
c=s[i-1]
s=s[:i-1]+s[i+1:]
else:
i+=1
if k-len(s)>=0:
print(s[:j]+c*(k-len(s))+s[j:])
else:
print("Impossible")
else:
c=0
for i in s:
if i=="?":
c+=1
t=len(s)-2*c
if k<t or t+c<k:
print("Impossible")
else:
i=1
co=0
while i<len(s):
if s[i]=="?":
if co<(k-t):
s=s[:i]+s[i+1:]
co+=1
else:
s=s[:i-1]+s[i+1:]
else:
i+=1
print(s)
``` | instruction | 0 | 79,967 | 6 | 159,934 |
Yes | output | 1 | 79,967 | 6 | 159,935 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andrey received a postcard from Irina. It contained only the words "Hello, Andrey!", and a strange string consisting of lowercase Latin letters, snowflakes and candy canes. Andrey thought that this string is an encrypted message, and decided to decrypt it.
Andrey noticed that snowflakes and candy canes always stand after the letters, so he supposed that the message was encrypted as follows. Candy cane means that the letter before it can be removed, or can be left. A snowflake means that the letter before it can be removed, left, or repeated several times.
For example, consider the following string:
<image>
This string can encode the message Β«happynewyearΒ». For this, candy canes and snowflakes should be used as follows:
* candy cane 1: remove the letter w,
* snowflake 1: repeat the letter p twice,
* candy cane 2: leave the letter n,
* snowflake 2: remove the letter w,
* snowflake 3: leave the letter e.
<image>
Please note that the same string can encode different messages. For example, the string above can encode Β«hayewyarΒ», Β«happpppynewwwwwyearΒ», and other messages.
Andrey knows that messages from Irina usually have a length of k letters. Help him to find out if a given string can encode a message of k letters, and if so, give an example of such a message.
Input
The first line contains the string received in the postcard. The string consists only of lowercase Latin letters, as well as the characters Β«*Β» and Β«?Β», meaning snowflake and candy cone, respectively. These characters can only appear immediately after the letter. The length of the string does not exceed 200.
The second line contains an integer number k (1 β€ k β€ 200), the required message length.
Output
Print any message of length k that the given string can encode, or Β«ImpossibleΒ» if such a message does not exist.
Examples
Input
hw?ap*yn?eww*ye*ar
12
Output
happynewyear
Input
ab?a
2
Output
aa
Input
ab?a
3
Output
aba
Input
ababb
5
Output
ababb
Input
ab?a
1
Output
Impossible
Submitted Solution:
```
s = input()
k = int(input())
if '*' in s:
newk=''
bam = len(s)
cnt = 0
for t in range(len(s)-1):
if s[t+1] != '?' and s[t] != '?':
newk += s[t]
if s[t] == '*':
cnt += 1
if s[-1] == '*':
cnt += 1
if s[-1] != '?':
newk+=s[-1]
if k + cnt*2 < len(newk):
print('Impossible')
elif k + cnt*2 == len(newk):
zaz=''
for t in range(len(newk)-1):
if newk[t] != '*' and newk[t+1]!='*':
zaz+=newk[t]
if newk[-1] != '*':
zaz+=newk[-1]
print(zaz)
else:
newA = ''
z = k-(len(newk)-2*cnt+1)
fk = 1
bi = 0
for t in range(len(newk)-1):
if newk[t]!='*' and (newk[t+1] != '*' or fk):
newA += newk[t]
if newk[t+1]=='*':
newA += newk[t]*(z)
fk = 0
if newk[-1] != '*':
newA += newk[-1]
print(newA)
else:
led = s.count('?')
if k > len(s)-led or k < len(s)-2*led:
print('Impossible')
else:
zaaz =''
qqq = len(s)-led-k
for t in range(len(s)-1):
if qqq and s[t+1] == '?':
qqq -= 1
elif s[t] != '?':
zaaz += s[t]
if s[-1] != '?':
zaaz += s[-1]
print(zaaz)
``` | instruction | 0 | 79,968 | 6 | 159,936 |
Yes | output | 1 | 79,968 | 6 | 159,937 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andrey received a postcard from Irina. It contained only the words "Hello, Andrey!", and a strange string consisting of lowercase Latin letters, snowflakes and candy canes. Andrey thought that this string is an encrypted message, and decided to decrypt it.
Andrey noticed that snowflakes and candy canes always stand after the letters, so he supposed that the message was encrypted as follows. Candy cane means that the letter before it can be removed, or can be left. A snowflake means that the letter before it can be removed, left, or repeated several times.
For example, consider the following string:
<image>
This string can encode the message Β«happynewyearΒ». For this, candy canes and snowflakes should be used as follows:
* candy cane 1: remove the letter w,
* snowflake 1: repeat the letter p twice,
* candy cane 2: leave the letter n,
* snowflake 2: remove the letter w,
* snowflake 3: leave the letter e.
<image>
Please note that the same string can encode different messages. For example, the string above can encode Β«hayewyarΒ», Β«happpppynewwwwwyearΒ», and other messages.
Andrey knows that messages from Irina usually have a length of k letters. Help him to find out if a given string can encode a message of k letters, and if so, give an example of such a message.
Input
The first line contains the string received in the postcard. The string consists only of lowercase Latin letters, as well as the characters Β«*Β» and Β«?Β», meaning snowflake and candy cone, respectively. These characters can only appear immediately after the letter. The length of the string does not exceed 200.
The second line contains an integer number k (1 β€ k β€ 200), the required message length.
Output
Print any message of length k that the given string can encode, or Β«ImpossibleΒ» if such a message does not exist.
Examples
Input
hw?ap*yn?eww*ye*ar
12
Output
happynewyear
Input
ab?a
2
Output
aa
Input
ab?a
3
Output
aba
Input
ababb
5
Output
ababb
Input
ab?a
1
Output
Impossible
Submitted Solution:
```
s=input()
n=int(input())
a=int(0)
b=int(0)
for i in range(len(s)):
if s[i]=='?':
a+=1
elif s[i]=='*':
b+=1
if len(s)+1-a-b==n:
for i in range (len(s)):
if s[i]!='*' and s[i]!='?':
print(s[i], end='')
elif len(s)-a-b<n:
if b>0:
c=len(s)+1-n+a+b
x=s.index('*')
q=(s[0:x-1]+s[x-1]*c+s[x+1:len(s)])
for i in range(len(q)):
if q[i] != '*' and q[i] != '?':
print(q[i], end='')
else:
print('Impossible')
else:
if len(s)-n-a-b>a+b:
print('Impossible')
else:
z=len(s)-n-a-b
while a>0 and z>0:
f=s.index('?')
z-=1
if f<len(s):
s=s[0:f-1]+s[(f+1):]
else:
s=s[0:f-1]
while b>0 and z>0:
z-=1
f=s.index('*')
if f<len(s):
s=s[0:f-1]+s[(f+1):]
else:
s=s[0:f-1]
for i in range(len(s)):
if s[i] != '*' and s[i] != '?':
print(s[i], end='')
``` | instruction | 0 | 79,969 | 6 | 159,938 |
No | output | 1 | 79,969 | 6 | 159,939 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andrey received a postcard from Irina. It contained only the words "Hello, Andrey!", and a strange string consisting of lowercase Latin letters, snowflakes and candy canes. Andrey thought that this string is an encrypted message, and decided to decrypt it.
Andrey noticed that snowflakes and candy canes always stand after the letters, so he supposed that the message was encrypted as follows. Candy cane means that the letter before it can be removed, or can be left. A snowflake means that the letter before it can be removed, left, or repeated several times.
For example, consider the following string:
<image>
This string can encode the message Β«happynewyearΒ». For this, candy canes and snowflakes should be used as follows:
* candy cane 1: remove the letter w,
* snowflake 1: repeat the letter p twice,
* candy cane 2: leave the letter n,
* snowflake 2: remove the letter w,
* snowflake 3: leave the letter e.
<image>
Please note that the same string can encode different messages. For example, the string above can encode Β«hayewyarΒ», Β«happpppynewwwwwyearΒ», and other messages.
Andrey knows that messages from Irina usually have a length of k letters. Help him to find out if a given string can encode a message of k letters, and if so, give an example of such a message.
Input
The first line contains the string received in the postcard. The string consists only of lowercase Latin letters, as well as the characters Β«*Β» and Β«?Β», meaning snowflake and candy cone, respectively. These characters can only appear immediately after the letter. The length of the string does not exceed 200.
The second line contains an integer number k (1 β€ k β€ 200), the required message length.
Output
Print any message of length k that the given string can encode, or Β«ImpossibleΒ» if such a message does not exist.
Examples
Input
hw?ap*yn?eww*ye*ar
12
Output
happynewyear
Input
ab?a
2
Output
aa
Input
ab?a
3
Output
aba
Input
ababb
5
Output
ababb
Input
ab?a
1
Output
Impossible
Submitted Solution:
```
s = str(input())
n = int(input())
x = s.count('?')
x1 = s.count('*')
res = len(s)-x-x1
if res==n:
ss = ""
for i in range(0,len(s)):
if s[i]!="?" and s[i]!="*":
ss+=s[i]
print(ss)
elif n > 0:
if (res < n and x==0) or (res > n and res-n > x+x1):
print("Impossible")
exit()
if res < n:
for i in range(0,len(s)):
if res==n:
q = 1
break
if s[i]=="?":
s = s[:i-1] + (s[i] * (n - res)) + s[i+1:]
q1 = 1
break
if res > n:
for i in range(0,len(s)):
if res==n:
q = 1
break
if s[i]=="*":
s = s[:i-1] + s[i+1:]
res-=1
x1-=1
if res > n and x1 == 0:
for i in range(0,len(s)):
if res==n:
q = 1
break
if s[i]=="?":
s = s[:i-1] + s[i+1:]
res-=1
x-=1
ss = ""
for i in range(0,len(s)):
if s[i]!="?" and s[i]!="*":
ss+=s[i]
print(ss)
``` | instruction | 0 | 79,970 | 6 | 159,940 |
No | output | 1 | 79,970 | 6 | 159,941 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andrey received a postcard from Irina. It contained only the words "Hello, Andrey!", and a strange string consisting of lowercase Latin letters, snowflakes and candy canes. Andrey thought that this string is an encrypted message, and decided to decrypt it.
Andrey noticed that snowflakes and candy canes always stand after the letters, so he supposed that the message was encrypted as follows. Candy cane means that the letter before it can be removed, or can be left. A snowflake means that the letter before it can be removed, left, or repeated several times.
For example, consider the following string:
<image>
This string can encode the message Β«happynewyearΒ». For this, candy canes and snowflakes should be used as follows:
* candy cane 1: remove the letter w,
* snowflake 1: repeat the letter p twice,
* candy cane 2: leave the letter n,
* snowflake 2: remove the letter w,
* snowflake 3: leave the letter e.
<image>
Please note that the same string can encode different messages. For example, the string above can encode Β«hayewyarΒ», Β«happpppynewwwwwyearΒ», and other messages.
Andrey knows that messages from Irina usually have a length of k letters. Help him to find out if a given string can encode a message of k letters, and if so, give an example of such a message.
Input
The first line contains the string received in the postcard. The string consists only of lowercase Latin letters, as well as the characters Β«*Β» and Β«?Β», meaning snowflake and candy cone, respectively. These characters can only appear immediately after the letter. The length of the string does not exceed 200.
The second line contains an integer number k (1 β€ k β€ 200), the required message length.
Output
Print any message of length k that the given string can encode, or Β«ImpossibleΒ» if such a message does not exist.
Examples
Input
hw?ap*yn?eww*ye*ar
12
Output
happynewyear
Input
ab?a
2
Output
aa
Input
ab?a
3
Output
aba
Input
ababb
5
Output
ababb
Input
ab?a
1
Output
Impossible
Submitted Solution:
```
s=input('')
k=int(input())
l=0
m=0
n=0
for i in range(0,len(s)):
if s[i]=='?':
l+=1
elif s[i]=='*':
m+=1
else:
n+=1
if n==k:
for i in range(0, len(s)):
if s[i]!='?' and s[i]!='*':
print(s[i],end='')
elif n>k:
if l+m>=n-k:
for i in range(0,len(s)):
if n!=k:
if s[i+1]== '?' or s[i+1]=='*' and i<=n-2:
n-=1
elif s[i]!= '?' or s[i]!='*':
print(s[i],end='')
elif s[i]!= '?' and s[i]!='*':
print(s[i],end='')
else:
print('Impossible')
else:
if m>0:
for i in range(0,len(s)-1):
if (s[i+1]=='*' and s[i]!='?' and i<=n-2):
while n!=k:
n+=1
print(s[i],end='')
elif s[i]!= '?' and s[i]!='*':
print(s[i],end='')
if s[i] != '?' and s[i] != '*':
print(s[i], end='')
else:
print('Impossible')
``` | instruction | 0 | 79,971 | 6 | 159,942 |
No | output | 1 | 79,971 | 6 | 159,943 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andrey received a postcard from Irina. It contained only the words "Hello, Andrey!", and a strange string consisting of lowercase Latin letters, snowflakes and candy canes. Andrey thought that this string is an encrypted message, and decided to decrypt it.
Andrey noticed that snowflakes and candy canes always stand after the letters, so he supposed that the message was encrypted as follows. Candy cane means that the letter before it can be removed, or can be left. A snowflake means that the letter before it can be removed, left, or repeated several times.
For example, consider the following string:
<image>
This string can encode the message Β«happynewyearΒ». For this, candy canes and snowflakes should be used as follows:
* candy cane 1: remove the letter w,
* snowflake 1: repeat the letter p twice,
* candy cane 2: leave the letter n,
* snowflake 2: remove the letter w,
* snowflake 3: leave the letter e.
<image>
Please note that the same string can encode different messages. For example, the string above can encode Β«hayewyarΒ», Β«happpppynewwwwwyearΒ», and other messages.
Andrey knows that messages from Irina usually have a length of k letters. Help him to find out if a given string can encode a message of k letters, and if so, give an example of such a message.
Input
The first line contains the string received in the postcard. The string consists only of lowercase Latin letters, as well as the characters Β«*Β» and Β«?Β», meaning snowflake and candy cone, respectively. These characters can only appear immediately after the letter. The length of the string does not exceed 200.
The second line contains an integer number k (1 β€ k β€ 200), the required message length.
Output
Print any message of length k that the given string can encode, or Β«ImpossibleΒ» if such a message does not exist.
Examples
Input
hw?ap*yn?eww*ye*ar
12
Output
happynewyear
Input
ab?a
2
Output
aa
Input
ab?a
3
Output
aba
Input
ababb
5
Output
ababb
Input
ab?a
1
Output
Impossible
Submitted Solution:
```
s = input()
k = int(input())
count1 = 0
count2 = 0
count3 = 0
flag2 = False
for i in s:
if i =='?':
count1+=1
elif i =='*':
count2+=1
flag2 = True
else:
count3+=1
flag = True
count = count3-count2-count1
l = 0
ans = ''
if count<=k and count3>=k:
if flag2:
for i in range(len(s)-1):
if s[i+1] =='*' and flag:
ans+=(s[i]*(k-count))
flag = False
elif s[i+1] == '?' or s[i] == '?':
l = 0
elif s[i+1] =='*' or s[i] == '*':
l = 0
else:
ans+=s[i]
if len(ans)!=k:
ans+=s[len(s)-1]
print(ans)
else:
tempcount = 0
tmp = ['' for i in s]
for i in range(len(s)):
tmp[i] = s[i]
for i in range(len(s)):
if tempcount<k-count:
if s[i] == '?':
tmp[i] = ''
tempcount+=1
else:
if s[i] == '?':
tmp[i] = ''
tmp[i-1] = ''
ans = ''.join(tmp)
print(ans)
else:
print('Impossible')
``` | instruction | 0 | 79,972 | 6 | 159,944 |
No | output | 1 | 79,972 | 6 | 159,945 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ternary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as Β«.Β», 1 as Β«-.Β» and 2 as Β«--Β». You are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet.
Input
The first line contains a number in Borze code. The length of the string is between 1 and 200 characters. It's guaranteed that the given string is a valid Borze code of some ternary number (this number can have leading zeroes).
Output
Output the decoded ternary number. It can have leading zeroes.
Examples
Input
.-.--
Output
012
Input
--.
Output
20
Input
-..-.--
Output
1012 | instruction | 0 | 80,287 | 6 | 160,574 |
Tags: expression parsing, implementation
Correct Solution:
```
def scan(type):
return list(map(type, input().split()))
word, = scan(str)
sz = len(word)
i = 0
while (i < sz):
if i+1 < sz and word[i] == '-':
if word[i+1] == '-':
print(2,end='')
i += 1
elif word[i+1] == '.':
print(1,end='')
i += 1
else:
print('error1')
elif word[i] == '.':
print(0,end='')
else:
print('error2')
i += 1
print()
``` | output | 1 | 80,287 | 6 | 160,575 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".
Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you.
Input
The first line contains two non-negative numbers n and m (0 β€ n β€ 3Β·105, 0 β€ m β€ 3Β·105) β the number of the initial strings and the number of queries, respectively.
Next follow n non-empty strings that are uploaded to the memory of the mechanism.
Next follow m non-empty strings that are the queries to the mechanism.
The total length of lines in the input doesn't exceed 6Β·105. Each line consists only of letters 'a', 'b', 'c'.
Output
For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes).
Examples
Input
2 3
aaaaa
acacaca
aabaa
ccacacc
caaac
Output
YES
NO
NO | instruction | 0 | 80,387 | 6 | 160,774 |
Tags: binary search, data structures, hashing, string suffix structures, strings
Correct Solution:
```
M=9999999999879997
def Hash(s):
h=0
p=1
for c in s:
h=(h+p*ord(c))%M
p=(p*197)%M
return h
n,m=map(int,input().split())
a = set()
for i in range(n):
s=input()
h=Hash(s)
p=1
for j in range(len(s)):
for k in range(97,100):
if ord(s[j])!=k:
a.add((h+p*(k-ord(s[j])))%M)
p=(p*197)%M
ans=[]
for i in range(m):
s=input()
b=Hash(s)
if b in a:
ans.append('YES')
else:
ans.append('NO')
print ('\n'.join(ans))
``` | output | 1 | 80,387 | 6 | 160,775 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".
Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you.
Input
The first line contains two non-negative numbers n and m (0 β€ n β€ 3Β·105, 0 β€ m β€ 3Β·105) β the number of the initial strings and the number of queries, respectively.
Next follow n non-empty strings that are uploaded to the memory of the mechanism.
Next follow m non-empty strings that are the queries to the mechanism.
The total length of lines in the input doesn't exceed 6Β·105. Each line consists only of letters 'a', 'b', 'c'.
Output
For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes).
Examples
Input
2 3
aaaaa
acacaca
aabaa
ccacacc
caaac
Output
YES
NO
NO | instruction | 0 | 80,388 | 6 | 160,776 |
Tags: binary search, data structures, hashing, string suffix structures, strings
Correct Solution:
```
n, m = map(int, input().split())
mod = 9999999999999983
v = set()
for i in range(n):
s = input()
l = len(s)
pow = 1
h = 0
for i in range(l):
h = (h + ord(s[i]) * pow) % mod
pow = (pow * 203) % mod
pow = 1
for i in range(l):
for j in range(97, 100):
if ord(s[i]) != j:
v.add((h + (j - ord(s[i])) * pow) % mod)
pow = (pow * 203) % mod
#print(v)
ans = []
for i in range(m):
s = input()
pow = 1
h = 0
for i in range(len(s)):
h = (h + ord(s[i]) * pow) % mod
pow = (pow * 203) % mod
#print(h)
ans.append('YES' if h in v else 'NO')
print('\n'.join(ans))
``` | output | 1 | 80,388 | 6 | 160,777 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".
Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you.
Input
The first line contains two non-negative numbers n and m (0 β€ n β€ 3Β·105, 0 β€ m β€ 3Β·105) β the number of the initial strings and the number of queries, respectively.
Next follow n non-empty strings that are uploaded to the memory of the mechanism.
Next follow m non-empty strings that are the queries to the mechanism.
The total length of lines in the input doesn't exceed 6Β·105. Each line consists only of letters 'a', 'b', 'c'.
Output
For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes).
Examples
Input
2 3
aaaaa
acacaca
aabaa
ccacacc
caaac
Output
YES
NO
NO | instruction | 0 | 80,389 | 6 | 160,778 |
Tags: binary search, data structures, hashing, string suffix structures, strings
Correct Solution:
```
'''
@author: ChronoCorax
'''
seed = 201
div = 9999999999999983
ABC = ['a', 'b', 'c']
def hashi(s):
L = len(s)
h = 0;
pseed = 1
for i in range(L):
h, pseed = (h + ord(s[i]) * pseed) % div, (pseed * seed) % div
return h
n, m = [int(c) for c in input().split()]
S = set()
for _ in range(n):
s = input()
L = len(s)
hashs = hashi(s)
pseed = 1
for i in range(L):
orig = s[i]
for c in ABC:
if c == orig: continue
S.add((hashs + pseed * (ord(c) - ord(orig)) + div) % div)
pseed = (pseed * seed) % div
res = []
for _ in range(m):
hi = hashi(input())
if hi in S:
res.append('YES')
else:
res.append('NO')
print('\n'.join(res))
``` | output | 1 | 80,389 | 6 | 160,779 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".
Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you.
Input
The first line contains two non-negative numbers n and m (0 β€ n β€ 3Β·105, 0 β€ m β€ 3Β·105) β the number of the initial strings and the number of queries, respectively.
Next follow n non-empty strings that are uploaded to the memory of the mechanism.
Next follow m non-empty strings that are the queries to the mechanism.
The total length of lines in the input doesn't exceed 6Β·105. Each line consists only of letters 'a', 'b', 'c'.
Output
For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes).
Examples
Input
2 3
aaaaa
acacaca
aabaa
ccacacc
caaac
Output
YES
NO
NO | instruction | 0 | 80,390 | 6 | 160,780 |
Tags: binary search, data structures, hashing, string suffix structures, strings
Correct Solution:
```
from sys import stdin
from functools import reduce
from collections import defaultdict
data = stdin.read().split('\n')
n, m = [int(x) for x in data[0].split()]
B = 10007
MOD = 1000000000000000003
h = lambda s: reduce(lambda s, c: (B * s + ord(c)) % MOD, s, 0)
hs = defaultdict(set)
def insert(s):
hs[len(s)].add(h(s))
def find(s):
v = h(s)
b = 1
for c in reversed(s):
for d in 'abc':
if c != d:
u = (v - b * ord(c) + b * ord(d)) % MOD
if u in hs[len(s)]:
return True
b *= B
b %= MOD
return False
for i in range(n):
s = data[i + 1]
insert(s)
buf = []
for i in range(m):
s = data[i + n + 1]
buf.append('YES' if find(s) else 'NO')
print('\n'.join(buf))
``` | output | 1 | 80,390 | 6 | 160,781 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".
Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you.
Input
The first line contains two non-negative numbers n and m (0 β€ n β€ 3Β·105, 0 β€ m β€ 3Β·105) β the number of the initial strings and the number of queries, respectively.
Next follow n non-empty strings that are uploaded to the memory of the mechanism.
Next follow m non-empty strings that are the queries to the mechanism.
The total length of lines in the input doesn't exceed 6Β·105. Each line consists only of letters 'a', 'b', 'c'.
Output
For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes).
Examples
Input
2 3
aaaaa
acacaca
aabaa
ccacacc
caaac
Output
YES
NO
NO | instruction | 0 | 80,391 | 6 | 160,782 |
Tags: binary search, data structures, hashing, string suffix structures, strings
Correct Solution:
```
n,m=map(int,input().split())
M=9999999999999999
v=set()
for i in range(n):
s=input()
l=len(s)
pow=1
h=0
for i in range(l):
h=(h+ord(s[i])*pow)%M
pow=(pow*203)%M
pow=1
for i in range(l):
for j in range(97,100):
if ord(s[i])!=j:
v.add((h+(j-ord(s[i]))*pow)%M)
pow=(pow*203)%M
ans=[]
for i in range(m):
s=input()
pow=1
h=0
for i in range(len(s)):
h=(h+ord(s[i])*pow)%M
pow=(pow*203)%M
ans.append('YES' if h in v else 'NO')
print('\n'.join(ans))
``` | output | 1 | 80,391 | 6 | 160,783 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".
Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you.
Input
The first line contains two non-negative numbers n and m (0 β€ n β€ 3Β·105, 0 β€ m β€ 3Β·105) β the number of the initial strings and the number of queries, respectively.
Next follow n non-empty strings that are uploaded to the memory of the mechanism.
Next follow m non-empty strings that are the queries to the mechanism.
The total length of lines in the input doesn't exceed 6Β·105. Each line consists only of letters 'a', 'b', 'c'.
Output
For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes).
Examples
Input
2 3
aaaaa
acacaca
aabaa
ccacacc
caaac
Output
YES
NO
NO | instruction | 0 | 80,392 | 6 | 160,784 |
Tags: binary search, data structures, hashing, string suffix structures, strings
Correct Solution:
```
M=9999999999999983
def Hash(s):
h=0
p=1
for c in s:
h=(h+p*(ord(c)-94))%M
p=(p*197)%M
return h
n,m=map(int,input().split())
a=set()
for i in range(n):
s=input()
h=Hash(s)
p=1
for j in range(len(s)):
for k in range(97,100):
if ord(s[j])!=k:
a.add((h+p*(k-ord(s[j])))%M)
p=(p*197)%M
ans=[]
for i in range(m):
s=input()
b=Hash(s)
if b in a:
ans.append('YES')
else:
ans.append('NO')
print ('\n'.join(ans))
``` | output | 1 | 80,392 | 6 | 160,785 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".
Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you.
Input
The first line contains two non-negative numbers n and m (0 β€ n β€ 3Β·105, 0 β€ m β€ 3Β·105) β the number of the initial strings and the number of queries, respectively.
Next follow n non-empty strings that are uploaded to the memory of the mechanism.
Next follow m non-empty strings that are the queries to the mechanism.
The total length of lines in the input doesn't exceed 6Β·105. Each line consists only of letters 'a', 'b', 'c'.
Output
For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes).
Examples
Input
2 3
aaaaa
acacaca
aabaa
ccacacc
caaac
Output
YES
NO
NO | instruction | 0 | 80,393 | 6 | 160,786 |
Tags: binary search, data structures, hashing, string suffix structures, strings
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
_print = print
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')
def inp():
return sys.stdin.readline().rstrip()
def mpint():
return map(int, inp().split(' '))
def itg():
return int(inp())
# ############################## import
_HASH_A, _HASH_B = 79, 46 # '0': 48, 'A': 65, 'a': 97
_HASH_MOD = 10 ** 9 + 7
def multi_hash(hash_func, mod_list=(10 ** 4 + 7, 10 ** 8 + 7, 10 ** 9 + 7)):
def new_func(*args, **kwargs):
result = [hash_func(*args, mod=mod, **kwargs) for mod in mod_list]
if type(result[0]) is int:
return tuple(result)
return list(zip(*result))
return new_func
@multi_hash
def full_hash(s: str, a=_HASH_A, b=_HASH_B, mod=_HASH_MOD) -> int:
""":return hash(s)"""
h = 0
for c in map(ord, s):
h = (h * a + c - b) % mod
return h
@multi_hash
def replace_one_hash(s: str, a=_HASH_A, b=_HASH_B, mod=_HASH_MOD):
"""
:return A hash list with length len(s)
the hash values that obtain replace each letter in s
by 0 as a coefficient
"""
n = len(s)
full = [1] * n
for i in reversed(range(n - 1)):
full[i] = full[i + 1] * a % mod
for i, c in enumerate(map(ord, s)):
full[i] *= c - b # omit mod
full_h = sum(full) % mod
return [(full_h - h) % mod for h in full]
# ############################## main
def main():
n, q = mpint()
d = {}
for _ in range(n):
s = inp()
full_h = full_hash(s)
for h in replace_one_hash(s):
if h in d:
if d[h] != full_h: # there may have two string differ one
d[h] = -1
# else: two strings may be exactly the same
else:
d[h] = full_h
for _ in range(q):
s = inp()
full_h = full_hash(s)
for h in replace_one_hash(s):
if h in d:
if d[h] == full_h: # they are the same, not differ exactly one
continue
print("YES")
break
else:
print("NO")
DEBUG = 0
URL = 'https://codeforces.com/contest/514/problem/C'
if __name__ == '__main__':
# 0: normal, 1: runner, 2: debug, 3: interactive
if DEBUG == 1:
import requests
from ACgenerator.Y_Test_Case_Runner import TestCaseRunner
runner = TestCaseRunner(main, URL)
inp = runner.input_stream
print = runner.output_stream
runner.checking()
else:
if DEBUG != 2:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
if DEBUG:
def print(*args, **kwargs):
_print(*args, **kwargs)
sys.stdout.flush()
main()
# Please check!
``` | output | 1 | 80,393 | 6 | 160,787 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".
Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you.
Input
The first line contains two non-negative numbers n and m (0 β€ n β€ 3Β·105, 0 β€ m β€ 3Β·105) β the number of the initial strings and the number of queries, respectively.
Next follow n non-empty strings that are uploaded to the memory of the mechanism.
Next follow m non-empty strings that are the queries to the mechanism.
The total length of lines in the input doesn't exceed 6Β·105. Each line consists only of letters 'a', 'b', 'c'.
Output
For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes).
Examples
Input
2 3
aaaaa
acacaca
aabaa
ccacacc
caaac
Output
YES
NO
NO | instruction | 0 | 80,394 | 6 | 160,788 |
Tags: binary search, data structures, hashing, string suffix structures, strings
Correct Solution:
```
n,m = [int(i) for i in input().split()]
memory = set()
M = 99999923990274967
d = 2193
for i in range(n):
s = input()
t = 0
p = 1
for char in s:
t = (t+ord(char)*p)%M
p = (p*d)%M
p = 1
for j in range(len(s)):
for k in range(97,100):
if ord(s[j]) != k:
memory.add((t+(k-ord(s[j]))*p)%M)
p = (p*d)%M
answer = []
for i in range(m):
s = input()
t = 0
p = 1
for char in s:
t = (t+ord(char)*p)%M
p = (p*d)%M
if t in memory:
answer.append('YES')
else:
answer.append('NO')
print('\n' .join(answer))
``` | output | 1 | 80,394 | 6 | 160,789 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.
Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).
To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.
String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.
For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically.
Input
The first line of the input contains a single integer n (2 β€ n β€ 100 000) β the number of strings.
The second line contains n integers ci (0 β€ ci β€ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string.
Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000.
Output
If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent.
Examples
Input
2
1 2
ba
ac
Output
1
Input
3
1 3 1
aa
ba
ac
Output
1
Input
2
5 5
bbb
aaa
Output
-1
Input
2
3 3
aaa
aa
Output
-1
Note
In the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.
In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1.
In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is - 1. | instruction | 0 | 80,459 | 6 | 160,918 |
Tags: dp, strings
Correct Solution:
```
"""
Author - Satwik Tiwari .
4th Oct , 2020 - Sunday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
# from itertools import *
from heapq import *
from math import gcd, factorial,floor,ceil
from copy import deepcopy
from collections import deque
# from collections import Counter as counter # Counter(list) return a dict with {key: count}
# from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
# from itertools import permutations as permutate
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
#==============================================================================================
#fast I/O region
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")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# inp = lambda: sys.stdin.readline().rstrip("\r\n")
#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
#### END ITERATE RECURSION ####
#===============================================================================================
#some shortcuts
mod = 10**9+7
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var)) #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n") #as stdout.write always print sring.
def testcase(t):
for pp in range(t):
solve(pp)
def printlist(a) :
for p in range(0,len(a)):
out(str(a[p]) + ' ')
def google(p):
print('Case #'+str(p)+': ',end='')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(x, y, p) :
res = 1 # Initialize result
x = x % p # Update x if it is more , than or equal to p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) : # If y is odd, multiply, x with result
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))
def isPrime(n) :
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
#===============================================================================================
# code here ;))
dp = [[-1,-1] for i in range(100005)]
inf = 10**18
@iterative
def rec(s,c,pos,flag):
if(pos==len(s)):
yield 0
if(dp[pos][1 if flag else 0]!=-1):
yield dp[pos][1 if flag else 0]
temp = 10**18
if(flag):
if(s[pos] >= s[pos-1][::-1]):
temp = min(temp,(yield rec(s,c,pos+1,False)))
if(s[pos][::-1] >= s[pos-1][::-1]):
temp = min(temp,c[pos]+(yield rec(s,c,pos+1,True)))
else:
if(s[pos] >= s[pos-1]):
temp = min(temp,(yield rec(s,c,pos+1,False)))
if(s[pos][::-1] >= s[pos-1]):
temp = min(temp,c[pos]+(yield rec(s,c,pos+1,True)))
dp[pos][1 if flag else 0] = temp
yield temp
def solve(case):
n = int(inp())
c = lis()
s = []
for i in range(n):
s.append(inp())
for i in range(1,n):
if(s[i]>s[i-1] or s[i]>s[i-1][::-1]):
continue
new = s[i][::-1]
if(new>=s[i-1] or new>=s[i-1][::-1]):
continue
print(-1)
return
dp[0][0],dp[0][1] = 0,c[0]
temp = min(c[0]+rec(s,c,1,True),rec(s,c,1,False))
if(temp>10**15):
print(-1)
return
print(temp)
testcase(1)
# testcase(int(inp()))
``` | output | 1 | 80,459 | 6 | 160,919 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.
Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).
To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.
String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.
For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically.
Input
The first line of the input contains a single integer n (2 β€ n β€ 100 000) β the number of strings.
The second line contains n integers ci (0 β€ ci β€ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string.
Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000.
Output
If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent.
Examples
Input
2
1 2
ba
ac
Output
1
Input
3
1 3 1
aa
ba
ac
Output
1
Input
2
5 5
bbb
aaa
Output
-1
Input
2
3 3
aaa
aa
Output
-1
Note
In the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.
In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1.
In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is - 1. | instruction | 0 | 80,460 | 6 | 160,920 |
Tags: dp, strings
Correct Solution:
```
def b3_hard_problems(n, c, s, t):
l = r = ''
a = b = 0
for i in range(n):
x = y = 10 ** 16
if s[i] >= l: x = a
if s[i] >= r: x = min(x, b)
if t[i] >= l: y = a + c[i]
if t[i] >= r: y = min(y, b + c[i])
l = s[i];
r = t[i];
a = x;
b = y
a = min(a, b)
if a == 10 ** 16: a = -1
return a
if __name__ == "__main__":
n = int(input())
a = list(map(int, input().split()))
s = []
t = []
for i in range(n):
s1 = input()
t1 = s1[::-1]
s.append(s1)
t.append(t1)
result = b3_hard_problems(n, a, s, t)
print(result)
``` | output | 1 | 80,460 | 6 | 160,921 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.
Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).
To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.
String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.
For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically.
Input
The first line of the input contains a single integer n (2 β€ n β€ 100 000) β the number of strings.
The second line contains n integers ci (0 β€ ci β€ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string.
Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000.
Output
If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent.
Examples
Input
2
1 2
ba
ac
Output
1
Input
3
1 3 1
aa
ba
ac
Output
1
Input
2
5 5
bbb
aaa
Output
-1
Input
2
3 3
aaa
aa
Output
-1
Note
In the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.
In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1.
In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is - 1. | instruction | 0 | 80,461 | 6 | 160,922 |
Tags: dp, strings
Correct Solution:
```
I = input
n, C, d = int(I()), list(map(int, I().split())), {'': 0}
for i in range(n):
if not d:
print(-1)
break
s, tmp = I(), {}
for s, c in ((s, 0), (s[::-1], C[i])):
for prev, val in d.items():
if prev <= s and (s not in tmp or tmp[s] > val + c):
tmp[s] = val + c
d = tmp
else:
print(min(d.values()) if d else -1)
``` | output | 1 | 80,461 | 6 | 160,923 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.
Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).
To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.
String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.
For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically.
Input
The first line of the input contains a single integer n (2 β€ n β€ 100 000) β the number of strings.
The second line contains n integers ci (0 β€ ci β€ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string.
Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000.
Output
If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent.
Examples
Input
2
1 2
ba
ac
Output
1
Input
3
1 3 1
aa
ba
ac
Output
1
Input
2
5 5
bbb
aaa
Output
-1
Input
2
3 3
aaa
aa
Output
-1
Note
In the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.
In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1.
In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is - 1. | instruction | 0 | 80,462 | 6 | 160,924 |
Tags: dp, strings
Correct Solution:
```
from collections import Counter
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")
##########################################################
# from collections import Counter
# from fractions import Fraction
# s=iter(input())
# from collections import deque
# n=int(input())
# n,k=map(int,input().split())
# arr=list(map(int,input().split()))
# ls=list(map(int,input().split()))
from bisect import bisect_right
import math
n=int(input())
#n, k = map(int, input().split())
c = list(map(int, input().split()))
#g=[[] for i in range(n)]
f=0
n=len(c)
pre=input()
dp=[[math.inf]*2 for i in range(n)]
dp[0][0]=0
dp[0][1]=c[0]
for i in range(1,n):
s = input()
if s >= pre:
dp[i][0] = min(dp[i][0], dp[i - 1][0])
if s >= pre[::-1]:
dp[i][0] = min(dp[i][0], dp[i - 1][1])
if s[::-1] >= pre:
dp[i][1] = min(dp[i][1], dp[i - 1][0] + c[i])
if s[::-1] >= pre[::-1]:
dp[i][1] = min(dp[i][1], dp[i - 1][1]+c[i])
pre = s
if dp[i][0] >=math.inf and dp[i][1] >=math.inf:
f = 1
break
if f==1:
print(-1)
else:
print(min(dp[n-1][0],dp[n-1][1]))
``` | output | 1 | 80,462 | 6 | 160,925 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.
Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).
To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.
String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.
For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically.
Input
The first line of the input contains a single integer n (2 β€ n β€ 100 000) β the number of strings.
The second line contains n integers ci (0 β€ ci β€ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string.
Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000.
Output
If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent.
Examples
Input
2
1 2
ba
ac
Output
1
Input
3
1 3 1
aa
ba
ac
Output
1
Input
2
5 5
bbb
aaa
Output
-1
Input
2
3 3
aaa
aa
Output
-1
Note
In the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.
In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1.
In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is - 1. | instruction | 0 | 80,463 | 6 | 160,926 |
Tags: dp, strings
Correct Solution:
```
import math
import sys
n=int(input())
c=list(map(int,input().split()))
f=[]
for i in range(n):
f.append(str(input()))
INF=10**18
dp=[[0],[c[0]]]
for i in range(1,n):
dp[0].append(INF)
if f[i]>=f[i-1]:
dp[0][-1]=dp[0][-2]
if f[i]>=f[i-1][::-1]:
dp[0][-1]=min(dp[0][-1],dp[1][-1])
dp[1].append(INF)
if f[i][::-1]>=f[i-1]:
dp[1][-1]=dp[0][-2]+c[i]
if f[i][::-1]>=f[i-1][::-1]:
dp[1][-1]=min(dp[1][-1],c[i]+dp[1][-2])
k=min(dp[0][-1],dp[1][-1])
if k>=INF:
print(-1)
else:
print(k)
``` | output | 1 | 80,463 | 6 | 160,927 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.
Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).
To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.
String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.
For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically.
Input
The first line of the input contains a single integer n (2 β€ n β€ 100 000) β the number of strings.
The second line contains n integers ci (0 β€ ci β€ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string.
Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000.
Output
If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent.
Examples
Input
2
1 2
ba
ac
Output
1
Input
3
1 3 1
aa
ba
ac
Output
1
Input
2
5 5
bbb
aaa
Output
-1
Input
2
3 3
aaa
aa
Output
-1
Note
In the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.
In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1.
In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is - 1. | instruction | 0 | 80,464 | 6 | 160,928 |
Tags: dp, strings
Correct Solution:
```
from math import inf
n = int(input())
l = [int(i) for i in input().split()]
s = []
for i in range(n):
s.append(input())
x,y = 0, l[0]
for i in range(1,n):
prev = s[i-1]
rprev = prev[::-1]
curr = s[i]
rcurr= curr[::-1]
xx, yy = inf, inf
if curr >= prev:
xx = x
if curr >= rprev:
xx = min(y, xx)
if rcurr >= prev:
yy = x+l[i]
if rcurr >= rprev:
yy = min(yy, y+l[i])
x,y = xx,yy
ans = min(x,y)
ans = -1 if ans == inf else ans
print(ans)
``` | output | 1 | 80,464 | 6 | 160,929 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.
Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).
To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.
String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.
For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically.
Input
The first line of the input contains a single integer n (2 β€ n β€ 100 000) β the number of strings.
The second line contains n integers ci (0 β€ ci β€ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string.
Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000.
Output
If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent.
Examples
Input
2
1 2
ba
ac
Output
1
Input
3
1 3 1
aa
ba
ac
Output
1
Input
2
5 5
bbb
aaa
Output
-1
Input
2
3 3
aaa
aa
Output
-1
Note
In the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.
In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1.
In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is - 1. | instruction | 0 | 80,465 | 6 | 160,930 |
Tags: dp, strings
Correct Solution:
```
n = int(input())
c = list(map(int,input().split()))
ver = (0, '')
rev = (0, '')
for i in range(n):
s = input().rstrip('\r\n')
r = s[::-1]
y = 1e16
n = 1e16
if ver[1] <= s:
n = ver[0]
if rev[1] <= s:
n = min(n, rev[0])
if ver[1] <= r:
y = ver[0] + c[i]
if rev[1] <= r:
y = min(y, rev[0] + c[i])
ver = (n, s)
rev = (y, r)
sol = min(ver[0], rev[0])
if sol < 1e15 :
print (sol)
else:
print (-1)
``` | output | 1 | 80,465 | 6 | 160,931 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.
Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).
To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.
String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.
For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically.
Input
The first line of the input contains a single integer n (2 β€ n β€ 100 000) β the number of strings.
The second line contains n integers ci (0 β€ ci β€ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string.
Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000.
Output
If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent.
Examples
Input
2
1 2
ba
ac
Output
1
Input
3
1 3 1
aa
ba
ac
Output
1
Input
2
5 5
bbb
aaa
Output
-1
Input
2
3 3
aaa
aa
Output
-1
Note
In the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.
In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1.
In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is - 1. | instruction | 0 | 80,466 | 6 | 160,932 |
Tags: dp, strings
Correct Solution:
```
n = int(input())
v = list(map(int,input().split()))
#print(v)
s = []
for i in range(n):
q = input()
l = []
l.append(q)
l.append("".join(reversed(q)))
s.append(l)
dp = [[1e18 for i in range(2)] for j in range(n)]
flag = 1
dp[0][0]=0
dp[0][1]=v[0]
for i in range(1,n):
if dp[i-1][0] == -1 and dp[i-1][1] == -1:
flag = 0
break
if dp[i-1][0] != -1:
if(s[i][0] >= s[i-1][0]):
dp[i][0] = min(dp[i][0],dp[i-1][0])
if s[i][1] >= s[i-1][0] :
dp[i][1] = min(dp[i][1], dp[i-1][0] + v[i])
if dp[i-1][1] != -1:
if(s[i][0] >= s[i-1][1]):
dp[i][0] = min(dp[i][0],dp[i-1][1])
if s[i][1] >= s[i-1][1] :
dp[i][1] = min(dp[i][1], dp[i-1][1] + v[i])
if dp[i][0] == 1e18:
dp[i][0] = -1
if dp[i][1] == 1e18 :
dp[i][1] = -1
if(flag == 0):
print(-1)
else :
if dp[n-1][0] != -1 and dp[n-1][1] != -1 :
print(min(dp[n-1][1], dp[n-1][0]))
else:
if(dp[n-1][1] != -1):
print(dp[n-1][1])
else :
print(dp[n-1][0])
``` | output | 1 | 80,466 | 6 | 160,933 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.