Problem:
 Score : 400 points    Problem Statement Let \mathrm{popcount}(n) be the number of 1 s in the binary representation of n .
For example, \mathrm{popcount}(3) = 2 , \mathrm{popcount}(7) = 3 , and \mathrm{popcount}(0) = 0 .  Let f(n) be the number of times the following operation will be done when we repeat it until n becomes 0 : "replace n with the remainder when n is divided by \mathrm{popcount}(n) ." (It can be proved that, under the constraints of this problem, n always becomes 0 after a finite number of operations.)  For example, when n=7 , it becomes 0 after two operations, as follows:   \mathrm{popcount}(7)=3 , so we divide 7 by 3 and replace it with the remainder, 1 .  \mathrm{popcount}(1)=1 , so we divide 1 by 1 and replace it with the remainder, 0 .   You are given an integer X with N digits in binary.
For each integer i such that 1 \leq i \leq N , let X_i be what X becomes when the i -th bit from the top is inverted.
Find f(X_1), f(X_2), \ldots, f(X_N) .      Constraints  1 \leq N \leq 2 \times 10^5  X is an integer with N digits in binary, possibly with leading zeros.         Input Input is given from Standard Input in the following format:  N  X       Output Print N lines. The i -th line should contain the value f(X_i) .        Sample Input 1 3
011      Sample Output 1 2
1
1   X_1 = 7 , which will change as follows: 7 \rightarrow 1 \rightarrow 0 . Thus, f(7) = 2 .  X_2 = 1 , which will change as follows: 1 \rightarrow 0 . Thus, f(1) = 1 .  X_3 = 2 , which will change as follows: 2 \rightarrow 0 . Thus, f(2) = 1 .        Sample Input 2 23
00110111001011011001110      Sample Output 2 2
1
2
2
1
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
1
3

