Problem:


Score : 400 points

Problem Statement

Let \mathrm{popcount}(n) be the number of 1s 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



Sample input:
3
011


Sample output:
2
1
1

Submission status: Time Limit Exceeded

Solution code:
def f(int):
  return str(bin(int)[2:]).count("1")

n,x=map(str,open(0).read().split());n=int(n)
l=[i for i in x]

for i in range(n-1,-1,-1):
  tl=l[::-1]
  if tl[i]=="0":
    tl[i]="1"
  else:
    tl[i]="0"
  x="".join(tl[::-1])
  ix=int(x,2)
  count=0
  while ix and n:
    t=ix%f(ix)
    ix=t
    count+=1
  print(count)

Submission status: Time Limit Exceeded

Solution code:
def m():
    N = int(input())
    X = input()
    def f(n):
        r = 0
        while n !=0:
            x = bin(n)[2:].count('1')
            n = n % x
            r +=1
        return r

    R = list(reversed(X))
    total = 0
    for i in range(N):
        total += int(R[i]) * pow(2, i)

    for i in range(N):
        ans = 0
        if X[i] == '1':
            ans = f(total - pow(2, N-1-i))
        else:
            ans = f(total + pow(2, N-1-i))
        print(ans)
    # return total
m()

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
x = input()

val = 0
rui = 1
mod = 0

nagasa = 2*10**5+1
#nagasa = 5
d_li = [0]*(nagasa)

for i in range(1,nagasa):
    t_v = i
    t_m = bin(t_v).count("1")
    ans = 0
    while t_v != 0:
        if d_li[t_v] != 0:
            ans += d_li[t_v]
            break
        ans += 1
        t_v %= t_m
        t_m = bin(t_v).count("1")
    d_li[i] = ans

#print(d_li)
#exit()

for i in range(n):
    val += int(x[n-1-i])*rui
    rui *= 2
    if int(x[n-1-i]) == 1:
        mod += 1

rui = 1
ans_li = []
    
for i in range(n):
    t_v = val
    t_m = mod
    if int(x[n-1-i]) == 1:
        t_v -= rui
        t_m -= 1
    else:
        t_v += rui
        t_m += 1
    rui *= 2
    ans = 0
    #while t_v != 0:
    if t_v != 0:
        t_v %= t_m
        ans += 1
    
    ans += d_li[t_v]
    #t_m = bin(t_v).count("1")
    ans_li.append(ans)
    #print(ans_li)

#print(ans_li)
for i in range(n):
    print(ans_li[n-1-i])

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import defaultdict

sys.setrecursionlimit(300000)

memp = {}
def popcount(n):
    if n == 0:
        return 0

    global memp
    if n in memp:
        return memp[n]
    
    memp[n] = (n & 1) + popcount(n >> 1)
    return memp[n]

memf = {}
def f(x):
    global memf

    if x in memf:
        return memf[x]

    _x = x
    a = 0
    while x != 0:
        x = x % popcount(x)
        a += 1
        if x in memf:
            memf[_x] = memf[x] + a
            return memf[_x]

    memf[_x] = a
    return a

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

ans = []
for j in range(n):
    i = n - 1 - j
    a = str(1 - int(x[i]))
    b = x[:i] + a + x[i+1:]
    ans.append(f(int(b, 2)))
for j in range(n):
    i = n - 1 - j
    print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
# D Anything Goes to Zero

import copy

def main():
  n = int(input())
  x = input()
  for i in range(n):
    xi = copy.copy(x)
    if xi[i] == "1":
      xi = xi[:i] + "0" + xi[i+1:]
    else:
      xi = xi[:i] + "1" + xi[i+1:]
    xi = int(xi, 2)

    ans = 0
    while xi != 0:
      xi = xi % popcount(xi)
      ans += 1
    print(ans)

        
def popcount(x):
  n = bin(x)[2:]
  cnt = 0
  for i in n:
    if i == "1":
      cnt += 1
  return cnt


if __name__ == "__main__":
  main()

Submission status: Time Limit Exceeded

Solution code:
def popcount(n):
    return str(bin(n)).count('1')
