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:
did = {}

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

def function(n):
  ret = 0
  i = n
  while i > 0:
    if i in did:
      ret += did[i]
      break
    ret += 1
    i %= popcount(i)
  
  did[n] = ret
  return ret

N = int(input())
X = int(input(), 2)

for i in range(N-1, -1, -1):
  print(function(X ^ (2 ** i)))

Submission status: Time Limit Exceeded

Solution code:
import sys
import time
import math
def inpl():
    return list(map(int, input().split()))
st = time.perf_counter()
# ------------------------------

def pc(n):
	p = '{:b}'.format(n)
	ret = 0
	for i in range(len(p)):
		if p[i]=='1':
			ret += 1 
	return ret

N = int(input())
X = int(input(), 2)
for i in range(N):
	x = X ^ 1<<(N-i-1)
	cnt = 0
	while x!=0:
		cnt+=1
		x = x%pc(x)
	print(cnt)
	
# ------------------------------
ed = time.perf_counter()
print('time:', ed-st, file=sys.stderr)

Submission status: Time Limit Exceeded

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

def popcount(n):
    count = 0
    while n:
        count += n % 2
        n //= 2
    return count

on = popcount(X)
for i in range(1, N+1):
    o = on
    if X & (1 << (N-i)):
        o -= 1
    else:
        o += 1
    
    x = X ^ (1 << (N - i))
    count = 0
    while x:
        x %= o
        count += 1
        o = popcount(x)
    print(count)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
x=input()
t=int(x,2)
from functools import *
@lru_cache(None)
def popcount(x):
  if x==0: return 0
  return popcount(x%bin(x).count('1'))+1
for i in range(n):
  s=t+2**(n-i-1)*(1-int(x[i])*2)
  print(popcount(s))

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
s=input()
num=int(s,2)
s=list(s)
bits=int(0)
for i in range(n):
    if(s[i]=='1'):
        bits+=1
for i in range(n):
    ns=s
    nnum=int(num)
    nbits=int(bits)
    if(ns[i]=='1'):
        ns[i]='0'
        nnum-=(2**(n-i-1))
        nbits-=1
    else:
      	ns[i]='1'
      	nnum+=(2**(n-i-1))
      	nbits+=1
    ans=int(0)
    while(nnum!=0):
        nnum%=nbits
        ans+=1
        nbits=bin(nnum).count('1')
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
X = input()
X2 = [int(i) for i in X]
S = int(X, 2)

def f(n):
    r = 0
    while n:
        n = n % bin(n).count("1")
        r += 1
    return r

for i in range(1, N+1):
    if not X2[i-1]:
        s = S + 2 ** (N - i)
    else:
        s = S - 2 ** (N - i)
    print(f(s))

Submission status: Time Limit Exceeded

Solution code:
import sys

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

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_s = lambda: readline().rstrip().decode('utf-8')
in_nl = lambda: list(map(int, readline().split()))
in_nl2 = lambda H: [in_nl() for _ in range(H)]
in_map = lambda: [s == ord('.') for s in readline() if s != ord('\n')]
in_map2 = lambda H: [in_map() for _ in range(H)]
in_all = lambda: map(int, read().split())


def main():
    N = in_n()
    X = int(in_s(), 2)

    #t = '1101101010' * 10**3
    #X = int(t, 2)
    #N = 10**4

    ans = [0] * N
    for i in range(N):
        a = X ^ (1 << N - i - 1)
        a = bin(a)[2:]
        count = 0
        while int(a, 2):
            a = bin(int(a, 2) % a.count('1'))[2:]
            count += 1
        ans[i] = count

    print('\n'.join(map(str, ans)))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

def calc(x):
    ans=0
    while x !=0:
        n=popcount(x)
        ans+=1
        x=x%n

    return ans


N=int(input())
X=int(input(),2)

ans=[]
for i in range(N-1,-1,-1):
    ans.append(calc(X ^ 1<<i))

for i in ans:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
X = int(input(),2)
from collections import Counter