Solution (Python):
import sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
rep=range
def Golf():n,*t=map(int,open(0).read().split())
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def MI():return map(int,input().split())
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def RA():return map(int,open(0).read().split())
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in R(V)]
    FromStdin=True if ls==None else False
    for i in R(E):
        if FromStdin:
            inp=LI()
            org_inp.append(inp)
        else:
            inp=ls[i]
        if len(inp)==2:
            a,b=inp;c=1
        else:
            a,b,c=inp
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'
    
    mp=[boundary]*(w+2);found={}
    for i in R(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def accum(ls):
    rt=[0]
    for i in ls:rt+=[rt[-1]+i]
    return rt
def bit_combination(n,base=2):
    rt=[]
    for tb in R(base**n):s=[tb//(base**bt)%base for bt in R(n)];rt+=[s]
    return rt
def gcd(x,y):
    if y==0:return x
    if x%y==0:return y
    while x%y!=0:x,y=y,x%y
    return y
def YN(x):print(['NO','YES'][x])
def Yn(x):print(['No','Yes'][x])
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)

mo=10**9+7
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
l_alp=string.ascii_lowercase

read=sys.stdin.buffer.read;readline=sys.stdin.buffer.readline;input=lambda:sys.stdin.readline().rstrip()

show_flg=False
show_flg=True

ans=0

def f(x):
    c=0
    while x>0:
        c+=1
        y=bin(x).count('1')
        x%=y
    return c

def f_init(x):
    rt=[0]*3
    p=x.count('1')
    N=len(x)
    for i in range(N):
        if x[i]=='1':
            for j in [-1,0,1]:
                rt[j]+=b[j][N-1-i]
                rt[j]%=p+j

    ans=[0]*3
    for j in [-1,0,1]:
        ans[j]=1+f(rt[j])
    return rt,ans
    


n=I()
s=S_()

N=2*10**5+10
a=[0]*(N+1)
p=s.count('1')


if p>1:
            
    for i in rep(N):
        a[i]=f(i)
    
    t=1
    t_p=1
    t_m=1
    p_p=p+1
    p_m=p-1
    
    f_x=0
    f_p=0
    f_m=0
    for i in rep(n)[::-1]:
        if s[i]=='1':
            f_x+=t%p
            f_p+=t_p%p_p
            f_m+=t_m%p_m
        t*=2
        t_p*=2
        t_m*=2
        t%=p
        t_p%=p_p
        t_m%=p_m
    
    t_p=1
    t_m=1
    ans=[]
    for i in rep(n)[::-1]:
        if s[i]=='1':
            nx=f_m-t_m%p_m
            nx%=p_m
        if s[i]=='0':
            nx=f_p+t_p%p_p
            nx%=p_p
        ans+=a[nx]+1,
    
        t*=2
        t_p*=2
        t_m*=2
        t%=p
        t_p%=p_p
        t_m%=p_m
    
    
    for i in ans[::-1]:
        print(i)

elif p==1:
       
    for i in rep(N):
        a[i]=f(i)
    
    t=1
    t_p=1
    t_m=1
    p_p=p+1
    p_m=p-1
    
    f_x=0
    f_p=0
    f_m=0
    for i in rep(n)[::-1]:
        if s[i]=='1':
            f_x+=t%p
            f_p+=t_p%p_p
            
        t*=2
        t_p*=2
        t_m*=2
        t%=p
        t_p%=p_p
        
    
    t_p=1
    t_m=1
    ans=[]
    for i in rep(n)[::-1]:
        if s[i]=='1':
            ans+=0,
        if s[i]=='0':
            nx=f_p+t_p%p_p
            nx%=p_p
            ans+=a[nx]+1,
    
        t*=2
        t_p*=2
        t_m*=2
        t%=p
        t_p%=p_p
        
    
    
    for i in ans[::-1]:
        print(i)

elif p==0:
       
    for i in rep(N):
        a[i]=f(i)
    
    t=1
    t_p=1
    t_m=1
    p_p=p+1
    p_m=p-1
    
    f_x=0
    f_p=0
    f_m=0
    for i in rep(n)[::-1]:
        if s[i]=='1':
            f_x+=t%p
            f_p+=t_p%p_p
            
        t*=2
        t_p*=2
        t_m*=2
        
        t_p%=p_p
        
    
    t_p=1
    t_m=1
    ans=[]
    for i in rep(n)[::-1]:
        if s[i]=='1':
            ans+=0,
        if s[i]=='0':
            nx=f_p+t_p%p_p
            nx%=p_p
            ans+=a[nx]+1,
    
        t*=2
        t_p*=2
        t_m*=2

        t_p%=p_p
        
    
    
    for i in ans[::-1]:
        print(i)

Solution (Python):
def bc(x):
    return bin(x).count("1")

def f(n):
    res = 0
    for i in range(n):
        if n == 0:
            return res
        else:
            res += 1
            n = n % bc(n)
    return res

N,X = open(0).read().split()
N = int(N)
pc = X.count('1')
na = 0
nb = 0
if N == 1:
    if X == '1':
        print(0)
    else:
        print(1)
else:
    if pc == 0:
        for i in range(N):
            print(1)
    elif pc == N:
        for i in range(1,N+1):
            na = (na+pow(2,N-i,N-1)) % (N-1)
        for i in range(1,N+1):
            temp = na
            temp = (temp-pow(2,N-i,N-1)) % (N-1)
            print(f(temp)+1)
    elif pc == 1:
        ind = X.index('1')
        na = pow(2,N-ind-1,2)
        for i in range(1,N+1):
            if i != ind + 1:
                temp = na
                temp = (temp+pow(2,N-i,2)) % 2
                print(f(temp)+1)
            else:
                print(0)
    else:
        for i in range(1,N+1):
            if X[i-1] == '1':
                na = (na+pow(2,N-i,pc-1)) % (pc-1)
        for i in range(1,N+1):
            if X[i-1] == '1':
                nb = (nb+pow(2,N-i,pc+1)) % (pc+1)
        for i in range(1,N+1):
            if X[i-1] == '1':
                temp = na
                temp = (temp-pow(2,N-i,pc-1)) % (pc-1)
                print(f(temp)+1)
            else:
                temp = nb
                temp = (temp+pow(2,N-i,pc+1)) % (pc+1)
                print(f(temp)+1)

Solution (Python):
import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 19
MOD = 10 ** 9 + 7
EPS = 10 ** -10

def popcount(i):
    return bin(i).count('1')

N = INT()
S = list(map(int, input()))[::-1]

pcnt1 = S.count(1) - 1
pcnt2 = S.count(1) + 1
base1 = base2 = 0
for i in range(N):
    if S[i]:
        if pcnt1 != 0:
            base1 += pow(2, i, pcnt1)
        base2 += pow(2, i, pcnt2)

ans = [0] * N
for i in range(N):
    if S[i] and pcnt1 == 0:
        ans[i] = 0
        continue
    cur = 0
    if S[i]:
        cur += (base1 - pow(2, i, pcnt1)) % pcnt1
    else:
        cur += (base2 + pow(2, i, pcnt2)) % pcnt2
    cnt = 1
    while cur:
        cur %= popcount(cur)
        cnt += 1
    ans[i] = cnt
for a in ans[::-1]:
    print(a)

Solution (Python):
from collections import Counter
import sys

sys.setrecursionlimit(10 ** 6)

mod = 1000000007
inf = int(1e18)

dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]


