1328B - K-th Beautiful String - CodeForces Solution


binary search brute force combinatorics implementation math *1300

Please click on ads to support us..

Python Code:

t = int(input())
 
def bin_search(low, high, target):
    
    while low < high:
        mid = low + (high - low)//2
        if (mid * (mid + 1))//2 > target:
            high = mid
        else:
            low = mid+1
            res = mid
        
    return low
 
while t > 0:
    
    maxi = int(2e9+7)
    n, k = [int(i) for i in input().split(" ")]
    r = bin_search(0, maxi, k)
    r -= 1
        return_sum = (r * (r+1))//2
    if return_sum == k:
        first_shift = n-1-r
    else:
        first_shift = n-2-r
        
    if return_sum == k:
        second_shift = first_shift+1
    else:
        second_shift = n-1-(k-return_sum-1)
    
        ans = ['a'] * n
    ans[first_shift] = 'b'
    ans[second_shift] = 'b'
    print("".join(ans))
    t -= 1

C++ Code:

#include<bits/stdc++.h>
#define io ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define pb push_back
#define pf push_front
#define fi first
#define se second
#define db double
#define endl "\n"
#define ll long long
#define pii pair<int,int>
using namespace std;
const int N =1e5+10;

void solve(){
    ll n,k;
    cin>>n>>k;
    //1 2 3 4 5 6
    ll l=0,r=n+1;
    while(l+1!=r){
        ll mid=l+r>>1;
        if((mid+1)*mid/2>=k) r=mid;
        else l=mid;
    }
    int pos1=n-r;//1-n-1 2-n-2 5-n-5
    int pos2=k-(ll)r*(r-1)/2;//1-n 2-n-1
    pos2=n+1-pos2;
    string s(n,'a');
    s[pos1-1]='b';
    s[pos2-1]='b';
    cout<<s<<endl;
    
    
}
int main()
{
    io;
    int t;
    cin>>t;
    while(t--){
        solve();
    }
    return 0;
    
}


Comments

Submit
0 Comments
More Questions

1302. Deepest Leaves Sum
1209. Remove All Adjacent Duplicates in String II
994. Rotting Oranges
983. Minimum Cost For Tickets
973. K Closest Points to Origin
969. Pancake Sorting
967. Numbers With Same Consecutive Differences
957. Prison Cells After N Days
946. Validate Stack Sequences
921. Minimum Add to Make Parentheses Valid
881. Boats to Save People
497. Random Point in Non-overlapping Rectangles
528. Random Pick with Weight
470. Implement Rand10() Using Rand7()
866. Prime Palindrome
1516A - Tit for Tat
622. Design Circular Queue
814. Binary Tree Pruning
791. Custom Sort String
787. Cheapest Flights Within K Stops
779. K-th Symbol in Grammar
701. Insert into a Binary Search Tree
429. N-ary Tree Level Order Traversal
739. Daily Temperatures
647. Palindromic Substrings
583. Delete Operation for Two Strings
518. Coin Change 2
516. Longest Palindromic Subsequence
468. Validate IP Address
450. Delete Node in a BST