Dream Permutation#12461

Dream Permutation (Editorial)

Problem Author:

Hadi Takla (TaklaOI)

Prepared by:

Hadi Takla (TaklaOI)

Edited by:

Hadi Takla (TaklaOI)

Solution

Since is a permutation , the maximum sum of two values we can obtain is n + n-1 = 2n - 1.

Now , for a fixed value , let's find the values where (x + y) (n+1) = 0

(x + y) (n+1) = 0 so x + y = k \cdot (n+1) , because we have positive sums k \in N

when k=1 \Rightarrow x + y = n+1 \Rightarrow y = n+1-x.

when k=2 , x + y = 2n+2 , but 2n+2 > 2n-1 so that sum is not obtainable.

Now , for a fixed value , let's find the values where (x + y) (n+1) = n.

(x + y) (n+1) = n so x + y = n + k \cdot (n+1) and k \in N.

when k = 0 \Rightarrow x + y = n \Rightarrow y =n - x.

when k = 1 , x + y = 2n + 1 , 2n + 1 > 2n - 1 so that sum is not obtainable.

so for a value there are at most two values which can be placed as a neighbor to , which are n+1-x , n - x.

when x = n , the values are , since we can't put in the permutation , the value must have only one neighbor , so the value should be either in index or .

since every value has at most two suitable neighbor values , we can build the permutation element by element after identifying the index of value .

Time complexity .

#include<bits/stdc++.h>
#define endl '\n'
using namespace std;
int main()
{
    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
    int tc;
    cin>>tc;
    while(tc -- )
    {
        int n;
        cin>>n;
        int l = 1 , r = n;
        for(int i=1;i<=n;i++)
        {
            cout<<(i%2 ? r-- : l++)<<' ';
        }
        cout<<endl;
    }
}