def inverse(a):
    return pow(a, mod - 2, mod)


def usearch(x, a):
    lft = 0
    rgt = len(a) + 1
    while rgt - lft > 1:
        mid = (rgt + lft) // 2
        if a[mid] <= x:
            lft = mid
        else:
            rgt = mid
    return lft


memo = {}

def countbit(x):
    i = 0
    cnt = 0
    while x >= 1<<i:
        if x & (1<<i):
            cnt += 1
        i += 1
    return cnt


def count(x):
    
    
    
    
    s = 0
    while x != 0:
        s += 1
        x = x % countbit(x)
    return s

def main():
    n = int(input())
    xs = list(input())
    c = len([i for i in xs if i == '1'])
    dp = {}
    dps = {}
    for i in range(-1, 2):
        cc = c + i
        if cc == 0:
            continue
        dp[cc] = [-1] * n
        base = 1 % cc
        dpstmp = 0
        for i in range(n):
            dp[cc][i] = base
            if xs[-i-1] == '1':
                dpstmp += base
            base = base * 2 % cc
        dps[cc] = dpstmp % cc

    for i in range(n):
        cc = c
        if xs[i] == '1':
            cc -= 1
        else:
            cc += 1
        if cc == 0:
            print(0)
            continue
        res = dps[cc]
        if xs[i] == '1':
            res = (res - dp[cc][-i-1]) % cc
        else:
            res = (res + dp[cc][-i-1]) % cc
        s = count(res) + 1
        print(s)


main()

Solution (Python):
n = int(input())
x = str(input())
kosu1 = 0
kazu = 0
for i in range(n):
    kazu += 2 ** (n - i - 1) * int(x[i])
    if x[i] == '1':
        kosu1 += 1
if kosu1 ==1:
    kazup = kazu % (kosu1 + 1)
    magic17 = [0, 1, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 2, 3, 1, 2]
    box = [0] * (kosu1 + 1)

    amarip = [1] * n
    amarim = [1] * n
    for i in range(1, n):
        amarip[i] = (amarip[i - 1] * 2) % (kosu1 + 1)
    for i in range(n):
        if x[i] == '1':
            print(0)
        else:
            a = (kazup + amarip[n - 1 - i]) % (kosu1 + 1)

            if a <= 18:
                print(magic17[a] + 1)
            else:
                num = 0
                for i in range(len(str(bin(a)))-2):
                    if str(bin(a))[-1 - i] == '1':

                        num += 1
                print(magic17[a % num] + 2)
else:
    kazup = kazu % (kosu1 + 1)
    kazum = kazu % (kosu1 - 1)
    magic17 = [0,1,1,2,1,2,1,2,1,2,1,2,1,2,2,3,1,2,1]
    box = [0] * (kosu1 +1)

    amarip = [1] * n
    amarim = [1] * n
    for i in range(1,n):
        amarip[i] = (amarip[i - 1]*2) % (kosu1 + 1)
        amarim[i] = (amarim[i - 1]*2) % (kosu1 - 1)
    for i in range(n):
        if x[i] == '1':
            a = (kazum - amarim[n-1-i]) % (kosu1 - 1)

            if a <= 18:
                print(magic17[a]+1)
            else:
                num = 0

                for i in range(len(str(bin(a)))-2):
                    if str(bin(a))[-1-i] == '1':

                        num += 1
                print(magic17[a % num] + 2)
        else:
            a = (kazup + amarip[n - 1 - i]) % (kosu1 + 1)
            if a <= 18:
                print(magic17[a] + 1)
            else:
                num = 0
                for i in range(len(str(bin(a)))-2):
                    if str(bin(a))[-1 - i] == '1':

                        num += 1
                print(magic17[a % num] + 2)

