"""Direct rank/unrank of coverage-constrained motifs in an internal CRT order.
Uses a shared canonical DP; optional localized count by branch bounds.
"""
from collections import Counter
from functools import lru_cache
from math import gcd,prod
from bisect import bisect_left
from motifs import primes,tail

class CoverFiber:
    def __init__(self,ps,hs,g):
        self.ps=tuple(ps);self.hs=tuple(hs);self.full=(1<<len(hs))-1
        self.opts=[];self.agg=[];self.sizes=[];self.bad=[];self.multi=[]
        for p in ps:
            op=[(a,sum(1<<j for j,h in enumerate(hs) if (a+h)%p==0)) for a in range(p) if a and (a+g)%p]
            cnt=Counter(b for a,b in op);self.opts.append(op);self.agg.append(tuple(cnt.items()));self.sizes.append(len(op))
            self.bad.append(sum(1<<j for j,h in enumerate(hs) if h%p in (0,g%p)))
            self.multi.append(tuple(b for b in cnt if b.bit_count()>1))
        z=len(ps);self.suffix=[1]*(z+1);self.special=[0]*(z+1)
        for i in range(z-1,-1,-1):
            self.suffix[i]=self.suffix[i+1]*self.sizes[i];self.special[i]=self.special[i+1]|self.bad[i]
            for b in self.multi[i]:self.special[i]|=b
        self.reps=[]
        for sp in self.special:
            x=self.full&~sp; a=[0]
            while x:b=x&-x;x^=b;a.append(a[-1]|b)
            self.reps.append(a)
        self.calls=0
        self._dp=lru_cache(None)(self._dp_impl)
        self._tail=lru_cache(None)(lambda i,m:tail(m,tuple(self.sizes[i:])))
        self.total=self.count(0,self.full)
    def count(self,i,mask):
        return self._dp(i,(mask&self.special[i])|self.reps[i][(mask&~self.special[i]).bit_count()])
    def _dp_impl(self,i,mask):
        self.calls+=1
        if not mask:return self.suffix[i]
        if i==len(self.ps):return 0
        m=mask.bit_count();cap=0;uni=0;sy=True
        for j in range(i,len(self.ps)):
            mx=max(((mask&b).bit_count() for b in self.multi[j]),default=0)
            uni|=mask&~self.bad[j];cap+=max(mx,int(bool(mask&~self.bad[j])))
            if self.bad[j]&mask or mx>1:sy=False
        if cap<m or uni!=mask:return 0
        if sy:return self._tail(i,m)
        C=Counter()
        for kill,c in self.agg[i]:C[mask&~kill]+=c
        return sum(c*self.count(i+1,left) for left,c in C.items())
    def unrank(self,k,r,D):
        if not 0<=k<self.total:raise ValueError('rank')
        mask=self.full
        for i,p in enumerate(self.ps):
            for a,b in self.opts[i]:
                c=self.count(i+1,mask&~b)
                if k>=c:k-=c;continue
                r+=D*((a-r)*pow(D,-1,p)%p);D*=p;mask&=~b;break
            else:raise AssertionError('no branch')
        assert not mask and k==0
        return r
    def rank(self,r):
        mask=self.full;k=0
        for i,p in enumerate(self.ps):
            for a,b in self.opts[i]:
                if r%p==a:mask&=~b;break
                k+=self.count(i+1,mask&~b)
            else:raise ValueError('not an event')
        if mask:raise ValueError('not an event')
        return k
    def prefix(self,X,r,D,R,cap=2_000_000):
        """Use exact branch cardinality and interval capacity bounds.
        Returns count and visited nodes; does not store a list of occurrences.
        """
        nodes=0
        def rec(i,mask,a,m):
            nonlocal nodes
            nodes+=1
            if nodes>cap:raise RuntimeError('interval node cap')
            T=self.count(i,mask)
            if not T or a>=X:return 0
            # all numbers in the branch progression (not just satisfying endpoints)
            P=R//m;K=1+(X-1-a)//m;K=min(K,P)
            lo=max(0,T-(P-K));hi=min(T,K)
            if lo==hi:return lo
            p=self.ps[i];inv=pow(m,-1,p)
            return sum(rec(i+1,mask&~b,a+m*((c-a)*inv%p),m*p) for c,b in self.opts[i])
        return rec(0,self.full,r,D),nodes

class Address:
    def __init__(self,n,g):
        if g<=0:raise ValueError('gap')
        self.R=prod(primes(n));self.g=g;small=[p for p in primes(n) if p<=5];self.D=prod(small);rest=[p for p in primes(n) if p>5];self.parts=[]
        for r in range(self.D):
            if gcd(r,self.D)!=1 or gcd(r+g,self.D)!=1:continue
            hs=[h for h in range(1,g) if gcd(r+h,self.D)==1]
            self.parts.append((r,CoverFiber(rest,hs,g)))
        self.total=sum(f.total for r,f in self.parts);self.nodes=0
    def unrank(self,k):
        if not 0<=k<self.total:raise ValueError('rank')
        for r,f in self.parts:
            if k<f.total:return f.unrank(k,r,self.D)
            k-=f.total
        raise AssertionError('rank')
    def rank(self,x):
        if not 0<=x<self.R:raise ValueError('residue')
        k=0
        for r,f in self.parts:
            if x%self.D==r:return k+f.rank(x)
            k+=f.total
        raise ValueError('not an event')
    def prefix(self,X,cap=2_000_000):
        if X<0:raise ValueError('X')
        q,x=divmod(X,self.R);out=q*self.total
        for r,f in self.parts:
            c,n=f.prefix(x,r,self.D,self.R,cap);out+=c;self.nodes+=n
        return out
    def select(self,k,cap=2_000_000):
        if k<0 or not self.total:raise ValueError('rank')
        q,k=divmod(k,self.total);lo=0;hi=self.R
        while lo<hi:
            m=(lo+hi)//2
            if self.prefix(m+1,cap)>k:hi=m
            else:lo=m+1
        return q*self.R+lo
    def sorted_small(self,cap=100000):
        if self.total>cap:raise MemoryError('too many events')
        return sorted(self.unrank(k) for k in range(self.total))