def pop_count(n):
    return n%Counter(bin(n))['1']
n = 7
ans = 0
for i in range(N-1,-1,-1):
    n = X^pow(2,i)
    while n != 0:
        n = pop_count(n)
        ans += 1
    print(ans)
    ans = 0

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
n = int(input())
x = input()
o = int(x, 2)
for i in reversed(range(n)):
    if o >> i & 1:
        t = o - 2**i
    else:
        t = o + 2**i
    count = 0
    while t > 0:
        t %= bin(t).count("1")
        count += 1
    print(count)

Submission status: Time Limit Exceeded

Solution code:
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)]


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]
    
N = rri()
num = int('0b'+rr(),2)
for i in range(N):
    cur_num = num ^ (1<<(N-i-1))
    print(f(cur_num))

Submission status: Time Limit Exceeded

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

for i in range(0, n):
  now = x ^ (1<<(n-1-i))
  #print(now)
  cnt = 0
  while now != 0:
    cnt += 1
    now = now % (bin(now).count("1"))
  print(cnt)

Submission status: Time Limit Exceeded

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

for i in range(N):
    if C[i] == "1":
        X = C[:i] + "0" + C[i+1:]
    else:
        X = C[:i] + "1" + C[i+1:]

    N = int(X,2)
    ans = 0
    while N > 0:
        cnt = 0
        for c in format(N,"b"):
            if c == "1":
                cnt += 1
        N %= cnt
        ans += 1
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys

sys.setrecursionlimit(10**7)
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  #空白あり
def LI2(): return list(map(int,sys.stdin.readline().rstrip()))  #空白なし
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())  #空白あり
def LS2(): return list(sys.stdin.readline().rstrip())  #空白なし

N = I()

A = [0]
for i in range(1,2*10**5):
    a = 0
    r = i
    for j in range(18):
        a += (i>>j)&1
    r %= a
    if r == 0:
        A.append(1)
    else:
        A.append(1+A[r])

X = LS2()

b = 0
for i in range(N):
    if X[i] == '1':
        b += 1
if b >= 2:
    c = b-1
    d = b+1

    r1 = 0
    r2 = 0

    for i in range(N):
        if X[i] == '1':
            r1 += pow(2,N-i-1)
            r1 %= c
            r2 += pow(2,N-i-1)
            r2 %= d
    ANS = []
    for i in range(N):
        if X[i] == '1':
            e = r1
            e -= pow(2,N-i-1)
            e %= c
            ANS.append(A[e]+1)
        else:
            f = r2
            f += pow(2,N-i-1)
            f %= d
            ANS.append(A[f]+1)
else:
    d = b + 1
    r2 = 0

    for i in range(N):
        if X[i] == '1':

            r2 += pow(2, N - i - 1)
            r2 %= d
    ANS = []
    for i in range(N):
        if X[i] == '1':

            ANS.append(0)
        else:
            f = r2
            f += pow(2, N - i - 1)
            f %= d
            ANS.append(A[f] + 1)


print(*ANS,sep='\n')

Submission status: Time Limit Exceeded

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

def f(n):
    ans=0
    while n!=0:
        n%=str(bin(n)).count("1")
        ans+=1
    return ans

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

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
s=input()
for i in range(n):
  if s[i]=='0':
    s1=int(s[:i]+'1'+s[i+1:],2)
  else:
    s1=int(s[:i]+'0'+s[i+1:],2)
  tmp=0
  while s1!=0:
    s1%=bin(s1).count('1')
    tmp+=1
  print(tmp)

Submission status: Time Limit Exceeded

Solution code:
def base10toN(num, base):
    converted_string, modstring = "", ""
    currentnum = num
    if not num:
        return '0'
    while currentnum:
        mod = currentnum % base
        currentnum = currentnum // base
        converted_string = chr(48 + mod + 7*(mod > 10)) + converted_string
    return converted_string