Solution (Python):
FAST_IO = 1
if FAST_IO:
    import io, sys, atexit
    rr = iter(sys.stdin.read().splitlines()).next
    sys.stdout = _OUTPUT_BUFFER = io.BytesIO()

    @atexit.register
    def write():
        sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
else:
    rr = raw_input
rri = lambda: int(rr())
rrm = lambda: map(int, rr().split())
rrmm = lambda n: [rrm() for _ in xrange(n)]
N = rri()

num = list(rr())
count = num.count('1')
pwrTwo_plus = [0] * N 
pwrTwo_plus[0] = 1 % (count+1)
if count>1:
    pwrTwo_minus = [0] * N 
    pwrTwo_minus[0] = 1 % (count-1)  
for i in range(1, N):  
    pwrTwo_plus[i] = pwrTwo_plus[i - 1] * (2 % count)  
    pwrTwo_plus[i] %= count+1
    if count>1:
        pwrTwo_minus[i] = pwrTwo_minus[i - 1] * (2 % count)  
        pwrTwo_minus[i] %= count-1

def getMod(_str, n, k, plus) :  
    
    
    res = 0
    i = 0
    j = n - 1
    while (i < n) :  
  
        
        if (_str[j] == '1') :  
  
            
            if plus:
                res += (pwrTwo_plus[i] )  
                res %= k  
            else:
                res += (pwrTwo_minus[i] )  
                res %= k  
              
        i += 1
        j -= 1
  
    return res  
dic = {}
def f(x):
    if x in dic:
        return dic[x]
    if x== 0:
        return 0
    tmp = x% bin(x).count('1')
    dic[x] = f(tmp)+1
    return dic[x]
    

ans_1 = getMod(num, N, count+1, True)
if count>1:
    ans_2 = getMod(num, N, count-1, False)
for i in range(N):
    if num[i] =='0':
        cur_count = count+1
    else:
        cur_count =count-1
    if cur_count ==0:
        print(0)
    else:
        if num[i] =='0':
            cur_num = ans_1
            cur_num += pwrTwo_plus[N-1-i]
            cur_num %= cur_count
            print(f(cur_num)+1)
        else:
            cur_num = ans_2
            cur_num -=pwrTwo_minus[N-1-i] 
            cur_num %= cur_count
            print(f(cur_num)+1)

Solution (Python):
import sys
sys.setrecursionlimit(100000000)

n = int(input())
x = input()

c1 = x.count('1')
if c1 > 1:
    cc1 = int('0b' + x, 0) % (c1 - 1)
cc2 = int('0b' + x, 0) % (c1 + 1)

def f(n):
    ans = 0
    while n > 0:
        ans += 1
        n = n % bin(n).count('1')
    return ans

if c1 == 1:
    for i in range(n):
        if x[i] == '1':
            print(0)
        else:
            print(f((pow(2, n-i-1, c1+1) + cc2) % (c1 + 1)) + 1)
    exit()

for i in range(n):
    if x[i] == '1':
        print(f((-pow(2, n-i-1, c1-1) + cc1) % (c1 - 1)) + 1)
    else:
        print(f((pow(2, n-i-1, c1+1) + cc2) % (c1 + 1)) + 1)

Solution (Python):
N=int(input())
X=input()

D={}
for i in range(1,N+1):
    Nun=i+0
    cnt=0
    while Nun!=0:
        if Nun in D:
            cnt+=D[Nun]
            Nun=0
        S=str(bin(Nun))
        One=S.count("1")
        if One==0:
            break
        else:
            Nun=Nun%One
            cnt+=1
    D[i]=cnt
D[0]=0


One=X.count("1")


