Problem Author: | Hasan Saleh (MathModel) |
Prepared by: | Hasan Saleh (MathModel) |
Edited by: | Hasan Saleh (MathModel) |
Solution
We are given a string of digits of length . For each position , we fix s_i at position and permute the remaining n-1 digits. We consider only distinct permutations and define:
Key idea
Instead of summing whole numbers directly, we sum contributions per position. Everything reduces to counting multiset permutations.
1) Basic facts
Let the digit counts be c_0,\dots,c_9.
Number of distinct permutations of digits:
Decimal weights: position (1-indexed from left) has weight
Define
So the sum of weights of all positions except is
2) Fixing one position
Fix index and let
Remove this digit from the multiset.
Fixed position contribution
The digit always sits at position . The remaining n-1 digits can be permuted in
ways.
Thus the contribution of the fixed position is
Other positions contribution
Now consider the remaining n-1 positions.
Pick a digit value still available. If we place in one specific other position, the remaining digits can be permuted in
ways.
This number does not depend on which position we choose. So summing over all other positions simply multiplies by the sum of their weights:
Hence, the total contribution of digit over all other positions is
Summing over all j=0\dots9 gives the full contribution of non-fixed positions.
3) Final formula
Putting everything together:
This is computed independently for each .
4) Complexity
Digits range only from to , so all factorial divisions are over a constant-size multiset. For each position, we iterate over digits .
Overall complexity: .
with a small constant factor.
Implementation
mod=10**9+7
mx=10**6+5
pw=[0]*mx
fc=[0]*mx
iv=[0]*mx
c=[0]*10
def solve():
s=input().strip()
n=len(s)
for i in range(10):c[i]=0
for x in s:c[int(x)]+=1
tp=0
for i in range(n):tp=(tp+pw[i])%mod
for i in range(n):
v=int(s[i])
tp2=(tp-pw[n-i-1])%mod
c[v]-=1
w=fc[n-1]
for k in range(10):w=w*iv[c[k]]%mod
ans=pw[n-i-1]*w%mod*v%mod
for j in range(1,10):
c[j]-=1
w2=fc[n-2]
for k in range(10):w2=w2*iv[c[k]]%mod
c[j]+=1
ans=(ans+w2*tp2%mod*j)%mod
c[v]+=1
print(ans,end=' ')
print()
pw[0]=fc[0]=iv[0]=1
for i in range(1,1000001):
pw[i]=pw[i-1]*10%mod
fc[i]=fc[i-1]*i%mod
iv[i]=pow(fc[i],mod-2,mod)
for _ in range(int(input())):solve()