def func(n):
    count = 0
    while n!=0:
        n=n%popcount(n)
        count+=1
    return count

N = int(input())
st = input()
for i in range(N):
    if st[i]=='0':
        tmp = st[:i] + '1' + st[i+1:]
    else:
        tmp = st[:i] + '0' + st[i+1:]
    print(func(int(tmp, 2)))

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
"""
@author: H_Hoshigi
"""

def f(x, dp_dict):
    try:
        dp_dict[x]
    except KeyError:
        popcount_x = bin(x).count("1")
        next_x = x%popcount_x
        f_x, dp_dict = f(next_x, dp_dict)
        f_x += 1
        dp_dict[x] = f_x
    else:
        f_x = dp_dict[x]
    return f_x, dp_dict

def main():
    N = int(input())
    bin_X = input()
    X = int(bin_X, 2)

    dp_dict = dict()
    dp_dict[0] = 0

    for i in range(N):
        this_X = X
        if bin_X[i] == "0":
            this_X += pow(2, N-1-i)
        else:
            this_X -= pow(2, N-1-i)
        f_i, dp_dict = f(this_X, dp_dict)
        print(f_i)
    return

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import copy
n=int(input())
x=list(input())
b=[]
for i in range(2**19):
  b.append(format(i,'0'+str(19)+'b'))
ct=[0]*(n+1)
for i in range(1,n):
  ct1=0
  for j in range(len(b[i])):
    if b[i][j]=='1':
      ct1+=1
  ct[i]=i%ct1

for i in range(n):
  y=copy.copy(x)
  y[i]=str(1-int(y[i]))
  ct1=0
  for j in range(n):
    if y[j]=='1':
      ct1+=1
  
      
  if ct1==0:
    print(0)
  else:
    z=0
    y.reverse()
    for j in range(n):
      if y[j]=='1':
        z+=pow(2,j,ct1)
        z%=ct1
    ans=1
    while z!=0:
      z=ct[z]
      ans+=1
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
x = int(input(), 2)
def popcount(x):
    return len([i for i in  "{:b}".format(x) if i == '1'])
def f(n):
    cnt = 0
    while n > 0:
        n %= popcount(n)
        cnt += 1

    return cnt

for i in range(n-1, -1, -1):
    t = x ^ (1 << i)
    print(f(t))

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
#import numpy as np
import re
import math
from collections import defaultdict,deque,Counter
from fractions import Fraction
import bisect
import itertools
from itertools import accumulate
from copy import deepcopy
import heapq
import random
import time
import os
import sys
from functools import lru_cache,reduce
readline=sys.stdin.readline
sys.setrecursionlimit(100000)
alp="abcdefghijklmnopqrstuvwxyz"
numbers="0123456789"
mod=int(10**9+7)
inf=int(10**19)
class Set():
    def __init__(self,A=[]):
        self.heap=[]
        self.dic=defaultdict(bool)
        self.size=0
        for a in A:self.add(a)
    
    def __str__(self):
        return str(self.heap)
    
    def add(self,x):
        if not self.find(x):
            heapq.heappush(self.heap,x)
            self.dic[x]=True
            self.size+=1

    def remove(self,x):
        if self.find(x):
            self.dic[x]=False
            self.size-=1

    def find(self,x):
        return self.dic[x]
    
    def top(self):
        while self.heap and self.dic[self.heap[0]]==False:
            heapq.heappop(self.heap)
        if self.heap:return self.heap[0]
        else:return None

    def pop(self):
        ret=None
        if self.heap:
            ret=self.top()
            self.remove(ret)
        return ret
class multiset():
    def __init__(self,A=[]):
        self.heap=[]
        self.dic=defaultdict(int)
        self.size=0
        for a in A:self.add(a)
    
    def __str__(self):
        return str(self.heap)
    
    def add(self,x):
        heapq.heappush(self.heap,x)
        self.dic[x]+=1
        self.size+=1

    def remove(self,x):
        if self.dic[x]>0:
            self.dic[x]-=1
            self.size-=1
    
    def count(self,x):
        return self.dic[x]

    def find(self,x):
        return self.dic[x]>0
    
    def top(self):
        while self.heap and self.dic[self.heap[0]]==0:
            heapq.heappop(self.heap)
        if self.heap:return self.heap[0]
        else:return None

    def pop(self):
        ret=None
        if self.heap:
            ret=self.top()
            self.remove(ret)
        return ret
