1353D - Constructing the Array - CodeForces Solution


constructive algorithms data structures sortings *1600

Please click on ads to support us..

Python Code:

import math,sys
from collections import defaultdict,deque
import bisect as bi
def yes():print('YES')
def no():print('NO')
def I():return (int(sys.stdin.readline()))
def In():return(map(int,sys.stdin.readline().split()))
def Sn():return sys.stdin.readline().strip()
def dict(a):
    d={} 
    for x in a:
        if d.get(x,-1)!=-1:
            d[x]+=1
        else:
            d[x]=1
    return d
def find_gt(a, x):
    'Find leftmost value greater than x'
    i = bi.bisect_left(a, x)
    if i != len(a):
        return i
    else:            
        return -1
def main():
    try:
        n=I()
        from heapq import heappush , heappop
        pq = [(-n,0,n-1)]
        ans = [0]*n
        cnt = 1
        while pq and cnt<=n:
            size , start,end = heappop(pq)
            size*=-1
            ind = ((size-1)//2)+start
            ans[ind]=cnt
            if start!=ind:
                heappush(pq,(-(ind-start),start,ind-1))
            if end!=ind:
                heappush(pq,(-(end-ind),ind+1,end))
            cnt+=1
        print(*ans)


    except:
        pass
        
M = 998244353
P = 1000000007
 
if __name__ == '__main__':
    for _ in range(I()):main()
    

C++ Code:

#include<bits/stdc++.h>
using namespace std;
#define int long long
#define ii pair<int,int>
#define iii pair<int,ii>
#define fr first
#define sc second

void solve(){
    int n,i=1;cin>>n;
    priority_queue<iii> pq;
    vector<int> a(n);
    pq.push({n,{0,-n+1}});
    while(pq.size()){
        iii top=pq.top();
        int x=top.fr,y=top.sc.fr,z=top.sc.sc;
//        cout<<x<<' '<<y<<' '<<z<<'\n';
//        system("pause");
        pq.pop();
        int mid=(-y-z)/2;
        a[mid]=i,i++;
        if(x==1)continue;
        if(mid+y>0)
            pq.push({mid+y,{y,-mid+1}});
        if(mid+z<0)
        pq.push({(mid+z)*-1,{-mid-1,z}});
    }
    for(auto i:a)cout<<i<<' ';
    cout<<'\n';
}

int32_t main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int t;cin>>t;
    while(t--)solve();
    return 0;
}


Comments

Submit
0 Comments
More Questions

96A - Football
702B - Powers of Two
1036A - Function Height
443A - Anton and Letters
1478B - Nezzar and Lucky Number
228A - Is your horseshoe on the other hoof
122A - Lucky Division
1611C - Polycarp Recovers the Permutation
432A - Choosing Teams
758A - Holiday Of Equality
1650C - Weight of the System of Nested Segments
1097A - Gennady and a Card Game
248A - Cupboards
1641A - Great Sequence
1537A - Arithmetic Array
1370A - Maximum GCD
149A - Business trip
34A - Reconnaissance 2
59A - Word
462B - Appleman and Card Game
1560C - Infinity Table
1605C - Dominant Character
1399A - Remove Smallest
208A - Dubstep
1581A - CQXYM Count Permutations
337A - Puzzles
495A - Digital Counter
796A - Buying A House
67A - Partial Teacher
116A - Tram