n=int(input())
popcount=[]
for i in range(1,2*10**5+1):
  temp=base10toN(i,2)
  ans=0
  for j in range(len(temp)):
    if temp[j]=='1':
      ans+=1
  popcount.append(ans)
x=input()
xint=int(x, 2)
ones=0
ans1=[]
for i in range(n):
  if x[i]=='1':
    ones+=1
for i in range(n):
  counter=0
  if x[i]=='0':
    temp=xint+pow(2,n-1-i)
    temp1=ones+1
  else:
    temp=xint-pow(2,n-1-i)
    temp1=ones-1
  ans=0
  while temp!=0:
    temp=temp%temp1
    temp1=popcount[temp-1]
    ans+=1
  ans1.append(str(ans))
print(' '.join(ans1))

Submission status: Time Limit Exceeded

Solution code:
def popcount(n):
    result = 0
    while n > 0:
        result += n % 2
        n = n // 2
    return result

def popfunc(n):
    result = 0
    while n > 0:
        result += 1
        n = n % popcount(n)
    return result

N = int(input())
divider = 2**(N-1)

X = int(input(), 2)

while divider > 0:
    print(popfunc(X^divider))
    divider = divider // 2

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
X = input()
fn = {0: 0}

def culc_fn(n, fn):
    if not n in fn.keys():
        popcount = bin(n).count('1')
        tmp = n%popcount
        fn[n] = culc_fn(tmp, fn) + 1
    return fn[n]

for i in range(N):
    tmp = int(X[:i] + ('0' if X[i] == '1' else '1') + X[i+1:], 2)
    print(culc_fn(tmp, fn))

Submission status: Time Limit Exceeded

Solution code:
def main():
    n = int(input())
    x = input()
    x = '0b'+x

    x = int(x,0)

    ans = dict()

    for i in range(n-1,-1,-1):
        a = x ^ (1<<i)
        b = a
        cnt = 0
        while a != 0:
            if a in ans.keys():
                cnt += ans[a]
                break
            cnt += 1
            a = solve(a)
        ans[b] = cnt
        # z.append(cnt)
        print(cnt)
    # print(z)
        
def solve(n):
    m = bin(n).count('1')
    return n%m

main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**8)
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return [LIST() for _ in range(n)]
def NSTR(n): return [input() for _ in range(n)]


INF = float("inf")
MOD = 10**9 + 7


def bit_sum(n):
    wa = 0
    while n > 0:
        wa += n & 1
        n >>= 1
    return wa

def bit(n, k):
    return (n >> k) & 1

def main():
    N = INT()
    X = input()
    origX = X
    wa = X.count("1")
    x = 0
    for c in X:
        x <<= 1
        if c == "1":
            x |= 1
    X = x
    # wa+1
    px = X % (wa+1)
    if wa != 1:
        nx = X % (wa-1)
    else:
        nx = None

    # 1 ~ Nについて答えを出しておく NlogN
    table = [None]*(N+1)
    table[0] = 0
    table[1] = 1
    for i in range(1, N+1):
        table[i] = table[i % bit_sum(i)] + 1

    for i, c in enumerate(origX):
        count = 0
        x = X ^ (1 << N-i-1)
        if c == "1":
            if x == 0:
                print(0)
                continue
            x = (nx-pow(2, N-i-1, wa-1)) % (wa-1)
            print(table[x]+1)
        else:
            if x == 0:
                print(0)
                continue
            x = (px+pow(2, N-i-1, wa+1)) % (wa+1)
            print(table[x]+1)
    return


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def  countSetBits(n): 
    count = 0
    while (n): 
        count += n & 1
        n >>= 1
    return count 

def calculate(number,count):
    if(number==0):
        print(0)
    else:
        ans=1
        number=number%count
        while(number!=0):
            val=countSetBits(number)
            ans+=1
            number%=val
        print(ans)
            

n=(int)(input())
s=input()
number,count=0,0
for i in range(n):
    if(s[i]=='1'):
        number+=2**(n-i-1)
        count+=1
        
