Chef has the string s of length n consisted of digits 4 and 7. The string s is called…
- User
Chef has the string s of length n consisted of digits 4 and 7. The string s is called balanced if there exits such integer x (1 ≤ x ≤ n) that the number of digits 4 in substring s[1; x) is equal to the number of digits 7 in substring s(x; n], where s[1; x) is the substring from the 1st digit to (x-1)th digit of s, and s(x; n] is the substring from the (x+1)th digit to nth digit of s. For example, s = 747474 is a balanced string, because s[1; 4) = 747 has one 4 and s(4; 6] = 74 has one 7. Note that x can be 1 or n and s[1; 1) and s(n; n] denote an empty string.
In one turn Chef can choose any pair of consecutive digits and swap them. Find for Chef the total number of different balanced string that can be obtained from string s using any (even 0) number of turns. Print the result modulo 1000000007. Input
The first line of the input contains one integer T, the number of test cases. Then T lines follow, each of which contains string s for the corresponding test.
Output T lines, each of which contains single integer - the answer for the corresponding test modulo 10^9+7.
Constraints
1 ≤ T ≤ 10
1 ≤ n ≤ 5000
Example
Input: 2 47 4477
Output: 1 4
Assistant
pythonMOD = 10**9 + 7 max_n = 5000 # Precompute factorial and inverse factorial modulo MOD fact = [1] * (max_n + 1) for i in range(1, max_n + 1): fact[i] = fact[i-1] * i % MOD inv_fact = [1] * (max_n + 1) inv_fact[max_n] = pow(fact[max_n], MOD-2, MOD) for i in range(max_n - 1, -1, -1): inv_fact[i] = inv_fact[i+1] * (i + 1) % MOD T = int(input()) for _ in range(T): s = input().strip() cnt4 = s.count('4') cnt7 = len(s) - cnt4 n = len(s) A = 0 if cnt4 >= 1: A = fact[n-1] * inv_fact[cnt4-1] % MOD A = A * inv_fact[cnt7] % MOD B = 0 if cnt7 >= 1: B = fact[n-1] * inv_fact[cnt4] % MOD B = B * inv_fact[cnt7-1] % MOD C = 0 if cnt4 >= 1 and cnt7 >= 1 and n >= 2: C = fact[n-2] * inv_fact[cnt4-1] % MOD C = C * inv_fact[cnt7-1] % MOD ans = (A + B - C) % MOD if ans < 0: ans += MOD print(ans)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.