题目 | K Derangement
AtCoder Regular Contest 144
C - K Derangement
https://atcoder.jp/contests/arc144/tasks/arc144_c
Time Limit: 2 sec / Memory Limit: 1024 MB
Score :
Problem Statement
You are given positive integers
for all ( ).
If there is no such permutation, print -1
.
Constraints
Input
Input is given from Standard Input in the following format:
Output
Print the lexicographically smallest permutation
If there is no such permutation, print -1
.
Sample Input 1
3 1
Sample Output 1
2 3 1
Two permutations satisfy the condition:
Sample Input 2
8 3
Sample Output 2
4 5 6 7 8 1 2 3
Sample Input 3
8 6
Sample Output 3
-1
解题笔记
首先需要找到存在这种排列的必要条件,即
接下来的重点就是找到通项公式。分为四种情况:
: 无解 : : :这个意思是前
位为 ,剩余的部分的 ,再选择符合 大小的公式。不断使用情况四的公式进行递推,一定可以转化为情况二或情况三。
代码
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int N, K;
cin >> N >> K;
if (2 * K > N)
{
cout << -1 << endl;
return 0;
}
int cnt = 0;
while (N - cnt >= 4 * K)
{
for (int i = 1; i <= K; i++)
cout << cnt + i + K << ' ';
for (int i = 1; i <= K; i++)
cout << cnt + i << ' ';
cnt += 2 * K;
}
if (N - cnt <= 3 * K)
{
int i = 1;
for (; i <= (N - cnt) - K; i++)
cout << i + K + cnt << ' ';
for (; i <= (N - cnt); i++)
cout << i - (N - cnt) + K + cnt << ' ';
}
else
{
int i = 1;
for (; i <= K; i++)
cout << i + K + cnt << ' ';
for (; i <= (N - cnt) - 2 * K; i++)
cout << i - K + cnt << ' ';
for (; i <= (N - cnt) - K; i++)
cout << i + K + cnt << ' ';
for (; i <= 3 * K; i++)
cout << i - 2 * K + cnt << ' ';
for (; i <= (N - cnt); i++)
cout << i - K + cnt << ' ';
}
cout << endl;
return 0;
}
本文采用 CC BY-SA 4.0 许可,本文 Markdown 源码:Haotian-BiJi