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.
The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows:
* employee ::= name. | name:employee1,employee2, ... ,employeek.
* name ::= name of an employee
That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description.
For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself.
In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is s writes a letter to another person whose name is also s. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates).
Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it.
<image>
Input
The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length.
Output
Print a single number — the number of uncomfortable situations in the company.
Examples
Input
MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY...
Output
3
Input
A:A..
Output
1
Input
A:C:C:C:C.....
Output
6
|
instruction
| 0
| 101,609
| 6
| 203,218
|
Tags: data structures, expression parsing, implementation
Correct Solution:
```
def main():
alpha = "QWERTYUIOPLKJHGFDSAZXCVBNM"
s = input()
n = len(s)
i = 0
st = []
ans = 0
while i < n:
j = i
if s[i] in alpha:
while j+1 < n and s[j+1] in alpha:
j += 1
name = s[i:j+1]
i = j
ans += st.count(name)
st.append(name)
elif s[i] == '.':
st.pop(-1)
i += 1
print(ans)
if __name__ == '__main__':
main()
```
|
output
| 1
| 101,609
| 6
| 203,219
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows:
* employee ::= name. | name:employee1,employee2, ... ,employeek.
* name ::= name of an employee
That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description.
For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself.
In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is s writes a letter to another person whose name is also s. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates).
Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it.
<image>
Input
The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length.
Output
Print a single number — the number of uncomfortable situations in the company.
Examples
Input
MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY...
Output
3
Input
A:A..
Output
1
Input
A:C:C:C:C.....
Output
6
|
instruction
| 0
| 101,610
| 6
| 203,220
|
Tags: data structures, expression parsing, implementation
Correct Solution:
```
s = input()
a = []
cnt = 0
s = ':' + s
s1 = ''
flag = False
for i in range(len(s)):
if flag:
if s[i] != '.' and s[i] != ':' and s[i] != ',':
s1 += s[i]
continue
else:
a.append(s1)
flag = False
for j in range(len(a) - 1):
if a[j] == a[-1]:
cnt += 1
if s[i] != '.' and s[i] != ':' and s[i] != ',':
flag = True
s1 = s[i]
elif s[i] == '.':
a.pop()
print(cnt)
# Made By Mostafa_Khaled
```
|
output
| 1
| 101,610
| 6
| 203,221
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows:
* employee ::= name. | name:employee1,employee2, ... ,employeek.
* name ::= name of an employee
That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description.
For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself.
In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is s writes a letter to another person whose name is also s. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates).
Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it.
<image>
Input
The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length.
Output
Print a single number — the number of uncomfortable situations in the company.
Examples
Input
MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY...
Output
3
Input
A:A..
Output
1
Input
A:C:C:C:C.....
Output
6
|
instruction
| 0
| 101,611
| 6
| 203,222
|
Tags: data structures, expression parsing, implementation
Correct Solution:
```
#!/usr/bin/env python3
tree = input().strip()
def get_answer(tree, start_index = 0, prev = []):
colon_index = tree.find(':', start_index)
period_index = tree.find('.', start_index)
name_end_index = colon_index if ((colon_index != -1) and (colon_index < period_index)) else period_index
name = tree[start_index:name_end_index]
answer = prev.count(name)
if ((colon_index == -1) or (period_index < colon_index)):
return (answer, period_index+1)
else:
# Recurse
prev_names = prev + [name]
next_start = colon_index
while tree[next_start] != '.':
(sub_answer, next_start) = get_answer(tree, next_start+1, prev_names)
answer += sub_answer
return (answer, next_start+1)
print(get_answer(tree)[0])
```
|
output
| 1
| 101,611
| 6
| 203,223
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows:
* employee ::= name. | name:employee1,employee2, ... ,employeek.
* name ::= name of an employee
That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description.
For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself.
In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is s writes a letter to another person whose name is also s. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates).
Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it.
<image>
Input
The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length.
Output
Print a single number — the number of uncomfortable situations in the company.
Examples
Input
MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY...
Output
3
Input
A:A..
Output
1
Input
A:C:C:C:C.....
Output
6
|
instruction
| 0
| 101,612
| 6
| 203,224
|
Tags: data structures, expression parsing, implementation
Correct Solution:
```
def main():
alpha = "QWERTYUIOPLKJHGFDSAZXCVBNM"
s = input()
n = len(s)
i = 0
st = ["root-0"]
name = ""
ans = 0
first = True
while i < n:
j = i
if s[i] in alpha:
while j+1 < n and s[j+1] in alpha:
j += 1
name = s[i:j+1]
first = True
i = j
ans += st.count(name)
elif s[i] == ":":
first = True
st.append(name)
elif s[i] == ',':
first = True
elif s[i] == '.' and first:
first = False
else:
st.pop(-1)
i += 1
print(ans)
if __name__ == '__main__':
main()
```
|
output
| 1
| 101,612
| 6
| 203,225
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows:
* employee ::= name. | name:employee1,employee2, ... ,employeek.
* name ::= name of an employee
That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description.
For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself.
In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is s writes a letter to another person whose name is also s. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates).
Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it.
<image>
Input
The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length.
Output
Print a single number — the number of uncomfortable situations in the company.
Examples
Input
MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY...
Output
3
Input
A:A..
Output
1
Input
A:C:C:C:C.....
Output
6
|
instruction
| 0
| 101,613
| 6
| 203,226
|
Tags: data structures, expression parsing, implementation
Correct Solution:
```
import sys
from array import array # noqa: F401
from collections import Counter
def input():
return sys.stdin.buffer.readline().decode('utf-8')
class Employee(object):
def __init__(self, name: str):
self.name = name
self.sub = []
def add_sub(self, sub: 'Employee'):
self.sub.append(sub)
def __repr__(self):
return self.name
stack = [Employee('*** God ***')] # type: list[Employee]
s = input().rstrip()
n, l = len(s), 0
while l < n:
if s[l] == '.':
stack.pop()
l += 1
continue
if s[l] == ',':
l += 1
continue
r = l
while 65 <= ord(s[r]) <= 90:
r += 1
e = Employee(s[l:r])
if stack:
stack[-1].add_sub(e)
if s[r] == ':':
stack.append(e)
l = r + 1
def rec(e: Employee):
count = 0
name_dict = Counter()
for sub in e.sub:
cnt, d = rec(sub)
count += cnt
for k, v in d.items():
name_dict[k] += v
count += name_dict[e.name]
name_dict[e.name] += 1
return count, name_dict
print(rec(stack[0])[0])
```
|
output
| 1
| 101,613
| 6
| 203,227
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows:
* employee ::= name. | name:employee1,employee2, ... ,employeek.
* name ::= name of an employee
That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description.
For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself.
In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is s writes a letter to another person whose name is also s. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates).
Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it.
<image>
Input
The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length.
Output
Print a single number — the number of uncomfortable situations in the company.
Examples
Input
MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY...
Output
3
Input
A:A..
Output
1
Input
A:C:C:C:C.....
Output
6
|
instruction
| 0
| 101,614
| 6
| 203,228
|
Tags: data structures, expression parsing, implementation
Correct Solution:
```
######directed
def dfs(graph,n,currnode,match):
visited=[False for x in range(n+1)]
stack=[currnode]
ans=0
while stack:
currnode=stack[-1]
if visited[currnode]==False:
visited[currnode]=True
if arr[currnode]==match:ans+=1
if currnode in graph:
for neighbour in graph[currnode]:
if visited[neighbour]==False:
visited[neighbour]=True
stack.append(neighbour)
if arr[neighbour]==match:ans+=1
break #####if we remove break it becomes bfs
else:
stack.pop() ####we are backtracking to previous node which is in our stack
else:
stack.pop()
return ans
def buildgraph(arr):
graph={}
currnode=0
graph[0]=[]
parent=[None for x in range(len(arr))]
i=2
while i in range(1,len(arr)):
if arr[i] not in look:
if currnode in graph:
graph[currnode].append(i)
else:
graph[currnode]=[i]
parent[i]=currnode
if arr[i+1]==":":
currnode=i
i+=2
else:
if arr[i]==".":
currnode=parent[currnode]
i+=1
return graph,parent
###main code
s=input()
arr=[]
dict={}
look={".",":",","}
name=""
for i in range(len(s)):
if s[i] not in look:
name+=s[i]
else:
if name!="":
arr.append(name)
name=""
arr.append(s[i])
else:
arr.append(s[i])
if len(arr)>2:
count=0
graph,parent=buildgraph(arr)
for i in range(len(arr)):
if arr[i] not in look:
count+=dfs(graph,len(arr),i,arr[i])
count-=1
print(count)
else:
print(0)
```
|
output
| 1
| 101,614
| 6
| 203,229
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows:
* employee ::= name. | name:employee1,employee2, ... ,employeek.
* name ::= name of an employee
That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description.
For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself.
In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is s writes a letter to another person whose name is also s. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates).
Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it.
<image>
Input
The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length.
Output
Print a single number — the number of uncomfortable situations in the company.
Examples
Input
MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY...
Output
3
Input
A:A..
Output
1
Input
A:C:C:C:C.....
Output
6
|
instruction
| 0
| 101,615
| 6
| 203,230
|
Tags: data structures, expression parsing, implementation
Correct Solution:
```
s = input()
a = []
cnt = 0
s = ':' + s
s1 = ''
flag = False
for i in range(len(s)):
if flag:
if s[i] != '.' and s[i] != ':' and s[i] != ',':
s1 += s[i]
continue
else:
a.append(s1)
flag = False
for j in range(len(a) - 1):
if a[j] == a[-1]:
cnt += 1
if s[i] != '.' and s[i] != ':' and s[i] != ',':
flag = True
s1 = s[i]
elif s[i] == '.':
a.pop()
print(cnt)
```
|
output
| 1
| 101,615
| 6
| 203,231
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows:
* employee ::= name. | name:employee1,employee2, ... ,employeek.
* name ::= name of an employee
That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description.
For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself.
In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is s writes a letter to another person whose name is also s. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates).
Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it.
<image>
Input
The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length.
Output
Print a single number — the number of uncomfortable situations in the company.
Examples
Input
MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY...
Output
3
Input
A:A..
Output
1
Input
A:C:C:C:C.....
Output
6
|
instruction
| 0
| 101,616
| 6
| 203,232
|
Tags: data structures, expression parsing, implementation
Correct Solution:
```
import re
a,ans=[],0
for x in re.split('[:,]',input()):
dl=x.count(".")
if dl==0:
ans+=a.count(x)
a+=[x]
else:
x=x[:-dl]
ans+=a.count(x)
a+=[x]
a=a[:-dl]
print(ans)
```
|
output
| 1
| 101,616
| 6
| 203,233
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows:
* employee ::= name. | name:employee1,employee2, ... ,employeek.
* name ::= name of an employee
That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description.
For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself.
In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is s writes a letter to another person whose name is also s. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates).
Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it.
<image>
Input
The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length.
Output
Print a single number — the number of uncomfortable situations in the company.
Examples
Input
MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY...
Output
3
Input
A:A..
Output
1
Input
A:C:C:C:C.....
Output
6
Submitted Solution:
```
from collections import defaultdict, Counter
def dfs(cur, counter, adj_list, visited):
neighbhours = []
if cur in adj_list.keys():
neighbhours = adj_list[cur]
# print("visting", cur)
# input()
cur = cur.split('-')[0]
ans = 0
ans += counter[cur]
counter[cur] += 1
for p in neighbhours:
if not visited[p]:
ans += dfs(p, counter, adj_list, visited)
counter[cur] -= 1
return ans
def main():
#sys.stdin = open('input.txt', 'r')
#sys.stdout = open('output.txt', 'w')
s = input()
n = len(s)
alpha = "QWERTYUIOPLKJHGFDSAZXCVBNM"
adj_list = defaultdict(lambda : [])
Counter_dict = {"root": 0}
visited = {"root": False}
i = 0
st = ["root-0"]
name = ""
ind = 0
while i < n:
# print(i)
# input()
j = i
if s[i] in alpha:
while j+1 < n and s[j+1] in alpha:
j += 1
name = s[i:j+1]
ind += 1
adj_list[st[-1]].append(name + "-" + str(ind))
Counter_dict[name] = 0
visited[name+"-"+str(ind)] = False
first = True
i = j
elif s[i] == ":":
first = True
st.append(name+"-"+str(ind))
elif s[i] == ',':
first = True
elif s[i] == '.' and first:
first = False
else:
st.pop(-1)
i += 1
# print("stack:", *st)
adj_list = dict(adj_list)
# for key in adj_list.keys():
# print(key, adj_list[key])
# print("counter", Counter_dict)
# print('visited', visited)
ans = dfs("root-0", Counter_dict, adj_list, visited)
print(ans)
if __name__ == '__main__':
main()
```
|
instruction
| 0
| 101,617
| 6
| 203,234
|
Yes
|
output
| 1
| 101,617
| 6
| 203,235
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows:
* employee ::= name. | name:employee1,employee2, ... ,employeek.
* name ::= name of an employee
That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description.
For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself.
In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is s writes a letter to another person whose name is also s. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates).
Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it.
<image>
Input
The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length.
Output
Print a single number — the number of uncomfortable situations in the company.
Examples
Input
MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY...
Output
3
Input
A:A..
Output
1
Input
A:C:C:C:C.....
Output
6
Submitted Solution:
```
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz'
M=10**9+7
EPS=1e-6
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
# vsInput()
for _ in range(1):
s=input()
n=len(s)
i=0
stack=[]
count=defaultdict(int)
i=0
ans=0
while(i<n):
# print(stack)
if(s[i] in '.'):
count[stack.pop()]-=1
i+=1
elif(s[i] in ':,'):
i+=1
pass
else:
name=s[i]
i+=1
while(i<n and s[i] not in',:.'):
name+=s[i]
i+=1
ans+=count[name]
count[name]+=1
stack.append(name)
print(ans)
```
|
instruction
| 0
| 101,618
| 6
| 203,236
|
Yes
|
output
| 1
| 101,618
| 6
| 203,237
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows:
* employee ::= name. | name:employee1,employee2, ... ,employeek.
* name ::= name of an employee
That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description.
For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself.
In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is s writes a letter to another person whose name is also s. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates).
Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it.
<image>
Input
The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length.
Output
Print a single number — the number of uncomfortable situations in the company.
Examples
Input
MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY...
Output
3
Input
A:A..
Output
1
Input
A:C:C:C:C.....
Output
6
Submitted Solution:
```
def P():
n=a[0];a.pop(0);d={n:1};r=0
while a[0]!='.':
a.pop(0);l,t=P();r+=l
for k in t.keys():
d[k]=d.get(k,0)+t[k]
if k==n:r+=t[k]
a.pop(0)
return r,d
a=[]
x=''
for i in input():
if i in ':.,':
if x:a+=[x]
a+=[i];x=''
else:x+=i
print(P()[0])
```
|
instruction
| 0
| 101,619
| 6
| 203,238
|
Yes
|
output
| 1
| 101,619
| 6
| 203,239
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows:
* employee ::= name. | name:employee1,employee2, ... ,employeek.
* name ::= name of an employee
That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description.
For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself.
In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is s writes a letter to another person whose name is also s. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates).
Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it.
<image>
Input
The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length.
Output
Print a single number — the number of uncomfortable situations in the company.
Examples
Input
MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY...
Output
3
Input
A:A..
Output
1
Input
A:C:C:C:C.....
Output
6
Submitted Solution:
```
from collections import defaultdict, Counter
def dfs(cur, counter, adj_list, visited):
neighbhours = []
if cur in adj_list.keys():
neighbhours = adj_list[cur]
# print("visting", cur)
# input()
cur = cur.split('-')[0]
ans = 0
ans += counter[cur]
counter[cur] += 1
for p in neighbhours:
if not visited[p]:
ans += dfs(p, counter, adj_list, visited)
counter[cur] -= 1
return ans
def main():
#sys.stdin = open('input.txt', 'r')
#sys.stdout = open('output.txt', 'w')
s = input()
n = len(s)
alpha = "QWERTYUIOPLKJHGFDSAZXCVBNM"
adj_list = defaultdict(lambda : [])
Counter_dict = {"root": 0}
visited = {"root": False}
i = 0
st = ["root-0"]
name = ""
ind = 1
while i < n:
# print(i)
# input()
j = i
if s[i] in alpha:
while j+1 < n and s[j+1] in alpha:
j += 1
name = s[i:j+1]
adj_list[st[-1]].append(name + "-" + str(ind))
first = True
i = j
Counter_dict[name] = 0
visited[name+"-"+str(ind)] = False
elif s[i] == ":":
first = True
st.append(name+"-"+str(ind))
ind += 1
elif s[i] == ',':
first = True
elif s[i] == '.' and first:
first = False
else:
st.pop(-1)
i += 1
# print("stack:", *st)
adj_list = dict(adj_list)
# for key in adj_list.keys():
# print(key, adj_list[key])
# print("counter", Counter_dict)
# print('visited', visited)
ans = dfs("root-0", Counter_dict, adj_list, visited)
print(ans)
if __name__ == '__main__':
main()
```
|
instruction
| 0
| 101,620
| 6
| 203,240
|
No
|
output
| 1
| 101,620
| 6
| 203,241
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of:
* Operation AND ('&', ASCII code 38)
* Operation OR ('|', ASCII code 124)
* Operation NOT ('!', ASCII code 33)
* Variables x, y and z (ASCII codes 120-122)
* Parentheses ('(', ASCII code 40, and ')', ASCII code 41)
If more than one expression of minimum length exists, you should find the lexicographically smallest one.
Operations have standard priority. NOT has the highest priority, then AND goes, and OR has the lowest priority. The expression should satisfy the following grammar:
E ::= E '|' T | T
T ::= T '&' F | F
F ::= '!' F | '(' E ')' | 'x' | 'y' | 'z'
Input
The first line contains one integer n — the number of functions in the input (1 ≤ n ≤ 10 000).
The following n lines contain descriptions of functions, the i-th of them contains a string of length 8 that consists of digits 0 and 1 — the truth table of the i-th function. The digit on position j (0 ≤ j < 8) equals to the value of the function in case of <image>, <image> and <image>.
Output
You should output n lines, the i-th line should contain the expression of minimum length which equals to the i-th function. If there is more than one such expression, output the lexicographically smallest of them. Expressions should satisfy the given grammar and shouldn't contain white spaces.
Example
Input
4
00110011
00000111
11110000
00011111
Output
y
(y|z)&x
!x
x|y&z
Note
The truth table for the second function:
<image>
|
instruction
| 0
| 101,746
| 6
| 203,492
|
Tags: bitmasks, dp, shortest paths
Correct Solution:
```
table = "!x&x x&y&z !z&x&y x&y !y&x&z x&z !y&x&z|!z&x&y (y|z)&x !y&!z&x !y&!z&x|x&y&z !z&x !z&x|x&y !y&x !y&x|x&z !(y&z)&x x !x&y&z y&z !x&y&z|!z&x&y (x|z)&y !x&y&z|!y&x&z (x|y)&z !x&y&z|!y&x&z|!z&x&y (x|y)&z|x&y !x&y&z|!y&!z&x !y&!z&x|y&z !x&y&z|!z&x !z&x|y&z !x&y&z|!y&x !y&x|y&z !(y&z)&x|!x&y&z x|y&z !x&!z&y !x&!z&y|x&y&z !z&y !z&y|x&y !x&!z&y|!y&x&z !x&!z&y|x&z !y&x&z|!z&y !z&y|x&z !(!x&!y|x&y|z) !(!x&!y|x&y|z)|x&y&z !z&(x|y) !z&(x|y)|x&y !x&!z&y|!y&x !x&!z&y|!y&x|x&z !y&x|!z&y !z&y|x !x&y !x&y|y&z !(x&z)&y y !x&y|!y&x&z !x&y|x&z !(x&z)&y|!y&x&z x&z|y !x&y|!y&!z&x !x&y|!y&!z&x|y&z !x&y|!z&x !z&x|y !x&y|!y&x !x&y|!y&x|x&z !(x&z)&y|!y&x x|y !x&!y&z !x&!y&z|x&y&z !x&!y&z|!z&x&y !x&!y&z|x&y !y&z !y&z|x&z !y&z|!z&x&y !y&z|x&y !(!x&!z|x&z|y) !(!x&!z|x&z|y)|x&y&z !x&!y&z|!z&x !x&!y&z|!z&x|x&y !y&(x|z) !y&(x|z)|x&z !y&z|!z&x !y&z|x !x&z !x&z|y&z !x&z|!z&x&y !x&z|x&y !(x&y)&z z !(x&y)&z|!z&x&y x&y|z !x&z|!y&!z&x !x&z|!y&!z&x|y&z !x&z|!z&x !x&z|!z&x|x&y !x&z|!y&x !y&x|z !(x&y)&z|!z&x x|z !(!y&!z|x|y&z) !(!y&!z|x|y&z)|x&y&z !x&!y&z|!z&y !x&!y&z|!z&y|x&y !x&!z&y|!y&z !x&!z&y|!y&z|x&z !y&z|!z&y !y&z|!z&y|x&y !(!x&!y|x&y|z)|!x&!y&z !(!x&!y|x&y|z)|!x&!y&z|x&y&z !x&!y&z|!z&(x|y) !x&!y&z|!z&(x|y)|x&y !x&!z&y|!y&(x|z) !x&!z&y|!y&(x|z)|x&z !y&(x|z)|!z&y !y&z|!z&y|x !x&(y|z) !x&(y|z)|y&z !x&z|!z&y !x&z|y !x&y|!y&z !x&y|z !(x&y)&z|!z&y y|z !x&(y|z)|!y&!z&x !x&(y|z)|!y&!z&x|y&z !x&(y|z)|!z&x !x&z|!z&x|y !x&(y|z)|!y&x !x&y|!y&x|z !x&y|!y&z|!z&x x|y|z !(x|y|z) !(x|y|z)|x&y&z !(!x&y|!y&x|z) !(x|y|z)|x&y !(!x&z|!z&x|y) !(x|y|z)|x&z !(!x&y|!y&x|z)|!y&x&z !(x|y|z)|(y|z)&x !y&!z !y&!z|x&y&z !(!x&y|z) !y&!z|x&y !(!x&z|y) !y&!z|x&z !(!x&y|z)|!y&x !y&!z|x !(!y&z|!z&y|x) !(x|y|z)|y&z !(!x&y|!y&x|z)|!x&y&z !(x|y|z)|(x|z)&y !(!x&z|!z&x|y)|!x&y&z !(x|y|z)|(x|y)&z !(!x&y|!y&x|z)|!x&y&z|!y&x&z !(x|y|z)|(x|y)&z|x&y !x&y&z|!y&!z !y&!z|y&z !(!x&y|z)|!x&y&z !(!x&y|z)|y&z !(!x&z|y)|!x&y&z !(!x&z|y)|y&z !(!x&y|z)|!x&y&z|!y&x !y&!z|x|y&z !x&!z !x&!z|x&y&z !(!y&x|z) !x&!z|x&y !x&!z|!y&x&z !x&!z|x&z !(!y&x|z)|!y&x&z !(!y&x|z)|x&z !(x&y|z) !(x&y|z)|x&y&z !z !z|x&y !x&!z|!y&x !(x&y|z)|x&z !y&x|!z !z|x !(!y&z|x) !x&!z|y&z !(!y&x|z)|!x&y !x&!z|y !(!y&z|x)|!y&x&z !(!y&z|x)|x&z !(!y&x|z)|!x&y|!y&x&z !x&!z|x&z|y !x&y|!y&!z !(x&y|z)|y&z !x&y|!z !z|y !(!x&!y&z|x&y) !x&!z|!y&x|y&z !x&y|!y&x|!z !z|x|y !x&!y !x&!y|x&y&z !x&!y|!z&x&y !x&!y|x&y !(!z&x|y) !x&!y|x&z !(!z&x|y)|!z&x&y !(!z&x|y)|x&y !(x&z|y) !(x&z|y)|x&y&z !x&!y|!z&x !(x&z|y)|x&y !y !y|x&z !y|!z&x !y|x !(!z&y|x) !x&!y|y&z !(!z&y|x)|!z&x&y !(!z&y|x)|x&y !(!z&x|y)|!x&z !x&!y|z !(!z&x|y)|!x&z|!z&x&y !x&!y|x&y|z !x&z|!y&!z !(x&z|y)|y&z !(!x&!z&y|x&z) !x&!y|!z&x|y&z !x&z|!y !y|z !x&z|!y|!z&x !y|x|z !(x|y&z) !(x|y&z)|x&y&z !x&!y|!z&y !(x|y&z)|x&y !x&!z|!y&z !(x|y&z)|x&z !(!y&!z&x|y&z) !x&!y|!z&y|x&z !((x|y)&z|x&y) !((x|y)&z|x&y)|x&y&z !x&!y|!z !x&!y|!z|x&y !x&!z|!y !x&!z|!y|x&z !y|!z !y|!z|x !x !x|y&z !x|!z&y !x|y !x|!y&z !x|z !x|!y&z|!z&y !x|y|z !x|!y&!z !x|!y&!z|y&z !x|!z !x|!z|y !x|!y !x|!y|z !(x&y&z) !x|x".split()
n = int(input())
for i in range(n):
print(table[int(input(), 2)])
exit(0)
E = set()
T = set()
F = set('xyz')
prv = 0
x = int('00001111', 2)
y = int('00110011', 2)
z = int('01010101', 2)
fam = 2 ** 8
tmpl = '#' * 99
ans = [tmpl] * fam
def cmpr(E):
global ans
ans = [tmpl] * fam
for e in E:
res = eval(e.replace('!', '~')) & (fam - 1)
if len(ans[res]) > len(e) or len(ans[res]) == len(e) and ans[res] > e:
ans[res] = e
return set(ans) - {tmpl}
def cmpr3(E, T, F):
return cmpr(E), cmpr(T), cmpr(F)
while prv != (E, T, F):
prv = E.copy(), T.copy(), F.copy()
for f in prv[2]:
F.add('!' + f)
T.add(f)
for t in prv[1]:
T.add(t + '&' + f)
for t in prv[1]:
E.add(t)
for e in prv[0]:
if e not in F:
F.add('(' + e + ')')
for t in prv[1]:
E.add(e + '|' + t)
E, T, F = cmpr3(E, T, F)
cmpr(E)
for f in ans:
print(f)
print(ans.count(tmpl), fam - ans.count(tmpl))
```
|
output
| 1
| 101,746
| 6
| 203,493
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of:
* Operation AND ('&', ASCII code 38)
* Operation OR ('|', ASCII code 124)
* Operation NOT ('!', ASCII code 33)
* Variables x, y and z (ASCII codes 120-122)
* Parentheses ('(', ASCII code 40, and ')', ASCII code 41)
If more than one expression of minimum length exists, you should find the lexicographically smallest one.
Operations have standard priority. NOT has the highest priority, then AND goes, and OR has the lowest priority. The expression should satisfy the following grammar:
E ::= E '|' T | T
T ::= T '&' F | F
F ::= '!' F | '(' E ')' | 'x' | 'y' | 'z'
Input
The first line contains one integer n — the number of functions in the input (1 ≤ n ≤ 10 000).
The following n lines contain descriptions of functions, the i-th of them contains a string of length 8 that consists of digits 0 and 1 — the truth table of the i-th function. The digit on position j (0 ≤ j < 8) equals to the value of the function in case of <image>, <image> and <image>.
Output
You should output n lines, the i-th line should contain the expression of minimum length which equals to the i-th function. If there is more than one such expression, output the lexicographically smallest of them. Expressions should satisfy the given grammar and shouldn't contain white spaces.
Example
Input
4
00110011
00000111
11110000
00011111
Output
y
(y|z)&x
!x
x|y&z
Note
The truth table for the second function:
<image>
|
instruction
| 0
| 101,747
| 6
| 203,494
|
Tags: bitmasks, dp, shortest paths
Correct Solution:
```
answers = [
'!x&x',
'x&y&z',
'!z&x&y',
'x&y',
'!y&x&z',
'x&z',
'!y&x&z|!z&x&y',
'(y|z)&x',
'!y&!z&x',
'!y&!z&x|x&y&z',
'!z&x',
'!z&x|x&y',
'!y&x',
'!y&x|x&z',
'!(y&z)&x',
'x',
'!x&y&z',
'y&z',
'!x&y&z|!z&x&y',
'(x|z)&y',
'!x&y&z|!y&x&z',
'(x|y)&z',
'!x&y&z|!y&x&z|!z&x&y',
'(x|y)&z|x&y',
'!x&y&z|!y&!z&x',
'!y&!z&x|y&z',
'!x&y&z|!z&x',
'!z&x|y&z',
'!x&y&z|!y&x',
'!y&x|y&z',
'!(y&z)&x|!x&y&z',
'x|y&z',
'!x&!z&y',
'!x&!z&y|x&y&z',
'!z&y',
'!z&y|x&y',
'!x&!z&y|!y&x&z',
'!x&!z&y|x&z',
'!y&x&z|!z&y',
'!z&y|x&z',
'!(!x&!y|x&y|z)',
'!(!x&!y|x&y|z)|x&y&z',
'!z&(x|y)',
'!z&(x|y)|x&y',
'!x&!z&y|!y&x',
'!x&!z&y|!y&x|x&z',
'!y&x|!z&y',
'!z&y|x',
'!x&y',
'!x&y|y&z',
'!(x&z)&y',
'y',
'!x&y|!y&x&z',
'!x&y|x&z',
'!(x&z)&y|!y&x&z',
'x&z|y',
'!x&y|!y&!z&x',
'!x&y|!y&!z&x|y&z',
'!x&y|!z&x',
'!z&x|y',
'!x&y|!y&x',
'!x&y|!y&x|x&z',
'!(x&z)&y|!y&x',
'x|y',
'!x&!y&z',
'!x&!y&z|x&y&z',
'!x&!y&z|!z&x&y',
'!x&!y&z|x&y',
'!y&z',
'!y&z|x&z',
'!y&z|!z&x&y',
'!y&z|x&y',
'!(!x&!z|x&z|y)',
'!(!x&!z|x&z|y)|x&y&z',
'!x&!y&z|!z&x',
'!x&!y&z|!z&x|x&y',
'!y&(x|z)',
'!y&(x|z)|x&z',
'!y&z|!z&x',
'!y&z|x',
'!x&z',
'!x&z|y&z',
'!x&z|!z&x&y',
'!x&z|x&y',
'!(x&y)&z',
'z',
'!(x&y)&z|!z&x&y',
'x&y|z',
'!x&z|!y&!z&x',
'!x&z|!y&!z&x|y&z',
'!x&z|!z&x',
'!x&z|!z&x|x&y',
'!x&z|!y&x',
'!y&x|z',
'!(x&y)&z|!z&x',
'x|z',
'!(!y&!z|x|y&z)',
'!(!y&!z|x|y&z)|x&y&z',
'!x&!y&z|!z&y',
'!x&!y&z|!z&y|x&y',
'!x&!z&y|!y&z',
'!x&!z&y|!y&z|x&z',
'!y&z|!z&y',
'!y&z|!z&y|x&y',
'!(!x&!y|x&y|z)|!x&!y&z',
'!(!x&!y|x&y|z)|!x&!y&z|x&y&z',
'!x&!y&z|!z&(x|y)',
'!x&!y&z|!z&(x|y)|x&y',
'!x&!z&y|!y&(x|z)',
'!x&!z&y|!y&(x|z)|x&z',
'!y&(x|z)|!z&y',
'!y&z|!z&y|x',
'!x&(y|z)',
'!x&(y|z)|y&z',
'!x&z|!z&y',
'!x&z|y',
'!x&y|!y&z',
'!x&y|z',
'!(x&y)&z|!z&y',
'y|z',
'!x&(y|z)|!y&!z&x',
'!x&(y|z)|!y&!z&x|y&z',
'!x&(y|z)|!z&x',
'!x&z|!z&x|y',
'!x&(y|z)|!y&x',
'!x&y|!y&x|z',
'!x&y|!y&z|!z&x',
'x|y|z',
'!(x|y|z)',
'!(x|y|z)|x&y&z',
'!(!x&y|!y&x|z)',
'!(x|y|z)|x&y',
'!(!x&z|!z&x|y)',
'!(x|y|z)|x&z',
'!(!x&y|!y&x|z)|!y&x&z',
'!(x|y|z)|(y|z)&x',
'!y&!z',
'!y&!z|x&y&z',
'!(!x&y|z)',
'!y&!z|x&y',
'!(!x&z|y)',
'!y&!z|x&z',
'!(!x&y|z)|!y&x',
'!y&!z|x',
'!(!y&z|!z&y|x)',
'!(x|y|z)|y&z',
'!(!x&y|!y&x|z)|!x&y&z',
'!(x|y|z)|(x|z)&y',
'!(!x&z|!z&x|y)|!x&y&z',
'!(x|y|z)|(x|y)&z',
'!(!x&y|!y&x|z)|!x&y&z|!y&x&z',
'!(x|y|z)|(x|y)&z|x&y',
'!x&y&z|!y&!z',
'!y&!z|y&z',
'!(!x&y|z)|!x&y&z',
'!(!x&y|z)|y&z',
'!(!x&z|y)|!x&y&z',
'!(!x&z|y)|y&z',
'!(!x&y|z)|!x&y&z|!y&x',
'!y&!z|x|y&z',
'!x&!z',
'!x&!z|x&y&z',
'!(!y&x|z)',
'!x&!z|x&y',
'!x&!z|!y&x&z',
'!x&!z|x&z',
'!(!y&x|z)|!y&x&z',
'!(!y&x|z)|x&z',
'!(x&y|z)',
'!(x&y|z)|x&y&z',
'!z',
'!z|x&y',
'!x&!z|!y&x',
'!(x&y|z)|x&z',
'!y&x|!z',
'!z|x',
'!(!y&z|x)',
'!x&!z|y&z',
'!(!y&x|z)|!x&y',
'!x&!z|y',
'!(!y&z|x)|!y&x&z',
'!(!y&z|x)|x&z',
'!(!y&x|z)|!x&y|!y&x&z',
'!x&!z|x&z|y',
'!x&y|!y&!z',
'!(x&y|z)|y&z',
'!x&y|!z',
'!z|y',
'!(!x&!y&z|x&y)',
'!x&!z|!y&x|y&z',
'!x&y|!y&x|!z',
'!z|x|y',
'!x&!y',
'!x&!y|x&y&z',
'!x&!y|!z&x&y',
'!x&!y|x&y',
'!(!z&x|y)',
'!x&!y|x&z',
'!(!z&x|y)|!z&x&y',
'!(!z&x|y)|x&y',
'!(x&z|y)',
'!(x&z|y)|x&y&z',
'!x&!y|!z&x',
'!(x&z|y)|x&y',
'!y',
'!y|x&z',
'!y|!z&x',
'!y|x',
'!(!z&y|x)',
'!x&!y|y&z',
'!(!z&y|x)|!z&x&y',
'!(!z&y|x)|x&y',
'!(!z&x|y)|!x&z',
'!x&!y|z',
'!(!z&x|y)|!x&z|!z&x&y',
'!x&!y|x&y|z',
'!x&z|!y&!z',
'!(x&z|y)|y&z',
'!(!x&!z&y|x&z)',
'!x&!y|!z&x|y&z',
'!x&z|!y',
'!y|z',
'!x&z|!y|!z&x',
'!y|x|z',
'!(x|y&z)',
'!(x|y&z)|x&y&z',
'!x&!y|!z&y',
'!(x|y&z)|x&y',
'!x&!z|!y&z',
'!(x|y&z)|x&z',
'!(!y&!z&x|y&z)',
'!x&!y|!z&y|x&z',
'!((x|y)&z|x&y)',
'!((x|y)&z|x&y)|x&y&z',
'!x&!y|!z',
'!x&!y|!z|x&y',
'!x&!z|!y',
'!x&!z|!y|x&z',
'!y|!z',
'!y|!z|x',
'!x',
'!x|y&z',
'!x|!z&y',
'!x|y',
'!x|!y&z',
'!x|z',
'!x|!y&z|!z&y',
'!x|y|z',
'!x|!y&!z',
'!x|!y&!z|y&z',
'!x|!z',
'!x|!z|y',
'!x|!y',
'!x|!y|z',
'!(x&y&z)',
'!x|x']
N = int(input())
for i in range(N):
q = int(input(), 2)
print(answers[q])
```
|
output
| 1
| 101,747
| 6
| 203,495
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of:
* Operation AND ('&', ASCII code 38)
* Operation OR ('|', ASCII code 124)
* Operation NOT ('!', ASCII code 33)
* Variables x, y and z (ASCII codes 120-122)
* Parentheses ('(', ASCII code 40, and ')', ASCII code 41)
If more than one expression of minimum length exists, you should find the lexicographically smallest one.
Operations have standard priority. NOT has the highest priority, then AND goes, and OR has the lowest priority. The expression should satisfy the following grammar:
E ::= E '|' T | T
T ::= T '&' F | F
F ::= '!' F | '(' E ')' | 'x' | 'y' | 'z'
Input
The first line contains one integer n — the number of functions in the input (1 ≤ n ≤ 10 000).
The following n lines contain descriptions of functions, the i-th of them contains a string of length 8 that consists of digits 0 and 1 — the truth table of the i-th function. The digit on position j (0 ≤ j < 8) equals to the value of the function in case of <image>, <image> and <image>.
Output
You should output n lines, the i-th line should contain the expression of minimum length which equals to the i-th function. If there is more than one such expression, output the lexicographically smallest of them. Expressions should satisfy the given grammar and shouldn't contain white spaces.
Example
Input
4
00110011
00000111
11110000
00011111
Output
y
(y|z)&x
!x
x|y&z
Note
The truth table for the second function:
<image>
|
instruction
| 0
| 101,748
| 6
| 203,496
|
Tags: bitmasks, dp, shortest paths
Correct Solution:
```
sol = {'01010101': 'z', '00110011': 'y', '00001111': 'x', '10101010': '!z', '11001100': '!y', '11110000': '!x', '01110111': 'y|z', '01011111': 'x|z', '00010001': 'y&z', '00000101': 'x&z', '00111111': 'x|y', '00000011': 'x&y', '11111111': '!x|x', '11011101': '!y|z', '11110101': '!x|z', '00000000': '!x&x', '01000100': '!y&z', '01010000': '!x&z', '10111011': '!z|y', '11110011': '!x|y', '00100010': '!z&y', '00110000': '!x&y', '10101111': '!z|x', '11001111': '!y|x', '00001010': '!z&x', '00001100': '!y&x', '01111111': 'x|y|z', '01010111': 'x&y|z', '00011111': 'x|y&z', '00000001': 'x&y&z', '00110111': 'x&z|y', '11110111': '!x|y|z', '01110101': '!x&y|z', '11011111': '!y|x|z', '01011101': '!y&x|z', '11110001': '!x|y&z', '00010000': '!x&y&z', '11001101': '!y|x&z', '00000100': '!y&x&z', '01110011': '!x&z|y', '10111111': '!z|x|y', '00111011': '!z&x|y', '10101011': '!z|x&y', '00000010': '!z&x&y', '01001111': '!y&z|x', '00101111': '!z&y|x', '10001000': '!y&!z', '10100000': '!x&!z', '11101110': '!y|!z', '11111010': '!x|!z', '11000000': '!x&!y', '11111100': '!x|!y', '00010101': '(x|y)&z', '00010011': '(x|z)&y', '00000111': '(y|z)&x', '11010101': '!x&!y|z', '11111101': '!x|!y|z', '01010001': '!x&z|y&z', '00110001': '!x&y|y&z', '00011011': '!z&x|y&z', '00011101': '!y&x|y&z', '01000101': '!y&z|x&z', '00100111': '!z&y|x&z', '00110101': '!x&y|x&z', '00001101': '!y&x|x&z', '01000000': '!x&!y&z', '01010100': '!(x&y)&z', '10110011': '!x&!z|y', '11111011': '!x|!z|y', '01000111': '!y&z|x&y', '01010011': '!x&z|x&y', '00100011': '!z&y|x&y', '00001011': '!z&x|x&y', '00100000': '!x&!z&y', '00110010': '!(x&z)&y', '10001111': '!y&!z|x', '11101111': '!y|!z|x', '00001000': '!y&!z&x', '00001110': '!(y&z)&x', '10000000': '!(x|y|z)', '01110000': '!x&(y|z)', '10101000': '!(x&y|z)', '01001100': '!y&(x|z)', '11100000': '!(x|y&z)', '11111110': '!(x&y&z)', '11001000': '!(x&z|y)', '00101010': '!z&(x|y)', '10100010': '!(!y&x|z)', '10111010': '!x&y|!z', '10001010': '!(!x&y|z)', '10101110': '!y&x|!z', '10110001': '!x&!z|y&z', '10001101': '!y&!z|x&z', '11101010': '!x&!y|!z', '00011001': '!y&!z&x|y&z', '00100101': '!x&!z&y|x&z', '11000100': '!(!z&x|y)', '11011100': '!x&z|!y', '10001100': '!(!x&z|y)', '11001110': '!y|!z&x', '11010001': '!x&!y|y&z', '10001011': '!y&!z|x&y', '11101100': '!x&!z|!y', '01000011': '!x&!y&z|x&y', '11010000': '!(!z&y|x)', '11110100': '!x|!y&z', '10110000': '!(!y&z|x)', '11110010': '!x|!z&y', '11000101': '!x&!y|x&z', '10100011': '!x&!z|x&y', '11111000': '!x|!y&!z', '00010111': '(x|y)&z|x&y', '01110001': '!x&(y|z)|y&z', '01100110': '!y&z|!z&y', '01110010': '!x&z|!z&y', '01110100': '!x&y|!y&z', '01101111': '!y&z|!z&y|x', '01100111': '!y&z|!z&y|x&y', '00000110': '!y&x&z|!z&x&y', '01100000': '!(!y&!z|x|y&z)', '01110110': '!(x&y)&z|!z&y', '01001101': '!y&(x|z)|x&z', '01001110': '!y&z|!z&x', '01011010': '!x&z|!z&x', '01011100': '!x&z|!y&x', '01111011': '!x&z|!z&x|y', '01011011': '!x&z|!z&x|x&y', '00010010': '!x&y&z|!z&x&y', '01011110': '!(x&y)&z|!z&x', '01001000': '!(!x&!z|x&z|y)', '10011001': '!y&!z|y&z', '10011111': '!y&!z|x|y&z', '10010001': '!(x|y|z)|y&z', '10111001': '!(x&y|z)|y&z', '11011001': '!(x&z|y)|y&z', '10100101': '!x&!z|x&z', '10110111': '!x&!z|x&z|y', '10000101': '!(x|y|z)|x&z', '10101101': '!(x&y|z)|x&z', '11100101': '!(x|y&z)|x&z', '00101011': '!z&(x|y)|x&y', '00101110': '!y&x|!z&y', '00111010': '!x&y|!z&x', '00111100': '!x&y|!y&x', '01111101': '!x&y|!y&x|z', '00111101': '!x&y|!y&x|x&z', '00010100': '!x&y&z|!y&x&z', '00101000': '!(!x&!y|x&y|z)', '00111110': '!(x&z)&y|!y&x', '11000011': '!x&!y|x&y', '11010111': '!x&!y|x&y|z', '10000011': '!(x|y|z)|x&y', '11100011': '!(x|y&z)|x&y', '11001011': '!(x&z|y)|x&y', '10011101': '!(!x&z|y)|y&z', '10001001': '!y&!z|x&y&z', '11011000': '!x&z|!y&!z', '00001001': '!y&!z&x|x&y&z', '10110101': '!(!y&z|x)|x&z', '10100001': '!x&!z|x&y&z', '11100100': '!x&!z|!y&z', '00100001': '!x&!z&y|x&y&z', '01000110': '!y&z|!z&x&y', '01100100': '!x&!z&y|!y&z', '01101110': '!y&(x|z)|!z&y', '01010010': '!x&z|!z&x&y', '01011000': '!x&z|!y&!z&x', '01111010': '!x&(y|z)|!z&x', '10011011': '!(!x&y|z)|y&z', '10111000': '!x&y|!y&!z', '11010011': '!(!z&y|x)|x&y', '11000001': '!x&!y|x&y&z', '11100010': '!x&!y|!z&y', '01000001': '!x&!y&z|x&y&z', '00100110': '!y&x&z|!z&y', '01100010': '!x&!y&z|!z&y', '00110100': '!x&y|!y&x&z', '00111000': '!x&y|!y&!z&x', '01111100': '!x&(y|z)|!y&x', '10100111': '!(!y&x|z)|x&z', '10101100': '!x&!z|!y&x', '11000111': '!(!z&x|y)|x&y', '11001010': '!x&!y|!z&x', '00011010': '!x&y&z|!z&x', '01001010': '!x&!y&z|!z&x', '00011100': '!x&y&z|!y&x', '00101100': '!x&!z&y|!y&x', '01111110': '!x&y|!y&z|!z&x', '01010110': '!(x&y)&z|!z&x&y', '00011110': '!(y&z)&x|!x&y&z', '10000001': '!(x|y|z)|x&y&z', '10101001': '!(x&y|z)|x&y&z', '11100001': '!(x|y&z)|x&y&z', '11001001': '!(x&z|y)|x&y&z', '00110110': '!(x&z)&y|!y&x&z', '11100110': '!(!y&!z&x|y&z)', '10000111': '!(x|y|z)|(y|z)&x', '11100111': '!x&!y|!z&y|x&z', '11110110': '!x|!y&z|!z&y', '01100101': '!x&!z&y|!y&z|x&z', '11011010': '!(!x&!z&y|x&z)', '10010011': '!(x|y|z)|(x|z)&y', '11011011': '!x&!y|!z&x|y&z', '11011110': '!x&z|!y|!z&x', '01011001': '!x&z|!y&!z&x|y&z', '11111001': '!x|!y&!z|y&z', '10011000': '!x&y&z|!y&!z', '00011000': '!x&y&z|!y&!z&x', '10010000': '!(!y&z|!z&y|x)', '11101101': '!x&!z|!y|x&z', '10100100': '!x&!z|!y&x&z', '00100100': '!x&!z&y|!y&x&z', '10000100': '!(!x&z|!z&x|y)', '01100011': '!x&!y&z|!z&y|x&y', '10111100': '!(!x&!y&z|x&y)', '10010101': '!(x|y|z)|(x|y)&z', '10111101': '!x&!z|!y&x|y&z', '10111110': '!x&y|!y&x|!z', '00111001': '!x&y|!y&!z&x|y&z', '11101011': '!x&!y|!z|x&y', '11000010': '!x&!y|!z&x&y', '01000010': '!x&!y&z|!z&x&y', '10000010': '!(!x&y|!y&x|z)', '01001011': '!x&!y&z|!z&x|x&y', '00101101': '!x&!z&y|!y&x|x&z', '10001110': '!(!x&y|z)|!y&x', '11101000': '!((x|y)&z|x&y)', '10110010': '!(!y&x|z)|!x&y', '11010100': '!(!z&x|y)|!x&z', '01101010': '!x&!y&z|!z&(x|y)', '01101100': '!x&!z&y|!y&(x|z)', '01111000': '!x&(y|z)|!y&!z&x', '00010110': '!x&y&z|!y&x&z|!z&x&y', '01100001': '!(!y&!z|x|y&z)|x&y&z', '01001001': '!(!x&!z|x&z|y)|x&y&z', '10010111': '!(x|y|z)|(x|y)&z|x&y', '01111001': '!x&(y|z)|!y&!z&x|y&z', '01101101': '!x&!z&y|!y&(x|z)|x&z', '00101001': '!(!x&!y|x&y|z)|x&y&z', '01101011': '!x&!y&z|!z&(x|y)|x&y', '10011100': '!(!x&z|y)|!x&y&z', '10110100': '!(!y&z|x)|!y&x&z', '11000110': '!(!z&x|y)|!z&x&y', '11010010': '!(!z&y|x)|!z&x&y', '10011010': '!(!x&y|z)|!x&y&z', '10100110': '!(!y&x|z)|!y&x&z', '01101000': '!(!x&!y|x&y|z)|!x&!y&z', '11101001': '!((x|y)&z|x&y)|x&y&z', '11010110': '!(!z&x|y)|!x&z|!z&x&y', '10110110': '!(!y&x|z)|!x&y|!y&x&z', '10000110': '!(!x&y|!y&x|z)|!y&x&z', '10011110': '!(!x&y|z)|!x&y&z|!y&x', '10010010': '!(!x&y|!y&x|z)|!x&y&z', '10010100': '!(!x&z|!z&x|y)|!x&y&z', '01101001': '!(!x&!y|x&y|z)|!x&!y&z|x&y&z', '10010110': '!(!x&y|!y&x|z)|!x&y&z|!y&x&z'}
n = int(input())
for i in range(n):
print(sol[input()])
```
|
output
| 1
| 101,748
| 6
| 203,497
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of:
* Operation AND ('&', ASCII code 38)
* Operation OR ('|', ASCII code 124)
* Operation NOT ('!', ASCII code 33)
* Variables x, y and z (ASCII codes 120-122)
* Parentheses ('(', ASCII code 40, and ')', ASCII code 41)
If more than one expression of minimum length exists, you should find the lexicographically smallest one.
Operations have standard priority. NOT has the highest priority, then AND goes, and OR has the lowest priority. The expression should satisfy the following grammar:
E ::= E '|' T | T
T ::= T '&' F | F
F ::= '!' F | '(' E ')' | 'x' | 'y' | 'z'
Input
The first line contains one integer n — the number of functions in the input (1 ≤ n ≤ 10 000).
The following n lines contain descriptions of functions, the i-th of them contains a string of length 8 that consists of digits 0 and 1 — the truth table of the i-th function. The digit on position j (0 ≤ j < 8) equals to the value of the function in case of <image>, <image> and <image>.
Output
You should output n lines, the i-th line should contain the expression of minimum length which equals to the i-th function. If there is more than one such expression, output the lexicographically smallest of them. Expressions should satisfy the given grammar and shouldn't contain white spaces.
Example
Input
4
00110011
00000111
11110000
00011111
Output
y
(y|z)&x
!x
x|y&z
Note
The truth table for the second function:
<image>
|
instruction
| 0
| 101,749
| 6
| 203,498
|
Tags: bitmasks, dp, shortest paths
Correct Solution:
```
import zlib, base64
exec(zlib.decompress(base64.b64decode(b'eJyFV8lu2zAQPTdfIenAUGhR9FygXxLk4MJu4SJwAscJSIEfX4nLzHtDpT0kGM6+j3w83IYfw8M0BhemL8M0+pBiWuYMBzdGtwjYgMUpWGRWtnFJq6Srkh7g4JqSjW9Jm3wKjdYohIzALkivfuX/m02nYBUJ2ZNVLjZPAM5hrFTR5BFGasLg/RbOvPniIsSU0AXAtMgMnanRShPVFx+QA+jRad5CyWhoMUbIqCBL0RII5jSZd+Fg+sLB7dpNWOItRcaFNKqVyFpKgdkR9ELB2PpzhIJGt1amli/aSDlOQ1W5ymHiJFsYYHCkD0VZsMSmDSMl1XpmYM2R9HtTwgOYgCe3KLwXmJUdMRaiID+w28WKfGVICbfyzMaHNKq36IWCC+Qp7gTLoVYRL+28GH6Pjb7JmDjJ1l6AsDu2CGFzJR5RM58wnDCZ/8it9nlXgzYrihNlNr2dFmUoamj1pv961Y93meJ9B62u0gF2rkXzB3qlJziEzfWuYFHWPJQLSrNZExXlgesBaI1S7dDm4v6AYYZkwNRD40AGaBck3vYLibQi4e7Mpzdhf7YtAgh+loaltc0HVw5zYkuEsS7ggJBtuAiJjOrDswaBanOqF9E6C7ebnO0wdKn5+BjM3k1HOl5245pj1yknlqH5iOnZ4TG5pSsPGSN7oesOHf3AbWGaglqiO/MpdM2Q3zUjZBNwYFBD7Q46XvMWlWxICAFca8Mq7x2nQwpdqS0Pa6nXHaxAQUZTtby1qnH+YLH6sFyySaV6qRYumsLpNS4dRyPdzjkSFitEDDDFtXB6irVwggtgVE55RYBFZW4rWm62iMd91wK4JjOL11vfO9LMUS85aODCdWuK7Mu3g7BkuNqOLKSfJwXMY8k/hxLiokkkR2bGIdiZtTWOCWVgH+1NYMPDXMl+q8siUffUp05hY4Q6alBt8DSSVi3jvlzTAppNKU8dpwppDSokDq2uhenx7tfzdTgP58twPVx+n/z5clv/Xt5ufp7n73efXq4b5ni4PZzeD09++vZzGj4P9/df/zyfL/7p/Hrz19P76fp6OqrcPD/Od38BvToehw==')))
```
|
output
| 1
| 101,749
| 6
| 203,499
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of:
* Operation AND ('&', ASCII code 38)
* Operation OR ('|', ASCII code 124)
* Operation NOT ('!', ASCII code 33)
* Variables x, y and z (ASCII codes 120-122)
* Parentheses ('(', ASCII code 40, and ')', ASCII code 41)
If more than one expression of minimum length exists, you should find the lexicographically smallest one.
Operations have standard priority. NOT has the highest priority, then AND goes, and OR has the lowest priority. The expression should satisfy the following grammar:
E ::= E '|' T | T
T ::= T '&' F | F
F ::= '!' F | '(' E ')' | 'x' | 'y' | 'z'
Input
The first line contains one integer n — the number of functions in the input (1 ≤ n ≤ 10 000).
The following n lines contain descriptions of functions, the i-th of them contains a string of length 8 that consists of digits 0 and 1 — the truth table of the i-th function. The digit on position j (0 ≤ j < 8) equals to the value of the function in case of <image>, <image> and <image>.
Output
You should output n lines, the i-th line should contain the expression of minimum length which equals to the i-th function. If there is more than one such expression, output the lexicographically smallest of them. Expressions should satisfy the given grammar and shouldn't contain white spaces.
Example
Input
4
00110011
00000111
11110000
00011111
Output
y
(y|z)&x
!x
x|y&z
Note
The truth table for the second function:
<image>
|
instruction
| 0
| 101,750
| 6
| 203,500
|
Tags: bitmasks, dp, shortest paths
Correct Solution:
```
val='''!x&x
x&y&z
!z&x&y
x&y
!y&x&z
x&z
!y&x&z|!z&x&y
(y|z)&x
!y&!z&x
!y&!z&x|x&y&z
!z&x
!z&x|x&y
!y&x
!y&x|x&z
!(y&z)&x
x
!x&y&z
y&z
!x&y&z|!z&x&y
(x|z)&y
!x&y&z|!y&x&z
(x|y)&z
!x&y&z|!y&x&z|!z&x&y
(x|y)&z|x&y
!x&y&z|!y&!z&x
!y&!z&x|y&z
!x&y&z|!z&x
!z&x|y&z
!x&y&z|!y&x
!y&x|y&z
!(y&z)&x|!x&y&z
x|y&z
!x&!z&y
!x&!z&y|x&y&z
!z&y
!z&y|x&y
!x&!z&y|!y&x&z
!x&!z&y|x&z
!y&x&z|!z&y
!z&y|x&z
!(!x&!y|x&y|z)
!(!x&!y|x&y|z)|x&y&z
!z&(x|y)
!z&(x|y)|x&y
!x&!z&y|!y&x
!x&!z&y|!y&x|x&z
!y&x|!z&y
!z&y|x
!x&y
!x&y|y&z
!(x&z)&y
y
!x&y|!y&x&z
!x&y|x&z
!(x&z)&y|!y&x&z
x&z|y
!x&y|!y&!z&x
!x&y|!y&!z&x|y&z
!x&y|!z&x
!z&x|y
!x&y|!y&x
!x&y|!y&x|x&z
!(x&z)&y|!y&x
x|y
!x&!y&z
!x&!y&z|x&y&z
!x&!y&z|!z&x&y
!x&!y&z|x&y
!y&z
!y&z|x&z
!y&z|!z&x&y
!y&z|x&y
!(!x&!z|x&z|y)
!(!x&!z|x&z|y)|x&y&z
!x&!y&z|!z&x
!x&!y&z|!z&x|x&y
!y&(x|z)
!y&(x|z)|x&z
!y&z|!z&x
!y&z|x
!x&z
!x&z|y&z
!x&z|!z&x&y
!x&z|x&y
!(x&y)&z
z
!(x&y)&z|!z&x&y
x&y|z
!x&z|!y&!z&x
!x&z|!y&!z&x|y&z
!x&z|!z&x
!x&z|!z&x|x&y
!x&z|!y&x
!y&x|z
!(x&y)&z|!z&x
x|z
!(!y&!z|x|y&z)
!(!y&!z|x|y&z)|x&y&z
!x&!y&z|!z&y
!x&!y&z|!z&y|x&y
!x&!z&y|!y&z
!x&!z&y|!y&z|x&z
!y&z|!z&y
!y&z|!z&y|x&y
!(!x&!y|x&y|z)|!x&!y&z
!(!x&!y|x&y|z)|!x&!y&z|x&y&z
!x&!y&z|!z&(x|y)
!x&!y&z|!z&(x|y)|x&y
!x&!z&y|!y&(x|z)
!x&!z&y|!y&(x|z)|x&z
!y&(x|z)|!z&y
!y&z|!z&y|x
!x&(y|z)
!x&(y|z)|y&z
!x&z|!z&y
!x&z|y
!x&y|!y&z
!x&y|z
!(x&y)&z|!z&y
y|z
!x&(y|z)|!y&!z&x
!x&(y|z)|!y&!z&x|y&z
!x&(y|z)|!z&x
!x&z|!z&x|y
!x&(y|z)|!y&x
!x&y|!y&x|z
!x&y|!y&z|!z&x
x|y|z
!(x|y|z)
!(x|y|z)|x&y&z
!(!x&y|!y&x|z)
!(x|y|z)|x&y
!(!x&z|!z&x|y)
!(x|y|z)|x&z
!(!x&y|!y&x|z)|!y&x&z
!(x|y|z)|(y|z)&x
!y&!z
!y&!z|x&y&z
!(!x&y|z)
!y&!z|x&y
!(!x&z|y)
!y&!z|x&z
!(!x&y|z)|!y&x
!y&!z|x
!(!y&z|!z&y|x)
!(x|y|z)|y&z
!(!x&y|!y&x|z)|!x&y&z
!(x|y|z)|(x|z)&y
!(!x&z|!z&x|y)|!x&y&z
!(x|y|z)|(x|y)&z
!(!x&y|!y&x|z)|!x&y&z|!y&x&z
!(x|y|z)|(x|y)&z|x&y
!x&y&z|!y&!z
!y&!z|y&z
!(!x&y|z)|!x&y&z
!(!x&y|z)|y&z
!(!x&z|y)|!x&y&z
!(!x&z|y)|y&z
!(!x&y|z)|!x&y&z|!y&x
!y&!z|x|y&z
!x&!z
!x&!z|x&y&z
!(!y&x|z)
!x&!z|x&y
!x&!z|!y&x&z
!x&!z|x&z
!(!y&x|z)|!y&x&z
!(!y&x|z)|x&z
!(x&y|z)
!(x&y|z)|x&y&z
!z
!z|x&y
!x&!z|!y&x
!(x&y|z)|x&z
!y&x|!z
!z|x
!(!y&z|x)
!x&!z|y&z
!(!y&x|z)|!x&y
!x&!z|y
!(!y&z|x)|!y&x&z
!(!y&z|x)|x&z
!(!y&x|z)|!x&y|!y&x&z
!x&!z|x&z|y
!x&y|!y&!z
!(x&y|z)|y&z
!x&y|!z
!z|y
!(!x&!y&z|x&y)
!x&!z|!y&x|y&z
!x&y|!y&x|!z
!z|x|y
!x&!y
!x&!y|x&y&z
!x&!y|!z&x&y
!x&!y|x&y
!(!z&x|y)
!x&!y|x&z
!(!z&x|y)|!z&x&y
!(!z&x|y)|x&y
!(x&z|y)
!(x&z|y)|x&y&z
!x&!y|!z&x
!(x&z|y)|x&y
!y
!y|x&z
!y|!z&x
!y|x
!(!z&y|x)
!x&!y|y&z
!(!z&y|x)|!z&x&y
!(!z&y|x)|x&y
!(!z&x|y)|!x&z
!x&!y|z
!(!z&x|y)|!x&z|!z&x&y
!x&!y|x&y|z
!x&z|!y&!z
!(x&z|y)|y&z
!(!x&!z&y|x&z)
!x&!y|!z&x|y&z
!x&z|!y
!y|z
!x&z|!y|!z&x
!y|x|z
!(x|y&z)
!(x|y&z)|x&y&z
!x&!y|!z&y
!(x|y&z)|x&y
!x&!z|!y&z
!(x|y&z)|x&z
!(!y&!z&x|y&z)
!x&!y|!z&y|x&z
!((x|y)&z|x&y)
!((x|y)&z|x&y)|x&y&z
!x&!y|!z
!x&!y|!z|x&y
!x&!z|!y
!x&!z|!y|x&z
!y|!z
!y|!z|x
!x
!x|y&z
!x|!z&y
!x|y
!x|!y&z
!x|z
!x|!y&z|!z&y
!x|y|z
!x|!y&!z
!x|!y&!z|y&z
!x|!z
!x|!z|y
!x|!y
!x|!y|z
!(x&y&z)
!x|x'''.split()
for _ in range(int(input())):
n=0
for b in input():
n<<=1
if b=='1':
n|=1
print(val[n])
```
|
output
| 1
| 101,750
| 6
| 203,501
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of:
* Operation AND ('&', ASCII code 38)
* Operation OR ('|', ASCII code 124)
* Operation NOT ('!', ASCII code 33)
* Variables x, y and z (ASCII codes 120-122)
* Parentheses ('(', ASCII code 40, and ')', ASCII code 41)
If more than one expression of minimum length exists, you should find the lexicographically smallest one.
Operations have standard priority. NOT has the highest priority, then AND goes, and OR has the lowest priority. The expression should satisfy the following grammar:
E ::= E '|' T | T
T ::= T '&' F | F
F ::= '!' F | '(' E ')' | 'x' | 'y' | 'z'
Input
The first line contains one integer n — the number of functions in the input (1 ≤ n ≤ 10 000).
The following n lines contain descriptions of functions, the i-th of them contains a string of length 8 that consists of digits 0 and 1 — the truth table of the i-th function. The digit on position j (0 ≤ j < 8) equals to the value of the function in case of <image>, <image> and <image>.
Output
You should output n lines, the i-th line should contain the expression of minimum length which equals to the i-th function. If there is more than one such expression, output the lexicographically smallest of them. Expressions should satisfy the given grammar and shouldn't contain white spaces.
Example
Input
4
00110011
00000111
11110000
00011111
Output
y
(y|z)&x
!x
x|y&z
Note
The truth table for the second function:
<image>
|
instruction
| 0
| 101,751
| 6
| 203,502
|
Tags: bitmasks, dp, shortest paths
Correct Solution:
```
f =['!x&x', '!(x|y|z)', '!x&!y&z', '!x&!y', '!x&!z&y', '!x&!z', '!(!y&!z|x|y&z)', '!(x|y&z)', '!x&y&z', '!(!y&z|!z&y|x)', '!x&z', '!(!z&y|x)', '!x&y', '!(!y&z|x)', '!x&(y|z)', '!x', '!y&!z&x', '!y&!z', '!(!x&!z|x&z|y)', '!(x&z|y)', '!(!x&!y|x&y|z)', '!(x&y|z)', '!(!x&!y|x&y|z)|!x&!y&z', '!((x|y)&z|x&y)', '!x&y&z|!y&!z&x', '!x&y&z|!y&!z', '!x&z|!y&!z&x', '!x&z|!y&!z', '!x&y|!y&!z&x', '!x&y|!y&!z', '!x&(y|z)|!y&!z&x', '!x|!y&!z', '!y&x&z', '!(!x&z|!z&x|y)', '!y&z', '!(!z&x|y)', '!x&!z&y|!y&x&z', '!x&!z|!y&x&z', '!x&!z&y|!y&z', '!x&!z|!y&z', '!x&y&z|!y&x&z', '!(!x&z|!z&x|y)|!x&y&z', '!(x&y)&z', '!(!z&x|y)|!x&z', '!x&y|!y&x&z', '!(!y&z|x)|!y&x&z', '!x&y|!y&z', '!x|!y&z', '!y&x', '!(!x&z|y)', '!y&(x|z)', '!y', '!x&!z&y|!y&x', '!x&!z|!y&x', '!x&!z&y|!y&(x|z)', '!x&!z|!y', '!x&y&z|!y&x', '!(!x&z|y)|!x&y&z', '!x&z|!y&x', '!x&z|!y', '!x&y|!y&x', '!(!x&!y&z|x&y)', '!x&(y|z)|!y&x', '!x|!y', '!z&x&y', '!(!x&y|!y&x|z)', '!x&!y&z|!z&x&y', '!x&!y|!z&x&y', '!z&y', '!(!y&x|z)', '!x&!y&z|!z&y', '!x&!y|!z&y', '!x&y&z|!z&x&y', '!(!x&y|!y&x|z)|!x&y&z', '!x&z|!z&x&y', '!(!z&y|x)|!z&x&y', '!(x&z)&y', '!(!y&x|z)|!x&y', '!x&z|!z&y', '!x|!z&y', '!z&x', '!(!x&y|z)', '!x&!y&z|!z&x', '!x&!y|!z&x', '!z&(x|y)', '!z', '!x&!y&z|!z&(x|y)', '!x&!y|!z', '!x&y&z|!z&x', '!(!x&y|z)|!x&y&z', '!x&z|!z&x', '!(!x&!z&y|x&z)', '!x&y|!z&x', '!x&y|!z', '!x&(y|z)|!z&x', '!x|!z', '!y&x&z|!z&x&y', '!(!x&y|!y&x|z)|!y&x&z', '!y&z|!z&x&y', '!(!z&x|y)|!z&x&y', '!y&x&z|!z&y', '!(!y&x|z)|!y&x&z', '!y&z|!z&y', '!(!y&!z&x|y&z)', '!x&y&z|!y&x&z|!z&x&y', '!(!x&y|!y&x|z)|!x&y&z|!y&x&z', '!(x&y)&z|!z&x&y', '!(!z&x|y)|!x&z|!z&x&y', '!(x&z)&y|!y&x&z', '!(!y&x|z)|!x&y|!y&x&z', '!(x&y)&z|!z&y', '!x|!y&z|!z&y', '!(y&z)&x', '!(!x&y|z)|!y&x', '!y&z|!z&x', '!y|!z&x', '!y&x|!z&y', '!y&x|!z', '!y&(x|z)|!z&y', '!y|!z', '!(y&z)&x|!x&y&z', '!(!x&y|z)|!x&y&z|!y&x', '!(x&y)&z|!z&x', '!x&z|!y|!z&x', '!(x&z)&y|!y&x', '!x&y|!y&x|!z', '!x&y|!y&z|!z&x', '!(x&y&z)', 'x&y&z', '!(x|y|z)|x&y&z', '!x&!y&z|x&y&z', '!x&!y|x&y&z', '!x&!z&y|x&y&z', '!x&!z|x&y&z', '!(!y&!z|x|y&z)|x&y&z', '!(x|y&z)|x&y&z', 'y&z', '!(x|y|z)|y&z', '!x&z|y&z', '!x&!y|y&z', '!x&y|y&z', '!x&!z|y&z', '!x&(y|z)|y&z', '!x|y&z', '!y&!z&x|x&y&z', '!y&!z|x&y&z', '!(!x&!z|x&z|y)|x&y&z', '!(x&z|y)|x&y&z', '!(!x&!y|x&y|z)|x&y&z', '!(x&y|z)|x&y&z', '!(!x&!y|x&y|z)|!x&!y&z|x&y&z', '!((x|y)&z|x&y)|x&y&z', '!y&!z&x|y&z', '!y&!z|y&z', '!x&z|!y&!z&x|y&z', '!(x&z|y)|y&z', '!x&y|!y&!z&x|y&z', '!(x&y|z)|y&z', '!x&(y|z)|!y&!z&x|y&z', '!x|!y&!z|y&z', 'x&z', '!(x|y|z)|x&z', '!y&z|x&z', '!x&!y|x&z', '!x&!z&y|x&z', '!x&!z|x&z', '!x&!z&y|!y&z|x&z', '!(x|y&z)|x&z', '(x|y)&z', '!(x|y|z)|(x|y)&z', 'z', '!x&!y|z', '!x&y|x&z', '!(!y&z|x)|x&z', '!x&y|z', '!x|z', '!y&x|x&z', '!y&!z|x&z', '!y&(x|z)|x&z', '!y|x&z', '!x&!z&y|!y&x|x&z', '!(x&y|z)|x&z', '!x&!z&y|!y&(x|z)|x&z', '!x&!z|!y|x&z', '!y&x|y&z', '!(!x&z|y)|y&z', '!y&x|z', '!y|z', '!x&y|!y&x|x&z', '!x&!z|!y&x|y&z', '!x&y|!y&x|z', '!x|!y|z', 'x&y', '!(x|y|z)|x&y', '!x&!y&z|x&y', '!x&!y|x&y', '!z&y|x&y', '!x&!z|x&y', '!x&!y&z|!z&y|x&y', '!(x|y&z)|x&y', '(x|z)&y', '!(x|y|z)|(x|z)&y', '!x&z|x&y', '!(!z&y|x)|x&y', 'y', '!x&!z|y', '!x&z|y', '!x|y', '!z&x|x&y', '!y&!z|x&y', '!x&!y&z|!z&x|x&y', '!(x&z|y)|x&y', '!z&(x|y)|x&y', '!z|x&y', '!x&!y&z|!z&(x|y)|x&y', '!x&!y|!z|x&y', '!z&x|y&z', '!(!x&y|z)|y&z', '!x&z|!z&x|x&y', '!x&!y|!z&x|y&z', '!z&x|y', '!z|y', '!x&z|!z&x|y', '!x|!z|y', '(y|z)&x', '!(x|y|z)|(y|z)&x', '!y&z|x&y', '!(!z&x|y)|x&y', '!z&y|x&z', '!(!y&x|z)|x&z', '!y&z|!z&y|x&y', '!x&!y|!z&y|x&z', '(x|y)&z|x&y', '!(x|y|z)|(x|y)&z|x&y', 'x&y|z', '!x&!y|x&y|z', 'x&z|y', '!x&!z|x&z|y', 'y|z', '!x|y|z', 'x', '!y&!z|x', '!y&z|x', '!y|x', '!z&y|x', '!z|x', '!y&z|!z&y|x', '!y|!z|x', 'x|y&z', '!y&!z|x|y&z', 'x|z', '!y|x|z', 'x|y', '!z|x|y', 'x|y|z', '!x|x']
n = int(input())
for i in range(n):
s = input()
a = 0
for j in range(8):
a += int(s[j] == '1') << j
print(f[a])
```
|
output
| 1
| 101,751
| 6
| 203,503
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of:
* Operation AND ('&', ASCII code 38)
* Operation OR ('|', ASCII code 124)
* Operation NOT ('!', ASCII code 33)
* Variables x, y and z (ASCII codes 120-122)
* Parentheses ('(', ASCII code 40, and ')', ASCII code 41)
If more than one expression of minimum length exists, you should find the lexicographically smallest one.
Operations have standard priority. NOT has the highest priority, then AND goes, and OR has the lowest priority. The expression should satisfy the following grammar:
E ::= E '|' T | T
T ::= T '&' F | F
F ::= '!' F | '(' E ')' | 'x' | 'y' | 'z'
Input
The first line contains one integer n — the number of functions in the input (1 ≤ n ≤ 10 000).
The following n lines contain descriptions of functions, the i-th of them contains a string of length 8 that consists of digits 0 and 1 — the truth table of the i-th function. The digit on position j (0 ≤ j < 8) equals to the value of the function in case of <image>, <image> and <image>.
Output
You should output n lines, the i-th line should contain the expression of minimum length which equals to the i-th function. If there is more than one such expression, output the lexicographically smallest of them. Expressions should satisfy the given grammar and shouldn't contain white spaces.
Example
Input
4
00110011
00000111
11110000
00011111
Output
y
(y|z)&x
!x
x|y&z
Note
The truth table for the second function:
<image>
|
instruction
| 0
| 101,752
| 6
| 203,504
|
Tags: bitmasks, dp, shortest paths
Correct Solution:
```
# -*- coding: utf-8 -*-
dat = "硼磷碳磷溴硼氧磷氮硫氮氯氟溴硼磷碳硼硫碳氯溴硼磷碳硼硫溴硼磷碳硼氯碳硫溴硼磷碳硼氯溴硼氧硼硫碳硼氯氮磷氮硫碳氯氟溴硼氧磷氮硫碳氯氟溴硼磷碳硫碳氯溴硼氧硼硫碳氯氮硼氯碳硫氮磷氟溴硼磷碳氯溴硼氧硼氯碳硫氮磷氟溴硼磷碳硫溴硼氧硼硫碳氯氮磷氟溴硼磷碳氧硫氮氯氟溴硼磷溴硼硫碳硼氯碳磷溴硼硫碳硼氯溴硼氧硼磷碳硼氯氮磷碳氯氮硫氟溴硼氧磷碳氯氮硫氟溴硼氧硼磷碳硼硫氮磷碳硫氮氯氟溴硼氧磷碳硫氮氯氟溴硼氧硼磷碳硼硫氮磷碳硫氮氯氟氮硼磷碳硼硫碳氯溴硼氧氧磷氮硫氟碳氯氮磷碳硫氟溴硼磷碳硫碳氯氮硼硫碳硼氯碳磷溴硼磷碳硫碳氯氮硼硫碳硼氯溴硼磷碳氯氮硼硫碳硼氯碳磷溴硼磷碳氯氮硼硫碳硼氯溴硼磷碳硫氮硼硫碳硼氯碳磷溴硼磷碳硫氮硼硫碳硼氯溴硼磷碳氧硫氮氯氟氮硼硫碳硼氯碳磷溴硼磷氮硼硫碳硼氯溴硼硫碳磷碳氯溴硼氧硼磷碳氯氮硼氯碳磷氮硫氟溴硼硫碳氯溴硼氧硼氯碳磷氮硫氟溴硼磷碳硼氯碳硫氮硼硫碳磷碳氯溴硼磷碳硼氯氮硼硫碳磷碳氯溴硼磷碳硼氯碳硫氮硼硫碳氯溴硼磷碳硼氯氮硼硫碳氯溴硼磷碳硫碳氯氮硼硫碳磷碳氯溴硼氧硼磷碳氯氮硼氯碳磷氮硫氟氮硼磷碳硫碳氯溴硼氧磷碳硫氟碳氯溴硼氧硼氯碳磷氮硫氟氮硼磷碳氯溴硼磷碳硫氮硼硫碳磷碳氯溴硼氧硼硫碳氯氮磷氟氮硼硫碳磷碳氯溴硼磷碳硫氮硼硫碳氯溴硼磷氮硼硫碳氯溴硼硫碳磷溴硼氧硼磷碳氯氮硫氟溴硼硫碳氧磷氮氯氟溴硼硫溴硼磷碳硼氯碳硫氮硼硫碳磷溴硼磷碳硼氯氮硼硫碳磷溴硼磷碳硼氯碳硫氮硼硫碳氧磷氮氯氟溴硼磷碳硼氯氮硼硫溴硼磷碳硫碳氯氮硼硫碳磷溴硼氧硼磷碳氯氮硫氟氮硼磷碳硫碳氯溴硼磷碳氯氮硼硫碳磷溴硼磷碳氯氮硼硫溴硼磷碳硫氮硼硫碳磷溴硼氧硼磷碳硼硫碳氯氮磷碳硫氟溴硼磷碳氧硫氮氯氟氮硼硫碳磷溴硼磷氮硼硫溴硼氯碳磷碳硫溴硼氧硼磷碳硫氮硼硫碳磷氮氯氟溴硼磷碳硼硫碳氯氮硼氯碳磷碳硫溴硼磷碳硼硫氮硼氯碳磷碳硫溴硼氯碳硫溴硼氧硼硫碳磷氮氯氟溴硼磷碳硼硫碳氯氮硼氯碳硫溴硼磷碳硼硫氮硼氯碳硫溴硼磷碳硫碳氯氮硼氯碳磷碳硫溴硼氧硼磷碳硫氮硼硫碳磷氮氯氟氮硼磷碳硫碳氯溴硼磷碳氯氮硼氯碳磷碳硫溴硼氧硼氯碳硫氮磷氟氮硼氯碳磷碳硫溴硼氧磷碳氯氟碳硫溴硼氧硼硫碳磷氮氯氟氮硼磷碳硫溴硼磷碳氯氮硼氯碳硫溴硼磷氮硼氯碳硫溴硼氯碳磷溴硼氧硼磷碳硫氮氯氟溴硼磷碳硼硫碳氯氮硼氯碳磷溴硼磷碳硼硫氮硼氯碳磷溴硼氯碳氧磷氮硫氟溴硼氯溴硼磷碳硼硫碳氯氮硼氯碳氧磷氮硫氟溴硼磷碳硼硫氮硼氯溴硼磷碳硫碳氯氮硼氯碳磷溴硼氧硼磷碳硫氮氯氟氮硼磷碳硫碳氯溴硼磷碳氯氮硼氯碳磷溴硼氧硼磷碳硼氯碳硫氮磷碳氯氟溴硼磷碳硫氮硼氯碳磷溴硼磷碳硫氮硼氯溴硼磷碳氧硫氮氯氟氮硼氯碳磷溴硼磷氮硼氯溴硼硫碳磷碳氯氮硼氯碳磷碳硫溴硼氧硼磷碳硫氮硼硫碳磷氮氯氟氮硼硫碳磷碳氯溴硼硫碳氯氮硼氯碳磷碳硫溴硼氧硼氯碳磷氮硫氟氮硼氯碳磷碳硫溴硼硫碳磷碳氯氮硼氯碳硫溴硼氧硼硫碳磷氮氯氟氮硼硫碳磷碳氯溴硼硫碳氯氮硼氯碳硫溴硼氧硼硫碳硼氯碳磷氮硫碳氯氟溴硼磷碳硫碳氯氮硼硫碳磷碳氯氮硼氯碳磷碳硫溴硼氧硼磷碳硫氮硼硫碳磷氮氯氟氮硼磷碳硫碳氯氮硼硫碳磷碳氯溴硼氧磷碳硫氟碳氯氮硼氯碳磷碳硫溴硼氧硼氯碳磷氮硫氟氮硼磷碳氯氮硼氯碳磷碳硫溴硼氧磷碳氯氟碳硫氮硼硫碳磷碳氯溴硼氧硼硫碳磷氮氯氟氮硼磷碳硫氮硼硫碳磷碳氯溴硼氧磷碳硫氟碳氯氮硼氯碳硫溴硼磷氮硼硫碳氯氮硼氯碳硫溴硼氧硫碳氯氟碳磷溴硼氧硼磷碳硫氮氯氟氮硼硫碳磷溴硼硫碳氯氮硼氯碳磷溴硼硫氮硼氯碳磷溴硼硫碳磷氮硼氯碳硫溴硼硫碳磷氮硼氯溴硼硫碳氧磷氮氯氟氮硼氯碳硫溴硼硫氮硼氯溴硼氧硫碳氯氟碳磷氮硼磷碳硫碳氯溴硼氧硼磷碳硫氮氯氟氮硼磷碳硫碳氯氮硼硫碳磷溴硼氧磷碳硫氟碳氯氮硼氯碳磷溴硼磷碳氯氮硼硫氮硼氯碳磷溴硼氧磷碳氯氟碳硫氮硼硫碳磷溴硼磷碳硫氮硼硫碳磷氮硼氯溴硼磷碳硫氮硼硫碳氯氮硼氯碳磷溴硼氧磷碳硫碳氯氟溴磷碳硫碳氯溴硼氧磷氮硫氮氯氟氮磷碳硫碳氯溴硼磷碳硼硫碳氯氮磷碳硫碳氯溴硼磷碳硼硫氮磷碳硫碳氯溴硼磷碳硼氯碳硫氮磷碳硫碳氯溴硼磷碳硼氯氮磷碳硫碳氯溴硼氧硼硫碳硼氯氮磷氮硫碳氯氟氮磷碳硫碳氯溴硼氧磷氮硫碳氯氟氮磷碳硫碳氯溴硫碳氯溴硼氧磷氮硫氮氯氟氮硫碳氯溴硼磷碳氯氮硫碳氯溴硼磷碳硼硫氮硫碳氯溴硼磷碳硫氮硫碳氯溴硼磷碳硼氯氮硫碳氯溴硼磷碳氧硫氮氯氟氮硫碳氯溴硼磷氮硫碳氯溴硼硫碳硼氯碳磷氮磷碳硫碳氯溴硼硫碳硼氯氮磷碳硫碳氯溴硼氧硼磷碳硼氯氮磷碳氯氮硫氟氮磷碳硫碳氯溴硼氧磷碳氯氮硫氟氮磷碳硫碳氯溴硼氧硼磷碳硼硫氮磷碳硫氮氯氟氮磷碳硫碳氯溴硼氧磷碳硫氮氯氟氮磷碳硫碳氯溴硼氧硼磷碳硼硫氮磷碳硫氮氯氟氮硼磷碳硼硫碳氯氮磷碳硫碳氯溴硼氧氧磷氮硫氟碳氯氮磷碳硫氟氮磷碳硫碳氯溴硼硫碳硼氯碳磷氮硫碳氯溴硼硫碳硼氯氮硫碳氯溴硼磷碳氯氮硼硫碳硼氯碳磷氮硫碳氯溴硼氧磷碳氯氮硫氟氮硫碳氯溴硼磷碳硫氮硼硫碳硼氯碳磷氮硫碳氯溴硼氧磷碳硫氮氯氟氮硫碳氯溴硼磷碳氧硫氮氯氟氮硼硫碳硼氯碳磷氮硫碳氯溴硼磷氮硼硫碳硼氯氮硫碳氯溴磷碳氯溴硼氧磷氮硫氮氯氟氮磷碳氯溴硼硫碳氯氮磷碳氯溴硼磷碳硼硫氮磷碳氯溴硼磷碳硼氯碳硫氮磷碳氯溴硼磷碳硼氯氮磷碳氯溴硼磷碳硼氯碳硫氮硼硫碳氯氮磷碳氯溴硼氧磷氮硫碳氯氟氮磷碳氯溴氧磷氮硫氟碳氯溴硼氧磷氮硫氮氯氟氮氧磷氮硫氟碳氯溴氯溴硼磷碳硼硫氮氯溴硼磷碳硫氮磷碳氯溴硼氧硼硫碳氯氮磷氟氮磷碳氯溴硼磷碳硫氮氯溴硼磷氮氯溴硼硫碳磷氮磷碳氯溴硼硫碳硼氯氮磷碳氯溴硼硫碳氧磷氮氯氟氮磷碳氯溴硼硫氮磷碳氯溴硼磷碳硼氯碳硫氮硼硫碳磷氮磷碳氯溴硼氧磷碳硫氮氯氟氮磷碳氯溴硼磷碳硼氯碳硫氮硼硫碳氧磷氮氯氟氮磷碳氯溴硼磷碳硼氯氮硼硫氮磷碳氯溴硼硫碳磷氮硫碳氯溴硼氧硼磷碳氯氮硫氟氮硫碳氯溴硼硫碳磷氮氯溴硼硫氮氯溴硼磷碳硫氮硼硫碳磷氮磷碳氯溴硼磷碳硼氯氮硼硫碳磷氮硫碳氯溴硼磷碳硫氮硼硫碳磷氮氯溴硼磷氮硼硫氮氯溴磷碳硫溴硼氧磷氮硫氮氯氟氮磷碳硫溴硼磷碳硼硫碳氯氮磷碳硫溴硼磷碳硼硫氮磷碳硫溴硼氯碳硫氮磷碳硫溴硼磷碳硼氯氮磷碳硫溴硼磷碳硼硫碳氯氮硼氯碳硫氮磷碳硫溴硼氧磷氮硫碳氯氟氮磷碳硫溴氧磷氮氯氟碳硫溴硼氧磷氮硫氮氯氟氮氧磷氮氯氟碳硫溴硼磷碳氯氮磷碳硫溴硼氧硼氯碳硫氮磷氟氮磷碳硫溴硫溴硼磷碳硼氯氮硫溴硼磷碳氯氮硫溴硼磷氮硫溴硼氯碳磷氮磷碳硫溴硼硫碳硼氯氮磷碳硫溴硼磷碳硼硫碳氯氮硼氯碳磷氮磷碳硫溴硼氧磷碳氯氮硫氟氮磷碳硫溴硼氯碳氧磷氮硫氟氮磷碳硫溴硼氯氮磷碳硫溴硼磷碳硼硫碳氯氮硼氯碳氧磷氮硫氟氮磷碳硫溴硼磷碳硼硫氮硼氯氮磷碳硫溴硼氯碳磷氮硫碳氯溴硼氧硼磷碳硫氮氯氟氮硫碳氯溴硼磷碳氯氮硼氯碳磷氮磷碳硫溴硼磷碳硼硫氮硼氯碳磷氮硫碳氯溴硼氯碳磷氮硫溴硼氯氮硫溴硼磷碳氯氮硼氯碳磷氮硫溴硼磷氮硼氯氮硫溴氧硫氮氯氟碳磷溴硼氧磷氮硫氮氯氟氮氧硫氮氯氟碳磷溴硼硫碳氯氮磷碳硫溴硼氧硼氯碳磷氮硫氟氮磷碳硫溴硼氯碳硫氮磷碳氯溴硼氧硼硫碳磷氮氯氟氮磷碳氯溴硼硫碳氯氮硼氯碳硫氮磷碳硫溴硼磷碳硼硫氮硼氯碳硫氮磷碳氯溴氧磷氮硫氟碳氯氮磷碳硫溴硼氧磷氮硫氮氯氟氮氧磷氮硫氟碳氯氮磷碳硫溴磷碳硫氮氯溴硼磷碳硼硫氮磷碳硫氮氯溴磷碳氯氮硫溴硼磷碳硼氯氮磷碳氯氮硫溴硫氮氯溴硼磷氮硫氮氯溴磷溴硼硫碳硼氯氮磷溴硼硫碳氯氮磷溴硼硫氮磷溴硼氯碳硫氮磷溴硼氯氮磷溴硼硫碳氯氮硼氯碳硫氮磷溴硼硫氮硼氯氮磷溴磷氮硫碳氯溴硼硫碳硼氯氮磷氮硫碳氯溴磷氮氯溴硼硫氮磷氮氯溴磷氮硫溴硼氯氮磷氮硫溴磷氮硫氮氯溴硼磷氮磷".split('溴')
d1, d2 = "硼碳氮氧氟磷硫氯", "!&|()xyz"
for i in range(int(input())):
s = dat[eval("0b" + ''.join(list(reversed(input()))))]
for i in range(8): s = s.replace(d1[i], d2[i])
print(s)
```
|
output
| 1
| 101,752
| 6
| 203,505
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The letters shop showcase is a string s, consisting of n lowercase Latin letters. As the name tells, letters are sold in the shop.
Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string s.
There are m friends, the i-th of them is named t_i. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount.
* For example, for s="arrayhead" and t_i="arya" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="harry" 6 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="ray" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="r" 2 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="areahydra" all 9 letters have to be bought ("arrayhead").
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
Input
The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of showcase string s.
The second line contains string s, consisting of exactly n lowercase Latin letters.
The third line contains one integer m (1 ≤ m ≤ 5 ⋅ 10^4) — the number of friends.
The i-th of the next m lines contains t_i (1 ≤ |t_i| ≤ 2 ⋅ 10^5) — the name of the i-th friend.
It is guaranteed that ∑ _{i=1}^m |t_i| ≤ 2 ⋅ 10^5.
Output
For each friend print the length of the shortest prefix of letters from s s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount.
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Example
Input
9
arrayhead
5
arya
harry
ray
r
areahydra
Output
5
6
5
2
9
|
instruction
| 0
| 102,072
| 6
| 204,144
|
Tags: binary search, implementation, strings
Correct Solution:
```
from collections import Counter
def contains(a, b):
for k in a.keys():
if a[k] > b[k]:
return False
return True
_ = int(input())
letters = input()
T = int(input())
memo = {}
for t in range(T):
name = input()
ctr = Counter(name)
ctr_encoded = tuple(sorted(ctr.items()))
if ctr_encoded in memo:
print(memo[ctr_encoded])
continue
letters_ctr = Counter()
for i in range(len(letters)):
letters_ctr[letters[i]] += 1
# ctr[k] <= letters_ctr[k] for all k in ctr
if contains(ctr, letters_ctr):
print(i + 1)
memo[ctr_encoded] = i + 1
break
```
|
output
| 1
| 102,072
| 6
| 204,145
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The letters shop showcase is a string s, consisting of n lowercase Latin letters. As the name tells, letters are sold in the shop.
Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string s.
There are m friends, the i-th of them is named t_i. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount.
* For example, for s="arrayhead" and t_i="arya" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="harry" 6 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="ray" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="r" 2 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="areahydra" all 9 letters have to be bought ("arrayhead").
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
Input
The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of showcase string s.
The second line contains string s, consisting of exactly n lowercase Latin letters.
The third line contains one integer m (1 ≤ m ≤ 5 ⋅ 10^4) — the number of friends.
The i-th of the next m lines contains t_i (1 ≤ |t_i| ≤ 2 ⋅ 10^5) — the name of the i-th friend.
It is guaranteed that ∑ _{i=1}^m |t_i| ≤ 2 ⋅ 10^5.
Output
For each friend print the length of the shortest prefix of letters from s s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount.
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Example
Input
9
arrayhead
5
arya
harry
ray
r
areahydra
Output
5
6
5
2
9
|
instruction
| 0
| 102,073
| 6
| 204,146
|
Tags: binary search, implementation, strings
Correct Solution:
```
import copy
n = int(input())
s = input()
d = {}
for i in range(n):
if s[i] not in d:
d[s[i]] = [i]
else:
d[s[i]].append(i)
m = int(input())
for _ in range(m):
t = input()
dx = {i:0 for i in d}
ma = 0
for i in t:
ma = max(ma,d[i][dx[i]])
dx[i]+=1
print(ma+1)
```
|
output
| 1
| 102,073
| 6
| 204,147
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The letters shop showcase is a string s, consisting of n lowercase Latin letters. As the name tells, letters are sold in the shop.
Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string s.
There are m friends, the i-th of them is named t_i. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount.
* For example, for s="arrayhead" and t_i="arya" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="harry" 6 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="ray" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="r" 2 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="areahydra" all 9 letters have to be bought ("arrayhead").
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
Input
The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of showcase string s.
The second line contains string s, consisting of exactly n lowercase Latin letters.
The third line contains one integer m (1 ≤ m ≤ 5 ⋅ 10^4) — the number of friends.
The i-th of the next m lines contains t_i (1 ≤ |t_i| ≤ 2 ⋅ 10^5) — the name of the i-th friend.
It is guaranteed that ∑ _{i=1}^m |t_i| ≤ 2 ⋅ 10^5.
Output
For each friend print the length of the shortest prefix of letters from s s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount.
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Example
Input
9
arrayhead
5
arya
harry
ray
r
areahydra
Output
5
6
5
2
9
|
instruction
| 0
| 102,074
| 6
| 204,148
|
Tags: binary search, implementation, strings
Correct Solution:
```
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
#vsInput()
n=Int()
s=input()
freq={}
q=Int()
for i in 'qwertyuiopasdfghjklzxcvbnm':
if(s[0]==i):
freq[i]=[1]
else:
freq[i]=[0]
for i in range(1,len(s)):
for j in 'qwertyuiopasdfghjklzxcvbnm':
if(j==s[i]):
freq[j].append(freq[j][-1]+1)
else:
freq[j].append(freq[j][-1])
#print(freq)
for _ in range(q):
t=input()
count={}
for i in t:
try:
count[i]+=1
except:
count[i]=1
ans=0
for i in count:
ans=max(ans,bisect_left(freq[i],count[i]))
print(ans+1)
```
|
output
| 1
| 102,074
| 6
| 204,149
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The letters shop showcase is a string s, consisting of n lowercase Latin letters. As the name tells, letters are sold in the shop.
Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string s.
There are m friends, the i-th of them is named t_i. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount.
* For example, for s="arrayhead" and t_i="arya" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="harry" 6 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="ray" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="r" 2 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="areahydra" all 9 letters have to be bought ("arrayhead").
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
Input
The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of showcase string s.
The second line contains string s, consisting of exactly n lowercase Latin letters.
The third line contains one integer m (1 ≤ m ≤ 5 ⋅ 10^4) — the number of friends.
The i-th of the next m lines contains t_i (1 ≤ |t_i| ≤ 2 ⋅ 10^5) — the name of the i-th friend.
It is guaranteed that ∑ _{i=1}^m |t_i| ≤ 2 ⋅ 10^5.
Output
For each friend print the length of the shortest prefix of letters from s s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount.
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Example
Input
9
arrayhead
5
arya
harry
ray
r
areahydra
Output
5
6
5
2
9
|
instruction
| 0
| 102,075
| 6
| 204,150
|
Tags: binary search, implementation, strings
Correct Solution:
```
n =int(input())
main = input()
dic ={}
for i in range(n):
if main[i] in dic:
dic[main[i]].append(i)
else:
dic[main[i]]=[i]
num = int(input())
for i in range(num):
a = 0
name = input()
dic_name ={}
for i in range(len(name)):
if name[i] in dic_name:
dic_name[name[i]]+=1
else:
dic_name[name[i]]=0
for k in dic_name:
a=max(a,dic[k][dic_name[k]])
print(a+1)
```
|
output
| 1
| 102,075
| 6
| 204,151
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The letters shop showcase is a string s, consisting of n lowercase Latin letters. As the name tells, letters are sold in the shop.
Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string s.
There are m friends, the i-th of them is named t_i. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount.
* For example, for s="arrayhead" and t_i="arya" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="harry" 6 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="ray" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="r" 2 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="areahydra" all 9 letters have to be bought ("arrayhead").
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
Input
The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of showcase string s.
The second line contains string s, consisting of exactly n lowercase Latin letters.
The third line contains one integer m (1 ≤ m ≤ 5 ⋅ 10^4) — the number of friends.
The i-th of the next m lines contains t_i (1 ≤ |t_i| ≤ 2 ⋅ 10^5) — the name of the i-th friend.
It is guaranteed that ∑ _{i=1}^m |t_i| ≤ 2 ⋅ 10^5.
Output
For each friend print the length of the shortest prefix of letters from s s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount.
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Example
Input
9
arrayhead
5
arya
harry
ray
r
areahydra
Output
5
6
5
2
9
|
instruction
| 0
| 102,076
| 6
| 204,152
|
Tags: binary search, implementation, strings
Correct Solution:
```
n=int(input())
s=input()
d={}
for i in range(len(s)):
if(s[i] in d):
d[s[i]].append(i+1)
else:
d[s[i]]=[i+1]
for _ in range(int(input())):
res=[]
s=input()
f={}
for i in range(len(s)):
if(s[i] in f):
f[s[i]]+=1
else:
f[s[i]]=1
for key,value in f.items():
res.append(d[key][value-1])
print(max(res))
```
|
output
| 1
| 102,076
| 6
| 204,153
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The letters shop showcase is a string s, consisting of n lowercase Latin letters. As the name tells, letters are sold in the shop.
Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string s.
There are m friends, the i-th of them is named t_i. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount.
* For example, for s="arrayhead" and t_i="arya" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="harry" 6 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="ray" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="r" 2 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="areahydra" all 9 letters have to be bought ("arrayhead").
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
Input
The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of showcase string s.
The second line contains string s, consisting of exactly n lowercase Latin letters.
The third line contains one integer m (1 ≤ m ≤ 5 ⋅ 10^4) — the number of friends.
The i-th of the next m lines contains t_i (1 ≤ |t_i| ≤ 2 ⋅ 10^5) — the name of the i-th friend.
It is guaranteed that ∑ _{i=1}^m |t_i| ≤ 2 ⋅ 10^5.
Output
For each friend print the length of the shortest prefix of letters from s s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount.
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Example
Input
9
arrayhead
5
arya
harry
ray
r
areahydra
Output
5
6
5
2
9
|
instruction
| 0
| 102,077
| 6
| 204,154
|
Tags: binary search, implementation, strings
Correct Solution:
```
from collections import Counter,defaultdict
n=int(input())
s=str(input())
a=defaultdict(list)
for i in range(len(s)):
a[s[i]].append(i)
for j in range(int(input())):
t=Counter(input())
#print(t)
p=max([a[o][t[o]-1]for o in t])
print(p+1)
```
|
output
| 1
| 102,077
| 6
| 204,155
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The letters shop showcase is a string s, consisting of n lowercase Latin letters. As the name tells, letters are sold in the shop.
Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string s.
There are m friends, the i-th of them is named t_i. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount.
* For example, for s="arrayhead" and t_i="arya" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="harry" 6 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="ray" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="r" 2 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="areahydra" all 9 letters have to be bought ("arrayhead").
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
Input
The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of showcase string s.
The second line contains string s, consisting of exactly n lowercase Latin letters.
The third line contains one integer m (1 ≤ m ≤ 5 ⋅ 10^4) — the number of friends.
The i-th of the next m lines contains t_i (1 ≤ |t_i| ≤ 2 ⋅ 10^5) — the name of the i-th friend.
It is guaranteed that ∑ _{i=1}^m |t_i| ≤ 2 ⋅ 10^5.
Output
For each friend print the length of the shortest prefix of letters from s s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount.
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Example
Input
9
arrayhead
5
arya
harry
ray
r
areahydra
Output
5
6
5
2
9
|
instruction
| 0
| 102,078
| 6
| 204,156
|
Tags: binary search, implementation, strings
Correct Solution:
```
n=int(input())
s=input()
dic={}
for i in range(n):
if(s[i] in dic):
dic[s[i]].append(i+1)
else:
dic[s[i]]=[i+1]
# print(d)
q=int(input())
while(q>0):
x=input()
temp=0
aux={}
for i in range(len(x)):
if(x[i] in aux):
aux[x[i]]+=1
else:
aux[x[i]]=1
for i,j in aux.items():
if(temp<=dic[i][j-1]):
temp=dic[i][j-1]
print(temp)
q-=1
```
|
output
| 1
| 102,078
| 6
| 204,157
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The letters shop showcase is a string s, consisting of n lowercase Latin letters. As the name tells, letters are sold in the shop.
Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string s.
There are m friends, the i-th of them is named t_i. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount.
* For example, for s="arrayhead" and t_i="arya" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="harry" 6 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="ray" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="r" 2 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="areahydra" all 9 letters have to be bought ("arrayhead").
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
Input
The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of showcase string s.
The second line contains string s, consisting of exactly n lowercase Latin letters.
The third line contains one integer m (1 ≤ m ≤ 5 ⋅ 10^4) — the number of friends.
The i-th of the next m lines contains t_i (1 ≤ |t_i| ≤ 2 ⋅ 10^5) — the name of the i-th friend.
It is guaranteed that ∑ _{i=1}^m |t_i| ≤ 2 ⋅ 10^5.
Output
For each friend print the length of the shortest prefix of letters from s s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount.
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Example
Input
9
arrayhead
5
arya
harry
ray
r
areahydra
Output
5
6
5
2
9
|
instruction
| 0
| 102,079
| 6
| 204,158
|
Tags: binary search, implementation, strings
Correct Solution:
```
n = int(input())
l = list(input())
d = dict()
for i in set(l):
d[i] = ([k for k, n in enumerate(l) if n == i])
for i in range(int(input())):
s = input()
mx = 0
dc = dict()
for i in s:
j = dc.get(i, 0)
mx = max(mx, d[i][j])
dc[i] = j +1
print(mx+1)
```
|
output
| 1
| 102,079
| 6
| 204,159
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The letters shop showcase is a string s, consisting of n lowercase Latin letters. As the name tells, letters are sold in the shop.
Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string s.
There are m friends, the i-th of them is named t_i. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount.
* For example, for s="arrayhead" and t_i="arya" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="harry" 6 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="ray" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="r" 2 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="areahydra" all 9 letters have to be bought ("arrayhead").
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
Input
The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of showcase string s.
The second line contains string s, consisting of exactly n lowercase Latin letters.
The third line contains one integer m (1 ≤ m ≤ 5 ⋅ 10^4) — the number of friends.
The i-th of the next m lines contains t_i (1 ≤ |t_i| ≤ 2 ⋅ 10^5) — the name of the i-th friend.
It is guaranteed that ∑ _{i=1}^m |t_i| ≤ 2 ⋅ 10^5.
Output
For each friend print the length of the shortest prefix of letters from s s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount.
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Example
Input
9
arrayhead
5
arya
harry
ray
r
areahydra
Output
5
6
5
2
9
Submitted Solution:
```
# -*- coding: utf-8 -*-
# @Date : 2019-07-01 07:44:43
# @Author : raj lath (oorja.halt@gmail.com)
# @Link : link
# @Version : 1.0.0
import sys
sys.setrecursionlimit(10**5+1)
inf = int(10 ** 20)
max_val = inf
min_val = -inf
RW = lambda : sys.stdin.readline().strip()
RI = lambda : int(RW())
RMI = lambda : [int(x) for x in sys.stdin.readline().strip().split()]
RWI = lambda : [x for x in sys.stdin.readline().strip().split()]
from collections import defaultdict
has = defaultdict(list)
lens = RI()
given = input()
for i, v in enumerate(given):
has[v].append(i + 1)
nb_word = RI()
for i in range(nb_word):
answer = 0
current = input()
dicts = defaultdict(int)
for i,v in enumerate(current):
dicts[v] += 1
answer = (max(answer, has[v][dicts[v] - 1] ))
print(answer)
```
|
instruction
| 0
| 102,080
| 6
| 204,160
|
Yes
|
output
| 1
| 102,080
| 6
| 204,161
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The letters shop showcase is a string s, consisting of n lowercase Latin letters. As the name tells, letters are sold in the shop.
Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string s.
There are m friends, the i-th of them is named t_i. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount.
* For example, for s="arrayhead" and t_i="arya" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="harry" 6 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="ray" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="r" 2 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="areahydra" all 9 letters have to be bought ("arrayhead").
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
Input
The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of showcase string s.
The second line contains string s, consisting of exactly n lowercase Latin letters.
The third line contains one integer m (1 ≤ m ≤ 5 ⋅ 10^4) — the number of friends.
The i-th of the next m lines contains t_i (1 ≤ |t_i| ≤ 2 ⋅ 10^5) — the name of the i-th friend.
It is guaranteed that ∑ _{i=1}^m |t_i| ≤ 2 ⋅ 10^5.
Output
For each friend print the length of the shortest prefix of letters from s s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount.
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Example
Input
9
arrayhead
5
arya
harry
ray
r
areahydra
Output
5
6
5
2
9
Submitted Solution:
```
import sys
inf = float("inf")
#from collections import deque, Counter, OrderedDict,defaultdict
#from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace
from math import ceil,floor,log,log2,sqrt,factorial,pow,pi,gcd
#from bisect import bisect_left,bisect_right
# abc='abcdefghijklmnopqrstuvwxyz'
# abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
# mod,MOD=1000000007,998244353
# vow=['a','e','i','o','u']
# dx,dy=[-1,1,0,0],[0,0,1,-1]
def get_array(): return list(map(int, sys.stdin.readline().strip().split()))
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def input(): return sys.stdin.readline().strip()
mydict={chr(i):[] for i in range(97,123)}
N=int(input())
name=input()
for i in range(N):
mydict[name[i]].append(i+1)
k=int(input())
for i in range(k):
z=list(input())
mydict2=dict()
for i in z:
mydict2[i]=mydict2.get(i,0)+1
maximum=-1
for i in mydict2:
maximum=max(maximum,mydict[i][mydict2[i]-1])
print(maximum)
```
|
instruction
| 0
| 102,081
| 6
| 204,162
|
Yes
|
output
| 1
| 102,081
| 6
| 204,163
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The letters shop showcase is a string s, consisting of n lowercase Latin letters. As the name tells, letters are sold in the shop.
Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string s.
There are m friends, the i-th of them is named t_i. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount.
* For example, for s="arrayhead" and t_i="arya" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="harry" 6 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="ray" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="r" 2 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="areahydra" all 9 letters have to be bought ("arrayhead").
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
Input
The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of showcase string s.
The second line contains string s, consisting of exactly n lowercase Latin letters.
The third line contains one integer m (1 ≤ m ≤ 5 ⋅ 10^4) — the number of friends.
The i-th of the next m lines contains t_i (1 ≤ |t_i| ≤ 2 ⋅ 10^5) — the name of the i-th friend.
It is guaranteed that ∑ _{i=1}^m |t_i| ≤ 2 ⋅ 10^5.
Output
For each friend print the length of the shortest prefix of letters from s s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount.
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Example
Input
9
arrayhead
5
arya
harry
ray
r
areahydra
Output
5
6
5
2
9
Submitted Solution:
```
n = int(input());
s = input();
cnt = [0 for i in range(26)]
dp = [[-1 for i in range(n)] for i in range(26)];
for i in range(n):
cnt[ord(s[i])-97]+=1;
#print(cnt)
dp[ord(s[i])-97][cnt[ord(s[i])-97]-1]=i;
q = int(input());
for i in range(q):
ts = input();
tcnt = [0 for i in range(26)];
for i in range(len(ts)):
tcnt[ord(ts[i])-97]+=1;
ans = 0;
for i in range(26):
if(tcnt[i]>0):
ans = max(ans,dp[i][tcnt[i]-1])
print(ans+1)
```
|
instruction
| 0
| 102,082
| 6
| 204,164
|
Yes
|
output
| 1
| 102,082
| 6
| 204,165
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The letters shop showcase is a string s, consisting of n lowercase Latin letters. As the name tells, letters are sold in the shop.
Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string s.
There are m friends, the i-th of them is named t_i. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount.
* For example, for s="arrayhead" and t_i="arya" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="harry" 6 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="ray" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="r" 2 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="areahydra" all 9 letters have to be bought ("arrayhead").
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
Input
The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of showcase string s.
The second line contains string s, consisting of exactly n lowercase Latin letters.
The third line contains one integer m (1 ≤ m ≤ 5 ⋅ 10^4) — the number of friends.
The i-th of the next m lines contains t_i (1 ≤ |t_i| ≤ 2 ⋅ 10^5) — the name of the i-th friend.
It is guaranteed that ∑ _{i=1}^m |t_i| ≤ 2 ⋅ 10^5.
Output
For each friend print the length of the shortest prefix of letters from s s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount.
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Example
Input
9
arrayhead
5
arya
harry
ray
r
areahydra
Output
5
6
5
2
9
Submitted Solution:
```
from collections import Counter
n = int(input())
a = input()
string1 = {'a':[],'b':[],'c':[],'d':[],'e':[],'f':[],'g':[],'h':[],'i':[],'j':[],'k':[],'l':[],'m':[],'n':[],'o':[],'p':[],'q':[],'r':[],'s':[],'t':[],'u':[],'v':[],'w':[],'x':[],'y':[],'z':[]}
for i,j in enumerate(a):
string1[j].append(i)
m = int(input())
for _ in range(m):
p = dict(Counter(input()))
keys = list(p.keys())
o = 0
for i in keys:
x = p[i]-1
y = string1[i][x]
o = max(o,y)
print(o+1)
```
|
instruction
| 0
| 102,083
| 6
| 204,166
|
Yes
|
output
| 1
| 102,083
| 6
| 204,167
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The letters shop showcase is a string s, consisting of n lowercase Latin letters. As the name tells, letters are sold in the shop.
Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string s.
There are m friends, the i-th of them is named t_i. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount.
* For example, for s="arrayhead" and t_i="arya" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="harry" 6 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="ray" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="r" 2 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="areahydra" all 9 letters have to be bought ("arrayhead").
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
Input
The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of showcase string s.
The second line contains string s, consisting of exactly n lowercase Latin letters.
The third line contains one integer m (1 ≤ m ≤ 5 ⋅ 10^4) — the number of friends.
The i-th of the next m lines contains t_i (1 ≤ |t_i| ≤ 2 ⋅ 10^5) — the name of the i-th friend.
It is guaranteed that ∑ _{i=1}^m |t_i| ≤ 2 ⋅ 10^5.
Output
For each friend print the length of the shortest prefix of letters from s s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount.
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Example
Input
9
arrayhead
5
arya
harry
ray
r
areahydra
Output
5
6
5
2
9
Submitted Solution:
```
n = int(input())
string = input()
t = int(input())
for i in range(t):
subs = input()
dct = {}
l = len(subs)
temp = []
flag = 1
for i in subs:
if i not in string[0:l]:
temp.append(i)
if temp == []:
flag = 0
else:
for i in temp:
dct[i] = l-1
for i in temp:
dct[i] = string.index(i,dct[i]+1)
if flag:
print(max(dct.values())+1)
else:
print(l)
```
|
instruction
| 0
| 102,084
| 6
| 204,168
|
No
|
output
| 1
| 102,084
| 6
| 204,169
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The letters shop showcase is a string s, consisting of n lowercase Latin letters. As the name tells, letters are sold in the shop.
Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string s.
There are m friends, the i-th of them is named t_i. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount.
* For example, for s="arrayhead" and t_i="arya" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="harry" 6 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="ray" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="r" 2 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="areahydra" all 9 letters have to be bought ("arrayhead").
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
Input
The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of showcase string s.
The second line contains string s, consisting of exactly n lowercase Latin letters.
The third line contains one integer m (1 ≤ m ≤ 5 ⋅ 10^4) — the number of friends.
The i-th of the next m lines contains t_i (1 ≤ |t_i| ≤ 2 ⋅ 10^5) — the name of the i-th friend.
It is guaranteed that ∑ _{i=1}^m |t_i| ≤ 2 ⋅ 10^5.
Output
For each friend print the length of the shortest prefix of letters from s s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount.
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Example
Input
9
arrayhead
5
arya
harry
ray
r
areahydra
Output
5
6
5
2
9
Submitted Solution:
```
n=int(input())
s=str(input())
m=int(input())
result=[]
for i in range(m):
sub=str(input())
mini=0
for j in sub:
if(s.index(j)>mini):
mini=s.index(j)
result.append(mini+1)
for i in result:
print(i)
```
|
instruction
| 0
| 102,085
| 6
| 204,170
|
No
|
output
| 1
| 102,085
| 6
| 204,171
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The letters shop showcase is a string s, consisting of n lowercase Latin letters. As the name tells, letters are sold in the shop.
Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string s.
There are m friends, the i-th of them is named t_i. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount.
* For example, for s="arrayhead" and t_i="arya" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="harry" 6 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="ray" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="r" 2 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="areahydra" all 9 letters have to be bought ("arrayhead").
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
Input
The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of showcase string s.
The second line contains string s, consisting of exactly n lowercase Latin letters.
The third line contains one integer m (1 ≤ m ≤ 5 ⋅ 10^4) — the number of friends.
The i-th of the next m lines contains t_i (1 ≤ |t_i| ≤ 2 ⋅ 10^5) — the name of the i-th friend.
It is guaranteed that ∑ _{i=1}^m |t_i| ≤ 2 ⋅ 10^5.
Output
For each friend print the length of the shortest prefix of letters from s s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount.
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Example
Input
9
arrayhead
5
arya
harry
ray
r
areahydra
Output
5
6
5
2
9
Submitted Solution:
```
#AM.EN.U4CSE19114 question number:1187B
n=int(input())
l=[]
t=[]
k=[]
o=1
if(n>=1 and n<=200000):
s=""
s=input()
p=list(s)
h=list(s)
if len(p)==n:
m=int(input())
if(m<=50000 and m>=1):
for j in range (m):
f=""
f=input()
l.append(f)
for u in range(m):
if(len(l[u])<=200000 and len(l[u])>=1):
for y in range(len(l[u])):
t=list(l[u])
if t[y] in p:
k.append(p.index(t[y]))
if(t.count(t[y])>p.count(t[y])):
o=0
else:
o=0
if o==1:
print(max(k)+1)
o=1
k=[]
```
|
instruction
| 0
| 102,086
| 6
| 204,172
|
No
|
output
| 1
| 102,086
| 6
| 204,173
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The letters shop showcase is a string s, consisting of n lowercase Latin letters. As the name tells, letters are sold in the shop.
Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string s.
There are m friends, the i-th of them is named t_i. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount.
* For example, for s="arrayhead" and t_i="arya" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="harry" 6 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="ray" 5 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="r" 2 letters have to be bought ("arrayhead").
* For example, for s="arrayhead" and t_i="areahydra" all 9 letters have to be bought ("arrayhead").
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
Input
The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of showcase string s.
The second line contains string s, consisting of exactly n lowercase Latin letters.
The third line contains one integer m (1 ≤ m ≤ 5 ⋅ 10^4) — the number of friends.
The i-th of the next m lines contains t_i (1 ≤ |t_i| ≤ 2 ⋅ 10^5) — the name of the i-th friend.
It is guaranteed that ∑ _{i=1}^m |t_i| ≤ 2 ⋅ 10^5.
Output
For each friend print the length of the shortest prefix of letters from s s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount.
It is guaranteed that every friend can construct her/his name using the letters from the string s.
Example
Input
9
arrayhead
5
arya
harry
ray
r
areahydra
Output
5
6
5
2
9
Submitted Solution:
```
"""
Author : co_devil Chirag Garg
Institute : JIIT
"""
from __future__ import division, print_function
import itertools, os, sys, threading
from collections import deque, Counter, OrderedDict, defaultdict
import heapq
from math import ceil,floor,log,sqrt,factorial,pow,pi
# from bisect import bisect_left,bisect_right
# from decimal import *,threading
"""from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
else:
from builtins import str as __str__
str = lambda x=b'': x if type(x) is bytes else __str__(x).encode()
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._buffer = BytesIO()
self._fd = file.fileno()
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):
return self._buffer.read() if self._buffer.tell() else os.read(self._fd, os.fstat(self._fd).st_size)
def readline(self):
while self.newlines == 0:
b, ptr = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)), self._buffer.tell()
self._buffer.seek(0, 2), self._buffer.write(b), self._buffer.seek(ptr)
self.newlines += b.count(b'\n') + (not b)
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)
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip(b'\r\n')
def print(*args, **kwargs):
sep, file = kwargs.pop('sep', b' '), 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', b'\n'))
if kwargs.pop('flush', False):
file.flush()
"""
def ii(): return int(input())
def si(): return str(input())
def mi(): return map(int,input().split())
def li(): return list(mi())
abc = 'abcdefghijklmnopqrstuvwxyz'
abd = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12,
'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24,
'z': 25}
mod = 1000000007
dx, dy = [-1, 1, 0, 0], [0, 0, 1, -1]
def getKey(item): return item[0]
def sort2(l): return sorted(l, key=getKey)
def d2(n, m, num): return [[num for x in range(m)] for y in range(n)]
def isPowerOfTwo(x): return (x and (not (x & (x - 1))))
def decimalToBinary(n): return bin(n).replace("0b", "")
def ntl(n): return [int(i) for i in str(n)]
def powerMod(x, y, p):
res = 1
x %= p
while y > 0:
if y & 1:
res = (res * x) % p
y = y >> 1
x = (x * x) % p
return res
def gcd(x, y):
while y:
x, y = y, x % y
return x
# For getting input from input.txt file
# sys.stdin = open('input.txt', 'r')
# Printing the Output to output.txt file
# sys.stdout = open('output.txt', 'w')
graph = defaultdict(list)
visited = [0] * 1000000
col = [-1] * 1000000
def dfs(v, c):
if visited[v]:
if col[v] != c:
print('-1')
exit()
return
col[v] = c
visited[v] = 1
for i in graph[v]:
dfs(i, c ^ 1)
def bfs(d,v):
q=[]
q.append(v)
visited[v]=1
while len(q)!=0:
x=q[0]
q.pop(0)
for i in d[x]:
if visited[i]!=1:
visited[i]=1
q.append(i)
print(x)
print(l)
def make_graph(e):
d={}
for i in range(e):
x,y=mi()
if x not in d.keys():
d[x]=[y]
else:
d[x].append(y)
if y not in d.keys():
d[y] = [x]
else:
d[y].append(x)
return d
def gr2(n):
d={}
for i in range(n):
x,y=mi()
if x not in d.keys():
d[x]=[y]
else:
d[x].append(y)
return d
def connected_components(graph):
seen = set()
def dfs(v):
vs = set([v])
component=[]
while vs:
v = vs.pop()
seen.add(v)
vs |= set(graph[v]) - seen
component.append(v)
return component
ans=[]
for v in graph:
if v not in seen:
d=dfs(v)
ans.append(d)
return ans
n=ii()
s=list(si())
d={}
for i in range(1,27):
d[chr(96+i)]=[]
for i in range(n):
d[s[i]].append(i+1)
m=ii()
for j in range(m):
x=si()
l=[0]*26
z = d[x[0]][l[ord(x[0])-97]]
l[ord(x[0])-97]+=1
for i in range(1,len(x)):
if d[x[i]][l[ord(x[i])-97]]>z:
z=d[x[i]][l[ord(x[i])-97]]
l[ord(x[i])-97]+=1
print(z)
```
|
instruction
| 0
| 102,087
| 6
| 204,174
|
No
|
output
| 1
| 102,087
| 6
| 204,175
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 ≤ |s| ≤ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
|
instruction
| 0
| 102,402
| 6
| 204,804
|
Tags: implementation, math
Correct Solution:
```
s1, s2 = map(str, input().split('^'))
l1, l2 = 0, 0
for i in range(len(s1)):
if s1[i].isdigit():
l1 += int(s1[i]) * (len(s1) - i)
for i in range(len(s2)):
if s2[i].isdigit():
l2 += int(s2[i]) * (i + 1)
if l1 == l2:
print('balance')
elif l1 > l2:
print('left')
else:
print('right')
```
|
output
| 1
| 102,402
| 6
| 204,805
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 ≤ |s| ≤ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
|
instruction
| 0
| 102,403
| 6
| 204,806
|
Tags: implementation, math
Correct Solution:
```
s = input()
pivot = s.find('^')
value = 0
for i in range(len(s)):
if s[i].isdigit():
value += int(s[i]) * (i - pivot)
if value < 0:
print('left')
elif value == 0:
print('balance')
else:
print('right')
```
|
output
| 1
| 102,403
| 6
| 204,807
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 ≤ |s| ≤ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
|
instruction
| 0
| 102,404
| 6
| 204,808
|
Tags: implementation, math
Correct Solution:
```
s = input().strip()
n = len(s)
i = s.find('^')
left = 0
right = 0
l = i - 1
r = i + 1
while l >= 0 or r < n:
if l >= 0 and s[l] != '=':
left += int(s[l])*(i - l)
l -= 1
else:
l -= 1
if r < n and s[r] != '=':
right += int(s[r]) * (r - i)
r += 1
else:
r += 1
if left == right:
print("balance")
elif left > right:
print("left")
else:
print("right")
```
|
output
| 1
| 102,404
| 6
| 204,809
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 ≤ |s| ≤ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
|
instruction
| 0
| 102,405
| 6
| 204,810
|
Tags: implementation, math
Correct Solution:
```
a=input()
p=a.index('^')
c=sum((i-p)*int(y) for i,y in enumerate(a) if y.isdigit())
print([['balance','right'][c>0],'left'][c<0])
```
|
output
| 1
| 102,405
| 6
| 204,811
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 ≤ |s| ≤ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
|
instruction
| 0
| 102,406
| 6
| 204,812
|
Tags: implementation, math
Correct Solution:
```
s = input()
p = s.index('^')
f = 0
for i in range(len(s)):
if s[i]=='1':
f = f-((p-i)*1)
elif s[i]=='2':
f = f - ((p-i)*2)
elif s[i]=='3':
f = f - ((p-i)*3)
elif s[i]=='4':
f = f - ((p-i)*4)
elif s[i]=='5':
f = f - ((p-i)*5)
elif s[i]=='6':
f = f - ((p-i)*6)
elif s[i]=='7':
f = f - ((p-i)*7)
elif s[i]=='8':
f = f - ((p-i)*8)
elif s[i]=='9':
f = f - ((p-i)*9)
if f<0:
print("left")
elif f>0:
print("right")
else:
print("balance")
```
|
output
| 1
| 102,406
| 6
| 204,813
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 ≤ |s| ≤ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
|
instruction
| 0
| 102,407
| 6
| 204,814
|
Tags: implementation, math
Correct Solution:
```
s=[n for n in input()]
k=s.index('^')
a=s[:k][::-1]
b=s[k+1:]
m=0
for n in range(len(a)):
if ord('0')<=ord(a[n])<=ord('9'):
m+=int(a[n])*(n+1)
p=0
for n in range(len(b)):
if ord('0')<=ord(b[n])<=ord('9'):
p+=int(b[n])*(n+1)
if m==p:
print('balance')
elif m>p:
print('left')
elif m<p:
print('right')
```
|
output
| 1
| 102,407
| 6
| 204,815
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 ≤ |s| ≤ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
|
instruction
| 0
| 102,408
| 6
| 204,816
|
Tags: implementation, math
Correct Solution:
```
a = input()
i = 0
r = 0
l = 0
while(a[i] != "^"):
i = i+1
k = i
for j in range(i):
if(a[j]!= "="):
l = l +k*int(a[j])
k = k-1
k = 1
i +=1
while(i<len(a)):
if(a[i]!= "="):
r = r+k*int(a[i])
i = i+1
k = k+1
if(r==l):
print("balance")
elif(l>r):
print("left")
else:
print("right")
```
|
output
| 1
| 102,408
| 6
| 204,817
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 ≤ |s| ≤ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
|
instruction
| 0
| 102,409
| 6
| 204,818
|
Tags: implementation, math
Correct Solution:
```
# -*- coding: utf-8 -*-
s1, s2 = input().split('^')
s1 = s1[::-1]
l1 = sum([(i+1) * int(s1[i]) for i in range(len(s1)) if s1[i] != '='])
l2 = sum([(i+1) * int(s2[i]) for i in range(len(s2)) if s2[i] != '='])
print('balance' if l1==l2 else 'left' if l1>l2 else 'right')
```
|
output
| 1
| 102,409
| 6
| 204,819
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Programmer Vasya is studying a new programming language &K*. The &K* language resembles the languages of the C family in its syntax. However, it is more powerful, which is why the rules of the actual C-like languages are unapplicable to it. To fully understand the statement, please read the language's description below carefully and follow it and not the similar rules in real programming languages.
There is a very powerful system of pointers on &K* — you can add an asterisk to the right of the existing type X — that will result in new type X * . That is called pointer-definition operation. Also, there is the operation that does the opposite — to any type of X, which is a pointer, you can add an ampersand — that will result in a type &X, to which refers X. That is called a dereference operation.
The &K* language has only two basic data types — void and errtype. Also, the language has operators typedef and typeof.
* The operator "typedef A B" defines a new data type B, which is equivalent to A. A can have asterisks and ampersands, and B cannot have them. For example, the operator typedef void** ptptvoid will create a new type ptptvoid, that can be used as void**.
* The operator "typeof A" returns type of A, brought to void, that is, returns the type void**...*, equivalent to it with the necessary number of asterisks (the number can possibly be zero). That is, having defined the ptptvoid type, as shown above, the typeof ptptvoid operator will return void**.
An attempt of dereferencing of the void type will lead to an error: to a special data type errtype. For errtype the following equation holds true: errtype* = &errtype = errtype. An attempt to use the data type that hasn't been defined before that will also lead to the errtype.
Using typedef, we can define one type several times. Of all the definitions only the last one is valid. However, all the types that have been defined earlier using this type do not change.
Let us also note that the dereference operation has the lower priority that the pointer operation, in other words &T * is always equal to T.
Note, that the operators are executed consecutively one by one. If we have two operators "typedef &void a" and "typedef a* b", then at first a becomes errtype, and after that b becomes errtype* = errtype, but not &void* = void (see sample 2).
Vasya does not yet fully understand this powerful technology, that's why he asked you to help him. Write a program that analyzes these operators.
Input
The first line contains an integer n (1 ≤ n ≤ 100) — the number of operators. Then follow n lines with operators. Each operator is of one of two types: either "typedef A B", or "typeof A". In the first case the B type differs from void and errtype types, and besides, doesn't have any asterisks and ampersands.
All the data type names are non-empty lines of no more than 20 lowercase Latin letters. The number of asterisks and ampersands separately in one type in any operator does not exceed 10, however if we bring some types to void with several asterisks, their number may exceed 10.
Output
For every typeof operator print on the single line the answer to that operator — the type that the given operator returned.
Examples
Input
5
typedef void* ptv
typeof ptv
typedef &&ptv node
typeof node
typeof &ptv
Output
void*
errtype
void
Input
17
typedef void* b
typedef b* c
typeof b
typeof c
typedef &b b
typeof b
typeof c
typedef &&b* c
typeof c
typedef &b* c
typeof c
typedef &void b
typeof b
typedef b******* c
typeof c
typedef &&b* c
typeof c
Output
void*
void**
void
void**
errtype
void
errtype
errtype
errtype
Note
Let's look at the second sample.
After the first two queries typedef the b type is equivalent to void*, and с — to void**.
The next query typedef redefines b — it is now equal to &b = &void* = void. At that, the с type doesn't change.
After that the с type is defined as &&b* = &&void* = &void = errtype. It doesn't influence the b type, that's why the next typedef defines c as &void* = void.
Then the b type is again redefined as &void = errtype.
Please note that the c type in the next query is defined exactly as errtype******* = errtype, and not &void******* = void******. The same happens in the last typedef.
|
instruction
| 0
| 102,619
| 6
| 205,238
|
Tags: implementation, strings
Correct Solution:
```
import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
n = int(input())
name = {'void': 'void'}
errtype = 'errtype'
def resolve(t):
nest = 0
while t[-1] == '*':
nest += 1
t = t[:-1]
while t[0] == '&':
nest -= 1
t = t[1:]
if t not in name:
return errtype
t = name[t]
while nest < 0 and t[-1] == '*':
nest += 1
t = t[:-1]
if nest < 0:
return errtype
else:
return t + '*' * nest
def f(s):
if s[:7] == errtype:
return errtype
else:
return s
ans = []
for _ in range(n):
query = input().split()
if query[0] == 'typeof':
ans.append(f(resolve(query[1])))
else:
name[query[2]] = resolve(query[1])
print(*ans, sep='\n')
```
|
output
| 1
| 102,619
| 6
| 205,239
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Programmer Vasya is studying a new programming language &K*. The &K* language resembles the languages of the C family in its syntax. However, it is more powerful, which is why the rules of the actual C-like languages are unapplicable to it. To fully understand the statement, please read the language's description below carefully and follow it and not the similar rules in real programming languages.
There is a very powerful system of pointers on &K* — you can add an asterisk to the right of the existing type X — that will result in new type X * . That is called pointer-definition operation. Also, there is the operation that does the opposite — to any type of X, which is a pointer, you can add an ampersand — that will result in a type &X, to which refers X. That is called a dereference operation.
The &K* language has only two basic data types — void and errtype. Also, the language has operators typedef and typeof.
* The operator "typedef A B" defines a new data type B, which is equivalent to A. A can have asterisks and ampersands, and B cannot have them. For example, the operator typedef void** ptptvoid will create a new type ptptvoid, that can be used as void**.
* The operator "typeof A" returns type of A, brought to void, that is, returns the type void**...*, equivalent to it with the necessary number of asterisks (the number can possibly be zero). That is, having defined the ptptvoid type, as shown above, the typeof ptptvoid operator will return void**.
An attempt of dereferencing of the void type will lead to an error: to a special data type errtype. For errtype the following equation holds true: errtype* = &errtype = errtype. An attempt to use the data type that hasn't been defined before that will also lead to the errtype.
Using typedef, we can define one type several times. Of all the definitions only the last one is valid. However, all the types that have been defined earlier using this type do not change.
Let us also note that the dereference operation has the lower priority that the pointer operation, in other words &T * is always equal to T.
Note, that the operators are executed consecutively one by one. If we have two operators "typedef &void a" and "typedef a* b", then at first a becomes errtype, and after that b becomes errtype* = errtype, but not &void* = void (see sample 2).
Vasya does not yet fully understand this powerful technology, that's why he asked you to help him. Write a program that analyzes these operators.
Input
The first line contains an integer n (1 ≤ n ≤ 100) — the number of operators. Then follow n lines with operators. Each operator is of one of two types: either "typedef A B", or "typeof A". In the first case the B type differs from void and errtype types, and besides, doesn't have any asterisks and ampersands.
All the data type names are non-empty lines of no more than 20 lowercase Latin letters. The number of asterisks and ampersands separately in one type in any operator does not exceed 10, however if we bring some types to void with several asterisks, their number may exceed 10.
Output
For every typeof operator print on the single line the answer to that operator — the type that the given operator returned.
Examples
Input
5
typedef void* ptv
typeof ptv
typedef &&ptv node
typeof node
typeof &ptv
Output
void*
errtype
void
Input
17
typedef void* b
typedef b* c
typeof b
typeof c
typedef &b b
typeof b
typeof c
typedef &&b* c
typeof c
typedef &b* c
typeof c
typedef &void b
typeof b
typedef b******* c
typeof c
typedef &&b* c
typeof c
Output
void*
void**
void
void**
errtype
void
errtype
errtype
errtype
Note
Let's look at the second sample.
After the first two queries typedef the b type is equivalent to void*, and с — to void**.
The next query typedef redefines b — it is now equal to &b = &void* = void. At that, the с type doesn't change.
After that the с type is defined as &&b* = &&void* = &void = errtype. It doesn't influence the b type, that's why the next typedef defines c as &void* = void.
Then the b type is again redefined as &void = errtype.
Please note that the c type in the next query is defined exactly as errtype******* = errtype, and not &void******* = void******. The same happens in the last typedef.
|
instruction
| 0
| 102,620
| 6
| 205,240
|
Tags: implementation, strings
Correct Solution:
```
#------------------------template--------------------------#
import os
import sys
# from math import *
from collections import *
# from fractions import *
# from heapq import*
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz'
M=10**9+7
EPS=1e-6
def Ceil(a,b): return a//b+int(a%b>0)
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
# vsInput()
def get(s):
if(s=="void" or s=='errtype'): return (s,0)
c1,c2=0,0
l=0
while(s[l]=='&'):
c1+=1
l+=1
r=len(s)-1
while(s[r]=='*'):
c2+=1
r-=1
if(r<l): return get('errtype')
here=c2-c1+cat[s[l:r+1]][1]
# print(s[l:r+1])
ans=get(cat[s[l:r+1]][0])
ans=(ans[0],ans[1]+here)
return ans
n=Int()
cat=defaultdict(lambda : ('errtype',0))
cat['void']=('void',0)
for i in range(n):
query=input()
if('typeof' in query):
_,var=query.split()
ans=get(var)
if(ans[1]<0 or ans[0]=='errtype'):
ans=('errtype',0)
print(ans[0],'*'*ans[1],sep="")
else:
_,ty,var=query.split()
ans=get(ty)
# print(ans)
if(ans[1]<0 or ans[0]=='errtype'):
ans=('errtype',0)
cat[var]=ans
```
|
output
| 1
| 102,620
| 6
| 205,241
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Programmer Vasya is studying a new programming language &K*. The &K* language resembles the languages of the C family in its syntax. However, it is more powerful, which is why the rules of the actual C-like languages are unapplicable to it. To fully understand the statement, please read the language's description below carefully and follow it and not the similar rules in real programming languages.
There is a very powerful system of pointers on &K* — you can add an asterisk to the right of the existing type X — that will result in new type X * . That is called pointer-definition operation. Also, there is the operation that does the opposite — to any type of X, which is a pointer, you can add an ampersand — that will result in a type &X, to which refers X. That is called a dereference operation.
The &K* language has only two basic data types — void and errtype. Also, the language has operators typedef and typeof.
* The operator "typedef A B" defines a new data type B, which is equivalent to A. A can have asterisks and ampersands, and B cannot have them. For example, the operator typedef void** ptptvoid will create a new type ptptvoid, that can be used as void**.
* The operator "typeof A" returns type of A, brought to void, that is, returns the type void**...*, equivalent to it with the necessary number of asterisks (the number can possibly be zero). That is, having defined the ptptvoid type, as shown above, the typeof ptptvoid operator will return void**.
An attempt of dereferencing of the void type will lead to an error: to a special data type errtype. For errtype the following equation holds true: errtype* = &errtype = errtype. An attempt to use the data type that hasn't been defined before that will also lead to the errtype.
Using typedef, we can define one type several times. Of all the definitions only the last one is valid. However, all the types that have been defined earlier using this type do not change.
Let us also note that the dereference operation has the lower priority that the pointer operation, in other words &T * is always equal to T.
Note, that the operators are executed consecutively one by one. If we have two operators "typedef &void a" and "typedef a* b", then at first a becomes errtype, and after that b becomes errtype* = errtype, but not &void* = void (see sample 2).
Vasya does not yet fully understand this powerful technology, that's why he asked you to help him. Write a program that analyzes these operators.
Input
The first line contains an integer n (1 ≤ n ≤ 100) — the number of operators. Then follow n lines with operators. Each operator is of one of two types: either "typedef A B", or "typeof A". In the first case the B type differs from void and errtype types, and besides, doesn't have any asterisks and ampersands.
All the data type names are non-empty lines of no more than 20 lowercase Latin letters. The number of asterisks and ampersands separately in one type in any operator does not exceed 10, however if we bring some types to void with several asterisks, their number may exceed 10.
Output
For every typeof operator print on the single line the answer to that operator — the type that the given operator returned.
Examples
Input
5
typedef void* ptv
typeof ptv
typedef &&ptv node
typeof node
typeof &ptv
Output
void*
errtype
void
Input
17
typedef void* b
typedef b* c
typeof b
typeof c
typedef &b b
typeof b
typeof c
typedef &&b* c
typeof c
typedef &b* c
typeof c
typedef &void b
typeof b
typedef b******* c
typeof c
typedef &&b* c
typeof c
Output
void*
void**
void
void**
errtype
void
errtype
errtype
errtype
Note
Let's look at the second sample.
After the first two queries typedef the b type is equivalent to void*, and с — to void**.
The next query typedef redefines b — it is now equal to &b = &void* = void. At that, the с type doesn't change.
After that the с type is defined as &&b* = &&void* = &void = errtype. It doesn't influence the b type, that's why the next typedef defines c as &void* = void.
Then the b type is again redefined as &void = errtype.
Please note that the c type in the next query is defined exactly as errtype******* = errtype, and not &void******* = void******. The same happens in the last typedef.
|
instruction
| 0
| 102,621
| 6
| 205,242
|
Tags: implementation, strings
Correct Solution:
```
n=int(input())
def Ref(v):
stars=0
ands=0
nam=""
for item in v:
if(item=='*'):
stars+=1
elif(item=='&'):
ands+=1
else:
nam+=item
if(nam not in T):
return "errtype"
x=T[nam]
if(x=="errtype"):
return str(x)
x+=stars
x-=ands
if(x<0):
return "errtype"
return x
T={'void':0}
for i in range(n):
s=input()
if(s[4]=='d'):
s=s[8:].split()
v=str(s[0])
name=str(s[1])
T[name]=Ref(v)
else:
s=s[7:]
x=Ref(str(s))
if(x=="errtype"):
print(x)
else:
print("void"+("*"*x))
```
|
output
| 1
| 102,621
| 6
| 205,243
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Programmer Vasya is studying a new programming language &K*. The &K* language resembles the languages of the C family in its syntax. However, it is more powerful, which is why the rules of the actual C-like languages are unapplicable to it. To fully understand the statement, please read the language's description below carefully and follow it and not the similar rules in real programming languages.
There is a very powerful system of pointers on &K* — you can add an asterisk to the right of the existing type X — that will result in new type X * . That is called pointer-definition operation. Also, there is the operation that does the opposite — to any type of X, which is a pointer, you can add an ampersand — that will result in a type &X, to which refers X. That is called a dereference operation.
The &K* language has only two basic data types — void and errtype. Also, the language has operators typedef and typeof.
* The operator "typedef A B" defines a new data type B, which is equivalent to A. A can have asterisks and ampersands, and B cannot have them. For example, the operator typedef void** ptptvoid will create a new type ptptvoid, that can be used as void**.
* The operator "typeof A" returns type of A, brought to void, that is, returns the type void**...*, equivalent to it with the necessary number of asterisks (the number can possibly be zero). That is, having defined the ptptvoid type, as shown above, the typeof ptptvoid operator will return void**.
An attempt of dereferencing of the void type will lead to an error: to a special data type errtype. For errtype the following equation holds true: errtype* = &errtype = errtype. An attempt to use the data type that hasn't been defined before that will also lead to the errtype.
Using typedef, we can define one type several times. Of all the definitions only the last one is valid. However, all the types that have been defined earlier using this type do not change.
Let us also note that the dereference operation has the lower priority that the pointer operation, in other words &T * is always equal to T.
Note, that the operators are executed consecutively one by one. If we have two operators "typedef &void a" and "typedef a* b", then at first a becomes errtype, and after that b becomes errtype* = errtype, but not &void* = void (see sample 2).
Vasya does not yet fully understand this powerful technology, that's why he asked you to help him. Write a program that analyzes these operators.
Input
The first line contains an integer n (1 ≤ n ≤ 100) — the number of operators. Then follow n lines with operators. Each operator is of one of two types: either "typedef A B", or "typeof A". In the first case the B type differs from void and errtype types, and besides, doesn't have any asterisks and ampersands.
All the data type names are non-empty lines of no more than 20 lowercase Latin letters. The number of asterisks and ampersands separately in one type in any operator does not exceed 10, however if we bring some types to void with several asterisks, their number may exceed 10.
Output
For every typeof operator print on the single line the answer to that operator — the type that the given operator returned.
Examples
Input
5
typedef void* ptv
typeof ptv
typedef &&ptv node
typeof node
typeof &ptv
Output
void*
errtype
void
Input
17
typedef void* b
typedef b* c
typeof b
typeof c
typedef &b b
typeof b
typeof c
typedef &&b* c
typeof c
typedef &b* c
typeof c
typedef &void b
typeof b
typedef b******* c
typeof c
typedef &&b* c
typeof c
Output
void*
void**
void
void**
errtype
void
errtype
errtype
errtype
Note
Let's look at the second sample.
After the first two queries typedef the b type is equivalent to void*, and с — to void**.
The next query typedef redefines b — it is now equal to &b = &void* = void. At that, the с type doesn't change.
After that the с type is defined as &&b* = &&void* = &void = errtype. It doesn't influence the b type, that's why the next typedef defines c as &void* = void.
Then the b type is again redefined as &void = errtype.
Please note that the c type in the next query is defined exactly as errtype******* = errtype, and not &void******* = void******. The same happens in the last typedef.
|
instruction
| 0
| 102,622
| 6
| 205,244
|
Tags: implementation, strings
Correct Solution:
```
types = {'void':'void', 'errtype':'errtype'}
def getRealType(type_expr):
expr_type = type_expr.strip('&*')
full_type_name = type_expr.replace(expr_type, types.get(expr_type, "errtype"))
base_type = full_type_name.strip('&*')
if base_type == "void":
addr_count = full_type_name.count('*')
deref_count = full_type_name.count('&')
if deref_count > addr_count:
return "errtype"
return base_type + "*" * (addr_count - deref_count)
else:
return "errtype"
def setTypeAlias(type_expr, alias_name):
types[alias_name] = getRealType(type_expr)
n = int(input())
for _ in range(n):
operator = input().split()
command = operator[0]
if command == "typedef":
setTypeAlias(operator[1], operator[2])
else:
print(getRealType(operator[1]))
# Made By Mostafa_Khaled
```
|
output
| 1
| 102,622
| 6
| 205,245
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Programmer Vasya is studying a new programming language &K*. The &K* language resembles the languages of the C family in its syntax. However, it is more powerful, which is why the rules of the actual C-like languages are unapplicable to it. To fully understand the statement, please read the language's description below carefully and follow it and not the similar rules in real programming languages.
There is a very powerful system of pointers on &K* — you can add an asterisk to the right of the existing type X — that will result in new type X * . That is called pointer-definition operation. Also, there is the operation that does the opposite — to any type of X, which is a pointer, you can add an ampersand — that will result in a type &X, to which refers X. That is called a dereference operation.
The &K* language has only two basic data types — void and errtype. Also, the language has operators typedef and typeof.
* The operator "typedef A B" defines a new data type B, which is equivalent to A. A can have asterisks and ampersands, and B cannot have them. For example, the operator typedef void** ptptvoid will create a new type ptptvoid, that can be used as void**.
* The operator "typeof A" returns type of A, brought to void, that is, returns the type void**...*, equivalent to it with the necessary number of asterisks (the number can possibly be zero). That is, having defined the ptptvoid type, as shown above, the typeof ptptvoid operator will return void**.
An attempt of dereferencing of the void type will lead to an error: to a special data type errtype. For errtype the following equation holds true: errtype* = &errtype = errtype. An attempt to use the data type that hasn't been defined before that will also lead to the errtype.
Using typedef, we can define one type several times. Of all the definitions only the last one is valid. However, all the types that have been defined earlier using this type do not change.
Let us also note that the dereference operation has the lower priority that the pointer operation, in other words &T * is always equal to T.
Note, that the operators are executed consecutively one by one. If we have two operators "typedef &void a" and "typedef a* b", then at first a becomes errtype, and after that b becomes errtype* = errtype, but not &void* = void (see sample 2).
Vasya does not yet fully understand this powerful technology, that's why he asked you to help him. Write a program that analyzes these operators.
Input
The first line contains an integer n (1 ≤ n ≤ 100) — the number of operators. Then follow n lines with operators. Each operator is of one of two types: either "typedef A B", or "typeof A". In the first case the B type differs from void and errtype types, and besides, doesn't have any asterisks and ampersands.
All the data type names are non-empty lines of no more than 20 lowercase Latin letters. The number of asterisks and ampersands separately in one type in any operator does not exceed 10, however if we bring some types to void with several asterisks, their number may exceed 10.
Output
For every typeof operator print on the single line the answer to that operator — the type that the given operator returned.
Examples
Input
5
typedef void* ptv
typeof ptv
typedef &&ptv node
typeof node
typeof &ptv
Output
void*
errtype
void
Input
17
typedef void* b
typedef b* c
typeof b
typeof c
typedef &b b
typeof b
typeof c
typedef &&b* c
typeof c
typedef &b* c
typeof c
typedef &void b
typeof b
typedef b******* c
typeof c
typedef &&b* c
typeof c
Output
void*
void**
void
void**
errtype
void
errtype
errtype
errtype
Note
Let's look at the second sample.
After the first two queries typedef the b type is equivalent to void*, and с — to void**.
The next query typedef redefines b — it is now equal to &b = &void* = void. At that, the с type doesn't change.
After that the с type is defined as &&b* = &&void* = &void = errtype. It doesn't influence the b type, that's why the next typedef defines c as &void* = void.
Then the b type is again redefined as &void = errtype.
Please note that the c type in the next query is defined exactly as errtype******* = errtype, and not &void******* = void******. The same happens in the last typedef.
|
instruction
| 0
| 102,623
| 6
| 205,246
|
Tags: implementation, strings
Correct Solution:
```
types = {'void':'void', 'errtype':'errtype'}
def getRealType(type_expr):
expr_type = type_expr.strip('&*')
full_type_name = type_expr.replace(expr_type, types.get(expr_type, "errtype"))
base_type = full_type_name.strip('&*')
if base_type == "void":
addr_count = full_type_name.count('*')
deref_count = full_type_name.count('&')
if deref_count > addr_count:
return "errtype"
return base_type + "*" * (addr_count - deref_count)
else:
return "errtype"
def setTypeAlias(type_expr, alias_name):
types[alias_name] = getRealType(type_expr)
n = int(input())
for _ in range(n):
operator = input().split()
command = operator[0]
if command == "typedef":
setTypeAlias(operator[1], operator[2])
else:
print(getRealType(operator[1]))
```
|
output
| 1
| 102,623
| 6
| 205,247
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Programmer Vasya is studying a new programming language &K*. The &K* language resembles the languages of the C family in its syntax. However, it is more powerful, which is why the rules of the actual C-like languages are unapplicable to it. To fully understand the statement, please read the language's description below carefully and follow it and not the similar rules in real programming languages.
There is a very powerful system of pointers on &K* — you can add an asterisk to the right of the existing type X — that will result in new type X * . That is called pointer-definition operation. Also, there is the operation that does the opposite — to any type of X, which is a pointer, you can add an ampersand — that will result in a type &X, to which refers X. That is called a dereference operation.
The &K* language has only two basic data types — void and errtype. Also, the language has operators typedef and typeof.
* The operator "typedef A B" defines a new data type B, which is equivalent to A. A can have asterisks and ampersands, and B cannot have them. For example, the operator typedef void** ptptvoid will create a new type ptptvoid, that can be used as void**.
* The operator "typeof A" returns type of A, brought to void, that is, returns the type void**...*, equivalent to it with the necessary number of asterisks (the number can possibly be zero). That is, having defined the ptptvoid type, as shown above, the typeof ptptvoid operator will return void**.
An attempt of dereferencing of the void type will lead to an error: to a special data type errtype. For errtype the following equation holds true: errtype* = &errtype = errtype. An attempt to use the data type that hasn't been defined before that will also lead to the errtype.
Using typedef, we can define one type several times. Of all the definitions only the last one is valid. However, all the types that have been defined earlier using this type do not change.
Let us also note that the dereference operation has the lower priority that the pointer operation, in other words &T * is always equal to T.
Note, that the operators are executed consecutively one by one. If we have two operators "typedef &void a" and "typedef a* b", then at first a becomes errtype, and after that b becomes errtype* = errtype, but not &void* = void (see sample 2).
Vasya does not yet fully understand this powerful technology, that's why he asked you to help him. Write a program that analyzes these operators.
Input
The first line contains an integer n (1 ≤ n ≤ 100) — the number of operators. Then follow n lines with operators. Each operator is of one of two types: either "typedef A B", or "typeof A". In the first case the B type differs from void and errtype types, and besides, doesn't have any asterisks and ampersands.
All the data type names are non-empty lines of no more than 20 lowercase Latin letters. The number of asterisks and ampersands separately in one type in any operator does not exceed 10, however if we bring some types to void with several asterisks, their number may exceed 10.
Output
For every typeof operator print on the single line the answer to that operator — the type that the given operator returned.
Examples
Input
5
typedef void* ptv
typeof ptv
typedef &&ptv node
typeof node
typeof &ptv
Output
void*
errtype
void
Input
17
typedef void* b
typedef b* c
typeof b
typeof c
typedef &b b
typeof b
typeof c
typedef &&b* c
typeof c
typedef &b* c
typeof c
typedef &void b
typeof b
typedef b******* c
typeof c
typedef &&b* c
typeof c
Output
void*
void**
void
void**
errtype
void
errtype
errtype
errtype
Note
Let's look at the second sample.
After the first two queries typedef the b type is equivalent to void*, and с — to void**.
The next query typedef redefines b — it is now equal to &b = &void* = void. At that, the с type doesn't change.
After that the с type is defined as &&b* = &&void* = &void = errtype. It doesn't influence the b type, that's why the next typedef defines c as &void* = void.
Then the b type is again redefined as &void = errtype.
Please note that the c type in the next query is defined exactly as errtype******* = errtype, and not &void******* = void******. The same happens in the last typedef.
Submitted Solution:
```
#------------------------template--------------------------#
import os
import sys
# from math import *
from collections import *
# from fractions import *
# from heapq import*
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz'
M=10**9+7
EPS=1e-6
def Ceil(a,b): return a//b+int(a%b>0)
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
# vsInput()
def get(s):
if(s=="void" or s=='errtype'): return (s,0)
c1,c2=0,0
l=0
while(s[l]=='&'):
c1+=1
l+=1
r=len(s)-1
while(s[r]=='*'):
c2+=1
r-=1
if(r<l): return get('errtype')
here=c2-c1+cat[s[l:r+1]][1]
# print(s[l:r+1])
ans=get(cat[s[l:r+1]][0])
ans=(ans[0],ans[1]+here)
return ans
n=Int()
cat=defaultdict(lambda : ('errtype',0))
cat['void']=('void',0)
for i in range(n):
query=input()
if('typeof' in query):
_,var=query.split()
ans=get(var)
if(ans[1]<0 or ans[0]=='errtype'):
ans=('errtype',0)
print(ans[0],'*'*ans[1])
else:
_,ty,var=query.split()
ans=get(ty)
# print(ans)
if(ans[1]<0 or ans[0]=='errtype'):
ans=('errtype',0)
cat[var]=ans
```
|
instruction
| 0
| 102,624
| 6
| 205,248
|
No
|
output
| 1
| 102,624
| 6
| 205,249
|
Provide tags and a correct Python 3 solution for this coding contest problem.
When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided to rearrange them. Help him restore the original number, on condition that it was the maximum possible one.
Input
The first line contains a single integer n (1 ⩽ n ⩽ 10^5) — the length of the string. The second line contains a string consisting of English lowercase letters: 'z', 'e', 'r', 'o' and 'n'.
It is guaranteed that it is possible to rearrange the letters in such a way that they form a sequence of words, each being either "zero" which corresponds to the digit 0 or "one" which corresponds to the digit 1.
Output
Print the maximum possible number in binary notation. Print binary digits separated by a space. The leading zeroes are allowed.
Examples
Input
4
ezor
Output
0
Input
10
nznooeeoer
Output
1 1 0
Note
In the first example, the correct initial ordering is "zero".
In the second example, the correct initial ordering is "oneonezero".
|
instruction
| 0
| 103,001
| 6
| 206,002
|
Tags: implementation, sortings, strings
Correct Solution:
```
length = int(input())
string = input()
contador_0 = 0
contador_1 = 0
for letter in string:
if letter == 'z':
contador_0 += 1
elif letter == 'n':
contador_1 += 1
string = ''
for contador in range(contador_1):
string += '1 '
for contador in range(contador_0):
string += '0 '
string=''.join(list(string)[:-1])
print(string)
```
|
output
| 1
| 103,001
| 6
| 206,003
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.