class Edge():
    def __init__(self,x,y,val=1):
        self.x=x
        self.y=y
        self.val=val
class unionfind():
    def __init__(self,n):
        self.n=n
        self.P=[a for a in range(n)]
        self.rank=[0]*n
 
    def find(self,x):
        if(x!=self.P[x]):
            self.P[x]=self.find(self.P[x])
        return self.P[x]
 
    def same(self,x,y):
        return self.find(x)==self.find(y)
 
    def link(self,x,y):
        if self.rank[x]<self.rank[y]:
            self.P[x]=y
        elif self.rank[y]<self.rank[x]:
            self.P[y]=x
        else:
            self.P[x]=y
            self.rank[y]+=1
 
    def unite(self,x,y):
        self.link(self.find(x),self.find(y))
 
    def size(self):
        S=set()
        for a in range(self.n):
            S.add(self.find(a))
        return len(S)
def yn(b):print("yes" if b else "no")
def Yn(b):print("Yes" if b else "No")
def YN(b):print("YES" if b else "NO")
def ispow(a,b):
    now=b
    while now<a:
        now*=b
    return now==a
def getbin(num,size):
    A=[0]*size
    for a in range(size):
        if (num>>(size-a-1))&1==1:
            A[a]=1
        else:
            A[a]=0
    return A
def getfacs(n,mod_=0):
    A=[1]*(n+1)
    for a in range(2,len(A)):
        A[a]=A[a-1]*a
        if(mod_>0):A[a]%=mod_
    return A
def comb(n,r,mod,fac):
    if(n-r<0):return 0
    return (fac[n]*pow(fac[n-r],mod-2,mod)*pow(fac[r],mod-2,mod))%mod
def nextcomb(num,size):
    x=num&(-num)
    y=num+x
    z=num&(~y)
    z//=x
    z=z>>1
    num=(y|z)
    if(num>=(1<<size)):return False
    else:return num
def getprimes(n):
    if n==0:return []
    A=[True]*(n+1)
    A[0]=False
    A[1]=False
    for a in range(2,n+1):
        if A[a]:
            for b in range(a*2,n+1,a):
                A[b]=False
    ret=[]
    for a in range(n+1):
        if(A[a]):ret.append(a)
    return ret
def isprime(num):
    if(num<=1):return False
    i=2
    while i*i<=num:
       if(num%i==0):return False
       i+=1
    return True
def ifelse(b,t,f):return t if b else f
def factorize(n):
    b = 2
    ret=defaultdict(int)
    while b * b <= n:
        while n % b == 0:
            n //= b
            ret[b]+=1
        b+=1
    if n > 1:ret[n]+=1
    return ret
def inputintlist(row=1): 
    if row==1:
        ret=list(map(int,input().split()))
    else:
        ret=[None]*row
        for a in range(row):
            ret[a]=int(input())
    return ret
def inputfloatlist(row=1): 
    if row==1:
        ret=list(map(float,input().split()))
    else:
        ret=[None]*row
        for a in range(row):
            ret[a]=float(input())
    return ret
