codeforces -891B Gluttony 排列,构造题

来源:互联网 发布:数据专员招聘要求 编辑:程序博客网 时间:2024/05/22 16:44

B. Gluttony
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given an array a with n distinct integers. Construct an array b by permuting a such that for every non-empty subset of indices S = {x1, x2, …, xk} (1 ≤ xi ≤ n, 0 < k < n) the sums of elements on that positions in a and b are different, i. e.

Input
The first line contains one integer n (1 ≤ n ≤ 22) — the size of the array.

The second line contains n space-separated distinct integers a1, a2, …, an (0 ≤ ai ≤ 109) — the elements of the array.

Output
If there is no such array b, print -1.

Otherwise in the only line print n space-separated integers b1, b2, …, bn. Note that b must be a permutation of a.

If there are multiple answers, print any of them.

Examples
input
2
1 2
output
2 1
input
4
1000 100 10 1
output
100 1 1000 10
Note
An array x is a permutation of y, if we can shuffle elements of y such that it will coincide with x.

Note that the empty subset and the subset containing all indices are not counted.

题解:

这是一道构造题,题目的要求就是求一个b序列,使得b序列是a序列的一个排列,然后任取a、b序列相应位置的子序列(长度小于n),a的子序列的和总不等于b的子序列的和。

我们可以这样构造,始终让a序列对应位置的数小于b序列对应位置的数,这样的话,不管怎么取,b子序列的和总是大于a子序列的和。

我们可以把a序列做一个排序,设为c序列,然后我们开始构造b序列
b[i]=c[(j+1)%n],满足c[j]=a[i]
例如:
a=[0,3,1,2]
那么
c=[0,1,2,3]
那么
b=[1,0,2,3]
b 就是我们要构造的序列。

显然这里还是存在一个问题的,也就是说我们并 没有让条件:

始终让a序列对应位置的数小于b序列对应位置的数

满足啊,按上面构造方法来看a的最大值显然要对应着b的最小值。
不信你看a[1]=3>b[1]=0
这就是本题的巧妙之处了,这样的话算法仍然是正确的。

证明:

a) 假设我在a序列中取得子序列不包含最大值的话。那么一定满足a的子序列的和总小于b的子序列的和

b) 假设我在a序列中取得子序列包含最大值的话。那么只要子序列的长度小于n,就一定会有a的子序列的和总大于b的子序列的和

综上所述,a、b中挑选对应位置的子序列,只要长度<n,那么和就永远不可能相等

代码:

#include <bits/stdc++.h>using namespace std;const int maxn = 30;int a[maxn],b[maxn];map<int,int> mp;int main(){    int n;    scanf("%d",&n);    for(int i = 0;i < n;++i){        scanf("%d",&a[i]);        b[i] = a[i];    }    sort(b,b+n);    for(int i = 0;i < n;++i){        mp[b[i]] = b[(i+1)%n];    }    for(int i = 0;i < n;++i){        cout<<mp[a[i]]<<' ';    }    return 0;}