for i in range(n):
    if(s[i]=='1'):
        number-=2**(n-i-1)
        count-=1
        calculate(number,count)
        number+=2**(n-i-1)
        count+=1
    else:
        number+=2**(n-i-1)
        count+=1
        calculate(number,count)
        number-=2**(n-i-1)
        count-=1

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(700000)

def s_in():
    return input()

def n_in():
    return int(input())

def l_in():
    return list(map(int, input().split()))

n = n_in()
x = s_in()

popcnt = sum(i == '1' for i in x)

def mod_add(a, b):
  return (a+b)%MOD

def mod_sub(a, b):
  return (a+MOD-b)%MOD

def mod_mul(a, b):
  return a*b%MOD

#互いに素なa,bについて、a*x+b*y=1の一つの解
def extgcd(a,b):
    r = (1,0,a)
    w = (0,1,b)
    while w[2]!=1:
        q = r[2]//w[2]
        r2 = w
        w2 = [r[0]-q*w[0],r[1]-q*w[1],r[2]-q*w[2]]
        r = r2
        w = w2
    return (w[0],w[1])

def mod_inv(a):
    x,_  = extgcd(a, MOD)
    return (MOD+x%MOD)%MOD

def mod_div(a, b):
    return a*mod_inv(b)%MOD

def mod_pow(a, b):
    res = 1
    while b > 0:
        if b & 1:
            res = res * a % MOD
        a = a * a % MOD
        b >>= 1
    return res

memo = {}

MOD = popcnt+1
memo[MOD] = []
for i in range(n):
    memo[MOD].append(mod_pow(2, i))
    

if popcnt-1 > 0:
    MOD = popcnt-1
    memo[MOD] = []
    for i in range(n):
        memo[MOD].append(mod_pow(2, i))

        
for i in range(n):
    cnt = 0
    current = 0
    if x[i] == '0':        
        MOD = popcnt + 1
        for j in range(n):
            if x[j] == '1' or i == j:
                current = mod_add(current, memo[MOD][n-j-1])
#                current = mod_add(current, mod_pow(2, n-j-1))
        cnt += 1
        while current > 0:
            MOD = sum(c=='1' for c in bin(current)[2:])
            current = current%MOD
            cnt += 1
    else:
        MOD = popcnt - 1
        if MOD == 0:
            print(0)
            continue
        for j in range(n):
            if x[j] == '1' and j != i:
                current = mod_add(current, memo[MOD][n-j-1])
        cnt += 1
        while current > 0:
            MOD = sum(c=='1' for c in bin(current)[2:])
            current = current%MOD
            cnt += 1

    print(cnt)

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
######################################################################################################
@lru_cache(maxsize=None)
def f(n,N):
    if n==0:return 0
    num=n%getbin(n,N).count(1)
    return 1+f(num,N)


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

for i in range(N):
    d=2**(N-1-i)
    num=x10
    if X[i]==0:num+=d
    else:num-=d
    print(f(num,N))

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(100000)

from functools import lru_cache


@lru_cache(maxsize=None)
def popcount(n):
    ans = 0
    while n > 0:
        ans += n & 1
        n //= 2
    return ans


memo = {0: 0}

@lru_cache(maxsize=None)
def rec(n):
    if n in memo:
        return memo[n]

    p = popcount(n)
    new_n = n % p
    ans = rec(new_n) + 1
    memo[n] = ans
    return memo[n]


def submit():
    n = int(input())
    x = input()
    x = int('0b' + x, 0)

    ans = []
    for i in range(1, n + 1):
        mask = 1 << (n - i)
        xi = x ^ mask
        ans.append(rec(xi))

    for a in ans:
        print(a)


if __name__ == "__main__":
    submit()

Submission status: Time Limit Exceeded

Solution code:
import sys
import bisect
import itertools
import collections
import fractions
import heapq
import math
from operator import mul
from functools import reduce
from functools import lru_cache


