Codeforces 622D Optimal Number Permutation 【贪心】

D. Optimal Number Permutation
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.

Let number i be in positions xi, yi (xi < yi) in the permuted array a. Let's define the value di = yi - xi — the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .

Input

The only line contains integer n (1 ≤ n ≤ 5·105).

Output

Print 2n integers — the permuted array a that minimizes the value of the sum s.

Sample test(s)
input
2
output
1 1 2 2
input
1
output
1 1


 

题意:有n个数,要求每个数出现2次,位置分别为xi、yi(xi < yi),定义di = yi-xi。让你找到一个全排列使得sigma((n-i) * |di+i-n|)最小。


思路:假设贪心的认为结果为0。那么1之间需要间隔n-2个数,2之间需要间隔n-3个数,同理向下推。

n-2个空位可以做什么?可以保证填3,剩下n-4个空位可以填5......

对于2剩下的n-3个空位也这样利用。


AC代码:


#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define INF 1000000
#define eps 1e-8
#define MAXN (1000000+10)
#define MAXM (2000000+10)
#define Ri(a) scanf("%d", &a)
#define Rl(a) scanf("%lld", &a)
#define Rf(a) scanf("%lf", &a)
#define Rs(a) scanf("%s", a)
#define Pi(a) printf("%d\n", (a))
#define Pf(a) printf("%.2lf\n", (a))
#define Pl(a) printf("%lld\n", (a))
#define Ps(a) printf("%s\n", (a))
#define W(a) while((a)--)
#define CLR(a, b) memset(a, (b), sizeof(a))
#define MOD 1000000007
#define LL long long
#define lson o<<1, l, mid
#define rson o<<1|1, mid+1, r
#define ll o<<1
#define rr o<<1|1
#define PI acos(-1.0)
#pragma comment(linker, "/STACK:102400000,102400000")
#define fi first
#define se second
using namespace std;
typedef pair pii;
int ans[MAXN];
int main()
{
    int n; Ri(n); CLR(ans, -1);
    if(n == 1) {printf("1 1\n"); return 0; }
    int l = 1, r = n;
    ans[l] = ans[r] = 1;
    int j = 3; l++, r--;
    while(r > l)
    {
        ans[l] = ans[r] = j;
        l++, r--; j += 2;
    }
    l = n+1; r = n*2-1;
    ans[l] = ans[r] = 2;
    j = 4, l++, r--;
    while(r > l)
    {
        ans[l] = ans[r] = j;
        l++, r--; j += 2;
    }
    printf("%d", ans[1] == -1 ? n : ans[1]);
    for(int i = 2; i <= 2*n; i++) printf(" %d", ans[i] == -1 ? n : ans[i]);
    printf("\n");
    return 0;
}


你可能感兴趣的:(贪心,codeforces)