1508B - Almost Sorted - CodeForces Solution


binary search combinatorics constructive algorithms implementation *1800

Please click on ads to support us..

Python Code:

from heapq import heapify, heappop, heappush
from itertools import cycle
from math import sqrt,ceil
import os

import sys
from collections import defaultdict,deque
from io import BytesIO, IOBase
     
         
             
 
    
 
 
 
 
 
 
    
from collections import Counter
from functools import lru_cache
from collections import deque
def main():
    from heapq import heappush,heappop,heapify
   
                
    

        

            
        
        
                        
                
        
        
                            
        
                                                                
    
            import bisect,math
    class SortedList():
        BUCKET_RATIO = 50
        REBUILD_RATIO = 170
    
        def __init__(self,buckets):
            buckets = list(buckets)
            buckets = sorted(buckets)
            self._build(buckets)
    
        def __iter__(self):
            for i in self.buckets:
                for j in i: yield j
    
        def __reversed__(self):
            for i in reversed(self.buckets):
                for j in reversed(i): yield j
    
        def __len__(self):
            return self.size
    
        def __contains__(self,x):
            if self.size == 0: return False
            bucket = self._find_bucket(x)
            i = bisect.bisect_left(bucket,x)
            return i != len(bucket) and bucket[i] == x
    
        def __getitem__(self,x):
            if x < 0: x += self.size
            if x < 0: raise IndexError
            for i in self.buckets:
                if x < len(i): return i[x]
                x -= len(i)
            raise IndexError
    
        def _build(self,buckets=None):
            if buckets is None: buckets = list(self)
            self.size = len(buckets)
            bucket_size = int(math.ceil(math.sqrt(self.size/self.BUCKET_RATIO)))
            tmp = []
            for i in range(bucket_size):
                t = buckets[(self.size*i)//bucket_size:(self.size*(i+1))//bucket_size]
                tmp.append(t)
            self.buckets = tmp
    
        def _find_bucket(self,x):
            for i in self.buckets:
                if x <= i[-1]:
                    return i
            return i
    
        def add(self,x):
                        if self.size == 0:
                self.buckets = [[x]]
                self.size = 1
                return True
    
            bucket = self._find_bucket(x)
            bisect.insort(bucket,x)
            self.size += 1
            if len(bucket) > len(self.buckets) * self.REBUILD_RATIO:
                self._build()
            return True
    
        def remove(self,x):
                        if self.size == 0: return False
            bucket = self._find_bucket(x)
            i = bisect.bisect_left(bucket,x)
            if i == len(bucket) or bucket[i] != x: return False
            bucket.pop(i)
            self.size -= 1
            if len(bucket) == 0: self._build()
            return True
    
        def lt(self,x):
                        for i in reversed(self.buckets):
                if i[0] < x:
                    return i[bisect.bisect_left(i,x) - 1]
    
        def le(self,x):
                        for i in reversed(self.buckets):
                if i[0] <= x:
                    return i[bisect.bisect_right(i,x) - 1]
    
        def gt(self,x):
                        for i in self.buckets:
                if i[-1] > x:
                    return i[bisect.bisect_right(i,x)]
    
        def ge(self,x):
                        for i in self.buckets:
                if i[-1] >= x:
                    return i[bisect.bisect_left(i,x)]
        def index(self,x):
                        ans = 0
            for i in self.buckets:
                if i[-1] >= x:
                    return ans + bisect.bisect_left(i,x)
                ans += len(i)
            return ans
    
        def index_right(self,x):
                        ans = 0
            for i in self.buckets:
                if i[-1] > x:
                    return ans + bisect.bisect_right(i,x)
                ans += len(i)
            return ans

        for _ in range(int(input())):
        n,k=map(int,input().split())
        if (n<62 and k>(1<<(n-1))):
            print(-1)
        else :
            s=[]
            for i in range(n):
                s.append("0")
            k-=1
            for b in range(min(61,n-1)):
                if (k>>b)&1:
                    s[n-2-b]="1"
            curr=1
            sz=1
            ans=[]
            for i in range(n):
                if s[i]=="0":
                    for j in range(curr+sz-1,curr-1,-1):
                        ans.append(j)
                    curr+=sz
                    sz=1
                else :
                    sz+=1
            print(*ans)   
    
        
        

                    

    
                
            
        
                           
        
 
BUFSIZE = 8192
 
 
class FastIO(IOBase):
    newlines = 0
 
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = 'x' in file.mode or 'r' not in file.mode
        self.write = self.buffer.write if self.writable else None
 
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
 
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b'\n') + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
 
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
 
 
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode('ascii'))
        self.read = lambda: self.buffer.read().decode('ascii')
        self.readline = lambda: self.buffer.readline().decode('ascii')
 
 
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
 
 
 
if __name__ == '__main__':
    main()

C++ Code:

#include <bits/stdc++.h>
using namespace std;
using ll = long long;

void solve() {
    int n;
    ll k;
    cin >> n >> k;

    if(n < 62 && k > 1LL << (n - 1)) {
        cout << "-1\n";
        return;
    }

    string s;
    for(int i = 0; i < n; i++)
        s += '0';
    k--;
    for(ll b = 0; b < min(60LL, (ll)(n - 1)); b++) {
        if((k >> b) & 1)
            s[n - 2 - b] = '1';
    }
    int cur = 1, sz = 1;
    vector<int> ans;
    for(int i = 0; i < n; i++) {
        if(s[i] == '0') {
            for(int j = cur + sz - 1; j >= cur; j--)
                ans.push_back(j);
            cur += sz;
            sz = 1;
        }
        else
            sz++;
    }
    for(auto &x : ans)
        cout << x << " ";
    cout << '\n';
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);

    int t;
    cin >> t;
    while(t--)
        solve();
}


Comments

Submit
0 Comments
More Questions

1706C - Qpwoeirut And The City
1697A - Parkway Walk
1505B - DMCA
478B - Random Teams
1705C - Mark and His Unfinished Essay
1401C - Mere Array
1613B - Absent Remainder
1536B - Prinzessin der Verurteilung
1699B - Almost Ternary Matrix
1545A - AquaMoon and Strange Sort
538B - Quasi Binary
424A - Squats
1703A - YES or YES
494A - Treasure
48B - Land Lot
835A - Key races
1622C - Set or Decrease
1682A - Palindromic Indices
903C - Boxes Packing
887A - Div 64
755B - PolandBall and Game
808B - Average Sleep Time
1515E - Phoenix and Computers
1552B - Running for Gold
994A - Fingerprints
1221C - Perfect Team
1709C - Recover an RBS
378A - Playing with Dice
248B - Chilly Willy
1709B - Also Try Minecraft