def solve():
    readline = sys.stdin.buffer.readline
    mod = 10 ** 9 + 7

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

    popdic = {}
    xx = int(X, 2)

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

    for i in range(1, N+1):
        x = xx
        tmp = x
        if X[i-1] == "1":
            x -= 2**(N-i)
        else:
            x += 2**(N-i)
        count = 0
        while(x!=0):
            if x not in popdic:
                count += 1
                x = popcount(x)
            else:
                count = popdic[x]
                break
        popdic[tmp] = count
        print(count)


if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

Solution code:
def f(val):
    if val == 0:
        return 0
    re = 0
    tmp = val
    popcount = 0
    while tmp > 0:
        if tmp%2 == 1:
            popcount += 1
        tmp //= 2
    return f(val%popcount) + 1

def main():
    n = int(input())
    X = [s for s in input()] + [""]
    Ans = []
    for i in range(n):
        if X[i] == "0":
            tmp = int("".join(X[:i] + ["1"] + X[i + 1:]),2)
        else:
            tmp = int("".join(X[:i] + ["0"] + X[i + 1:]),2)
        Ans.append(f(tmp))
    print(*Ans,sep="\n")


    return
if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
def func(n):
    ans = 0
    while n > 0:
        cnt = 0
        for i in range(65):
            if (n & (1<<i)) != 0:
                cnt += 1
        ans += 1
        n %= cnt
    return ans

def main():
    n = int(input())
    s = input()
    ans = [0]*n
    cnt = 0
    for c in s:
        if c == "1":
            cnt += 1
    ad = cnt + 1
    df = cnt - 1
    start_ad = 0
    start_df = 0
    for i in range(n):
        if ad > 0:
            if s[n-1-i] == "1":
                start_ad += pow(2, i, ad)
                start_ad %= ad
        if df > 0:
            if s[n-1-i] == "1":
                start_df += pow(2, i, df)
                start_df %= df
    for i in range(n):
        if s[i] == "0":
            ans[i] = 1
            tmp = (start_ad + pow(2, n-1-i, ad)) % ad
            ans[i] += func(tmp)
        else:
            if cnt == 1:
                ans[i] = 0
            else:
                ans[i] = 1
                tmp = (start_df - pow(2, n-1-i, df)) % df
                ans[i] += func(tmp)
    for v in ans:
        print(v)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

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

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

for i in range(n):
    xx = x[:]
    if xx[i]=="0":
        xx[i] = "1"
        pop = popcount0+1
    else:
        xx[i] = "0"
        pop = popcount0-1
        
    intxi = int( "0b"+"".join(xx) ,0 )
#    print(intxi,intxi%pop)
    if intxi==0:
        print(0)
        continue
    else:
        c=0
        while intxi!=0:
            c+=1
            intxi=intxi%popcount(intxi)
            #print(m)
        print(c)
#        print("f(n)=",c)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
m=input()
x=int(m,2)
li=list(m)
def popcount(num):
  return list(str(bin(num))).count("1")
for i in range(n):
  if li[i]=="0":
    a=x+2**(n-i-1)
  else:
    a=x-2**(n-i-1)
  co=0
  while a!=0:
    co+=1
    a%=popcount(a)
  print(co)

Submission status: Time Limit Exceeded

Solution code:
def toggle_nth_bit(num: int, n: int):
    return num ^ (1 << n)
N = int(input())
X = input()
X_10 = int(X,2)
X_list = [0]*N
ans = [0]*N
for i in range(N):
    j = toggle_nth_bit(X_10,N-i-1)
    while j>0:
        j=j%str(bin(j)).count('1')
        ans[i] += 1
for i in ans:
    print(i)

Submission status: Time Limit Exceeded

Solution code:

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

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

    def f(x):
        temp = x
        count = 0
        while temp > 0:
            temp = temp % popcount(temp)
            count += 1
        return count
    ans = [0]*N
    for i in range(0, N):
        xi = X ^ (1 << i)
        ans[N-i-1] = f(xi)
    for a in ans:
        print(a)
main()