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:
import bisect
import sys
import math
from collections import deque
from heapq import heappush, heappop

def sRaw():
    return input().rstrip("\r")


def iRaw():
    return int(input())


def ssRaw():
    return input().split()


def isRaw():
    return list(map(int, ssRaw()))


INF = 1 << 29

DIV = (10**9) + 7
#DIV = 998244353

def mod_inv_prime(a, mod=DIV):
    return pow(a, mod-2, mod)


def mod_inv(a, b):
    r = a
    w = b
    u = 1
    v = 0
    while w != 0:
        t = r//w
        r -= t*w
        r, w = w, r
        u -= t*v
        u, v = v, u
    return (u % b+b) % b


def CONV_TBL(max, mod=DIV):
    fac, finv, inv = [0]*max, [0]*max, [0]*max
    fac[0] = fac[1] = 1
    finv[0] = finv[1] = 1
    inv[1] = 1
    for i in range(2, max):
        fac[i] = fac[i-1]*i % mod
        inv[i] = mod - inv[mod % i] * (mod//i) % mod
        finv[i] = finv[i-1]*inv[i] % mod

    class CONV:
        def __init__(self):
            self.fac = fac
            self.finv = finv
            pass

        def ncr(self, n, k):
            if(n < k):
                return 0
            if(n < 0 or k < 0):
                return 0
            return fac[n]*(finv[k]*finv[n-k] % DIV) % DIV

    return CONV()


def cumsum(As):
    s = 0
    for a in As:
        s += a
        yield s


sys.setrecursionlimit(200005)


def dijkstra(G,start=0):
    heap = []
    cost = [INF]*len(G)
    heappush(heap,(0,start))
    while len(heap)!=0:
        c,n = heappop(heap)
        if cost[n] !=INF:
            continue
        cost[n]=c
        for e in G[n]:
            ec,v = e
            if cost[v]!=INF:
                continue
            heappush(heap,(ec+c,v))
    return cost


def main():
    cache={}
    def f(s,cur=0):
        if s in cache:
            return cache[s]
        ins = int(s,2)
        if ins==0:
            return cur
        pc = sum([c=='1' for c in s])
        ret = f(bin(ins%pc)[2:],cur+1)
        cache[s]=ret
        return ret
    N=iRaw()
    Xs=sRaw()
    for n in range(N):
        xl = [x for x in Xs]
        xl[n]="1" if xl[n]=="0" else "0"
        print(f("".join(xl)))

main()

Submission status: Time Limit Exceeded

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

for i in range(n):
  temp = list(rep)
  if temp[i] == '1':
    temp[i] = '0'
  else:
    temp[i] = '1'
  x = int(''.join(temp), 2)
  ans = 0
  while x:
    x = x % bin(x)[2:].count('1')
    ans += 1
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
def popcount(n):
    if n == 0:
        return 0
    n2 = n
    diver = 0
    while n2 != 0:
        if n2 % 2 == 1:
            diver += 1
        n2 = n2 // 2
    return diver


N = int(input())
X_in = input()
X_len = len(X_in)
X_d_r = list(X_in.lstrip('0'))[::-1]
X = 0
for i, c in enumerate(X_d_r):
    if c == '1':
        X += 2**i
# print('X in dec is ', X)
for i in range(X_len-1, -1, -1):
    # print(i, X_in[-i-1])
    if X_in[-i-1] == '0':
        X_tmp = X + 2**i
    else:
        X_tmp = X - 2**i
    # print(X_tmp)
    ans = 0
    while X_tmp != 0:
        ans += 1
        X_tmp = X_tmp % popcount(X_tmp)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
from functools import lru_cache

import sys
sys.setrecursionlimit(10**6)
# buff_readline = sys.stdin.buffer.readline
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 = y.count('1')
        if c == 0:
            return 0
        r = 0
        for b in y:
            b = int(b)
            r *= 2
            r += b % c
        r %= c
        if r == 0:
            return 1

        return 1 + f(bin(r)[2:])

    X = [x for x in X]
    for i in range(N):
        b = X[i]
        if X[i] == '1':
            X[i] = '0'
        else:
            X[i] = '1'
        # print(X)
        print(f(''.join(X)))
        X[i] = b


def main():
    N = read_int()
    X = read_str()
    slv(N, X)
    # N = 10**5
    # N *= 2
    # X = ''.join(random.choices('01', k=N))
    # print(slv(N, X))




if __name__ == '__main__':
    main()

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
######################################################################################################
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:
n = int(input())
x = list(input())
def popcount(n):
    pop = list(bin(n))[2:]
    pop = [ int(x) for x in pop]
    return sum(pop)
def f(n,cnt):
    if n != 0:
        f(n%popcount(n),cnt+1)
    else:
        print(cnt)
for i in range(n):
    tmpx = []
    for j in range(n):
        if j != i:
            tmpx.append(x[j])
        else:
            if x[j] == "1":
                tmpx.append("0")
            else:
                tmpx.append("1")
    k = int("".join(tmpx),2)
    f(k,0)

Submission status: Time Limit Exceeded

Solution code:

import collections
from functools import lru_cache


def read():
    return input().strip()


def readInt():
    return int(input().strip())


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


def solve(n, x):
    ans = [0 for _ in range(n)]
    num = 0

    for i, val in enumerate(x):
        bit = n-i-1

        num += 2**bit * int(val)

    @lru_cache(None)
    def popCount(n):
        ans = 0

        while n:
            ans += int(n & 1)
            n //= 2

        return ans

    @lru_cache(None)
    def f(n):
        ans = 0

        while n:
            n = n % popCount(n)
            ans += 1

        return ans

    for i, val in enumerate(x):
        bit = n-i-1
        val = int(val)

        if val:
            ans[i] = f(num - 2**bit)
        else:
            ans[i] = f(num + 2**bit)

    return "\n".join(map(str, ans))


n = readInt()
x = [ch for ch in read()]

print(solve(n, x))

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)]

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

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:
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
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
  print(ans)