def istanchouzouka(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>=a:
            f=False
        prev=a
    return f
def istanchouhigensyou(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>a:
            f=False
        prev=a
    return f
def getallsum(A):
    s=sum(A)
    dp=defaultdict(int)
    dp[0]=1
    for a in range(0,len(A)):
        for b in range(s,-1,-1):
            if b-A[a]>=0:
                dp[b]+=dp[b-A[a]]
    return dp
def yuukoutomukou(edges):
    ret=deepcopy(edges)
    for edge in edges:
        if not edge.x==edge.y:
            ret.append(Edge(edge.y,edge.x,edge.val))
    return ret
def dijkstra(edges,V,start):
    mincost=[inf]*V
    G=[[] for a in range(V)]
    for edge in edges:
        G[edge.x].append([edge.val,edge.y])
    Q=PriorityQueue()
    Q.put([0,start])#[cost,x]
    while not Q.empty():
        nowcost,nowx=Q.get()
        if mincost[nowx]==inf:
            mincost[nowx]=nowcost
            for cost,y in G[nowx]:
                newcost=nowcost+cost
                Q.put([newcost,y])
    return mincost
def warshallfloyd(edges,V):
    mincost=[[inf for b in range(V)] for a in range(V)]
    for a in range(V):mincost[a][a]=0
    for edge in edges:
        mincost[edge.x][edge.y]=min(mincost[edge.x][edge.y],edge.val)#x→yが複数ある場合のためにmin()する
    for k in range(V):
        for s in range(V):
            for t in range(V):
                if mincost[s][k]==inf or mincost[k][t]==inf:continue
                mincost[s][t]=min(mincost[s][t],mincost[s][k]+mincost[k][t])
    return mincost
def bellemanford(edges,V,start):
    mincost=[inf]*V
    mincost[start]=0
    for _ in range(V):
        for edge in edges:
            if mincost[edge.x]==inf:continue
            mincost[edge.y]=min(mincost[edge.y],mincost[edge.x]+edge.val)
    return mincost
def getmd(x1,y1,x2,y2):return abs(x1-x2)+abs(y1-y2)
def geted(x1,y1,x2,y2):return math.sqrt((x1-x2)**2+(y1-y2)**2)
class fordfulkerson():
    def __init__(self,edges,V,s,t):
        self.V=V
        self.used=[False]*V
        self.G=[[] for a in range(V)]
        self.s=s
        self.t=t
        for edge in edges:
            self.G[edge.x].append({"x":edge.x,"y":edge.y,"cap":edge.val,"rev":len(self.G[edge.y])})
            self.G[edge.y].append({"x":edge.y,"y":edge.x,"cap":0,"rev":len(self.G[edge.x])-1})
    def dfs(self,v,t,f=inf):
        if v==t:return f
        self.used[v]=True
        for a in range(len(self.G[v])):
            x=self.G[v][a]["x"]
            y=self.G[v][a]["y"]
            cap=self.G[v][a]["cap"]
            rev=self.G[y][self.G[x][a]["rev"]]
            if self.used[y] or cap==0:continue
            f2=self.dfs(y,t,min(f,cap))
            if f2>0:
                self.G[v][a]["cap"]-=f2
                rev["cap"]+=f2
                return f2
        return 0
    def maxflow(self):
        flow=0
        while True:
            self.used=[False]*V
            zouka=self.dfs(self.s,self.t)
            if zouka==0:break
            flow+=zouka
        return flow
def zipsort(*args):
    ziplist=sorted(zip(*args))
    for a in range(len(args)):
        for b in range(len(ziplist)):
            args[a][b]=ziplist[b][a]
def zipreverse(*args):
    ziplist=list(zip(*args))
    rev=[]
    for a in range(len(ziplist)-1,-1,-1):
        rev.append(ziplist[a])
    for a in range(len(args)):
        for b in range(len(rev)):
            args[a][b]=rev[b][a]

def to10(A):
    ret=0
    for a in range(len(A)-1,-1,-1):
        ret+=X[a]*2**(N-1-a)
    return ret
######################################################################################################



N=int(input())
X=list(map(int,list(input())))
xnt1=X.count(1)
x10=to10(X)

F=[0]*(N+1)
for a in range(1,len(F)):
    F[a]=F[a%getbin(a,N).count(1)]+1


for i in range(N):
    d=2**(N-1-i)
    num=x10
    if X[i]==0:num+=d
    else:num-=d
    if num<=N:
        print(F[num])
    else:
        print(F[num%getbin(num,N).count(1)]+1)

Submission status: Time Limit Exceeded

Solution code:
def bitcount(N):  # 立ってるbitの数
    bitcnt = [0]
    for _ in range(N):
        bitcnt += [i + 1 for i in bitcnt]
    return bitcnt

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

num = 0
for i, bit in enumerate(x[::-1]):
    num += int(bit) * 2 ** i

lbit = bitcount(18)
cnt = x.count('1')
for i in range(n):
    ans = 0
    tmp = num ^ (2 ** (n - (i + 1)))
    ctmp = cnt - 2 * int(x[i]) + 1
    while tmp > 0:
        ans += 1
        tmp %= ctmp
        ctmp = lbit[tmp]
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
from functools import lru_cache
@lru_cache(maxsize=1000)
def popcount(n, bit, cnt):
    if n == 0:return cnt
    new = bin(n%bit).count("1")
    return popcount(n%bit, new, cnt + 1)
    
n = int(input())
x = input()
cnt = x.count('1')
num = 0
for i in range(n):
    num += int(x[-(i + 1)]) * pow(2, i)

   
for i in range(n):
    res = 0
    if x[i] == "1":
        temp = num - pow(2, n - i - 1)
        print(popcount(temp, cnt - 1, 0))
    else:
        temp = num + pow(2, n - i - 1)
        print(popcount(temp, cnt + 1, 0))

Submission status: Time Limit Exceeded

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

for i in range(N):
    S = list(X)
    if S[i] == '0':
        S[i] = '1'
    else:
        S[i] = '0'
    S = "".join(S)

    A = int(S, 2)

    c=0
    while A>0:
        A = A % S.count('1')
        S = format(A, 'b')
        c+=1

    print(c)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
x = list(input())

B = 2**20 - 1

memo = [None for _ in range(2*n)]


def popcount(p):
    return bin(p).count("1")


def calc(p, offset):
    if p == 0:
        return 0

    tmp = p % popcount(p)
    if memo[tmp] is not None:
        return memo[tmp] + offset + 1

    a = calc(tmp, 0) + offset + 1

    if p < len(memo):
        memo[p] = a
    return a


for i in range(n):
    tmp = x[:]
    tmp[i] = '1' if tmp[i] == '0' else '0'
    tmp = int(''.join(tmp), 2)
    print(calc(tmp, 0))

Submission status: Time Limit Exceeded

Solution code:
#d
n=int(input())
x=list(input())
n=len(x)
def popcount(m):
    return bin(m).count("1")

popcount0 = popcount(int( "0b"+"".join(x) ,0 ))
intx = int( "0b"+"".join(x) ,0 )

jisho = ["yet"]*n
for i in range(n):
    xx = x[:]
    if xx[i]=="0":
        xx[i] = "1"
        pop = popcount0+1
        intxi = intx+pow(2,n-i-1)
    else:
        xx[i] = "0"
        pop = popcount0-1
        intxi = intx-pow(2,n-i-1)

        
    if intxi==0:
        print(0)
        continue
    else:
        c=0
        while intxi!=0:
            if c==0:
                intxi=intxi%pop
            else:
                if jisho[intxi]=="yet":
                    togo = intxi%popcount(intxi)
                    jisho[intxi]= togo
                    intxi = togo
                else:
                    intxi =jisho[intxi]
                
            #print(intxi)
            c+=1
        print(c)
        #print()
#        print("f(n)=",c)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
x = input()

def popcount(n):
    n_b = str(bin(n))
    return n_b.count("1")

x_i = int(x, 2)
solve = 0
for i in range(n):
    if x[i] == "0":
        solve = x_i+2**(n-i-1)
    else:
        solve = x_i-2**(n-i-1)
    count = 0
    while solve > 0:
        solve = solve % popcount(solve)
        count+=1
    print(count)

Submission status: Time Limit Exceeded

Solution code:



def popcnt(n):
    return bin(n).count("1")

def waru(n):
    count=0
    
    while(n!=0):
        n=n%popcnt(n)
        count+=1
    return count


N=int(input())
X="0b"+input()

a=bin(1<<N-1)
b=int(a,2) 
x=int(X,2)
li=[]

for i in range(N):
    li.append(int(bin((b>>i)^x) ,2))

for i in li:
    print(waru(i))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
X = str(input())
x = list(X)
def popcount(x):
    return sum(int(i) for i in list(x))

for n in range(N):
  xn = x.copy()
  xn[n] = str(1 - int(xn[n]))
  xn = ''.join(map(str, xn))
  count = 0
  while int(xn) != 0:
    xn = str(bin(int(xn, 2)%popcount(xn)))[2:]
    count += 1
  print(count)

Submission status: Time Limit Exceeded

Solution code:
n,x=int(input()),input()

g=int(x,2)
c=pow(2,n-1)
memo={}
for b in x:
    if b=="1":
        p=g-c
    else:
        p=g+c
    ret=0
    while p:
        q=bin(p).count("1")
        if p in memo:print(ret+memo[p]);break 
        p%=q
        ret+=1
    c//=2
    memo[p]=ret
    print(ret)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
x = input()

x_1 = x.count('1')
flag = 0
if(x_1 == 0):
    flag = 1
if(x_1 == 1):
    flag = 2

data = [0 for i in range(n+1)]
data[0] = 0
for i in range(1,n+1):
    i_str = format(i,'b')
    ne = i % (i_str.count('1'))
    data[i] = data[ne] + 1

up = [0 for i in range(n)]
do = [0 for i in range(n)]

d = 1
for i in range(n):
    up[i] = d
    d *= 2
    d %= (x_1 + 1)
d = 1
if(flag == 0):
    for i in range(n):
        do[i] = d
        d *= 2
        d % (x_1 - 1)

upp = 0
dow = 0

for i in range(n):
    if(x[n-i-1] == '1'):
        upp += up[i]
        upp %= (x_1+1)
        if(flag == 0):
            dow += do[i]
            dow %= (x_1-1)


for i in range(n):
    if(x[i] == '0'):
        sam = upp + up[n-i-1]
        sam %= (x_1+1)
        print(data[sam]+1)
    elif(flag == 0):
        sam = dow - do[n-i-1]
        sam %= (x_1-1)
        print(data[sam]+1)
    elif(flag == 2):
        print('0')

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
x = input()
num = 0
count = 0
for i in range(n):
    if x[-(i+1)] == "1":
        num += 2**i
        count += 1

mod = [[0, 0] for _ in range(n)]
for i in range(n):
    mod[i][0] = 2**i%(count-1) if count!=1 else 0
    mod[i][1] = 2**i%(count+1)
mod1 = num%(count-1) if count!=1 else 0
mod2 = num%(count+1)

ans = [0]*n
for i in range(n):
    if x[-(i+1)] == "1":
        _num = num-2**i
        if _num == 0:
            continue
        _num = (mod1-mod[i][0])%(count-1)
    else:
        _num = num+2**i
        _num = (mod2+mod[i][1])%(count+1)
    ans[i] += 1
    _count = 0
    for c in bin(_num):
        if c == "1":
            _count += 1
    while True:
        if _num == 0:
            break
        _num %= _count
        _count = 0
        for c in bin(_num):
            if c == "1":
                _count += 1
        ans[i] += 1
for i in range(n):
    print(ans[-(i+1)])

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
from collections import deque
input = stdin.readline

N = int(input())
X = list(input().rstrip())

q = deque([])
b = X.count("1")

for i in range(N):
    if X[i] == "0":
        X[i] = "1"
        q.append(["".join(X), b + 1])
        X[i] = "0"
    else:
        X[i] = "0"
        q.append(["".join(X), b - 1])
        X[i] = "1"

while q:
    n, b = q.popleft()
    n = int(n, 2)
    cnt = 0

    while n > 0:
        n = n % b
        b = bin(n).count("1")
        cnt += 1

    print(cnt)

Submission status: Time Limit Exceeded

Solution code:


def main():
    n_ansl = [0]*(2*(10**5))
    for i in range(1,2*(10**5)):
    # for i in range(1,20):
        cnt = 0
        one_cnt = bin(i).count("1")
        rem = i
        while rem != 0:
            one_cnt = bin(rem).count("1")
            rem = rem%one_cnt   
            cnt += 1
        n_ansl[i] = cnt

    n = int(input())
    x = input()
    one_cnt = x.count('1')

    if one_cnt == 0:
        for _ in range(n):
            print(1)
        exit()
    
    curr_2b = 1
    curr_2b_p = 1
    curr_2b_m = 1
    curr_sum = 0
    curr_sum_p1 = 0
    curr_sum_m1 = 0
    for i in range(n-1, -1, -1):
        if x[i] == '1':
            curr_sum += curr_2b
            curr_sum_p1 += curr_2b_p
            curr_sum_m1 += curr_2b_m
            curr_sum%=one_cnt
            curr_sum_p1%=(one_cnt+1)
            if one_cnt > 1:
                curr_sum_m1%=(one_cnt-1)
        curr_2b*=2
        curr_2b_p*=2
        curr_2b_m*=2
        curr_2b%=one_cnt
        curr_2b_p%=(one_cnt+1)
        if one_cnt > 1:
            curr_2b_m%=(one_cnt-1)

        

    curr_2b = 1
    curr_2b_p = 1
    curr_2b_m = 1
    ansl = [0]*(n)
    for i in range(n-1, -1, -1):
        if x[i] == '1':
            diff = (-1)*curr_2b_m
            if one_cnt > 1:
                ans = (curr_sum_m1 + diff)%(one_cnt-1)
                ansl[i] = n_ansl[ans]+1
            else:
                ansl[i] = 0
        else:
            diff = curr_2b_p
            ans = (curr_sum_p1 + diff)%(one_cnt+1)
            ansl[i] = (n_ansl[ans]+1)
        # curr_2b *= 2
        curr_2b*=2
        curr_2b_p*=2
        curr_2b_m*=2
        curr_2b%=one_cnt
        curr_2b_p%=(one_cnt+1)
        if one_cnt > 1:
            curr_2b_m%=(one_cnt-1)


    # print(ansl)
    for a in ansl:
        print(a)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
x = list(input())

bitNum = 0
for bit in x:
    if bit == "1":
        bitNum+=1
valSum = 0
for i in range(len(x)):
    if x[i] == "1":
        valSum += 2**(len(x)-1-i)


mapP = {}
for i in range(len(x)):
    count = 0
    if x[i] == "1":
        val = valSum-(2**(len(x)-1-i))
        popC = bitNum-1
    else:
        val = valSum+(2**(len(x)-1-i))
        popC = bitNum+1
    while True:
        if val == 0:
            break
        newVal = val % popC
        newbitL = list(format(newVal, 'b'))
        newPopC = 0
        for b in newbitL:
            if b == "1":
                newPopC += 1
        count += 1
        if newVal == 0:
            break
        val = newVal
        popC = newPopC
    print(count)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
x = input()


def popcount(n):
    s = str(format(n, "b"))
    return s.count("1")


def f(n):
    cnt = 0
    while n > 0:
        n = n % popcount(n)
        cnt += 1
    return cnt


def getX(m, i):
    s = (ord(x[i]) % 2 + 1) % 2
    s = x[:i] + str(s) + x[i + 1:]
    return int(s, 2)


for i in range(n):
    rx = getX(x, i)
    print(f(rx))

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    sys.setrecursionlimit(200000)
    N = int(input())
    Y = input()
    X = int(Y,2)
    memo = {}
    Ycnt = Y.count("1")

    def f(n,cnt):
        if n == 0:
            return 0
        if n not in memo:
            d = cnt
            nx = n%d
            nxCnt = bin(nx).count("1")
            memo[n] = f(nx,nxCnt)+1
        return memo[n]

    for i in range(N):
        if Y[i] == "1":
            cnt = Ycnt - 1
        else:
            cnt = Ycnt + 1
        a = N-i
        tmp = 2**(a-1)
        n = X^tmp
        print(f(n,cnt))
main()

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
x = list(input())

dp=[-1]*(n+1)

dp[0]=0
dp[1]=1

def cou(num):
    ans = 0
    while num>0:
        ans+=num%2
        num//=2
    return ans

def fun(num,step):
    num2=num%cou(num)
    if dp[num2]!=-1:
        dp[num]=dp[num2]+step
    else:
        fun(num2,step+1)

for i in range(2,n+1):
    fun(i,1)

for i in range(n):
    x2=x.copy()
    if x[i]=='1':
        x2[i]='0'
    else:
        x2[i]='1'
    num1=''.join(x2)
    num2=int(num1,2)
    su = sum(list(map(int,x2)))
    if su == 0:
        print('0')
        continue
    else:
        num3=num2%su
    print(dp[num3]+1)

Submission status: Time Limit Exceeded

Solution code:
def popcount(n):
    bin_n = format(n, "b")
    ans = 0
    for e in bin_n:
        if e=="1":
            ans += 1
    return ans

N = int(input())
bin_X = input()

max_pop = 200000
pop_list = [0] * (max_pop+1)
for i in range(1, max_pop+1):
    pop_list[i] = popcount(i)

ans_list = [0] * (max_pop+1)
for i in range(1, max_pop+1):
    new = i
    ans = 0
    while True:
        if new == 0:
            break
        ans += 1
        new = new % pop_list[new]
    ans_list[i] = ans

pop = 0
for e in bin_X:
    if e=="1":
        pop += 1


for i in range(N):
    if bin_X[i] == "0":
        bin_new = bin_X[:i] + "1" + bin_X[i+1:]
        pop_new = pop + 1
    else:
        bin_new = bin_X[:i] + "0" + bin_X[i+1:]
        pop_new = pop - 1
    #print(bin_new)
    new = int(bin_new, 2)
    #print(new)
    if new == 0:
        ans = 0
    else:
        new = new % pop_new
        ans = ans_list[new] + 1
        
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import math
import collections
import bisect
from collections import deque
from copy import copy, deepcopy


def popcount(n):
    return bin(n).count("1")


def main():
    N = int(input())
    X = input()
    decX = int(X, 2)

    ans = 0
    flip = 2 ** N
    memo_dict = {}
    for i in range(0, N):
        flip = flip >> 1
        tmp = flip ^ decX
        ans = 0
        tmp_list = []
        while(1):
            tmp_list.append(tmp)
            if tmp in memo_dict:
                ans += memo_dict[tmp]
                break
            if tmp == 0:
                break
            tmp %= popcount(tmp)
            ans += 1

        #print(tmp_list, ans)
        for i, t in enumerate(tmp_list):
            memo_dict[t] = ans - i
        print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
x=input()
xx=x.count('1')
xx2=int(x,2)
for i in range(n):
    if x[i]=='0':
        xxx=xx+1
        xxx2=xx2+2**(n-1-i)
    else:
        xxx=xx-1
        xxx2=xx2-2**(n-1-i)
    count=0

    while xxx2!=0:
        xxx2%=xxx
        xxx=str(bin(xxx2)).count('1')
        count+=1
    print(count)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# Your code here!

n = int(input())

x = input()

c = x.count('1')

L = {}


for i in range(n):
    #print(int(str(x[:i]+str((int(x[i])+1)%2)+x[i+1:]),2))
    a = int(str(x[:i]+str((int(x[i])+1)%2)+x[i+1:]),2)
    b = 0
    if x[i] == '1':
        b = c-1
    else:
        b = c+1
    cnt = 0
    h = a
    while True:
        #print(a,h,b)
        if h==0:
            
            print(cnt)
            L[a] = cnt
            break
        h = h%b
        b = bin(h).count('1')
        cnt += 1
        if h in L:
            cnt += L[h]
            print(cnt)
            L[a] = cnt
            break

Submission status: Time Limit Exceeded

Solution code:
def popcount(n):
    return bin(n).count('1')

N = int(input())
X = input()

for i in range(1,N+1):
    XX = []
    for j in X:
        XX.append(j)
    
    count = 0
    
    if XX[i-1] == '0':
        XX[i-1] = '1' 
        XX = ''.join(XX)
        x = int(XX, 2)
        while x > 0:
            x = x % popcount(x)
            count += 1
        print(count)
    
    
    
    
    
    else:
        XX[i-1] = '0'
        XX = ''.join(XX)
        x = int(XX, 2)
        while x > 0:
            x = x % popcount(x)
            count += 1
        print(count)