First things first, let g=6 be the primitive root of M(Primitive roots can be calculated in O(M)). So by definition, we can express any number =0 using some power of g under modulo M. Let, Fi≡gGi(modM). Notice that, for the given mod, M, there is no such value k≤106 s.t. Fk≡0(modM). So we don't have to worry about dealing with zeroes. All Gi for 0<i<M can be calculated in O(M).
Now, FlFr≡gGl⋅Fr(modM).
So our equation becomes P(k)≡l=1∏nr=l,MEX(l,r)=k∏ngGl⋅Fr(modM)
or, P(k)≡gl=1∑nr=l,MEX(l,r)=k∑nGl⋅Fr(modM)
So we have to compute the sum of the products Gl⋅Fr.
Let ansk=i=k∑nP(k). We will compute ansk for each k from 0 to n.
Build an array left where leftr is the maximum index ≤r such that for each index l≤leftr, MEX of the subarray [l,r] is ≥k.
Now, let's build the array left for each k from 0 to n in order. To generate the array for k+1, update the array left using the occurrences of k in a. For that we have to perform:
range updates like set lefti=min(lefti,x):L≤i≤R for some range (L,R) and some integer x.
range queries like sum of Fi⋅(G1+G2+⋯+Glefti):1≤i≤n.
We can solve this part using Segment Tree Beats. Please see the setter’s solution for more clarity.
One can also observe that left is a non-decreasing array. So the operations can also be done using a normal segment tree.