Submission status: Time Limit Exceeded

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


def arrayTo2(A):
    ans = 0
    l = len(A)
    for i in range(l):
        if (A[i] == '1'):
            ans += 2 ** (l-i-1)

    return ans


N = int(input())

X = input()

for i in range(N):
    Xi = []
    for j in range(N):
        if (i == j):
            if (X[i] == '0'):
                Xi.append('1')
            else:
                Xi.append('0')
        else:
            Xi.append(X[j])

    ans = 0
    n = arrayTo2(Xi)
    while (n > 0):
        n = n % popcount(n)
        ans += 1

    print(ans)

Submission status: Time Limit Exceeded

Solution code:
k=int(input())
x=input()
cnt=x.count("1")
n=0
for i in range(k): n+=(2**i)*int(x[k-i-1])
for i in range(k):
    temp=0
    ntemp=n
    if x[i]=="0":
        temp=cnt+1
        ntemp+=(2**(k-i-1))
    else:
        temp=cnt-1
        ntemp-=(2**(k-i-1))
    ans=0
    while ntemp>0:
        ntemp%=temp
        temp=str(bin(ntemp)).count("1")
        ans+=1
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
# Coding is about expressing your feeling, and
# there is always a better way to express your feeling_feelme
import sys
import math
# sys.stdin=open('input.txt','r')
# sys.stdout=open('output2.txt','w')
from sys import stdin,stdout
from collections import deque,defaultdict
from math import ceil,floor,inf,sqrt,factorial,gcd,log2
from copy import deepcopy
ii1=lambda:int(stdin.readline().strip())
is1=lambda:stdin.readline().strip()
iia=lambda:list(map(int,stdin.readline().strip().split()))
isa=lambda:stdin.readline().strip().split()
mod=int(1e9 + 7)

def fun(n):
    count=0
    while n>0:
        a=bin(n).count('1')
        ans=n%a
        n=ans
        count+=1
    print(count)

n=ii1()
s=list(is1())
n=len(s)
for i in range(n):
    if s[i]=='0':
        s[i]='1'
        no='0b'
        no =''.join(s)
        fun(int(no,2))
        s[i]='0'
    else:
        s[i]='0'
        no='0b'
        no +=''.join(s)
        fun(int(no,2))
        s[i]='1'

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
x=input()
f={0:0,1:1,2:1,3:2}
# for i in range(1,2**n):
#     popcount=format(i,'b').count('1')
#     f[i]=f[i%popcount]+1
for i in range(len(x)):
    if x[i]=='1':
        x_changed=x[:i]+'0'+x[i+1:]
    else:
        x_changed=x[:i]+'1'+x[i+1:]
    num_changed=int(x_changed,2)
    # print(x_changed,num_changed)
    add=[]
    tmp=num_changed
    while True:
        if tmp not in f:
            popcount=format(tmp,'b').count('1')
            add.append(tmp)
            tmp%=popcount
        else:
            break
    while len(add)>0:
        cnt=f[tmp]
        tmp=add.pop()
        f[tmp]=cnt+1
    print(f[num_changed])