if One==0:
    for i in range(N):
        print(1)
elif One==1:
    for i in range(N-1):
        if X[i]=="1":
            print(0)
        else:
            print(1)
    if X[-1]=="0":
        print(2)
    else:
        print(0)
else:
    Num10=0
    for i in range(N):
        if X[i]=="1":
            Num10+=pow(2,N-1-i,One-1)
    Num10%=(One-1)
    
    Num01=0
    for i in range(N):
        if X[i]=="1":
            Num01+=pow(2,N-1-i,One+1)
    Num01%=(One+1)
    
    for i in range(N):
        if X[i]=="1":
            A=Num10-pow(2,N-1-i,One-1)
            
            if A==0:
                print(1)
            elif A%(One-1)==0:
                print(1)
            else:
                A%=(One-1)
                print(1+D[A])
            
        else:
            A=Num01+pow(2,N-1-i,One+1)
            if A%(One+1)==0:
                print(1)
            else:
                A%=(One+1)
                print(D[A]+1)

Solution (Python):
CH = [0,1,1,2,1,2,1,2,1,2,1,2,1,2,2,3,1,2,1,2,1]
N = int(input())
X = input()
s = 0
a = 1
A = []
B = []
for x in X:
    if x == "1":
        s += 1
for i in range(N):
    A.append(a)
    a = a*2 %(s+1)
a = 1
num = int(X,2)
num1 = num%(s+1)
if s > 1:
    num2 = num%(s-1)
    for i in range(N):
        B.append(a)
        a = a*2 %(s-1)
for i in range(N):
    if int(X[i])==1:
        p = s-1
        if p == 0:
            print(0)
            continue
        x = (num2-B[N-1-i])%p
        if x > 20:
            y = x%sum(map(int,list(bin(x))[2:]))
            print(2+CH[y])
        else:
            print(1+CH[x])
    else:
        p = s+1
        x = (num1+A[N-1-i])%p
        if x > 20:
            y = x%sum(map(int,list(bin(x))[2:]))
            print(2+CH[y])
        else:
            print(1+CH[x])

Solution (Python):
import sys
from collections import Counter
N = int(input())
X = list(input())
revX = reversed(X)
count01 = Counter(X)
if count01['1'] == 0:
    for i in range(N):
        print(1)
    sys.exit()
m1 = count01['1']-1
p1 = count01['1']+1
powrem = []
m1rem = 0
p1rem = 0
basem1 = 1
basep1 = 1
if m1 == 0:
    for i, xi in enumerate(revX):
    
        if xi == '0':
            powrem += [basep1 % p1]
        else:
            powrem += [0]
            p1rem = (p1rem + basep1) % p1
        basep1 = (basep1 * 2) % p1
    revpowrem = reversed(powrem)
    
    for xi, rem in zip(X, revpowrem):
        c = 1
        if xi == '0':
            r = (p1rem+rem)%p1
        else:
            print(0)
            continue
        
        while r != 0:
            p = bin(r).count('1')
            r = r % p
            c += 1
        print(c)
    sys.exit()

for i, xi in enumerate(revX):
    
    if xi == '0':
        powrem += [basep1 % p1]
    else:
        powrem += [basem1 % m1]
        m1rem = (m1rem + basem1) % m1
        p1rem = (p1rem + basep1) % p1
    basem1 = (basem1 * 2) % m1
    basep1 = (basep1 * 2) % p1
revpowrem = reversed(powrem)

for xi, rem in zip(X, revpowrem):
    c = 1
    if xi == '0':
        r = (p1rem+rem)%p1
    else:
        r = (m1rem-rem)%m1
    
    while r != 0:
        p = bin(r).count('1')
        r = r % p
        c += 1
    print(c)

Solution (Python):
import sys
import numpy as np
import numba
from numba import njit
i8 = numba.int64

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

@njit((), cache=True)
def compute_small_f():
    popcount = np.empty(1 << 18, np.int64)
    popcount[0] = 0
    for n in range(18):
        popcount[1 << n:1 << n + 1] = popcount[:1 << n] + 1
    f = np.empty(1 << 18, np.int64)
    f[0] = 0
    for n in range(1, 1 << 18):
        f[n] = 1 + f[n % popcount[n]]
    return f

