1713C - Build Permutation - CodeForces Solution


constructive algorithms dp math *1200

Please click on ads to support us..

Python Code:

import math
t = int(input())

for i in range(t) : 
    n = int(input())
    lst = [j for j in range(n)]
    ed = n - 1
    while ed >= 0:
        tmp = int(math.ceil(math.sqrt(ed)))
        st = tmp * tmp - ed
        i1 = st
        i2 = ed
        while i1 < i2 : 
            lst[i1], lst[i2] = lst[i2], lst[i1]
            i1 += 1
            i2 += -1
        ed = st - 1
    for i in lst :
        print(i, end=" ")
    print("\n")

C++ Code:

#include <bits/stdc++.h>

using namespace std;

#define mp make_pair
#define pb push_back
#define int long long
#define pii pair<int, int>
#define fi first
#define se second
#define all(v) v.begin(), v.end()

#define trace(x) cout << '>' << #x << ':' << x << "\n"
#define trace2(x,y) cout<< '>' << #x << ':' << x << " | " << #y << ':' << y << "\n"
#define trace3(a,b,c) cout<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<", "<<#c<<"="<<(c)<<"\n"
#define trace4(a,b,c,d) cout<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<", "<<#c<<"="<<(c)<<", "<<#d<<"="<<(d)<<"\n"

template <typename T>
void print(T var){
    cout << var << ' ';
    return;
}

template <typename T>
void print(vector <T> var){
    for (auto x: var)
        print(x);
    cout << "\n";
    return;
}

int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, -1, 0, 1};
const int mod = 1e9+7;

bool sq(int x) {
    int xx = sqrt(x);
    return (xx*xx==x);
}

signed main(){

    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    int t;
    cin >> t;

    while (t--) {
        int n;
        cin >> n;
        vector<int> v(n);
        iota(all(v),0);
        for (int i = n-1; i >= 0; i--) {
            for (int j = i; j >= 0; j--) {
                if (sq(i+j)) {
                    reverse(v.begin()+j, v.begin()+i+1);
                    i = j;
                    break;
                }
            }
        }
        for (int i: v) cout << i << ' ';
        cout << '\n';
    }

}


Comments

Submit
0 Comments
More Questions

368B - Sereja and Suffixes
1665C - Tree Infection
1665D - GCD Guess
29A - Spit Problem
1097B - Petr and a Combination Lock
92A - Chips
1665B - Array Cloning Technique
1665A - GCD vs LCM
118D - Caesar's Legions
1598A - Computer Game
1605A - AM Deviation
1461A - String Generation
1585B - Array Eversion
1661C - Water the Trees
1459A - Red-Blue Shuffle
1661B - Getting Zero
1661A - Array Balancing
1649B - Game of Ball Passing
572A - Arrays
1455A - Strange Functions
1566B - MIN-MEX Cut
678C - Joty and Chocolate
1352E - Special Elements
1520E - Arranging The Sheep
1157E - Minimum Array
1661D - Progressions Covering
262A - Roma and Lucky Numbers
1634B - Fortune Telling
1358A - Park Lighting
253C - Text Editor