1352G - Special Permutation - CodeForces Solution


constructive algorithms *1600

Please click on ads to support us..

C++ Code:

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

const int N = 1001;
vector<int> v[N + 1];
vector<bool> d(N + 1);
int n;
void reset()
{
    for(int i = 1; i <= n; i++)
    {
        v[i].clear();
    }
    for(int i = 1; i <= n; i++)
    {
        for(int j = 2; j <= 4; j++)
        {
            if(i + j <= n)
                v[i].push_back(i + j);
            if(i - j >= 1)
                v[i].push_back(i - j);
        }
    }
}

vector<int> ans(N + 1);
bool ok;

void dfs(int u, int num)
{
    if(ok) return;
    ans[num] = u;
    if(num == n)
    {
        ok = true;
        for(int i = 1; i <= n; i++)
            cout << ans[i] << ' ';
        return;
    }
    for(int x : v[u])
    {
        if(d[x]) continue;
        d[x] = true;
        dfs(x, num + 1);
    }
}

int main()
{
//    freopen("input.txt", "r", stdin);
//    freopen("output.txt", "w", stdout);
	ios::sync_with_stdio(false);
    cin.tie(0);
    int t;
    cin >> t;
    while(t--)
    {
        cin >> n;
        if(n <= 3) {
            cout << -1 << '\n';
            continue;
        }
        reset();
        for(int i = 1; i <= n; i++)
        {
            ok = false;
            for(int j = 1; j <= n; j++)
                d[j] = false;
            d[i] = true;
            ans[1] = i;
            dfs(i, 1);
            if(ok) break;
        }
        cout << '\n';
    }
	return 0;
}


Comments

Submit
0 Comments
More Questions

1326B - Maximums
1635C - Differential Sorting
961A - Tetris
1635B - Avoid Local Maximums
20A - BerOS file system
1637A - Sorting Parts
509A - Maximum in Table
1647C - Madoka and Childish Pranks
689B - Mike and Shortcuts
379B - New Year Present
1498A - GCD Sum
1277C - As Simple as One and Two
1301A - Three Strings
460A - Vasya and Socks
1624C - Division by Two and Permutation
1288A - Deadline
1617A - Forbidden Subsequence
914A - Perfect Squares
873D - Merge Sort
1251A - Broken Keyboard
463B - Caisa and Pylons
584A - Olesya and Rodion
799A - Carrot Cakes
1569B - Chess Tournament
1047B - Cover Points
1381B - Unmerge
1256A - Payment Without Change
908B - New Year and Buggy Bot
979A - Pizza Pizza Pizza
731A - Night at the Museum