@njit((i8[:], i8[:]), cache=True)
def main(X, f):
    N = len(X)
    popX = X.sum()
    MOD1 = popX + 1
    MOD2 = popX - 1
    if popX == 1:
        MOD2 = 1
    pow1 = np.ones_like(X)
    pow2 = np.ones_like(X)
    for n in range(1, N):
        pow1[n] = 2 * pow1[n - 1] % MOD1
        pow2[n] = 2 * pow2[n - 1] % MOD2

    X1, X2 = 0, 0
    for x in X:
        X1 = (2 * X1 + x) % MOD1
        X2 = (2 * X2 + x) % MOD2

    ans = np.empty(N, np.int64)
    for i in range(N):
        x = X[N - 1 - i]
        if x == 0:
            nxt = (X1 + pow1[i]) % (popX + 1)
            ans[i] = 1 + f[nxt]
        elif x == 1:
            if popX == 1:
                ans[i] = 0
            else:
                nxt = (X2 - pow2[i]) % (popX - 1)
                ans[i] = 1 + f[nxt]
    return ans[::-1]

N = int(readline())
X = np.array(list(read().rstrip()), np.int64) - ord('0')
ans = main(X, compute_small_f())
print('\n'.join(map(str, ans.tolist())))

Solution (Python):
import sys


def _s(): return sys.stdin.readline().strip()


def _i(): return int(sys.stdin.readline().strip())


def main():
    n = _i()
    s = _s()
    m = s.count("1")
    arr = list(range(max(1, m-1), m+2))
    d1 = {}
    for ai in arr:
        d1[ai] = [1 % ai]
        for i in range(n-1):
            d1[ai].append((2*d1[ai][-1]) % ai)

    d2 = {ai: 0 for ai in arr}
    for ai in arr:
        for i, c in enumerate(reversed(s)):
            if c == "1":
                d2[ai] = (d2[ai] + d1[ai][i]) % ai

    lst = [0] * (n+1)
    for i in range(1, n+1):
        t = i % bin(i)[2:].count("1")
        lst[i] = 1 + lst[t]

    i = n
    for c in s:
        i -= 1
        if c == "1":
            m1 = m - 1
            if m1 == 0:
                print(0)
                continue
            else:
                t = (d2[m1] - d1[m1][i]) % m1
        else:
            m1 = m + 1
            t = (d2[m1] + d1[m1][i]) % m1
        print(lst[t] + 1)


if __name__ == "__main__":
    main()

Solution (Python):




import sys
from io import StringIO
import unittest

sys.setrecursionlimit(20000000)

def yn(b):
    print("Yes" if b==1 else "No")
    return

def count_ones_by_bin(num):
    bin_num = bin(num)[2:]
    count = 0
    for i in bin_num:
            count += int(i)
    return count

def resolve():
    readline=sys.stdin.readline

    n=int(readline())
    x=readline().rstrip()

    
    
    
    amr1=[0]*((10**5)*2 + 5)
    amr2=[0]*((10**5)*2 + 5)
    bits=[False]*((10**5)*2 + 5)
    pc=[-1]*((10**5)*2 + 5)
    bcnt=0
    j=0
    for i in x:
        if int(i)==1:
            bcnt += 1
            bits[j]=True
        j+=1

    base1=0
    base2=0
    ni1=1
    ni2=1
    for j in range(n):
        i=n-1-j
        jo=n-i-1
        if j > 0:
            ni1*=2
            ni2*=2
        
        ni1=ni1%(bcnt+1)
        amr1[i]=ni1
        if (bcnt-1)==0:
            amr2[i]=0 
        else:
            
            ni2=ni2%(bcnt-1)
            amr2[i]=ni2
        if bits[i]==True:
            base1+=amr1[i]
            base2+=amr2[i]
    for i in range(n):
        ans=0
        if bits[i]==True: 
            if (bcnt-1)==0:
                base=0
            else:
                base=(base2-amr2[i])%(bcnt-1)
                ans+=1
        else:
            base=(base1+amr1[i])%(bcnt+1)
            ans+=1
        
        while base > 0:
            if pc[base]==-1:
                pc[base]=count_ones_by_bin(base)
            base=base%pc[base]
            ans+=1
        print(ans)
    return

