A ticket is a non-empty string of digits from 11 to 99.
A 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 1≤i,j≤n1≤�,�≤�) 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.
The first line contains a single integer n� (1≤n≤2⋅1051≤�≤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.
Print a single integer — the number of pairs (i,j)(�,�) (for 1≤i,j≤n1≤�,�≤�) such that si+sj��+�� is a lucky ticket.
20
13
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)