Submission status: Time Limit Exceeded

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


n = int(input())
X = input()
x = int(X, 2)
for i in range(n-1, -1, -1):
    pair = 1 << i
    Xi = x ^ pair
    count = 0
    while Xi:
        mod = popcount(Xi)
        Xi %= mod
        count += 1
    print(count)

Submission status: Time Limit Exceeded

Solution code:
def pop(x):
    c = 0
    while x != 0:
        a = format(x,'b')
        b = sum(i == '1' for i in a)
        x = x%b
        c += 1
    return c

n = int(input())
x = input()
for i in range(n):
    a = x[:i] + '1' + x[i+1:] if x[i] == '0' else x[:i] + '0' + x[i+1:]
    print(pop(int(a,2)))

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):
    X_list[i] = toggle_nth_bit(X_10,N-i-1)
for i,j in enumerate(X_list):
    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:
import sys

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline

def popcount(n):
    if n == 0:
        return 0
    return 1 + popcount(n % bin(n).count("1"))

def main():
    N = int(input())
    X = input().strip()


    x = int(X, 2)
    for i in range(N):
        if X[i] == '0':
            print(popcount(x + (2 ** (N - i - 1))))
        else:
            print(popcount(x - (2 ** (N - i - 1))))



    

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:


def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    mod=10**9+7
    def popcount(x):
        '''xの立っているビット数をカウントする関数
        (xは64bit整数)'''

        # 2bitごとの組に分け、立っているビット数を2bitで表現する
        x = x - ((x >> 1) & 0x5555555555555555)

        # 4bit整数に 上位2bit + 下位2bit を計算した値を入れる
        x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333)

        x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f # 8bitごと
        x = x + (x >> 8) # 16bitごと
        x = x + (x >> 16) # 32bitごと
        x = x + (x >> 32) # 64bitごと = 全部の合計
        return x & 0x0000007f
    
    N=I()
    Xst=input()
    
    dp=[0]*(N+1)
    for i in range(1,N+1):
        X=i
        X=X%popcount(X)
        dp[i]=dp[X]+1 
        
    a=Xst.count("1")
    X=int(Xst,2)
    
    
    
    for i in range(N):
        if Xst[i]=="0":
            xa=a+1
            X2=X+(1<<(N-i-1))
        else:
            xa=a-1
            X2=X-(1<<(N-i-1))
        cnt=0
        #print(X2,xa)
        if X2!=0:
            X2=X2%xa
            cnt=dp[X2]+1
        print(cnt)
    
    
        

main()

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([])

for i in range(len(X)):
    if X[i] == "0":
        X[i] = "1"
        q.append("".join(X))
        X[i] = "0"
    else:
        X[i] = "0"
        q.append("".join(X))
        X[i] = "1"

while q:
    n = int(q.popleft(), 2)
    b = bin(n).count("1")
    cnt = 0

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

    print(cnt)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
x=int(input(),2)
dic={}
def f(x):
    if x in dic:
        return dic[x]
    cnt=0
    for i in bin(x):
        cnt+=i=='1'
    if cnt == 0:
        return 0
    dic[x]=f(x%cnt)+1
    return dic[x]
for i in range(n-1,-1,-1):
    print(f(x^(1<<i)))

Submission status: Time Limit Exceeded

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

def function(n):
  ret = 0
  while n > 0:
    ret += 1
    n %= popcount(n)
  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, bisect, math, itertools, string, queue, copy
# import numpy as np
# import scipy
# from scipy.sparse.csgraph import floyd_warshall
from collections import Counter,defaultdict,deque
from itertools import permutations, combinations, combinations_with_replacement
from heapq import heappop, heappush, heapify
from fractions import gcd
# input = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7

def main():
    n = int(input())
    x = list(input())
    for i in range(n):
        x[i] = int(x[i])
    n = 2*10**5
    x = [1 for _ in range(n)]
    A = 0
    B = sum(x)
    for i in range(n):
        A += x[i]*pow(2,n-i-1,B)
        A %= B
    for i in range(n):
        if x[i] == 0:
            AA = A + pow(2,n-i-1)
            BB = B + 1
        else:
            AA = A - pow(2,n-i-1)
            BB = B - 1
        ans = 1
        while AA%BB:
            AA = AA%BB
            AAA = copy.deepcopy(AA)
            BB = 0
            while AAA != 0:
                BB += AAA%2
                AAA //= 2
            ans += 1
        print(ans)
    
