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.
Patrick has just finished writing a message to his sweetheart Stacey when he noticed that the message didn't look fancy. Patrick was nervous while writing the message, so some of the letters there were lowercase and some of them were uppercase.
Patrick believes that a message is fancy if any uppercase letter stands to the left of any lowercase one. In other words, this rule describes the strings where first go zero or more uppercase letters, and then β zero or more lowercase letters.
To make the message fancy, Patrick can erase some letter and add the same letter in the same place in the opposite case (that is, he can replace an uppercase letter with the lowercase one and vice versa). Patrick got interested in the following question: what minimum number of actions do we need to make a message fancy? Changing a letter's case in the message counts as one action. Patrick cannot perform any other actions.
Input
The only line of the input contains a non-empty string consisting of uppercase and lowercase letters. The string's length does not exceed 105.
Output
Print a single number β the least number of actions needed to make the message fancy.
Examples
Input
PRuvetSTAaYA
Output
5
Input
OYPROSTIYAOPECHATALSYAPRIVETSTASYA
Output
0
Input
helloworld
Output
0 | instruction | 0 | 16,249 | 6 | 32,498 |
Tags: dp
Correct Solution:
```
s=input()
n=len(s)
if all(i.isupper() for i in s):
print(0)
exit()
if all(i.islower() for i in s):
print(0)
exit()
pres=[0]*n
pre=[0]*n
if s[0].isupper():
pre[0]=1
else:
pres[0]=1
for i in range(1,n):
pre[i]=pre[i-1]+(s[i].isupper())
pres[i]=pres[i-1]+(s[i].islower())
mini=10**9
mini=min(mini,pre[n-1])
mini=min(mini,pres[n-1])
for i in range(1,n):
change=pres[i-1]+(pre[n-1]-pre[i-1])
mini=min(mini,change)
print(mini)
``` | output | 1 | 16,249 | 6 | 32,499 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Patrick has just finished writing a message to his sweetheart Stacey when he noticed that the message didn't look fancy. Patrick was nervous while writing the message, so some of the letters there were lowercase and some of them were uppercase.
Patrick believes that a message is fancy if any uppercase letter stands to the left of any lowercase one. In other words, this rule describes the strings where first go zero or more uppercase letters, and then β zero or more lowercase letters.
To make the message fancy, Patrick can erase some letter and add the same letter in the same place in the opposite case (that is, he can replace an uppercase letter with the lowercase one and vice versa). Patrick got interested in the following question: what minimum number of actions do we need to make a message fancy? Changing a letter's case in the message counts as one action. Patrick cannot perform any other actions.
Input
The only line of the input contains a non-empty string consisting of uppercase and lowercase letters. The string's length does not exceed 105.
Output
Print a single number β the least number of actions needed to make the message fancy.
Examples
Input
PRuvetSTAaYA
Output
5
Input
OYPROSTIYAOPECHATALSYAPRIVETSTASYA
Output
0
Input
helloworld
Output
0
Submitted Solution:
```
from collections import deque
from math import gcd,sqrt,log
def mi():return map(int,input().split())
def li():return list(mi())
def ii():return int(input())
s=input()
n=len(s)
upco=[0]*n
c1=0
if(s[n-1].isupper()):
c1+=1
for i in range(n-2,-1,-1):
upco[i]=c1
if(s[i].isupper()):
c1+=1
lowco=[0]*n
c1=0
if(s[0].islower()):
c1+=1
for i in range(1,n):
lowco[i]=c1
if(s[i].islower()):
c1+=1
x=1e5
for i in range(n):
x=min(x,upco[i]+lowco[i])
print(x)
``` | instruction | 0 | 16,253 | 6 | 32,506 |
Yes | output | 1 | 16,253 | 6 | 32,507 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Patrick has just finished writing a message to his sweetheart Stacey when he noticed that the message didn't look fancy. Patrick was nervous while writing the message, so some of the letters there were lowercase and some of them were uppercase.
Patrick believes that a message is fancy if any uppercase letter stands to the left of any lowercase one. In other words, this rule describes the strings where first go zero or more uppercase letters, and then β zero or more lowercase letters.
To make the message fancy, Patrick can erase some letter and add the same letter in the same place in the opposite case (that is, he can replace an uppercase letter with the lowercase one and vice versa). Patrick got interested in the following question: what minimum number of actions do we need to make a message fancy? Changing a letter's case in the message counts as one action. Patrick cannot perform any other actions.
Input
The only line of the input contains a non-empty string consisting of uppercase and lowercase letters. The string's length does not exceed 105.
Output
Print a single number β the least number of actions needed to make the message fancy.
Examples
Input
PRuvetSTAaYA
Output
5
Input
OYPROSTIYAOPECHATALSYAPRIVETSTASYA
Output
0
Input
helloworld
Output
0
Submitted Solution:
```
from collections import deque
from math import gcd,sqrt,log
def mi():return map(int,input().split())
def li():return list(mi())
def ii():return int(input())
s=input()
n=len(s)
c1=0
c2=0
f=0
for i in s:
if(f==1):
if(ord(i)>=97 and ord(i)<=122):
c1+=1
else:
c2+=1
if(f==0 and ord(i)>=97 and ord(i)<=122):
f=1
c1+=1
print(min(c1,c2))
``` | instruction | 0 | 16,256 | 6 | 32,512 |
No | output | 1 | 16,256 | 6 | 32,513 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order.
After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!
She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.
Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si β ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet.
Input
The first line contains an integer n (1 β€ n β€ 100): number of names.
Each of the following n lines contain one string namei (1 β€ |namei| β€ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different.
Output
If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on).
Otherwise output a single word "Impossible" (without quotes).
Examples
Input
3
rivest
shamir
adleman
Output
bcdefghijklmnopqrsatuvwxyz
Input
10
tourist
petr
wjmzbmr
yeputons
vepifanov
scottwu
oooooooooooooooo
subscriber
rowdark
tankengineer
Output
Impossible
Input
10
petr
egor
endagorion
feferivan
ilovetanyaromanova
kostka
dmitriyh
maratsnowbear
bredorjaguarturnik
cgyforever
Output
aghjlnopefikdmbcqrstuvwxyz
Input
7
car
care
careful
carefully
becarefuldontforgetsomething
otherwiseyouwillbehacked
goodluck
Output
acbdefhijklmnogpqrstuvwxyz | instruction | 0 | 16,362 | 6 | 32,724 |
Tags: dfs and similar, graphs, sortings
Correct Solution:
```
#http://codeforces.com/contest/510/problem/C
#https://www.quora.com/What-is-the-algorithmic-approach-to-solve-the-Codeforces-problem-Fox-and-Names
#Great problem, tests for cycles and also involves topological sorting
n=int(input())
strings=[]
for i in range(n):
t=input()
strings.append(t)
from collections import deque
from collections import defaultdict
class Graph:
def __init__(self):
self.neighbours=defaultdict(set)
def addEdge(self,u,v):
self.neighbours[u].add(v)
def isCyclicVisit(self,u,black_stack,grey_stack):
grey_stack[u]=True
black_stack[u]=True
for v in self.neighbours[u]:
if(not black_stack[v]):
if(self.isCyclicVisit(v,black_stack,grey_stack)):
return True
elif(grey_stack[v]):
return True
grey_stack[u]=False
return False
def isCyclic(self,white_stack):
black_stack=defaultdict(lambda:False)
grey_stack=defaultdict(lambda:False)
for w in white_stack:
grey_stack=defaultdict(lambda:False)
if(not black_stack[w]):
if(self.isCyclicVisit(w,black_stack,grey_stack)):
return True
return False
def dfs(self,u,visited,topological_order):
visited[u]=True
for v in self.neighbours[u]:
if(v not in visited):
self.dfs(v,visited,topological_order)
topological_order.appendleft(u)
def dfs_visit(self,s):
alphabets=[]
topological_order=deque()
visited=defaultdict(lambda:False)
for i in range(97,123):
alphabets.append(chr(i))
for c in alphabets:
if(c not in visited):
self.dfs(c,visited,topological_order)
return topological_order
g=Graph()
#add edges
leflag=False #careful followed by care is impossible
vertices=[]
for i in range(n-1):
first=strings[i]
second=strings[i+1]
flen=len(first)
slen=len(second)
if(flen>slen): #second is a substring of
if(first[:slen]==second):
leflag=True
break
for j in range(0,min(flen,slen)):
if(first[j]!=second[j]):
vertices.append(first[j])
#first mismatch
#MAKE SURE YOU ADD AN
g.addEdge(first[j],second[j])
break
order=g.dfs_visit('z')
if(leflag or g.isCyclic(vertices)):
print("Impossible")
else:
print(''.join(order))
``` | output | 1 | 16,362 | 6 | 32,725 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order.
After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!
She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.
Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si β ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet.
Input
The first line contains an integer n (1 β€ n β€ 100): number of names.
Each of the following n lines contain one string namei (1 β€ |namei| β€ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different.
Output
If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on).
Otherwise output a single word "Impossible" (without quotes).
Examples
Input
3
rivest
shamir
adleman
Output
bcdefghijklmnopqrsatuvwxyz
Input
10
tourist
petr
wjmzbmr
yeputons
vepifanov
scottwu
oooooooooooooooo
subscriber
rowdark
tankengineer
Output
Impossible
Input
10
petr
egor
endagorion
feferivan
ilovetanyaromanova
kostka
dmitriyh
maratsnowbear
bredorjaguarturnik
cgyforever
Output
aghjlnopefikdmbcqrstuvwxyz
Input
7
car
care
careful
carefully
becarefuldontforgetsomething
otherwiseyouwillbehacked
goodluck
Output
acbdefhijklmnogpqrstuvwxyz | instruction | 0 | 16,363 | 6 | 32,726 |
Tags: dfs and similar, graphs, sortings
Correct Solution:
```
import string
from collections import defaultdict
def solve(n, s):
g = defaultdict(set)
edges = []
for i in range(n - 1):
condition = None
for ca, cb in zip(s[i], s[i + 1]):
if ca == cb:
continue
condition = ca, cb
break
if condition is None:
if len(s[i]) > len(s[i + 1]):
return None
continue
parent, child = condition
edges.append((parent, child))
g[parent].add(child)
visited = set()
def gen_topology(e):
if e in visited:
return
visited.add(e)
if e in g:
for next in g[e]:
if next in visited:
continue
gen_topology(next)
stack.append(e)
stack = []
for e in g.keys():
if e in visited:
continue
gen_topology(e)
weight = {}
for i, e in enumerate(stack[::-1]):
weight[e] = i
for parent, child in edges:
if weight[parent] > weight[child]:
return None
r = stack[::-1]
for e in string.ascii_lowercase:
if e not in r:
r.append(e)
return r
n = int(input())
s = [input() for _ in range(n)]
r = solve(n, s)
if not r:
print('Impossible')
else:
print(''.join(r))
``` | output | 1 | 16,363 | 6 | 32,727 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order.
After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!
She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.
Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si β ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet.
Input
The first line contains an integer n (1 β€ n β€ 100): number of names.
Each of the following n lines contain one string namei (1 β€ |namei| β€ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different.
Output
If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on).
Otherwise output a single word "Impossible" (without quotes).
Examples
Input
3
rivest
shamir
adleman
Output
bcdefghijklmnopqrsatuvwxyz
Input
10
tourist
petr
wjmzbmr
yeputons
vepifanov
scottwu
oooooooooooooooo
subscriber
rowdark
tankengineer
Output
Impossible
Input
10
petr
egor
endagorion
feferivan
ilovetanyaromanova
kostka
dmitriyh
maratsnowbear
bredorjaguarturnik
cgyforever
Output
aghjlnopefikdmbcqrstuvwxyz
Input
7
car
care
careful
carefully
becarefuldontforgetsomething
otherwiseyouwillbehacked
goodluck
Output
acbdefhijklmnogpqrstuvwxyz | instruction | 0 | 16,364 | 6 | 32,728 |
Tags: dfs and similar, graphs, sortings
Correct Solution:
```
#import sys
#sys.stdin = open('in.txt')
#sys.setrecursionlimit(10000)
def isPrefix(sa, sb):
if len(sa) >= len(sb):
return False
return sa == sb[0:len(sa)]
def getOrder(sa, sb):
for i in range(min(len(sa), len(sb))):
if sa[i] != sb[i]:
return sa[i], sb[i]
test = False
if test:
fp = open('in.txt', 'r')
n = int(fp.readline().strip())
names = [fp.readline().strip() for _ in range(n)]
fp.close()
else:
n = int(input().strip())
names = [input().strip() for _ in range(n)]
res = True
g = [[False] * 26 for _ in range(26)]
"""
for i in range(26):
for j in range(26):
g[i][j] = False
"""
def printG():
print(" abcdefghijklmnopqrstuvwxyz")
for i in range(0, 26):
print(chr(ord('a') + i), "".join(["1" if x else "0" for x in g[i]]), sep =
"")
#get a table
for i in range(n - 1):
if names[i] == names[i + 1] or isPrefix(names[i], names[i + 1]):
continue
elif isPrefix(names[i + 1], names[i]):
res = False
break
else:
ca, cb = getOrder(names[i], names[i + 1])
#print(ca, '<', cb)
if g[ord(cb) - ord('a')][ord(ca) - ord('a')]:
res = False
break
else:
#pass
#printG()
a = ord(ca) - ord('a')
b = ord(cb) - ord('a')
g[a][b] = True
#printG()
if not res:
print("Impossible")
else:
def getZeroIndegreeNode():
for i in range(26):
if not vis[i] and Indegree[i] == 0:
return i
return -1
#cacl Indegree
strOrder = []
vis = [False] * 26
Indegree = [0] * 26
for i in range(26):
ithIndegree = 0
for j in range(26):
if g[j][i]: ithIndegree += 1
Indegree[i] = ithIndegree
#get the order string
for i in range(26):
ZeroIndegreeNode = getZeroIndegreeNode()
if ZeroIndegreeNode == -1:
res = False
break
else:
strOrder.append(chr(ord('a') + ZeroIndegreeNode))
vis[ZeroIndegreeNode] = True
for i in range(26):
if g[ZeroIndegreeNode][i]:
Indegree[i] -= 1
if not res:
print("Impossible")
else:
print("".join(strOrder))
``` | output | 1 | 16,364 | 6 | 32,729 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order.
After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!
She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.
Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si β ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet.
Input
The first line contains an integer n (1 β€ n β€ 100): number of names.
Each of the following n lines contain one string namei (1 β€ |namei| β€ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different.
Output
If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on).
Otherwise output a single word "Impossible" (without quotes).
Examples
Input
3
rivest
shamir
adleman
Output
bcdefghijklmnopqrsatuvwxyz
Input
10
tourist
petr
wjmzbmr
yeputons
vepifanov
scottwu
oooooooooooooooo
subscriber
rowdark
tankengineer
Output
Impossible
Input
10
petr
egor
endagorion
feferivan
ilovetanyaromanova
kostka
dmitriyh
maratsnowbear
bredorjaguarturnik
cgyforever
Output
aghjlnopefikdmbcqrstuvwxyz
Input
7
car
care
careful
carefully
becarefuldontforgetsomething
otherwiseyouwillbehacked
goodluck
Output
acbdefhijklmnogpqrstuvwxyz | instruction | 0 | 16,365 | 6 | 32,730 |
Tags: dfs and similar, graphs, sortings
Correct Solution:
```
# https://codeforces.com/problemset/problem/510/C
import heapq
def kahn(graph):
V = len(graph)
in_degree = [0] * V
for i in range(V):
for j in graph[i]:
in_degree[j] += 1
zero_in_degree = []
for i in range(V):
if in_degree[i] == 0:
heapq.heappush(zero_in_degree, i)
result = []
while zero_in_degree:
u = heapq.heappop(zero_in_degree)
result.append(chr(u + 97))
for i in graph[u]:
in_degree[i] -= 1
if in_degree[i] == 0:
heapq.heappush(zero_in_degree, i)
return result
def solution():
V = 26
E = int(input())
graph = [[] for i in range(V)]
names = []
for i in range(E):
names.append(input().strip())
for i in range(E - 1):
min_length = min(len(names[i]), len(names[i + 1]))
found = False
for j in range(min_length):
if names[i][j] != names[i + 1][j]:
found = True
graph[ord(names[i][j]) - 97].append(ord(names[i + 1][j]) - 97)
break
if not found and len(names[i]) > len(names[i + 1]):
print('Impossible')
return
result = kahn(graph)
if len(result) < V:
print('Impossible')
else:
print(*result, sep='')
solution()
``` | output | 1 | 16,365 | 6 | 32,731 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order.
After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!
She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.
Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si β ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet.
Input
The first line contains an integer n (1 β€ n β€ 100): number of names.
Each of the following n lines contain one string namei (1 β€ |namei| β€ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different.
Output
If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on).
Otherwise output a single word "Impossible" (without quotes).
Examples
Input
3
rivest
shamir
adleman
Output
bcdefghijklmnopqrsatuvwxyz
Input
10
tourist
petr
wjmzbmr
yeputons
vepifanov
scottwu
oooooooooooooooo
subscriber
rowdark
tankengineer
Output
Impossible
Input
10
petr
egor
endagorion
feferivan
ilovetanyaromanova
kostka
dmitriyh
maratsnowbear
bredorjaguarturnik
cgyforever
Output
aghjlnopefikdmbcqrstuvwxyz
Input
7
car
care
careful
carefully
becarefuldontforgetsomething
otherwiseyouwillbehacked
goodluck
Output
acbdefhijklmnogpqrstuvwxyz | instruction | 0 | 16,366 | 6 | 32,732 |
Tags: dfs and similar, graphs, sortings
Correct Solution:
```
from collections import defaultdict, Counter
if __name__ == "__main__":
G = defaultdict(set)
names = [input() for _ in range(int(input()))]
last = names[0]
has_in = Counter()
total = set([])
impossible = False
for name in names[1:]:
i = 0
while(i < len(name) and i < len(last) and last[i] == name[i]):
i += 1
if i < len(name) and i < len(last):
G[last[i]].add(name[i])
has_in[name[i]] += 1
total.add(last[i])
total.add(name[i])
elif len(last) > len(name):
impossible = True
break
last = name
if impossible:
print("Impossible")
else:
alphabet = []
def hierholzers(curr):
while(G[curr]):
next = G[curr].pop()
has_in[next] -= 1
hierholzers(next)
if not curr in alphabet:
alphabet.append(curr)
keys = list(G.keys())
for g in keys:
if has_in[g] <= 0:
hierholzers(g)
import random
if not alphabet and G or len(alphabet) != len(total):
print("Impossible")
else:
alphabet = list(reversed(alphabet))
for ch in range(ord("a"), ord("z") + 1):
if not (chr(ch) in alphabet):
if random.randint(1, 10) > 5:
alphabet = [chr(ch)] + alphabet
else:
alphabet.append(chr(ch))
print(''.join(alphabet))
``` | output | 1 | 16,366 | 6 | 32,733 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order.
After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!
She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.
Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si β ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet.
Input
The first line contains an integer n (1 β€ n β€ 100): number of names.
Each of the following n lines contain one string namei (1 β€ |namei| β€ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different.
Output
If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on).
Otherwise output a single word "Impossible" (without quotes).
Examples
Input
3
rivest
shamir
adleman
Output
bcdefghijklmnopqrsatuvwxyz
Input
10
tourist
petr
wjmzbmr
yeputons
vepifanov
scottwu
oooooooooooooooo
subscriber
rowdark
tankengineer
Output
Impossible
Input
10
petr
egor
endagorion
feferivan
ilovetanyaromanova
kostka
dmitriyh
maratsnowbear
bredorjaguarturnik
cgyforever
Output
aghjlnopefikdmbcqrstuvwxyz
Input
7
car
care
careful
carefully
becarefuldontforgetsomething
otherwiseyouwillbehacked
goodluck
Output
acbdefhijklmnogpqrstuvwxyz | instruction | 0 | 16,367 | 6 | 32,734 |
Tags: dfs and similar, graphs, sortings
Correct Solution:
```
from sys import stdin,stdout
inp=stdin.readline
op=stdout.write
n=int(inp())
st=[]
for i in range(n):
temp=list(inp()[:-1])
st.append(temp)
alph=list("abcdefghijklmnopqrstuvwxyz")
g={alph[i]:[] for i in range(26)}
pos=0
flag=1
for i in range(n-1):
x=st[i]
y=st[i+1]
pos=0
while(pos<len(x) and pos<len(y) and x[pos]==y[pos]):
if(pos+1<len(x) and pos+1>=len(y)):
break
else:
pos=pos+1
else:
if (pos<len(x) and pos<len(y)):
if(x[pos] in g[y[pos]]):
break
else:
g[x[pos]].append(y[pos])
continue
break
else:
flag=0
if(flag==0):
st=[]
vis={i:0 for i in list(g.keys())}
q=[]
indeg={i:0 for i in list(g.keys())}
for i in alph:
for j in g[i]:
if not(j==0):
indeg[j]+=1
for j in list(indeg.keys()):
if(indeg[j]==0):
q.append(j)
vis[j]=1
ans=[]
while(len(q)>0):
temp=q.pop(0)
ans.append(temp)
for j in g[temp]:
if not(j==0) and vis[j]==0:
indeg[j]-=1
for j in list(indeg.keys()):
if(indeg[j]==0 and vis[j]==0):
q.append(j)
vis[j]=1
if(len(ans)==26):
op(''.join(ans))
else:
op("Impossible\n")
else:
op("Impossible\n")
``` | output | 1 | 16,367 | 6 | 32,735 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order.
After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!
She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.
Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si β ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet.
Input
The first line contains an integer n (1 β€ n β€ 100): number of names.
Each of the following n lines contain one string namei (1 β€ |namei| β€ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different.
Output
If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on).
Otherwise output a single word "Impossible" (without quotes).
Examples
Input
3
rivest
shamir
adleman
Output
bcdefghijklmnopqrsatuvwxyz
Input
10
tourist
petr
wjmzbmr
yeputons
vepifanov
scottwu
oooooooooooooooo
subscriber
rowdark
tankengineer
Output
Impossible
Input
10
petr
egor
endagorion
feferivan
ilovetanyaromanova
kostka
dmitriyh
maratsnowbear
bredorjaguarturnik
cgyforever
Output
aghjlnopefikdmbcqrstuvwxyz
Input
7
car
care
careful
carefully
becarefuldontforgetsomething
otherwiseyouwillbehacked
goodluck
Output
acbdefhijklmnogpqrstuvwxyz | instruction | 0 | 16,368 | 6 | 32,736 |
Tags: dfs and similar, graphs, sortings
Correct Solution:
```
import queue
from collections import defaultdict
from string import ascii_lowercase
n = int(input())
x = [input() for i in range(n)]
post = defaultdict(lambda: set())
prior = defaultdict(lambda: set())
for i in range(n):
for j in range(i + 1, n):
match = -1
for k in range(min(len(x[i]), len(x[j]))):
if x[i][k] != x[j][k]:
match = k
break
if match == -1:
if len(x[i]) > len(x[j]):
print("Impossible")
exit()
else:
post[x[i][match]].add(x[j][match])
prior[x[j][match]].add(x[i][match])
q = queue.Queue()
visited = set()
for char in ascii_lowercase:
if len(prior[char]) == 0:
visited.add(char)
q.put(char)
s = ''
while q.qsize():
char = q.get()
for item in post[char]:
prior[item].remove(char)
s += char
for ch in ascii_lowercase:
if ch not in visited and len(prior[ch]) == 0:
visited.add(ch)
q.put(ch)
print(s if len(s) == 26 else "Impossible")
``` | output | 1 | 16,368 | 6 | 32,737 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order.
After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!
She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.
Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si β ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet.
Input
The first line contains an integer n (1 β€ n β€ 100): number of names.
Each of the following n lines contain one string namei (1 β€ |namei| β€ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different.
Output
If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on).
Otherwise output a single word "Impossible" (without quotes).
Examples
Input
3
rivest
shamir
adleman
Output
bcdefghijklmnopqrsatuvwxyz
Input
10
tourist
petr
wjmzbmr
yeputons
vepifanov
scottwu
oooooooooooooooo
subscriber
rowdark
tankengineer
Output
Impossible
Input
10
petr
egor
endagorion
feferivan
ilovetanyaromanova
kostka
dmitriyh
maratsnowbear
bredorjaguarturnik
cgyforever
Output
aghjlnopefikdmbcqrstuvwxyz
Input
7
car
care
careful
carefully
becarefuldontforgetsomething
otherwiseyouwillbehacked
goodluck
Output
acbdefhijklmnogpqrstuvwxyz | instruction | 0 | 16,369 | 6 | 32,738 |
Tags: dfs and similar, graphs, sortings
Correct Solution:
```
import string
import sys
input = sys.stdin.readline
def getInts():
return [int(s) for s in input().split()]
def getInt():
return int(input())
def getStrs():
return [s for s in input().split()]
def getStr():
return input().strip()
def listStr():
return list(input().strip())
import collections as col
import math,itertools
"""
"""
def getFirstDiff(s1,s2):
while s1 and s2:
l1, l2 = s1[0], s2[0]
if l1 != l2:
return l1, l2
s1, s2 = s1[1:], s2[1:]
return None, None
def solve():
nodes = set(list(string.ascii_lowercase))
roots = []
parents = col.defaultdict(set)
def bfs(graph,node,queue,visited_dict,nodes):
pref = '1'
visited_dict[node] = pref
nodes.remove(node)
queue.append((node,pref))
queue = col.deque(queue)
cycle = False
while queue:
s, pref = queue.popleft()
tmp = 0
for neighbour in graph[s]:
if neighbour in visited_dict:
pref1 = visited_dict[neighbour]
x = len(pref)
if pref == pref1[:len(pref)]:
#example t->y, t->w->x->y is *not* a cycle
cycle = True
if neighbour not in visited_dict and neighbour in nodes:
tmp += 1
visited_dict[neighbour] = pref+str(tmp)
nodes.remove(neighbour)
queue.append((neighbour,pref+str(tmp)))
return cycle, nodes
N = getInt()
children = col.defaultdict(set)
for letter in nodes:
children[letter] = set()
parents[letter] = set()
names = []
for n in range(N):
names.append(getStr())
for j in range(N-1):
a, b = getFirstDiff(names[j],names[j+1])
if a is None:
if len(names[j]) > len(names[j+1]):
if names[0] == "adjcquqdqcsvixgwglwrrmkhdsbebbjvcgz":
print("Hi")
return "Impossible"
continue
children[a].add(b)
parents[b].add(a)
ans = ''
for child in parents:
if len(parents[child]) == 0:
roots.append(child)
roots2 = list(roots)
while roots:
node = roots.pop()
cycle, nodes = bfs(children,node,[],{},nodes)
if cycle:
return "Impossible"
#so we know there are no cycles
nodes = set(list(string.ascii_lowercase))
def reverse_post_order(graph, root):
"""Return a post-order ordering of nodes in the graph."""
visited = set()
order = []
def dfs_walk(node):
visited.add(node)
if node in nodes:
nodes.remove(node)
for neighbour in graph[node]:
if neighbour in nodes and neighbour not in visited:
dfs_walk(neighbour)
order.append(node)
dfs_walk(root)
return order[::-1]
while roots2:
node = roots2.pop()
visited = reverse_post_order(children,node)
ans = ''.join(visited) + ans
if len(ans) < 26:
return "Impossible"
return ans
print(solve())
``` | output | 1 | 16,369 | 6 | 32,739 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order.
After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!
She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.
Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si β ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet.
Input
The first line contains an integer n (1 β€ n β€ 100): number of names.
Each of the following n lines contain one string namei (1 β€ |namei| β€ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different.
Output
If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on).
Otherwise output a single word "Impossible" (without quotes).
Examples
Input
3
rivest
shamir
adleman
Output
bcdefghijklmnopqrsatuvwxyz
Input
10
tourist
petr
wjmzbmr
yeputons
vepifanov
scottwu
oooooooooooooooo
subscriber
rowdark
tankengineer
Output
Impossible
Input
10
petr
egor
endagorion
feferivan
ilovetanyaromanova
kostka
dmitriyh
maratsnowbear
bredorjaguarturnik
cgyforever
Output
aghjlnopefikdmbcqrstuvwxyz
Input
7
car
care
careful
carefully
becarefuldontforgetsomething
otherwiseyouwillbehacked
goodluck
Output
acbdefhijklmnogpqrstuvwxyz
Submitted Solution:
```
imp = False
nodes = {}
for i in "abcdefghijklmnopqrstuvwxyz":
nodes[i] = set()
n = int(input())
prev = None
for i in range(n):
name = input()
if prev:
for x, y in zip(name, prev):
if x != y:
nodes[x].add(y)
break
else:
if prev > name:
imp = True
break
prev = name
q = []
r = []
for i in "abcdefghijklmnopqrstuvwxyz":
if not nodes[i]:
q.append(i)
else:
r.append(i)
l = []
while q:
e = q.pop()
l.append(e)
for i in r[:]:
if e in nodes[i]:
nodes[i].remove(e)
if not nodes[i]:
q.append(i)
r.remove(i)
if r or imp:
print("Impossible")
else:
print("".join(l))
``` | instruction | 0 | 16,370 | 6 | 32,740 |
Yes | output | 1 | 16,370 | 6 | 32,741 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order.
After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!
She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.
Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si β ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet.
Input
The first line contains an integer n (1 β€ n β€ 100): number of names.
Each of the following n lines contain one string namei (1 β€ |namei| β€ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different.
Output
If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on).
Otherwise output a single word "Impossible" (without quotes).
Examples
Input
3
rivest
shamir
adleman
Output
bcdefghijklmnopqrsatuvwxyz
Input
10
tourist
petr
wjmzbmr
yeputons
vepifanov
scottwu
oooooooooooooooo
subscriber
rowdark
tankengineer
Output
Impossible
Input
10
petr
egor
endagorion
feferivan
ilovetanyaromanova
kostka
dmitriyh
maratsnowbear
bredorjaguarturnik
cgyforever
Output
aghjlnopefikdmbcqrstuvwxyz
Input
7
car
care
careful
carefully
becarefuldontforgetsomething
otherwiseyouwillbehacked
goodluck
Output
acbdefhijklmnogpqrstuvwxyz
Submitted Solution:
```
###### ### ####### ####### ## # ##### ### #####
# # # # # # # # # # # # # ###
# # # # # # # # # # # # # ###
###### ######### # # # # # # ######### #
###### ######### # # # # # # ######### #
# # # # # # # # # # #### # # #
# # # # # # # ## # # # # #
###### # # ####### ####### # # ##### # # # #
from __future__ import print_function # for PyPy2
from collections import Counter, OrderedDict
from itertools import permutations as perm
from fractions import Fraction
from collections import deque
from sys import stdin
from bisect import *
from heapq import *
from math import *
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
mod = int(1e9)+7
inf = float("inf")
# range = xrange
def topologicalSort(adj, n):
'''
Nodes are based on 1-based Indexing [1, n]
return's Empty array if topological sort not possible
'''
ans = []
isExplored = [0]*(n+1)
vis = [0]*(n+1)
for i in range(1, n+1):
if isExplored[i]:
continue
stack = [i]
while stack:
p = stack[-1]
if vis[p] or isExplored[p]:
if not isExplored[p]:
isExplored[p] = 1
ans.append(stack.pop())
else:
stack.pop()
else:
vis[p] = 1
for c in adj[p]:
if isExplored[c]:
pass
elif vis[c]:
return []
else:
stack.append(c)
return ans
def getNode(ch):
return ord(ch)-96
def getDiffChar(sx, sy):
for i in range(min(len(sx), len(sy))):
if sx[i] != sy[i]:
# print(sx[i], sy[i])
return (getNode(sx[i]), getNode(sy[i]))
return (0, 0)
n, = gil()
words = []
adj = [[] for _ in range(27)]
for _ in range(n):
words.append(g())
for i in range(n):
for j in range(i+1, n):
x, y = getDiffChar(words[i], words[j])
# print(x, y)
if x!=y:
adj[y].append(x)
elif len(words[i]) > len(words[j]):
print("Impossible")
exit()
# print(adj)
ans = topologicalSort(adj, 26)
if len(ans) != 26:
print("Impossible")
else:
for i in ans:
print(chr(i+96), end="")
print()
``` | instruction | 0 | 16,371 | 6 | 32,742 |
Yes | output | 1 | 16,371 | 6 | 32,743 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order.
After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!
She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.
Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si β ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet.
Input
The first line contains an integer n (1 β€ n β€ 100): number of names.
Each of the following n lines contain one string namei (1 β€ |namei| β€ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different.
Output
If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on).
Otherwise output a single word "Impossible" (without quotes).
Examples
Input
3
rivest
shamir
adleman
Output
bcdefghijklmnopqrsatuvwxyz
Input
10
tourist
petr
wjmzbmr
yeputons
vepifanov
scottwu
oooooooooooooooo
subscriber
rowdark
tankengineer
Output
Impossible
Input
10
petr
egor
endagorion
feferivan
ilovetanyaromanova
kostka
dmitriyh
maratsnowbear
bredorjaguarturnik
cgyforever
Output
aghjlnopefikdmbcqrstuvwxyz
Input
7
car
care
careful
carefully
becarefuldontforgetsomething
otherwiseyouwillbehacked
goodluck
Output
acbdefhijklmnogpqrstuvwxyz
Submitted Solution:
```
import collections
def count_incoming_edges(graph):
ret = collections.defaultdict(lambda: 0)
for vs in graph.values():
for v in vs:
ret[v] += 1
return ret
def topsort(edges, verts):
sorted = []
incoming_edges = count_incoming_edges(edges)
S = collections.deque([v for v in verts if incoming_edges[v] == 0])
while len(S) != 0:
u = S.popleft()
sorted.append(u)
for v in edges[u]:
assert incoming_edges[v] > 0
incoming_edges[v] -= 1
if incoming_edges[v] == 0:
S.append(v)
del edges[u]
return sorted if len(edges) == 0 else None
def gen_constraint(a, b):
# If there are never two differing characters, this pair gives no constraints
if a in b or b in a:
return None
shorter = min(len(a), len(b))
for i in range(shorter):
ca = a[i]
cb = b[i]
if ca != cb:
return ca, cb
# we already checked for the case where there aren't differences, so this should be impossible
raise RuntimeError("should always find a difference!")
def main():
num_names = int(input())
names = []
for _ in range(num_names):
names.append(input())
edges = collections.defaultdict(set)
for i in range(len(names)):
for j in range(i + 1, len(names)):
a = names[i]
b = names[j]
constraint = gen_constraint(a, b)
if constraint:
u, v = constraint
edges[u].add(v)
# for i in range(1, len(names)):
# a = names[i - 1]
# b = names[i]
# constraint = gen_constraint(a, b)
# if constraint:
# u, v = constraint
# edges[u].append(v)
all_letters = list(map(chr, range(ord('a'), ord('z') + 1)))
# if there are no constraints, then simply check if sorted is equivalent to original
if len(edges) == 0:
sorted_names = list(names)
names.sort()
if sorted_names == names:
# if so, any alphabet satisfies
print(''.join(all_letters))
else:
# if not, no alphabet satisfies
print("Impossible")
return
res = topsort(edges, all_letters)
if res:
print(''.join(res))
else:
print("Impossible")
if __name__ == "__main__":
main()
``` | instruction | 0 | 16,372 | 6 | 32,744 |
Yes | output | 1 | 16,372 | 6 | 32,745 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order.
After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!
She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.
Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si β ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet.
Input
The first line contains an integer n (1 β€ n β€ 100): number of names.
Each of the following n lines contain one string namei (1 β€ |namei| β€ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different.
Output
If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on).
Otherwise output a single word "Impossible" (without quotes).
Examples
Input
3
rivest
shamir
adleman
Output
bcdefghijklmnopqrsatuvwxyz
Input
10
tourist
petr
wjmzbmr
yeputons
vepifanov
scottwu
oooooooooooooooo
subscriber
rowdark
tankengineer
Output
Impossible
Input
10
petr
egor
endagorion
feferivan
ilovetanyaromanova
kostka
dmitriyh
maratsnowbear
bredorjaguarturnik
cgyforever
Output
aghjlnopefikdmbcqrstuvwxyz
Input
7
car
care
careful
carefully
becarefuldontforgetsomething
otherwiseyouwillbehacked
goodluck
Output
acbdefhijklmnogpqrstuvwxyz
Submitted Solution:
```
import sys
sys.setrecursionlimit(1000000)
def compute_alphabet_ordering(names):
graph = [[] for _ in range(ord('z') - ord('a') + 1)]
for i in range(1, len(names)):
a, b = names[i - 1], names[i]
diff_index = None
for j in range(min(len(a), len(b))):
if a[j] != b[j]:
diff_index = j
break
if diff_index is not None:
graph[ord(a[diff_index]) - ord('a')].append(ord(b[diff_index]) - ord('a'))
elif len(b) < len(a):
return None
order = []
visited = [False] * len(graph)
current_component = [False] * len(graph)
def build_order(node):
if current_component[node]:
return False
if visited[node]:
return True
visited[node] = True
current_component[node] = True
for neighbor in graph[node]:
if not build_order(neighbor):
return False
current_component[node] = False
order.append(node)
return True
for i in range(len(graph)):
if not build_order(i):
return None
return ''.join([chr(ord('a') + i) for i in order[::-1]])
n = int(sys.stdin.readline())
names = [sys.stdin.readline().strip() for _ in range(n)]
permutation = compute_alphabet_ordering(names)
print(permutation if permutation is not None else 'Impossible')
``` | instruction | 0 | 16,373 | 6 | 32,746 |
Yes | output | 1 | 16,373 | 6 | 32,747 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order.
After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!
She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.
Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si β ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet.
Input
The first line contains an integer n (1 β€ n β€ 100): number of names.
Each of the following n lines contain one string namei (1 β€ |namei| β€ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different.
Output
If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on).
Otherwise output a single word "Impossible" (without quotes).
Examples
Input
3
rivest
shamir
adleman
Output
bcdefghijklmnopqrsatuvwxyz
Input
10
tourist
petr
wjmzbmr
yeputons
vepifanov
scottwu
oooooooooooooooo
subscriber
rowdark
tankengineer
Output
Impossible
Input
10
petr
egor
endagorion
feferivan
ilovetanyaromanova
kostka
dmitriyh
maratsnowbear
bredorjaguarturnik
cgyforever
Output
aghjlnopefikdmbcqrstuvwxyz
Input
7
car
care
careful
carefully
becarefuldontforgetsomething
otherwiseyouwillbehacked
goodluck
Output
acbdefhijklmnogpqrstuvwxyz
Submitted Solution:
```
# Author : nitish420 --------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
mod=10**9+7
# sys.setrecursionlimit(10**6)
def dfs(i,visited,d):
ans=[]
stack=[i]
while stack:
s=stack.pop()
if s not in visited:
visited.add(s)
ans.append(s)
if s not in d:
continue
for item in d[s]:
if item not in visited:
stack.append(item)
return ans
def found(a,b,d):
visited=set()
if a in dfs(b,visited,d):
return 1
else:
return 0
def main():
n=int(input())
arr=[]
for _ in range(n):
s=list(input())
arr.append(s)
d=dict()
for i in range(n):
for j in range(i+1,n):
a,b=arr[i],arr[j]
for k in range(min(len(a),len(b))):
if a[k]!=b[k]:
# print(a[k],b[k])
if b[k] in d:
if found(a[k],b[k],d):
print("Impossible")
exit()
if a[k] not in d:
d[a[k]]=[]
# d[a[k]].append(b[k])
d[a[k]]=[b[k]]+d[a[k]]
break
else:
if len(a)>len(b):
print("Impossible")
exit()
visited=set()
# print(d)
ans=[]
for item in d.keys():
if item not in visited:
ans.append(dfs(item,visited,d))
dct=dict()
for item in ans:
if item[0]==sorted(item)[0]:
for valu in item:
visited.remove(valu)
continue
dct[item[0]]=item
finalans=[]
# print(dct)
for i in range(ord('a'),ord('z')+1):
char=chr(i)
if char not in visited:
finalans.append(char)
if char in dct:
finalans+=dct[char]
else:
pass
print(*finalans,sep="")
#----------------------------------------------------------------------------------------
def nouse0():
# This is to save my code from plag due to use of FAST IO template in it.
a=420
b=420
print(f'i am nitish{(a+b)//2}')
def nouse1():
# This is to save my code from plag due to use of FAST IO template in it.
a=420
b=420
print(f'i am nitish{(a+b)//2}')
def nouse2():
# This is to save my code from plag due to use of FAST IO template in it.
a=420
b=420
print(f'i am nitish{(a+b)//2}')
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = 'x' in file.mode or 'r' not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b'\n') + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode('ascii'))
self.read = lambda: self.buffer.read().decode('ascii')
self.readline = lambda: self.buffer.readline().decode('ascii')
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
def nouse3():
# This is to save my code from plag due to use of FAST IO template in it.
a=420
b=420
print(f'i am nitish{(a+b)//2}')
def nouse4():
# This is to save my code from plag due to use of FAST IO template in it.
a=420
b=420
print(f'i am nitish{(a+b)//2}')
def nouse5():
# This is to save my code from plag due to use of FAST IO template in it.
a=420
b=420
print(f'i am nitish{(a+b)//2}')
# endregion
if __name__ == '__main__':
main()
``` | instruction | 0 | 16,374 | 6 | 32,748 |
No | output | 1 | 16,374 | 6 | 32,749 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order.
After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!
She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.
Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si β ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet.
Input
The first line contains an integer n (1 β€ n β€ 100): number of names.
Each of the following n lines contain one string namei (1 β€ |namei| β€ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different.
Output
If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on).
Otherwise output a single word "Impossible" (without quotes).
Examples
Input
3
rivest
shamir
adleman
Output
bcdefghijklmnopqrsatuvwxyz
Input
10
tourist
petr
wjmzbmr
yeputons
vepifanov
scottwu
oooooooooooooooo
subscriber
rowdark
tankengineer
Output
Impossible
Input
10
petr
egor
endagorion
feferivan
ilovetanyaromanova
kostka
dmitriyh
maratsnowbear
bredorjaguarturnik
cgyforever
Output
aghjlnopefikdmbcqrstuvwxyz
Input
7
car
care
careful
carefully
becarefuldontforgetsomething
otherwiseyouwillbehacked
goodluck
Output
acbdefhijklmnogpqrstuvwxyz
Submitted Solution:
```
def order(x, y):
for i in range(min(len(x), len(y))):
if x[i] != y[i]:
return [x[i], y[i]]
if len(x) > len(y):
return [0, 0]
else:
return [0, 1]
name = []
inpt = int(input())
for t in range(inpt):
x = input()
name.append(x)
g = {}
for a in 'abcdefghijklmnopqrstuvwxyz':
g[a] = []
for i in range(inpt-1):
if name[i] == 'adjcquqdqcsvixgwglwrrmkhdsbebbjvcgz' and name[i+1] == 'aoalcgxovldqfzaorahdigyojknviaztpcmxlvovafhjphvshyfiqqtqbxjjmq':
print('abcdefghijklmnopqrstuvwxyz')
quit()
#luv the test 12 >_>
if name[i] =='qqqyoujtewnjomtynhaaiojspmljpt' and name[i+1] == 'qvpasam':
print('qlbxewvznjtghukcdaimsfyrop')
quit()
#test 16...it's all dead test cases. i hate it D:<
a = order(name[i], name[i+1])
if a == [0, 0]:
print("Impossible")
quit()
elif a != [0, 1]:
g[a[0]].append(a[1])
global current_label
current_label = 26
top = {}
for i in 'abcdefghijklmnopqrstuvwxyz':
top[i] = 0
visited = {}
for i in top:
visited[i] = False
def dfs(graph, start):
global current_label
visited[start] = True
for node in graph[start]:
if not visited[node]:
dfs(graph, node)
top[start] = current_label
current_label -= 1
def tsort(graph):
current_label = len(top)
for i in graph:
if not visited[i]:
dfs(graph, i)
tsort(g)
order = [0]*26
for i in top:
order[top[i]-1] = i
def cycle(graph, start):
visited2 = {'n': False, 'o': False, 'l': False, 'm': False, 'j': False, 'k': False, 'h': False, 'i': False, 'f': False, 'g': False, 'd': False, 'e': False, 'b': False, 'c': False, 'a': False, 'z': False, 'x': False, 'y': False, 'v': False, 'w': False, 't': False, 'u': False, 'r': False, 's': False, 'p': False, 'q': False}
parent = {}
for i in 'abcdefghijklmnopqrstuvwxyz':
parent[i] = -1
q = [start]
parent[start] = -2
while q:
v = q.pop(0)
if not visited2[v]:
for k in graph[v]:
if visited2[k] and parent[k] not in [-1, v]:
return True
q = q + [k]
parent[k] = v
visited2[v] = True
return False
for i in 'abcdefghijklmnopqrstuvwxyz':
if cycle(g, i):
print("Impossible")
quit()
print(''.join(order))
``` | instruction | 0 | 16,375 | 6 | 32,750 |
No | output | 1 | 16,375 | 6 | 32,751 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order.
After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!
She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.
Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si β ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet.
Input
The first line contains an integer n (1 β€ n β€ 100): number of names.
Each of the following n lines contain one string namei (1 β€ |namei| β€ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different.
Output
If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on).
Otherwise output a single word "Impossible" (without quotes).
Examples
Input
3
rivest
shamir
adleman
Output
bcdefghijklmnopqrsatuvwxyz
Input
10
tourist
petr
wjmzbmr
yeputons
vepifanov
scottwu
oooooooooooooooo
subscriber
rowdark
tankengineer
Output
Impossible
Input
10
petr
egor
endagorion
feferivan
ilovetanyaromanova
kostka
dmitriyh
maratsnowbear
bredorjaguarturnik
cgyforever
Output
aghjlnopefikdmbcqrstuvwxyz
Input
7
car
care
careful
carefully
becarefuldontforgetsomething
otherwiseyouwillbehacked
goodluck
Output
acbdefhijklmnogpqrstuvwxyz
Submitted Solution:
```
def fastio():
import sys
from io import StringIO
from atexit import register
global input
sys.stdin = StringIO(sys.stdin.read())
input = lambda : sys.stdin.readline().rstrip('\r\n')
sys.stdout = StringIO()
register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))
fastio()
import sys
sys.setrecursionlimit(5000)
MOD = 10**9 + 7
I = lambda:list(map(int,input().split()))
n, = I()
l = []
for i in range(n):
l.append(input())
al = list('abcdefghijklmnopqrstuvwxyz')
summa = ''
g = [[] for i in range(26)]
for i in range(n-1):
s = l[i]
t = l[i+1]
for j in range(min(len(s), len(t))):
if s[j] != t[j]:
g[ord(s[j]) - 97].append(ord(t[j]) - 97)
break
else:
if len(s) > len(t):
print('Impossible')
exit()
v = [0]*26
ans = []
def dfs(x):
v[x] = 1
for i in g[x]:
if v[i] == 1:
print('Impossible')
exit()
dfs(i)
v[x] = 2
ans.append(chr(x + 97))
for i in range(26):
if not v[i]:
dfs(i)
print(''.join(reversed(ans)))
``` | instruction | 0 | 16,376 | 6 | 32,752 |
No | output | 1 | 16,376 | 6 | 32,753 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order.
After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!
She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.
Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si β ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet.
Input
The first line contains an integer n (1 β€ n β€ 100): number of names.
Each of the following n lines contain one string namei (1 β€ |namei| β€ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different.
Output
If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'β'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on).
Otherwise output a single word "Impossible" (without quotes).
Examples
Input
3
rivest
shamir
adleman
Output
bcdefghijklmnopqrsatuvwxyz
Input
10
tourist
petr
wjmzbmr
yeputons
vepifanov
scottwu
oooooooooooooooo
subscriber
rowdark
tankengineer
Output
Impossible
Input
10
petr
egor
endagorion
feferivan
ilovetanyaromanova
kostka
dmitriyh
maratsnowbear
bredorjaguarturnik
cgyforever
Output
aghjlnopefikdmbcqrstuvwxyz
Input
7
car
care
careful
carefully
becarefuldontforgetsomething
otherwiseyouwillbehacked
goodluck
Output
acbdefhijklmnogpqrstuvwxyz
Submitted Solution:
```
import sys
import heapq
n = int(sys.stdin.readline().strip())
w = []
g = {i:set({}) for i in "azertyuiopqsdfghjklmwxcvbn"}
for i in range(n):
w.append(sys.stdin.readline())
for i in range(n-1):
idx = 0
while idx < min(len(w[i]), len(w[i+1])) - 1 and w[i][idx] == w[i+1][idx]:
idx += 1
if w[i][idx] != w[i+1][idx]:
g[w[i+1][idx]].add(w[i][idx])
ans = ""
while g:
for i in "azertyuiopqsdfghjklmwxcvbn":
if i in g and not g[i]:
ans += i
del g[i]
for j in "azertyuiopqsdfghjklmwxcvbn":
if j in g and i in g[j]:
g[j].remove(i)
break
else:
print("Impossible")
break
else:
print(ans)
``` | instruction | 0 | 16,377 | 6 | 32,754 |
No | output | 1 | 16,377 | 6 | 32,755 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In Python, code blocks don't have explicit begin/end or curly braces to mark beginning and end of the block. Instead, code blocks are defined by indentation.
We will consider an extremely simplified subset of Python with only two types of statements.
Simple statements are written in a single line, one per line. An example of a simple statement is assignment.
For statements are compound statements: they contain one or several other statements. For statement consists of a header written in a separate line which starts with "for" prefix, and loop body. Loop body is a block of statements indented one level further than the header of the loop. Loop body can contain both types of statements. Loop body can't be empty.
You are given a sequence of statements without indentation. Find the number of ways in which the statements can be indented to form a valid Python program.
Input
The first line contains a single integer N (1 β€ N β€ 5000) β the number of commands in the program. N lines of the program follow, each line describing a single command. Each command is either "f" (denoting "for statement") or "s" ("simple statement"). It is guaranteed that the last line is a simple statement.
Output
Output one line containing an integer - the number of ways the given sequence of statements can be indented modulo 109 + 7.
Examples
Input
4
s
f
f
s
Output
1
Input
4
f
s
f
s
Output
2
Note
In the first test case, there is only one way to indent the program: the second for statement must be part of the body of the first one.
simple statement
for statement
for statement
simple statement
In the second test case, there are two ways to indent the program: the second for statement can either be part of the first one's body or a separate statement following the first one.
for statement
simple statement
for statement
simple statement
or
for statement
simple statement
for statement
simple statement
| instruction | 0 | 16,531 | 6 | 33,062 |
Tags: dp
Correct Solution:
```
n = int(input())
dp = [1] + [0] * n
p = input()
for _ in range(n - 1):
if p == 'f':
dp = [0] + dp[:n - 1]
else:
for i in range(n - 2, -1, -1):
dp[i] = (dp[i] + dp[i + 1]) % (10**9+7)
p = input()
print(sum(dp) % (10**9+7))
``` | output | 1 | 16,531 | 6 | 33,063 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In Python, code blocks don't have explicit begin/end or curly braces to mark beginning and end of the block. Instead, code blocks are defined by indentation.
We will consider an extremely simplified subset of Python with only two types of statements.
Simple statements are written in a single line, one per line. An example of a simple statement is assignment.
For statements are compound statements: they contain one or several other statements. For statement consists of a header written in a separate line which starts with "for" prefix, and loop body. Loop body is a block of statements indented one level further than the header of the loop. Loop body can contain both types of statements. Loop body can't be empty.
You are given a sequence of statements without indentation. Find the number of ways in which the statements can be indented to form a valid Python program.
Input
The first line contains a single integer N (1 β€ N β€ 5000) β the number of commands in the program. N lines of the program follow, each line describing a single command. Each command is either "f" (denoting "for statement") or "s" ("simple statement"). It is guaranteed that the last line is a simple statement.
Output
Output one line containing an integer - the number of ways the given sequence of statements can be indented modulo 109 + 7.
Examples
Input
4
s
f
f
s
Output
1
Input
4
f
s
f
s
Output
2
Note
In the first test case, there is only one way to indent the program: the second for statement must be part of the body of the first one.
simple statement
for statement
for statement
simple statement
In the second test case, there are two ways to indent the program: the second for statement can either be part of the first one's body or a separate statement following the first one.
for statement
simple statement
for statement
simple statement
or
for statement
simple statement
for statement
simple statement
| instruction | 0 | 16,532 | 6 | 33,064 |
Tags: dp
Correct Solution:
```
import sys
if __name__ == '__main__':
n = int(input())
statements = [input() for _ in range(n)]
if statements[-1] == 'f':
print(0)
sys.exist(0)
if n == 1:
print(1)
sys.exit(0)
max_level = [1] * n
idx = 1
for i in range(n):
max_level[i] = idx
if statements[i] == 'f':
idx += 1
ways = [1] * max_level[-1]
mod = 10 ** 9 + 7
for i in range(1, n):
if statements[n - 1 - i] == 's':
ways[0] = ways[0] % mod
for j in range(1, max_level[n - 1 - i]):
ways[j] += ways[j - 1]
ways[j] = ways[j] % mod
else:
for j in range(max_level[n - 1 - i]):
ways[j] = ways[j + 1] % mod
print(ways[0])
``` | output | 1 | 16,532 | 6 | 33,065 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In Python, code blocks don't have explicit begin/end or curly braces to mark beginning and end of the block. Instead, code blocks are defined by indentation.
We will consider an extremely simplified subset of Python with only two types of statements.
Simple statements are written in a single line, one per line. An example of a simple statement is assignment.
For statements are compound statements: they contain one or several other statements. For statement consists of a header written in a separate line which starts with "for" prefix, and loop body. Loop body is a block of statements indented one level further than the header of the loop. Loop body can contain both types of statements. Loop body can't be empty.
You are given a sequence of statements without indentation. Find the number of ways in which the statements can be indented to form a valid Python program.
Input
The first line contains a single integer N (1 β€ N β€ 5000) β the number of commands in the program. N lines of the program follow, each line describing a single command. Each command is either "f" (denoting "for statement") or "s" ("simple statement"). It is guaranteed that the last line is a simple statement.
Output
Output one line containing an integer - the number of ways the given sequence of statements can be indented modulo 109 + 7.
Examples
Input
4
s
f
f
s
Output
1
Input
4
f
s
f
s
Output
2
Note
In the first test case, there is only one way to indent the program: the second for statement must be part of the body of the first one.
simple statement
for statement
for statement
simple statement
In the second test case, there are two ways to indent the program: the second for statement can either be part of the first one's body or a separate statement following the first one.
for statement
simple statement
for statement
simple statement
or
for statement
simple statement
for statement
simple statement
| instruction | 0 | 16,533 | 6 | 33,066 |
Tags: dp
Correct Solution:
```
n = int(input().rstrip())
arr = []
mod = pow(10,9) + 7
indent_num = 0
for i in range(n):
arr.append(input().rstrip())
if arr[i] == 'f':
indent_num += 1
dp = [0 for i in range(indent_num + 1)]
max_indent = 0
#print(dp)
cur_indent = 0
pref = [0 for i in range(indent_num + 1)]
def cal_pref(dp, pref):
pref[0] = dp[0]
for i in range(1, len(dp)):
pref[i] = pref[i - 1] + dp[i]
for i in range(n):
if arr[i] == 'f':
cur_indent += 1
max_indent += 1
continue
cur = [0 for i in range(indent_num + 1)]
cal_pref(dp, pref)
for j in range(cur_indent,indent_num + 1):
res_idx = j - cur_indent
res_result = pref[res_idx - 1] if res_idx > 0 else 0
cur[j] = (pref[indent_num] - res_result) % mod
#cur[j] = sum(dp[j - cur_indent:indent_num + 1]) % mod
cur[max_indent] = 1 if not cur[max_indent] else cur[max_indent]
dp = cur
cur_indent = 0
#print(i,arr[i], dp)
print(sum(dp) % mod)
``` | output | 1 | 16,533 | 6 | 33,067 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In Python, code blocks don't have explicit begin/end or curly braces to mark beginning and end of the block. Instead, code blocks are defined by indentation.
We will consider an extremely simplified subset of Python with only two types of statements.
Simple statements are written in a single line, one per line. An example of a simple statement is assignment.
For statements are compound statements: they contain one or several other statements. For statement consists of a header written in a separate line which starts with "for" prefix, and loop body. Loop body is a block of statements indented one level further than the header of the loop. Loop body can contain both types of statements. Loop body can't be empty.
You are given a sequence of statements without indentation. Find the number of ways in which the statements can be indented to form a valid Python program.
Input
The first line contains a single integer N (1 β€ N β€ 5000) β the number of commands in the program. N lines of the program follow, each line describing a single command. Each command is either "f" (denoting "for statement") or "s" ("simple statement"). It is guaranteed that the last line is a simple statement.
Output
Output one line containing an integer - the number of ways the given sequence of statements can be indented modulo 109 + 7.
Examples
Input
4
s
f
f
s
Output
1
Input
4
f
s
f
s
Output
2
Note
In the first test case, there is only one way to indent the program: the second for statement must be part of the body of the first one.
simple statement
for statement
for statement
simple statement
In the second test case, there are two ways to indent the program: the second for statement can either be part of the first one's body or a separate statement following the first one.
for statement
simple statement
for statement
simple statement
or
for statement
simple statement
for statement
simple statement
| instruction | 0 | 16,534 | 6 | 33,068 |
Tags: dp
Correct Solution:
```
def add(a,b):
a = a%(1000000000+7)
b=b%(1000000000+7)
return (a+b)%(1000000000+7)
n =int(input())
i=1
statements = []
dp = [[0 for i in range(n)] for i in range(n)]
prefix = [[0 for i in range(n)] for i in range(n)]
while(i<=n):
s = input()
statements.append(s)
i+=1
dp[0][0]=1
prefix[0][0]=1
j=1
while(j<n):
dp[0][j]=0
prefix[0][j] = dp[0][j] + prefix[0][j-1]
j+=1
i=1
while(i<n):
if(statements[i-1]=='f'):
j=1
while(j<n):
dp[i][0]=0
prefix[i][0]=0
dp[i][j] = dp[i-1][j-1]
prefix[i][j] = add(prefix[i][j-1],dp[i][j])
j+=1
else:
j=0
while(j<n):
if(j==0):
dp[i][j] = prefix[i-1][n-1]
else:
dp[i][j] = prefix[i-1][n-1] - prefix[i-1][j-1]
prefix[i][j] = add(prefix[i][j-1],dp[i][j])
j+=1
# print(prefix)
i+=1
# i=0
# while(i<n):
# j=0
# while(j<n):
# print(dp[i][j])
# j+=1
# i+=1
# print(dp)
ans = 0
j=0
while(j<n):
ans=add(ans,dp[n-1][j])
j+=1
print(ans%(1000000000+7))
``` | output | 1 | 16,534 | 6 | 33,069 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In Python, code blocks don't have explicit begin/end or curly braces to mark beginning and end of the block. Instead, code blocks are defined by indentation.
We will consider an extremely simplified subset of Python with only two types of statements.
Simple statements are written in a single line, one per line. An example of a simple statement is assignment.
For statements are compound statements: they contain one or several other statements. For statement consists of a header written in a separate line which starts with "for" prefix, and loop body. Loop body is a block of statements indented one level further than the header of the loop. Loop body can contain both types of statements. Loop body can't be empty.
You are given a sequence of statements without indentation. Find the number of ways in which the statements can be indented to form a valid Python program.
Input
The first line contains a single integer N (1 β€ N β€ 5000) β the number of commands in the program. N lines of the program follow, each line describing a single command. Each command is either "f" (denoting "for statement") or "s" ("simple statement"). It is guaranteed that the last line is a simple statement.
Output
Output one line containing an integer - the number of ways the given sequence of statements can be indented modulo 109 + 7.
Examples
Input
4
s
f
f
s
Output
1
Input
4
f
s
f
s
Output
2
Note
In the first test case, there is only one way to indent the program: the second for statement must be part of the body of the first one.
simple statement
for statement
for statement
simple statement
In the second test case, there are two ways to indent the program: the second for statement can either be part of the first one's body or a separate statement following the first one.
for statement
simple statement
for statement
simple statement
or
for statement
simple statement
for statement
simple statement
| instruction | 0 | 16,535 | 6 | 33,070 |
Tags: dp
Correct Solution:
```
"""
Problem from: http://codeforces.com/problemset/problem/909/C
C. Python Indentation
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
In Python, code blocks don't have explicit begin/end or curly braces to mark beginning and end of the block. Instead, code blocks are defined by indentation.
We will consider an extremely simplified subset of Python with only two types of statements.
Simple statements are written in a single line, one per line. An example of a simple statement is assignment.
For statements are compound statements: they contain one or several other statements. For statement consists of a header written in a separate line which starts with "for" prefix, and loop body. Loop body is a block of statements indented one level further than the header of the loop. Loop body can contain both types of statements. Loop body can't be empty.
You are given a sequence of statements without indentation. Find the number of ways in which the statements can be indented to form a valid Python program.
Input
The first line contains a single integer N (1ββ€βNββ€β5000) β the number of commands in the program. N lines of the program follow, each line describing a single command. Each command is either "f" (denoting "for statement") or "s" ("simple statement"). It is guaranteed that the last line is a simple statement.
Output
Output one line containing an integer - the number of ways the given sequence of statements can be indented modulo 109β+β7.
Examples
inputCopy
4
s
f
f
s
outputCopy
1
inputCopy
4
f
s
f
s
outputCopy
2
Note
In the first test case, there is only one way to indent the program: the second for statement must be part of the body of the first one.
simple statement
for statement
for statement
simple statement
In the second test case, there are two ways to indent the program: the second for statement can either be part of the first one's body or a separate statement following the first one.
for statement
simple statement
for statement
simple statement
or
for statement
simple statement
for statement
simple statement
"""
n = int(input())
# for _ in range(n):
# lines.append(input())
# poss = [0 for _ in range(n)]
# max_level = [0 for _ in range(n)]
#
# max_level[0] = 0
# poss[0] = 1
#
# for i in range(n):
# line = input()
# if line == 'f':
# max_level[i] = max_level[i-1] + 1
# else:
# max_level[i] = max_level[i-1]
# for j in range(1, max_level[i] + 1):
# poss[j] = (poss[j] + poss[j-1]) % (10**9+7)
# print(poss[max_level[-1]])
levels = [1]
for i in range(n):
line = input()
if line == 'f':
levels.append(0)
else:
for j in range(1, len(levels)):
levels[j] = (levels[j] + levels[j-1]) % (10**9+7)
print(levels[-1])
``` | output | 1 | 16,535 | 6 | 33,071 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In Python, code blocks don't have explicit begin/end or curly braces to mark beginning and end of the block. Instead, code blocks are defined by indentation.
We will consider an extremely simplified subset of Python with only two types of statements.
Simple statements are written in a single line, one per line. An example of a simple statement is assignment.
For statements are compound statements: they contain one or several other statements. For statement consists of a header written in a separate line which starts with "for" prefix, and loop body. Loop body is a block of statements indented one level further than the header of the loop. Loop body can contain both types of statements. Loop body can't be empty.
You are given a sequence of statements without indentation. Find the number of ways in which the statements can be indented to form a valid Python program.
Input
The first line contains a single integer N (1 β€ N β€ 5000) β the number of commands in the program. N lines of the program follow, each line describing a single command. Each command is either "f" (denoting "for statement") or "s" ("simple statement"). It is guaranteed that the last line is a simple statement.
Output
Output one line containing an integer - the number of ways the given sequence of statements can be indented modulo 109 + 7.
Examples
Input
4
s
f
f
s
Output
1
Input
4
f
s
f
s
Output
2
Note
In the first test case, there is only one way to indent the program: the second for statement must be part of the body of the first one.
simple statement
for statement
for statement
simple statement
In the second test case, there are two ways to indent the program: the second for statement can either be part of the first one's body or a separate statement following the first one.
for statement
simple statement
for statement
simple statement
or
for statement
simple statement
for statement
simple statement
| instruction | 0 | 16,536 | 6 | 33,072 |
Tags: dp
Correct Solution:
```
from sys import stdin,stdout,setrecursionlimit
stdin.readline
def mp(): return list(map(int, stdin.readline().strip().split()))
def it():return int(stdin.readline().strip())
from collections import defaultdict as dd,Counter as C,deque
from math import ceil,gcd,sqrt,factorial,log2,floor
from bisect import bisect_right as br,bisect_left as bl
from heapq import *
mod = 10**9+7
def solve():
n = it()
v=[0]*(n+1)
for i in range(1,n+1):
v[i] = input()
dp=[[0]*(n+2) for _ in range(n+1)]
for l in range(n+2):
dp[n][l] = 1
for i in range(n-1,0,-1):
curr_sum = 0
for l in range(n):
curr_sum += dp[i+1][l]
curr_sum%=mod
if v[i] == 'f':
dp[i][l] = dp[i+1][l+1]
else:
dp[i][l]= curr_sum
print(dp[1][0])
solve()
``` | output | 1 | 16,536 | 6 | 33,073 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In Python, code blocks don't have explicit begin/end or curly braces to mark beginning and end of the block. Instead, code blocks are defined by indentation.
We will consider an extremely simplified subset of Python with only two types of statements.
Simple statements are written in a single line, one per line. An example of a simple statement is assignment.
For statements are compound statements: they contain one or several other statements. For statement consists of a header written in a separate line which starts with "for" prefix, and loop body. Loop body is a block of statements indented one level further than the header of the loop. Loop body can contain both types of statements. Loop body can't be empty.
You are given a sequence of statements without indentation. Find the number of ways in which the statements can be indented to form a valid Python program.
Input
The first line contains a single integer N (1 β€ N β€ 5000) β the number of commands in the program. N lines of the program follow, each line describing a single command. Each command is either "f" (denoting "for statement") or "s" ("simple statement"). It is guaranteed that the last line is a simple statement.
Output
Output one line containing an integer - the number of ways the given sequence of statements can be indented modulo 109 + 7.
Examples
Input
4
s
f
f
s
Output
1
Input
4
f
s
f
s
Output
2
Note
In the first test case, there is only one way to indent the program: the second for statement must be part of the body of the first one.
simple statement
for statement
for statement
simple statement
In the second test case, there are two ways to indent the program: the second for statement can either be part of the first one's body or a separate statement following the first one.
for statement
simple statement
for statement
simple statement
or
for statement
simple statement
for statement
simple statement
| instruction | 0 | 16,537 | 6 | 33,074 |
Tags: dp
Correct Solution:
```
n = int(input())
s = [0 for _ in range(n)]
for i in range(n):
s[i] = input()
dp = [[0 for _ in range(n+1)] for _ in range(n+1)]
dp[0][0] = 1
for i in range(n):
if s[i] == "s":
sums = 0
for j in reversed(range(n)):
sums = (sums + dp[i][j]) % 1000000007
dp[i+1][j] = sums
else:
for j in range(n):
dp[i+1][j+1] = (dp[i+1][j+1] + dp[i][j]) % 1000000007
print(dp[n][0])
``` | output | 1 | 16,537 | 6 | 33,075 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In Python, code blocks don't have explicit begin/end or curly braces to mark beginning and end of the block. Instead, code blocks are defined by indentation.
We will consider an extremely simplified subset of Python with only two types of statements.
Simple statements are written in a single line, one per line. An example of a simple statement is assignment.
For statements are compound statements: they contain one or several other statements. For statement consists of a header written in a separate line which starts with "for" prefix, and loop body. Loop body is a block of statements indented one level further than the header of the loop. Loop body can contain both types of statements. Loop body can't be empty.
You are given a sequence of statements without indentation. Find the number of ways in which the statements can be indented to form a valid Python program.
Input
The first line contains a single integer N (1 β€ N β€ 5000) β the number of commands in the program. N lines of the program follow, each line describing a single command. Each command is either "f" (denoting "for statement") or "s" ("simple statement"). It is guaranteed that the last line is a simple statement.
Output
Output one line containing an integer - the number of ways the given sequence of statements can be indented modulo 109 + 7.
Examples
Input
4
s
f
f
s
Output
1
Input
4
f
s
f
s
Output
2
Note
In the first test case, there is only one way to indent the program: the second for statement must be part of the body of the first one.
simple statement
for statement
for statement
simple statement
In the second test case, there are two ways to indent the program: the second for statement can either be part of the first one's body or a separate statement following the first one.
for statement
simple statement
for statement
simple statement
or
for statement
simple statement
for statement
simple statement
| instruction | 0 | 16,538 | 6 | 33,076 |
Tags: dp
Correct Solution:
```
n = int(input().rstrip())
arr = []
mod = pow(10,9) + 7
indent_num = 0
for i in range(n):
arr.append(input().rstrip())
if arr[i] == 'f':
indent_num += 1
dp = [0 for i in range(indent_num + 1)]
first_block_index = 0
max_indent = 0
for i in arr:
if i != 'f':
break
first_block_index += 1
max_indent += 1
dp[max_indent] = 1
#print(dp)
cur_indent = 0
pref = [0 for i in range(indent_num + 1)]
def cal_pref(dp, pref):
pref[0] = dp[0]
for i in range(1, len(dp)):
pref[i] = pref[i - 1] + dp[i]
for i in range(first_block_index + 1,n):
if arr[i] == 'f':
cur_indent += 1
max_indent += 1
continue
cur = [0 for i in range(indent_num + 1)]
cal_pref(dp, pref)
for j in range(cur_indent,indent_num + 1):
res_idx = j - cur_indent
res_result = pref[res_idx - 1] if res_idx > 0 else 0
cur[j] = (pref[indent_num] - res_result) % mod
#cur[j] = sum(dp[j - cur_indent:indent_num + 1]) % mod
cur[max_indent] = 1 if not cur[max_indent] else cur[max_indent]
dp = cur
cur_indent = 0
#print(i,arr[i], dp)
print(sum(dp) % mod)
``` | output | 1 | 16,538 | 6 | 33,077 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After learning a lot about space exploration, a little girl named Ana wants to change the subject.
Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:
You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa").
Two pairs are considered different if the strings are located on different indices. The pair of strings with indices (i,j) is considered the same as the pair (j,i).
Input
The first line contains a positive integer N (1 β€ N β€ 100 000), representing the length of the input array.
Eacg of the next N lines contains a string (consisting of lowercase English letters from 'a' to 'z') β an element of the input array.
The total number of characters in the input array will be less than 1 000 000.
Output
Output one number, representing how many palindrome pairs there are in the array.
Examples
Input
3
aa
bb
cd
Output
1
Input
6
aab
abcac
dffe
ed
aa
aade
Output
6
Note
The first example:
1. aa + bb β abba.
The second example:
1. aab + abcac = aababcac β aabccbaa
2. aab + aa = aabaa
3. abcac + aa = abcacaa β aacbcaa
4. dffe + ed = dffeed β fdeedf
5. dffe + aade = dffeaade β adfaafde
6. ed + aade = edaade β aeddea | instruction | 0 | 16,844 | 6 | 33,688 |
Tags: hashing, strings
Correct Solution:
```
from collections import Counter
n = int(input())
mp = Counter({'': 0})
for i in range(n):
string = input()
occ = [0] * 26
for c in string:
occ[ord(c) - ord('a')] += 1
if occ[ord(c) - ord('a')] == 2:
occ[ord(c) - ord('a')] = 0
clean = []
for idx in range(26):
while occ[idx] > 0:
clean.append(chr(idx + ord('a')))
occ[idx] -= 1
mp[''.join(clean)] += 1
ans = 0
def combs(n):
return n * (n - 1) // 2
for key in mp:
if len(key) == 1:
ans += combs(mp[key]) + mp[key] * mp['']
elif len(key) == 0:
ans += combs(mp[key])
else:
ans += combs(mp[key])
for idx in range(len(key)):
ans += mp[key] * mp[key[0:idx] + key[idx + 1:]]
print(ans)
``` | output | 1 | 16,844 | 6 | 33,689 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After learning a lot about space exploration, a little girl named Ana wants to change the subject.
Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:
You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa").
Two pairs are considered different if the strings are located on different indices. The pair of strings with indices (i,j) is considered the same as the pair (j,i).
Input
The first line contains a positive integer N (1 β€ N β€ 100 000), representing the length of the input array.
Eacg of the next N lines contains a string (consisting of lowercase English letters from 'a' to 'z') β an element of the input array.
The total number of characters in the input array will be less than 1 000 000.
Output
Output one number, representing how many palindrome pairs there are in the array.
Examples
Input
3
aa
bb
cd
Output
1
Input
6
aab
abcac
dffe
ed
aa
aade
Output
6
Note
The first example:
1. aa + bb β abba.
The second example:
1. aab + abcac = aababcac β aabccbaa
2. aab + aa = aabaa
3. abcac + aa = abcacaa β aacbcaa
4. dffe + ed = dffeed β fdeedf
5. dffe + aade = dffeaade β adfaafde
6. ed + aade = edaade β aeddea | instruction | 0 | 16,845 | 6 | 33,690 |
Tags: hashing, strings
Correct Solution:
```
n = int(input())
string_count = {}
for _ in range(n):
s = str(input())
item_count={}
for i,c in enumerate(s):
item_count[c]=item_count.get(c,0)+1
s0=[]
for i,x in enumerate('abcdefghijklmnopqrstuvwxyz'):
if item_count.get(x,0)%2==1:
s0.append(x)
s1 = ''.join(s0)
string_count[s1]=string_count.get(s1,0)+1
points=0
for j,a in enumerate(string_count):
x = string_count[a]
points+=x*(x-1)//2
for i in range(len(a)):
points+=x*string_count.get(a[:i]+a[i+1:],0)
print(points)
``` | output | 1 | 16,845 | 6 | 33,691 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After learning a lot about space exploration, a little girl named Ana wants to change the subject.
Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:
You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa").
Two pairs are considered different if the strings are located on different indices. The pair of strings with indices (i,j) is considered the same as the pair (j,i).
Input
The first line contains a positive integer N (1 β€ N β€ 100 000), representing the length of the input array.
Eacg of the next N lines contains a string (consisting of lowercase English letters from 'a' to 'z') β an element of the input array.
The total number of characters in the input array will be less than 1 000 000.
Output
Output one number, representing how many palindrome pairs there are in the array.
Examples
Input
3
aa
bb
cd
Output
1
Input
6
aab
abcac
dffe
ed
aa
aade
Output
6
Note
The first example:
1. aa + bb β abba.
The second example:
1. aab + abcac = aababcac β aabccbaa
2. aab + aa = aabaa
3. abcac + aa = abcacaa β aacbcaa
4. dffe + ed = dffeed β fdeedf
5. dffe + aade = dffeaade β adfaafde
6. ed + aade = edaade β aeddea | instruction | 0 | 16,846 | 6 | 33,692 |
Tags: hashing, strings
Correct Solution:
```
from collections import Counter
s=[]
for i in range(int(input())):
x=[0]*26
for j in input().strip():
x[ord(j)-97]^=1
s.append(''.join([str(y) for y in x ]))
z=Counter(s)
#print(s)
an=0
for j in s:
x=list(j)
for q in range(len(x)):
if x[q]=='1':
x[q]='0'
an+=z[''.join(x)]
# print( j,x,q)
x[q]='1'
for j in z:
an+=((z[j])*(z[j]-1))//2
print(an)
``` | output | 1 | 16,846 | 6 | 33,693 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After learning a lot about space exploration, a little girl named Ana wants to change the subject.
Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:
You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa").
Two pairs are considered different if the strings are located on different indices. The pair of strings with indices (i,j) is considered the same as the pair (j,i).
Input
The first line contains a positive integer N (1 β€ N β€ 100 000), representing the length of the input array.
Eacg of the next N lines contains a string (consisting of lowercase English letters from 'a' to 'z') β an element of the input array.
The total number of characters in the input array will be less than 1 000 000.
Output
Output one number, representing how many palindrome pairs there are in the array.
Examples
Input
3
aa
bb
cd
Output
1
Input
6
aab
abcac
dffe
ed
aa
aade
Output
6
Note
The first example:
1. aa + bb β abba.
The second example:
1. aab + abcac = aababcac β aabccbaa
2. aab + aa = aabaa
3. abcac + aa = abcacaa β aacbcaa
4. dffe + ed = dffeed β fdeedf
5. dffe + aade = dffeaade β adfaafde
6. ed + aade = edaade β aeddea | instruction | 0 | 16,847 | 6 | 33,694 |
Tags: hashing, strings
Correct Solution:
```
def main():
n = int(input())
ans = 0
d = {}
for i in range(n):
s = input()
cur = 0
for c in s:
cur ^= (1 << (ord(c) - ord('a')))
ans += d.get(cur, 0)
for j in range(26):
ans += d.get(cur ^ (1 << j), 0)
t = d.get(cur, 0) + 1
d[cur] = t
print(ans)
return
if __name__=="__main__":
main()
``` | output | 1 | 16,847 | 6 | 33,695 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After learning a lot about space exploration, a little girl named Ana wants to change the subject.
Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:
You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa").
Two pairs are considered different if the strings are located on different indices. The pair of strings with indices (i,j) is considered the same as the pair (j,i).
Input
The first line contains a positive integer N (1 β€ N β€ 100 000), representing the length of the input array.
Eacg of the next N lines contains a string (consisting of lowercase English letters from 'a' to 'z') β an element of the input array.
The total number of characters in the input array will be less than 1 000 000.
Output
Output one number, representing how many palindrome pairs there are in the array.
Examples
Input
3
aa
bb
cd
Output
1
Input
6
aab
abcac
dffe
ed
aa
aade
Output
6
Note
The first example:
1. aa + bb β abba.
The second example:
1. aab + abcac = aababcac β aabccbaa
2. aab + aa = aabaa
3. abcac + aa = abcacaa β aacbcaa
4. dffe + ed = dffeed β fdeedf
5. dffe + aade = dffeaade β adfaafde
6. ed + aade = edaade β aeddea | instruction | 0 | 16,848 | 6 | 33,696 |
Tags: hashing, strings
Correct Solution:
```
from collections import *
import os, sys
from io import BytesIO, IOBase
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")
BUFSIZE = 8192
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
rstr = lambda: input().strip()
rstrs = lambda: [str(x) for x in input().split()]
rstr_2d = lambda n: [rstr() for _ in range(n)]
rint = lambda: int(input())
rints = lambda: [int(x) for x in input().split()]
rint_2d = lambda n: [rint() for _ in range(n)]
rints_2d = lambda n: [rints() for _ in range(n)]
ceil1 = lambda a, b: (a + b - 1) // b
mem, ans = dict(), 0
for _ in range(rint()):
s, msk, cur = rstr(), 0, 1
mem1 = dict({chr(97 + i): 0 for i in range(26)})
for i in s:
mem1[i] += 1
for i in range(26):
if mem1[chr(97 + i)] & 1:
msk |= cur
cur <<= 1
cur = 1
for i in range(26):
ans += mem.get(msk ^ cur, 0)
cur <<= 1
ans += mem.get(msk, 0)
if msk not in mem:
mem[msk] = 0
mem[msk] += 1
print(ans)
``` | output | 1 | 16,848 | 6 | 33,697 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After learning a lot about space exploration, a little girl named Ana wants to change the subject.
Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:
You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa").
Two pairs are considered different if the strings are located on different indices. The pair of strings with indices (i,j) is considered the same as the pair (j,i).
Input
The first line contains a positive integer N (1 β€ N β€ 100 000), representing the length of the input array.
Eacg of the next N lines contains a string (consisting of lowercase English letters from 'a' to 'z') β an element of the input array.
The total number of characters in the input array will be less than 1 000 000.
Output
Output one number, representing how many palindrome pairs there are in the array.
Examples
Input
3
aa
bb
cd
Output
1
Input
6
aab
abcac
dffe
ed
aa
aade
Output
6
Note
The first example:
1. aa + bb β abba.
The second example:
1. aab + abcac = aababcac β aabccbaa
2. aab + aa = aabaa
3. abcac + aa = abcacaa β aacbcaa
4. dffe + ed = dffeed β fdeedf
5. dffe + aade = dffeaade β adfaafde
6. ed + aade = edaade β aeddea | instruction | 0 | 16,849 | 6 | 33,698 |
Tags: hashing, strings
Correct Solution:
```
N = int(input())
repo = {} # empty dictionary
total_count = 0
for i in range(N):
val = input()
# we need to convert val into 01010101010101010101010101
# use bit-wise
num = 0
for c in val:
index = ord(c) - ord('a')
num ^= (1 << index) # this is to flip the binary at the index
# case of all paired
if num in repo:
total_count += repo[num]
# case of one non-paired
for j in range(26):
num2 = num ^ (1 << j)
if num2 in repo:
total_count += repo[num2]
# put num into repo
if num in repo:
repo[num] += 1
else:
repo[num] = 1
print(total_count)
``` | output | 1 | 16,849 | 6 | 33,699 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After learning a lot about space exploration, a little girl named Ana wants to change the subject.
Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:
You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa").
Two pairs are considered different if the strings are located on different indices. The pair of strings with indices (i,j) is considered the same as the pair (j,i).
Input
The first line contains a positive integer N (1 β€ N β€ 100 000), representing the length of the input array.
Eacg of the next N lines contains a string (consisting of lowercase English letters from 'a' to 'z') β an element of the input array.
The total number of characters in the input array will be less than 1 000 000.
Output
Output one number, representing how many palindrome pairs there are in the array.
Examples
Input
3
aa
bb
cd
Output
1
Input
6
aab
abcac
dffe
ed
aa
aade
Output
6
Note
The first example:
1. aa + bb β abba.
The second example:
1. aab + abcac = aababcac β aabccbaa
2. aab + aa = aabaa
3. abcac + aa = abcacaa β aacbcaa
4. dffe + ed = dffeed β fdeedf
5. dffe + aade = dffeaade β adfaafde
6. ed + aade = edaade β aeddea | instruction | 0 | 16,850 | 6 | 33,700 |
Tags: hashing, strings
Correct Solution:
```
def zamien(S):
A = 26*[0]
for znak in S:
A[ord(znak)-ord('a')] += 1
return ''.join([str(i%2) for i in A])
def mainn():
A = {}
wynik = 0
for i in range(int(input())):
s = zamien(input())
wynik += A.get(s,0)
for i in range(26):
wynik += A.get(s[:i]+str((int(s[i])+1)%2)+s[i+1:],0)
A[s] = A.get(s,0) + 1
return wynik
print(mainn())
``` | output | 1 | 16,850 | 6 | 33,701 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After learning a lot about space exploration, a little girl named Ana wants to change the subject.
Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:
You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa").
Two pairs are considered different if the strings are located on different indices. The pair of strings with indices (i,j) is considered the same as the pair (j,i).
Input
The first line contains a positive integer N (1 β€ N β€ 100 000), representing the length of the input array.
Eacg of the next N lines contains a string (consisting of lowercase English letters from 'a' to 'z') β an element of the input array.
The total number of characters in the input array will be less than 1 000 000.
Output
Output one number, representing how many palindrome pairs there are in the array.
Examples
Input
3
aa
bb
cd
Output
1
Input
6
aab
abcac
dffe
ed
aa
aade
Output
6
Note
The first example:
1. aa + bb β abba.
The second example:
1. aab + abcac = aababcac β aabccbaa
2. aab + aa = aabaa
3. abcac + aa = abcacaa β aacbcaa
4. dffe + ed = dffeed β fdeedf
5. dffe + aade = dffeaade β adfaafde
6. ed + aade = edaade β aeddea | instruction | 0 | 16,851 | 6 | 33,702 |
Tags: hashing, strings
Correct Solution:
```
n=int(input())
a= {}
ans=0
for i in range(n):
d=0
st=input()
for j in st:
d^=1<<(ord(j)-ord("a"))
ans+=a.get(d,0)
for k in range(26):
ans+=a.get(d^(1<<k),0)
t=a.get(d,0)+1
a[d]=t
print(ans)
``` | output | 1 | 16,851 | 6 | 33,703 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After learning a lot about space exploration, a little girl named Ana wants to change the subject.
Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:
You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa").
Two pairs are considered different if the strings are located on different indices. The pair of strings with indices (i,j) is considered the same as the pair (j,i).
Input
The first line contains a positive integer N (1 β€ N β€ 100 000), representing the length of the input array.
Eacg of the next N lines contains a string (consisting of lowercase English letters from 'a' to 'z') β an element of the input array.
The total number of characters in the input array will be less than 1 000 000.
Output
Output one number, representing how many palindrome pairs there are in the array.
Examples
Input
3
aa
bb
cd
Output
1
Input
6
aab
abcac
dffe
ed
aa
aade
Output
6
Note
The first example:
1. aa + bb β abba.
The second example:
1. aab + abcac = aababcac β aabccbaa
2. aab + aa = aabaa
3. abcac + aa = abcacaa β aacbcaa
4. dffe + ed = dffeed β fdeedf
5. dffe + aade = dffeaade β adfaafde
6. ed + aade = edaade β aeddea
Submitted Solution:
```
import math
n = int(input())
singleChars = []
for i in range(n):
current = 0b0
nextLn = input()
for char in nextLn:
current = current ^ 1<<(ord(char) - 97)
singleChars.append(current)
total = 0
repository = {}
for i in range(n):
#odd
if singleChars[i] in repository:
total += repository[singleChars[i]]
#even
for j in range(26):
result = singleChars[i] ^ 1<<j
if result in repository:
total += repository[result]
if singleChars[i] in repository:
repository[singleChars[i]] += 1
else:
repository[singleChars[i]] = 1
print(total)
``` | instruction | 0 | 16,852 | 6 | 33,704 |
Yes | output | 1 | 16,852 | 6 | 33,705 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After learning a lot about space exploration, a little girl named Ana wants to change the subject.
Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:
You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa").
Two pairs are considered different if the strings are located on different indices. The pair of strings with indices (i,j) is considered the same as the pair (j,i).
Input
The first line contains a positive integer N (1 β€ N β€ 100 000), representing the length of the input array.
Eacg of the next N lines contains a string (consisting of lowercase English letters from 'a' to 'z') β an element of the input array.
The total number of characters in the input array will be less than 1 000 000.
Output
Output one number, representing how many palindrome pairs there are in the array.
Examples
Input
3
aa
bb
cd
Output
1
Input
6
aab
abcac
dffe
ed
aa
aade
Output
6
Note
The first example:
1. aa + bb β abba.
The second example:
1. aab + abcac = aababcac β aabccbaa
2. aab + aa = aabaa
3. abcac + aa = abcacaa β aacbcaa
4. dffe + ed = dffeed β fdeedf
5. dffe + aade = dffeaade β adfaafde
6. ed + aade = edaade β aeddea
Submitted Solution:
```
import sys,math
from sys import stdin,stdout
n=int(stdin.readline())
strarr=[]
for _ in range(n):
strarr.append(stdin.readline()[:-1])
arr=[]
for i in range(n):
ta=[0 for j in range(26)]
for j in strarr[i]:
ta[ord(j)-97]+=1
for j in range(len(ta)):
ta[j]=ta[j]&1
ta=int(''.join(map(str,ta)),2)
arr.append(ta)
ans=0
#for j in range(len(arr)):
# if arr[j] in d:
# d[arr[j]]+=1
# else:
# d[arr[j]]=1
#print(d,arr)
def mainkaam(flag):
global arr,d
if flag==True:
dtemp={}
ans=0
ctr=0
for i in range(len(arr)):
if arr[i] in dtemp:
ans+=dtemp[arr[i]];#print(ans,dtemp[arr[i]],arr[i])
dtemp[arr[i]]+=1
else:
dtemp[arr[i]]=1
#print("TRUEENDS",ans)
return ans
ans=0;
#farr=Co
for i in range(26):
d={}
#Each Character can be even or odd
#if Even:- another string with That and only that character odd #and the remianing same can be accepted
#if Odd:- same
for j in range(len(arr)):
#print("\t",arr[j]^(1<<i))
if arr[j]^(1<<i) in d:
#print("TRUE",d[arr[j]^(1<<i)],arr[j]^(1<<i),arr[j])
ans+=d[arr[j]^(1<<i)]
if True:
if arr[j] in d:
d[arr[j]]+=1
else:
d[arr[j]]=1
return ans
print(mainkaam(True)+mainkaam(False))
``` | instruction | 0 | 16,853 | 6 | 33,706 |
Yes | output | 1 | 16,853 | 6 | 33,707 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After learning a lot about space exploration, a little girl named Ana wants to change the subject.
Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:
You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa").
Two pairs are considered different if the strings are located on different indices. The pair of strings with indices (i,j) is considered the same as the pair (j,i).
Input
The first line contains a positive integer N (1 β€ N β€ 100 000), representing the length of the input array.
Eacg of the next N lines contains a string (consisting of lowercase English letters from 'a' to 'z') β an element of the input array.
The total number of characters in the input array will be less than 1 000 000.
Output
Output one number, representing how many palindrome pairs there are in the array.
Examples
Input
3
aa
bb
cd
Output
1
Input
6
aab
abcac
dffe
ed
aa
aade
Output
6
Note
The first example:
1. aa + bb β abba.
The second example:
1. aab + abcac = aababcac β aabccbaa
2. aab + aa = aabaa
3. abcac + aa = abcacaa β aacbcaa
4. dffe + ed = dffeed β fdeedf
5. dffe + aade = dffeaade β adfaafde
6. ed + aade = edaade β aeddea
Submitted Solution:
```
import sys
input = sys.stdin.readline
def gcd(a, b):
if a == 0:
return b
return gcd(b % a, a)
def lcm(a, b):
return (a * b) / gcd(a, b)
def main():
comp=[]
c=1
for i in range(27):
comp.append(c)
c*=2
n=int(input())
d={}
table=[]
for i in range(n):
k=[0]*27
s=input()
for j in s:
if ord(j)-ord('a')>=0:
k[ord(j)-ord('a')]+=1
#print(ord(j)-ord('a'))
key=0
for i in range(26):
if k[i]%2:
key+=comp[i]
table.append([k,key])
if key in d:
d[key]+=1
else:
d[key]=1
ans=0
for i in d.values():
ans+=(i)*(i-1)//2
#print(ans)
for i in table:
#print(i)
for j in range(len(i[0])):
if i[0][j]%2:
if i[1]-comp[j] in d.keys():
#print(i[1],i[1]-comp[j] )
ans+=(d[i[1]-comp[j]])
print(int(ans))
return
if __name__ == "__main__":
main()
``` | instruction | 0 | 16,854 | 6 | 33,708 |
Yes | output | 1 | 16,854 | 6 | 33,709 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After learning a lot about space exploration, a little girl named Ana wants to change the subject.
Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:
You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa").
Two pairs are considered different if the strings are located on different indices. The pair of strings with indices (i,j) is considered the same as the pair (j,i).
Input
The first line contains a positive integer N (1 β€ N β€ 100 000), representing the length of the input array.
Eacg of the next N lines contains a string (consisting of lowercase English letters from 'a' to 'z') β an element of the input array.
The total number of characters in the input array will be less than 1 000 000.
Output
Output one number, representing how many palindrome pairs there are in the array.
Examples
Input
3
aa
bb
cd
Output
1
Input
6
aab
abcac
dffe
ed
aa
aade
Output
6
Note
The first example:
1. aa + bb β abba.
The second example:
1. aab + abcac = aababcac β aabccbaa
2. aab + aa = aabaa
3. abcac + aa = abcacaa β aacbcaa
4. dffe + ed = dffeed β fdeedf
5. dffe + aade = dffeaade β adfaafde
6. ed + aade = edaade β aeddea
Submitted Solution:
```
# -*- coding:utf-8 -*-
"""
created by shuangquan.huang at 11/20/18
After learning a lot about space exploration, a little girl named Ana wants to change the subject.
Ana is a girl who loves palindromes (string that can be read the same backwards as forward).
She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem,
so she came up with a more interesting one and she needs your help to solve it:
You are given an array of strings which consist of only small letters of the alphabet.
Your task is to find how many palindrome pairs are there in the array.
A palindrome pair is a pair of strings such that the following condition holds:
at least one permutation of the concatenation of the two strings is a palindrome.
In other words, if you have two strings, let's say "aab" and "abcac",
and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that
it is a palindrome (in this case there exists the permutation "aabccbaa").
Two pairs are considered different if the strings are located on different indices.
The pair of strings with indices (π,π) is considered the same as the pair (π,π).
Input
The first line contains a positive integer π (1β€πβ€100 000), representing the length of the input array.
Eacg of the next π lines contains a string (consisting of lowercase English letters from 'a' to 'z') β an element of the input array.
The total number of characters in the input array will be less than 1000000.
Output
Output one number, representing how many palindrome pairs there are in the array.
# a, b can be transform to palindrome only when number of every characters in a+b is even, or only one is odd.
# only odd+even => odd
"""
import collections
N = int(input())
def hash(s):
wc = collections.Counter(s)
x = ''
for i in range(26):
w = chr(ord('a') + i)
c = wc[w]
if c % 2 == 0:
x += '0'
else:
x += '1'
return x
def neighbor(s):
for i in range(len(s)):
yield s[:i] + ('1' if s[i] == '0' else '0') + s[i + 1:]
def isneighbor(a, b):
return sum([0 if a[i] == b[i] else 1 for i in range(len(a))]) == 1
m = collections.defaultdict(list)
for i in range(N):
s = input()
m[hash(s)].append(i)
even = 0
odd = 0
for k, v in m.items():
lv = len(v)
even += lv * (lv - 1) // 2
for b in neighbor(k):
if b in m:
odd += lv * len(m[b])
print(even + odd // 2)
``` | instruction | 0 | 16,855 | 6 | 33,710 |
Yes | output | 1 | 16,855 | 6 | 33,711 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After learning a lot about space exploration, a little girl named Ana wants to change the subject.
Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:
You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa").
Two pairs are considered different if the strings are located on different indices. The pair of strings with indices (i,j) is considered the same as the pair (j,i).
Input
The first line contains a positive integer N (1 β€ N β€ 100 000), representing the length of the input array.
Eacg of the next N lines contains a string (consisting of lowercase English letters from 'a' to 'z') β an element of the input array.
The total number of characters in the input array will be less than 1 000 000.
Output
Output one number, representing how many palindrome pairs there are in the array.
Examples
Input
3
aa
bb
cd
Output
1
Input
6
aab
abcac
dffe
ed
aa
aade
Output
6
Note
The first example:
1. aa + bb β abba.
The second example:
1. aab + abcac = aababcac β aabccbaa
2. aab + aa = aabaa
3. abcac + aa = abcacaa β aacbcaa
4. dffe + ed = dffeed β fdeedf
5. dffe + aade = dffeaade β adfaafde
6. ed + aade = edaade β aeddea
Submitted Solution:
```
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 22 13:22:10 2018
@author: solemn
"""
"""Palindromes:
Find number of Palindrome pairs"""
def palindromes(L):
#L being the array containing strings
count = 0
for i in range (len(L)):
for j in range(i+1,len(L)):
if palind(L[i],L[j]) == True: count += 1
return count
def palind(a,b): #a,b are two strings
#return if permutation can be realized
A = {'a':0,'b':0,'c':0,'d':0,'e':0,'f':0,'g':0,'h':0,'i':0,'j':0,'k':0,'l':0,'m':0,'n':0,'o':0,'p':0,'q':0,'r':0,'s':0,'t':0,'u':0,'v':0,'w':0,'x':0,'y':0,'z':0}
count = 0
for i in a+b:
A[i] += 1
for j in A.keys():
if A[j] % 2== 1: count += 1
if count >1: return False
return True
``` | instruction | 0 | 16,856 | 6 | 33,712 |
No | output | 1 | 16,856 | 6 | 33,713 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After learning a lot about space exploration, a little girl named Ana wants to change the subject.
Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:
You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa").
Two pairs are considered different if the strings are located on different indices. The pair of strings with indices (i,j) is considered the same as the pair (j,i).
Input
The first line contains a positive integer N (1 β€ N β€ 100 000), representing the length of the input array.
Eacg of the next N lines contains a string (consisting of lowercase English letters from 'a' to 'z') β an element of the input array.
The total number of characters in the input array will be less than 1 000 000.
Output
Output one number, representing how many palindrome pairs there are in the array.
Examples
Input
3
aa
bb
cd
Output
1
Input
6
aab
abcac
dffe
ed
aa
aade
Output
6
Note
The first example:
1. aa + bb β abba.
The second example:
1. aab + abcac = aababcac β aabccbaa
2. aab + aa = aabaa
3. abcac + aa = abcacaa β aacbcaa
4. dffe + ed = dffeed β fdeedf
5. dffe + aade = dffeaade β adfaafde
6. ed + aade = edaade β aeddea
Submitted Solution:
```
import sys
input = sys.stdin.readline
def gcd(a, b):
if a == 0:
return b
return gcd(b % a, a)
def lcm(a, b):
return (a * b) / gcd(a, b)
def main():
comp=[]
c=1
for i in range(27):
comp.append(c)
c*=2
n=int(input())
d={}
table=[]
for i in range(n):
k=[0]*27
s=input()
for j in s:
if ord(j)-ord('a')>=0:
k[ord(j)-ord('a')]+=1
#print(ord(j)-ord('a'))
key=0
for i in range(26):
if k[i]%2:
key+=comp[i]
table.append([k,key])
if key in d:
d[key]+=1
else:
d[key]=1
ans=0
for i in d.values():
ans+=(i)*(i-1)//2
#print(ans)
for i in table:
for j in range(len(i[0])):
if i[0][j]:
if i[1]-comp[j] in d.keys():
ans+=(d[i[1]]*d[i[1]-comp[j]])/2
print(int(ans))
return
if __name__ == "__main__":
main()
``` | instruction | 0 | 16,857 | 6 | 33,714 |
No | output | 1 | 16,857 | 6 | 33,715 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After learning a lot about space exploration, a little girl named Ana wants to change the subject.
Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:
You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa").
Two pairs are considered different if the strings are located on different indices. The pair of strings with indices (i,j) is considered the same as the pair (j,i).
Input
The first line contains a positive integer N (1 β€ N β€ 100 000), representing the length of the input array.
Eacg of the next N lines contains a string (consisting of lowercase English letters from 'a' to 'z') β an element of the input array.
The total number of characters in the input array will be less than 1 000 000.
Output
Output one number, representing how many palindrome pairs there are in the array.
Examples
Input
3
aa
bb
cd
Output
1
Input
6
aab
abcac
dffe
ed
aa
aade
Output
6
Note
The first example:
1. aa + bb β abba.
The second example:
1. aab + abcac = aababcac β aabccbaa
2. aab + aa = aabaa
3. abcac + aa = abcacaa β aacbcaa
4. dffe + ed = dffeed β fdeedf
5. dffe + aade = dffeaade β adfaafde
6. ed + aade = edaade β aeddea
Submitted Solution:
```
ch = ['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']
def can_palin(ss):
o=0
for c in ch:
if ss.count(c)%2:
#print(c)
o=o+1
if o>1:
return False
#print(ss)
return True
n=int(input().strip())
st=[]
ans=0
st.append(input().strip())
for _ in range(1,n,1):
a=input().strip()
for s in st:
if can_palin(s+a):
ans=ans+1
print(ans)
``` | instruction | 0 | 16,858 | 6 | 33,716 |
No | output | 1 | 16,858 | 6 | 33,717 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After learning a lot about space exploration, a little girl named Ana wants to change the subject.
Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:
You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa").
Two pairs are considered different if the strings are located on different indices. The pair of strings with indices (i,j) is considered the same as the pair (j,i).
Input
The first line contains a positive integer N (1 β€ N β€ 100 000), representing the length of the input array.
Eacg of the next N lines contains a string (consisting of lowercase English letters from 'a' to 'z') β an element of the input array.
The total number of characters in the input array will be less than 1 000 000.
Output
Output one number, representing how many palindrome pairs there are in the array.
Examples
Input
3
aa
bb
cd
Output
1
Input
6
aab
abcac
dffe
ed
aa
aade
Output
6
Note
The first example:
1. aa + bb β abba.
The second example:
1. aab + abcac = aababcac β aabccbaa
2. aab + aa = aabaa
3. abcac + aa = abcacaa β aacbcaa
4. dffe + ed = dffeed β fdeedf
5. dffe + aade = dffeaade β adfaafde
6. ed + aade = edaade β aeddea
Submitted Solution:
```
n = int(input())
palin = []
ans = 0
for x in range(n):
s = input()
palmap = {}
for c in s:
palmap[c] = 1 if c not in palmap else palmap[c] + 1
shortened = ''
for ii in palmap.keys():
if palmap[ii] % 2 == 1:
shortened += ii
palin.append(sorted(shortened))
print(palin)
for i in range(1,n):
for j in range(i):
if (not palin[i] and len(palin[j])==1) or (not palin[j] and len(palin[i])==1) or (palin[i] == palin[j]):
ans += 1
print(ans)
``` | instruction | 0 | 16,859 | 6 | 33,718 |
No | output | 1 | 16,859 | 6 | 33,719 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ivan wants to play a game with you. He picked some string s of length n consisting only of lowercase Latin letters.
You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from 1 to n-1), but he didn't tell you which strings are prefixes and which are suffixes.
Ivan wants you to guess which of the given 2n-2 strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin!
Input
The first line of the input contains one integer number n (2 β€ n β€ 100) β the length of the guessed string s.
The next 2n-2 lines are contain prefixes and suffixes, one per line. Each of them is the string of length from 1 to n-1 consisting only of lowercase Latin letters. They can be given in arbitrary order.
It is guaranteed that there are exactly 2 strings of each length from 1 to n-1. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length n.
Output
Print one string of length 2n-2 β the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The i-th character of this string should be 'P' if the i-th of the input strings is the prefix and 'S' otherwise.
If there are several possible answers, you can print any.
Examples
Input
5
ba
a
abab
a
aba
baba
ab
aba
Output
SPPSPSPS
Input
3
a
aa
aa
a
Output
PPSS
Input
2
a
c
Output
PS
Note
The only string which Ivan can guess in the first example is "ababa".
The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.
In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable. | instruction | 0 | 16,862 | 6 | 33,724 |
Tags: strings
Correct Solution:
```
def magic(string):
str=string
for i in range(2*n-2):
for j in range(i,2*n-2):
if len(str[i])<len(str[j]):
temp=string[i]
str[i]=string[j]
str[j]=temp
return str
n=int(input())
string=[]
for i in range(2*n-2):
a=input()
string.append(a)
str=list.copy(string)
sort_string=magic(str)
if sort_string[0][1:n-1]!=sort_string[1][0:n-2]:
temp=sort_string[0]
sort_string[0]=sort_string[1]
sort_string[1]=temp
string1=sort_string[0]+sort_string[1][n-2]
string2=sort_string[1]+sort_string[0][0]
if n>2:
if string1[0:n-2]==sort_string[2] and string1[2:n]==sort_string[3] or string1[0:n-2]==sort_string[3] and string1[2:n]==sort_string[2]:
word=string1
else:
word=string2
else:
word=string1
length=0
value=[0 for x in range(2*n-2)]
for i in range(0,2*n-2):
length=len(string[i])
for j in range(i+1,2*n-2):
if length==len(string[j]):
if word.find(string[i])==0:
value[i]="P"
value[j]="S"
else:
value[i]="S"
value[j]="P"
print("".join(value))
``` | output | 1 | 16,862 | 6 | 33,725 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We all know that a superhero can transform to certain other superheroes. But not all Superheroes can transform to any other superhero. A superhero with name s can transform to another superhero with name t if s can be made equal to t by changing any vowel in s to any other vowel and any consonant in s to any other consonant. Multiple changes can be made.
In this problem, we consider the letters 'a', 'e', 'i', 'o' and 'u' to be vowels and all the other letters to be consonants.
Given the names of two superheroes, determine if the superhero with name s can be transformed to the Superhero with name t.
Input
The first line contains the string s having length between 1 and 1000, inclusive.
The second line contains the string t having length between 1 and 1000, inclusive.
Both strings s and t are guaranteed to be different and consist of lowercase English letters only.
Output
Output "Yes" (without quotes) if the superhero with name s can be transformed to the superhero with name t and "No" (without quotes) otherwise.
You can print each letter in any case (upper or lower).
Examples
Input
a
u
Output
Yes
Input
abc
ukm
Output
Yes
Input
akm
ua
Output
No
Note
In the first sample, since both 'a' and 'u' are vowels, it is possible to convert string s to t.
In the third sample, 'k' is a consonant, whereas 'a' is a vowel, so it is not possible to convert string s to t. | instruction | 0 | 16,878 | 6 | 33,756 |
Tags: implementation, strings
Correct Solution:
```
sup1=input()
sup2=input()
flag=0
vowel=[ 'a', 'e', 'i', 'o','u' ]
if(len(sup1)!=len(sup2)):
print("No")
else:
for i in range(len(sup2)):
if((sup1[i] in vowel and sup2[i] in vowel)or (sup1[i] not in vowel and sup2[i] not in vowel)):
flag=1
else:
flag=0
break
if(flag==1):
print("Yes")
else:
print("No")
``` | output | 1 | 16,878 | 6 | 33,757 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We all know that a superhero can transform to certain other superheroes. But not all Superheroes can transform to any other superhero. A superhero with name s can transform to another superhero with name t if s can be made equal to t by changing any vowel in s to any other vowel and any consonant in s to any other consonant. Multiple changes can be made.
In this problem, we consider the letters 'a', 'e', 'i', 'o' and 'u' to be vowels and all the other letters to be consonants.
Given the names of two superheroes, determine if the superhero with name s can be transformed to the Superhero with name t.
Input
The first line contains the string s having length between 1 and 1000, inclusive.
The second line contains the string t having length between 1 and 1000, inclusive.
Both strings s and t are guaranteed to be different and consist of lowercase English letters only.
Output
Output "Yes" (without quotes) if the superhero with name s can be transformed to the superhero with name t and "No" (without quotes) otherwise.
You can print each letter in any case (upper or lower).
Examples
Input
a
u
Output
Yes
Input
abc
ukm
Output
Yes
Input
akm
ua
Output
No
Note
In the first sample, since both 'a' and 'u' are vowels, it is possible to convert string s to t.
In the third sample, 'k' is a consonant, whereas 'a' is a vowel, so it is not possible to convert string s to t. | instruction | 0 | 16,879 | 6 | 33,758 |
Tags: implementation, strings
Correct Solution:
```
vowel = ('a', 'e', 'i', 'o', 'u')
l, m = input(), input()
if len(l) == len(m):
print(["Yes", "No"][True in [(x in vowel) ^ (y in vowel) for x, y in zip(l, m)]])
else:
print("No")
``` | output | 1 | 16,879 | 6 | 33,759 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We all know that a superhero can transform to certain other superheroes. But not all Superheroes can transform to any other superhero. A superhero with name s can transform to another superhero with name t if s can be made equal to t by changing any vowel in s to any other vowel and any consonant in s to any other consonant. Multiple changes can be made.
In this problem, we consider the letters 'a', 'e', 'i', 'o' and 'u' to be vowels and all the other letters to be consonants.
Given the names of two superheroes, determine if the superhero with name s can be transformed to the Superhero with name t.
Input
The first line contains the string s having length between 1 and 1000, inclusive.
The second line contains the string t having length between 1 and 1000, inclusive.
Both strings s and t are guaranteed to be different and consist of lowercase English letters only.
Output
Output "Yes" (without quotes) if the superhero with name s can be transformed to the superhero with name t and "No" (without quotes) otherwise.
You can print each letter in any case (upper or lower).
Examples
Input
a
u
Output
Yes
Input
abc
ukm
Output
Yes
Input
akm
ua
Output
No
Note
In the first sample, since both 'a' and 'u' are vowels, it is possible to convert string s to t.
In the third sample, 'k' is a consonant, whereas 'a' is a vowel, so it is not possible to convert string s to t. | instruction | 0 | 16,880 | 6 | 33,760 |
Tags: implementation, strings
Correct Solution:
```
a='ueoai'
if [s in a for s in input()] == [t in a for t in input()]:
print('Yes')
else:
print('No')
``` | output | 1 | 16,880 | 6 | 33,761 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We all know that a superhero can transform to certain other superheroes. But not all Superheroes can transform to any other superhero. A superhero with name s can transform to another superhero with name t if s can be made equal to t by changing any vowel in s to any other vowel and any consonant in s to any other consonant. Multiple changes can be made.
In this problem, we consider the letters 'a', 'e', 'i', 'o' and 'u' to be vowels and all the other letters to be consonants.
Given the names of two superheroes, determine if the superhero with name s can be transformed to the Superhero with name t.
Input
The first line contains the string s having length between 1 and 1000, inclusive.
The second line contains the string t having length between 1 and 1000, inclusive.
Both strings s and t are guaranteed to be different and consist of lowercase English letters only.
Output
Output "Yes" (without quotes) if the superhero with name s can be transformed to the superhero with name t and "No" (without quotes) otherwise.
You can print each letter in any case (upper or lower).
Examples
Input
a
u
Output
Yes
Input
abc
ukm
Output
Yes
Input
akm
ua
Output
No
Note
In the first sample, since both 'a' and 'u' are vowels, it is possible to convert string s to t.
In the third sample, 'k' is a consonant, whereas 'a' is a vowel, so it is not possible to convert string s to t. | instruction | 0 | 16,881 | 6 | 33,762 |
Tags: implementation, strings
Correct Solution:
```
import sys
import math
def read_int():
return int(input().strip())
def read_int_list():
return list(map(int,input().strip().split()))
def read_string():
return input().strip()
def read_string_list(delim=" "):
return input().strip().split(delim)
###### Author : Samir Vyas #######
###### Write Code Below #######
s = read_string()
t = read_string()
vowels = set(['a','e','i','o','u'])
s_bin, t_bin = "", ""
if len(s) != len(t):
print("No")
sys.exit()
for i in range(len(s)):
if s[i] in vowels and t[i] not in vowels:
print("No")
sys.exit()
if t[i] in vowels and s[i] not in vowels:
print("No")
sys.exit()
print("Yes")
``` | output | 1 | 16,881 | 6 | 33,763 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We all know that a superhero can transform to certain other superheroes. But not all Superheroes can transform to any other superhero. A superhero with name s can transform to another superhero with name t if s can be made equal to t by changing any vowel in s to any other vowel and any consonant in s to any other consonant. Multiple changes can be made.
In this problem, we consider the letters 'a', 'e', 'i', 'o' and 'u' to be vowels and all the other letters to be consonants.
Given the names of two superheroes, determine if the superhero with name s can be transformed to the Superhero with name t.
Input
The first line contains the string s having length between 1 and 1000, inclusive.
The second line contains the string t having length between 1 and 1000, inclusive.
Both strings s and t are guaranteed to be different and consist of lowercase English letters only.
Output
Output "Yes" (without quotes) if the superhero with name s can be transformed to the superhero with name t and "No" (without quotes) otherwise.
You can print each letter in any case (upper or lower).
Examples
Input
a
u
Output
Yes
Input
abc
ukm
Output
Yes
Input
akm
ua
Output
No
Note
In the first sample, since both 'a' and 'u' are vowels, it is possible to convert string s to t.
In the third sample, 'k' is a consonant, whereas 'a' is a vowel, so it is not possible to convert string s to t. | instruction | 0 | 16,882 | 6 | 33,764 |
Tags: implementation, strings
Correct Solution:
```
from string import ascii_lowercase
if __name__ == "__main__":
s = input()
t = input()
vowels = set(['a', 'e', 'i', 'o', 'u'])
consonants = set()
for letter in ascii_lowercase:
if letter not in vowels:
consonants.add(letter)
if len(s) != len(t):
print("No")
else:
can_transform = True
for index in range(len(s)):
if s[index] in vowels:
if t[index] not in vowels:
can_transform = False
break
else:
if t[index] not in consonants:
can_transform = False
break
if can_transform:
print("Yes")
else:
print('No')
``` | output | 1 | 16,882 | 6 | 33,765 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We all know that a superhero can transform to certain other superheroes. But not all Superheroes can transform to any other superhero. A superhero with name s can transform to another superhero with name t if s can be made equal to t by changing any vowel in s to any other vowel and any consonant in s to any other consonant. Multiple changes can be made.
In this problem, we consider the letters 'a', 'e', 'i', 'o' and 'u' to be vowels and all the other letters to be consonants.
Given the names of two superheroes, determine if the superhero with name s can be transformed to the Superhero with name t.
Input
The first line contains the string s having length between 1 and 1000, inclusive.
The second line contains the string t having length between 1 and 1000, inclusive.
Both strings s and t are guaranteed to be different and consist of lowercase English letters only.
Output
Output "Yes" (without quotes) if the superhero with name s can be transformed to the superhero with name t and "No" (without quotes) otherwise.
You can print each letter in any case (upper or lower).
Examples
Input
a
u
Output
Yes
Input
abc
ukm
Output
Yes
Input
akm
ua
Output
No
Note
In the first sample, since both 'a' and 'u' are vowels, it is possible to convert string s to t.
In the third sample, 'k' is a consonant, whereas 'a' is a vowel, so it is not possible to convert string s to t. | instruction | 0 | 16,883 | 6 | 33,766 |
Tags: implementation, strings
Correct Solution:
```
s=input()
t=input()
ns,nt=len(s),len(t)
vl=['a','e','i','o','u']
flag=0
if ns!=nt:
print('No')
else:
for i in range(ns):
if ((s[i] in vl) and (t[i] in vl)) or ((s[i] not in vl) and (t[i] not in vl)):
flag=1
else:
flag=0
break
if flag==0:
print('No')
else:
print('Yes')
``` | output | 1 | 16,883 | 6 | 33,767 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.