if 'doTest' not in globals():
    resolve()
    sys.exit()

Solution (Python):

import math

N = int(input())
X = list(input())
X = list(map(int, X))

def num_to_X(num):
    new_X = []
    new_N = int(math.log(num,2))+1
    for i in range(new_N):
        new_X.append(num>>i&1)
    return new_X[::-1]

def X_to_num(X):
    value = 0
    X = X[::-1]
    for i in range(len(X)):
        value += X[i]*pow(2,i)
    return value

def mode(X, mod):
    X = X[::-1]
    next_X = 0
    mod_2_i = 1
    for i in range(len(X)):
        next_X = (next_X+(X[i]*mod_2_i))%mod
        mod_2_i = (mod_2_i*2)%mod
    return next_X

def f(N, X, k):
    mod = sum(X)
    next_X = mode(X,mod)
    if next_X == 0:
        return k+1
    else:
        new_X = num_to_X(next_X)
        return f(len(new_X), new_X, k+1)

base_mod = sum(X)

if base_mod == 1:
    for i in range(N):
        
        if X[i] == 1:
            print(0)
        
        elif i != N-1:
            print(1)
        
        else:
            print(2)
    exit(0)

plus_amari = mode(X, base_mod+1)

minus_amari = mode(X, base_mod-1)


results = []
modplus_2_i = 1
modminus_2_i = 1
X_hanten = X[::-1]





for i in range(N):
    
    if X_hanten[i] == 0:


        amari = (plus_amari+modplus_2_i)%(base_mod+1)
    else:


        amari = (minus_amari-modminus_2_i)%(base_mod-1)


    if amari != 0:
        new_X = num_to_X(amari)
        results.append(f(len(new_X),new_X,1))
    else:
        results.append(1)

    modplus_2_i = (modplus_2_i*2)%(base_mod+1)
    modminus_2_i = (modminus_2_i*2)%(base_mod-1)


for result in results[::-1]:
    print(result)

Solution (Python):
N = int(input())
X = list(input())
one = X.count('1')
L1 = [1]
L2 = [1]

for _ in range(N-1):
    if one - 1 == 0:
        L1.append(0)
    else:
        L1.append((L1[-1] * 2) % (one - 1))
    L2.append((L2[-1] * 2) % (one + 1))

x1 = 0
x2 = 0
power1 = 1
power2 = 1

for i in range(N):
    if X[N-i-1] == '1':
        if one - 1 != 0:
            x1 += power1
        x2 += power2
    power1 *= 2
    power2 *= 2
    if one - 1 != 0:
        power1 %= one - 1
    power2 %= one + 1

def solve(X, cnt):
    if X == 0:
        return cnt
    
    X %= bin(X).count('1')
    return solve(X, cnt+1)

for i in range(N):
    if X[i] == '0':
        tmp = (x2 + L2[N-i-1]) % (one + 1)
        ans = solve(tmp, 0) + 1
    else:
        if one - 1 == 0:
            ans = 0
        else:
            tmp = (x1 - L1[N-i-1]) % (one - 1)
            ans = solve(tmp, 0) + 1
    print(ans)

Solution (Python):
def modpow(val, n, mod):
    ret = 1
    while n:
        if n & 1:
            ret = (ret * val) % mod
        val = (val * val) % mod
        n = n >> 1
    return ret


def calc(val, my_dict, cnt):
    num_one = bin(val).count('1')
    if val in my_dict:
        return cnt + my_dict[val]
    else:
        if num_one == 0:
            return cnt
        nex = val % num_one
        ret = calc(nex, my_dict, cnt+1)
        my_dict[val] = ret - cnt
        return ret


n = int(input())
x = input()
tmp = list(x)
my_dict = dict()

num_one = tmp.count('1')
num_one_plus = num_one + 1
num_one_minus = num_one - 1

modsum_plus = 0
modsum_minus = 0
for i in range(1, n+1):
    if tmp[-i] == '1':
        modsum_plus += modpow(2, i-1, num_one_plus) % num_one_plus
        if num_one_minus != 0:
            modsum_minus += modpow(2, i-1, num_one_minus) % num_one_minus

