[SOLUTION] Torn Lucky Ticket Solution Codeforces

A ticket is a non-empty string of digits from 11 to 99.

lucky ticket is such a ticket that:

  • it has an even length;
  • the sum of digits in the first half is equal to the sum of digits in the second half.

You are given n ticket pieces s1,s2,,sn�1,�2,…,��. How many pairs (i,j)(�,�) (for 1i,jn1≤�,�≤�) are there such that si+sj��+�� is a lucky ticket? Note that it’s possible that i=j�=�.

Here, the + operator denotes the concatenation of the two strings. For example, if si�� is 13, and sj�� is 37, then si+sj��+�� is 1337.

Input

The first line contains a single integer n (1n21051≤�≤2⋅105) — the number of ticket pieces.

The second line contains n non-empty strings s1,s2,,sn�1,�2,…,��, each of length at most 55 and consisting only of digits from 11 to 99.

Output

Print a single integer — the number of pairs (i,j)(�,�) (for 1i,jn1≤�,�≤�) such that si+sj��+�� is a lucky ticket.

Examples
input

Copy
10
5 93746 59 3746 593 746 5937 46 59374 6
output

Copy
20
input

Copy
5
2 22 222 2222 22222
output

Copy
13
input

Copy
3
1 1 1
output

Copy
9
SOLUTION

# Function to count the number of lucky pairs
def count_lucky_pairs(tickets):
even_lengths = {}
sum_half = {}

for ticket in tickets:
length = len(ticket)
if length % 2 == 0:
half = length // 2
first_half = ticket[:half]
second_half = ticket[half:]
even_lengths[length] = even_lengths.get(length, 0) + 1
sum_first_half = sum(map(int, first_half))
sum_second_half = sum(map(int, second_half))
sum_half[(sum_first_half, length)] = sum_half.get((sum_first_half, length), 0) + 1

lucky_pairs = 0

for length, count in even_lengths.items():
if count > 1:
lucky_pairs += count * (count – 1) // 2

for (sum_half1, length1), count in sum_half.items():
if sum_half1 == 0:
lucky_pairs += count * (count – 1) // 2

return lucky_pairs

# Read input
n = int(input())
tickets = input().split()

# Count the number of lucky pairs
result = count_lucky_pairs(tickets)
print(result)


Leave a Comment