Codeforces 233A-Perfect Permutation(規律),codeforces
A. Perfect Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output
A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.
Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfectpermutation is such permutation p that for any i (1 ≤ i ≤ n) (n is the permutation size) the following equations hold ppi = i and pi ≠ i. Nickolas asks you to print any perfect permutation of size n for the given n.
Input
A single line contains a single integer n (1 ≤ n ≤ 100) — the permutation size.
Output
If a perfect permutation of size n doesn't exist, print a single integer -1. Otherwise print n distinct integers from 1 to n, p1, p2, ..., pn — permutation p, that is perfect. Separate printed numbers by whitespaces.
Sample test(s)input
1
output
-1
input
2
output
2 1
input
4
output
2 1 4 3
題意: 給一個長度為n的序列p,序列中的元素大小範圍為[1,n]且各不相同,現在要求一個完美序列,使得 p[p[i]]=i&&p[i]!=i;
初看很難。仔細一想,假設初始化序列 f[i]=i; 現在只要交換奇偶位置上的元素值就可以了 即 swap(s[i],s[i+1]) (i%2==1) 前提條件是序列的大小為偶數
#include <iostream>#include <algorithm>#include <cstdio>#include <cstring>#include <string>#include <vector>using namespace std;int main(){int n;while(cin>>n){if(n%2)puts("-1");elsefor(int i=1;i<=n;i++)if(i%2)cout<<i+1<<" "; elsecout<<i-1<<" ";cout<<endl;}return 0;}
C語言Perfect Permutation的演算法
只有偶數個有答案,兩兩翻轉