for i in range(n):
    if num_one == 1 and tmp[i] == '1':
        print(0)
        continue
    if tmp[i] == '0':
        val = (modsum_plus + modpow(2, n-i-1, num_one_plus)) % num_one_plus
    else:
        if num_one_minus != 0:
            val = (modsum_minus - modpow(2, n-i-1, num_one_minus)) % num_one_minus
        else:
            val = 0
    if val != 0:
        print(calc(val, my_dict, 1))
    else:
        print(1)

Solution (Python):
from collections import defaultdict
N = int(input())
X = list(input())
d = defaultdict(int)

for i in range(1, N):
    c = 0
    t = 0
    k = format(i, "b")
    for j in k:
        if j == "1":
            c += 1
    d[i] = d[i%c] + 1


n = 0
for i in X:
    if i == "1":
        n += 1

p1 = 1
p2 = 1
total1 = 0
total2 = 0
for i in X[::-1]:
    if i == "1":
        total1 += p1 % (n+1)
        if n-1 > 0:
            total2 += p2 % (n-1)
    p1 *= 2
    p1 %= n+1
    if n-1 > 0:
        p2 *= 2
        p2 %= n-1

total1 %= (n+1)
if n-1 > 0:
    total2 %= (n-1)
Ans = []
p1 = 1
p2 = 1
for i in X[::-1]:
    c = 1
    if n - 1 <= 0 and i == "1":
        Ans.append(0)
    else:
        if i == "0":
            start = total1
            start += p1
            start %= (n+1)
        else:
            start = total2
            start -= p2
            start += n - 1
            start %= (n-1)
        Ans.append(c+d[start])
    p1 *= 2
    p1 %= n+1
    if n-1 > 0:
        p2 *= 2
        p2 %= n-1

for i in Ans[::-1]:
    print(i)

Solution (Python):

from functools import lru_cache

import sys
sys.setrecursionlimit(10**6)

buff_readline = sys.stdin.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


def read_int_n():
    return list(map(int, buff_readline().split()))


def read_float():
    return float(buff_readline())


def read_float_n():
    return list(map(float, buff_readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()

def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, X):
    @lru_cache(maxsize=None)
    def f(y):
        c = bin(y).count('1')
        if c == 0:
            return 0
        r = y % c

        return 1 + f(r)

    C = X.count('1')
    cmr = 0
    cpr = 0
    for b in X:
        cmr *= 2
        cmr += int(b)
        if C-1 == 0:
            cmr = 0
        else:
            cmr %= C - 1
        cpr *= 2
        cpr += int(b)
        cpr %= C + 1

    bp = 1
    bm = 1

    ans = []
    for i in range(N-1, -1, -1):
        t = 1
        if X[i] == '0':
            x = (cpr + bp) % (C+1)
        else:
            if C-1 == 0:
                x = 0
                t = 0
            else:
                x = (cmr - bm) % (C-1)
        while True:
            c = bin(x).count('1')
            
            if c == 0:
                break
            x = x % c
            t += 1
        ans.append(t)

        bp *= 2
        bp %= (C+1)
        if C - 1 != 0:
            bm *= 2
            bm %= (C-1)

    for a in reversed(ans):
        print(a)


def main():
    N = read_int()
    X = read_str()
    slv(N, X)

    
    
    
    
    




if __name__ == '__main__':
    main()

Solution (Python):
def main():
    n = int(input())
    x = input()
    k = int(x, 2)
    p = x.count("1")
    if p > 1:
        kp0 = k % (p - 1)
    kp1 = k % (p + 1)
    f = [0] * (n + 1)
    for i in range(1, n + 1):
        f[i] = f[i % bin(i).count("1")] + 1
    for i in range(n):
        if x[i] == "1":
            pi = p - 1
            if pi == 0:
                print(0)
                continue
            print(f[(kp0 - pow(2, n - i - 1, pi)) % pi] + 1)
        else:
            pi = p + 1
            print(f[(kp1 + pow(2, n - i - 1, pi)) % pi] + 1)


if __name__ == '__main__':
    main()