if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    mem = defaultdict(lambda : None)
    mem[0] = 0
    cnt = [0]
    for _ in range(23):
        cnt = [x+i for i in range(2) for x in cnt]
    def dfs(x):
        if mem[x] is not None:
            return mem[x]
        p = cnt[x]
        res = dfs(x%p)+1
        mem[x] = res
        return res
    ans = [dfs(i) for i in range(200000)]
    n = I()
    x = list(map(int, input()))
    cnt_x = sum(x)
    s = 0
    p = 1
    for i in range(n):
        s += x[-i-1]*p
        p <<= 1
    p >>= 1
    for i in range(n):
        x = s^p
        k = cnt_x-1 if s&p else cnt_x+1
        if k == 0:
            print(0)
        else:
            print(ans[x%k]+1)
        p >>= 1
    return

#Solve
if __name__ == "__main__":
    solve()

Submission status: Time Limit Exceeded

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

for i in range(N):
    x = list(X)
    if x[i] == '0':
        x[i] = '1'
    else:
        x[i] = '0'

    x = int(''.join(x), 2)
    pc = bin(x).count('1')

    ans = 0
    while x > 0:
        x %= pc
        pc = bin(x).count('1')
        ans += 1

    print(ans)

Submission status: Time Limit Exceeded

Solution code:
from copy import deepcopy


def popcount(n):
    return sum(map(int, list(f"{n:b}")))


def make_xi(n, i):
    n[i] = "1" if n[i] == "0" else "0"
    return int("".join(n), 2)


def main():
    n = int(input())
    x = list(input())
    ret = 0
    for i in range(n):
        _x = deepcopy(x)
        x_i = make_xi(_x, i)
        ret = 0
        while x_i > 0:
            tmp = popcount(x_i)
            x_i = x_i % tmp
            ret += 1
        print(ret)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
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 nxt(x):
    i = 0
    cnt = 0
    while x >= 1<<i:
        if x & (1<<i):
            cnt += 1
        i += 1
    return x % cnt


def count(x):
    s = 0
    a = [x]
    while x != 0:
        s += 1
        x = nxt(x)
        if x in memo:
            s = s + memo[x]
            break
        a.append(x)
    for i in range(len(a)):
        memo[a[i]] = s - i
    return s

def main():
    n = int(input())
    x = input()
    x = int(x, 2)
    for i in range(n):
        y = x ^ (1<<(n-i-1))
        s = count(y)
        print(s)


main()

Submission status: Time Limit Exceeded

Solution code:
import collections
n = int(raw_input())
x = int(raw_input(),2)
mem = {0:0}
def f(x):
	if x in mem:
		return mem[x]
	cc=  collections.Counter(bin(x))
	
	if x % cc['1'] == 0: 
		mem[x] = 1
		return 1
	mem[x] = 1 + f(x % cc['1'])
	return 1 + f(x % cc['1'])

for i in range(n)[::-1]:
	print f(x ^ (1 << i))

Submission status: Time Limit Exceeded

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


cache = [-1] * (2 * 10 ** 5 + 1)


def f(n):
    if cache[X] != -1:
        return cache[X]
    return f(n % popcount(n)) + 1


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

result = []
for i in range(N):
    n = X ^ (1 << (N - 1 - i))
    t = 0
    while n != 0:
        n %= popcount(n)
        t += 1
    result.append(t)
print(*result, sep='\n')

Submission status: Time Limit Exceeded

Solution code:
def callMe(nn):
  count=0
  while(nn>0):
    c = bin(nn).count('1')
    nn=nn%c
    count+=1
  return count
n = int(input())
x=input()
for i in range(n):
  s = list(x) 
  if(s[i]=='1'):
    s[i]='0'
  else:
    s[i]='1'
  ss = ''.join(s)
  print(callMe(int(ss,2)))

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

ans = [0]*n
for i in range(n):
    if x[-(i+1)] == "1":
        _num = num-2**i
        _count = count-1
    else:
        _num = num+2**i
        _count = 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:
N = int(input())
X = list(map(int, list(input())))
#print(X)

def f(n):
  global call
  call += 1
  bit = 0
  m = n
  while m > 0:
    if m % 2 == 1:
      bit += 1
    m //= 2
  next_n = n % bit
  if next_n > 0:
    f(next_n)

def num(A):
  b = 1
  r = 0
  for i in range(len(A)):
    r += b*A[-i-1]
    b *= 2
  return r

for i in range(N):
  A = X.copy()
  A[i] ^= 1
#  print(A)
  n = num(A)
#  print(n)
  call = 0
  if n > 0:
    f(n)
  print(call)