CF 483C Diverse Permutation(构造)

C. Diverse Permutation
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Permutation p is an ordered set of integers p1,   p2,   ...,   pn, consisting of n distinct positive integers not larger than n. We'll denote as nthe length of permutation p1,   p2,   ...,   pn.

Your task is to find such permutation p of length n, that the group of numbers |p1 - p2|, |p2 - p3|, ..., |pn - 1 - pn| has exactly k distinct elements.

Input

The single line of the input contains two space-separated positive integers nk (1 ≤ k < n ≤ 105).

Output

Print n integers forming the permutation. If there are multiple answers, print any of them.

Examples
input
Copy
3 2
output
Copy
1 3 2
input
Copy
3 1
output
Copy
1 2 3
input
Copy
5 2
output
Copy
1 3 2 4 5
Note

By |x| we denote the absolute value of number x.

题意:

从1-n的数中构造出一个序列,使得相邻数的差的绝对值的不同值的个数恰好为k,构造出这样的序列。

思路:

可以发现这样的一件事,当我们有n个数,k=n-1的时候,例如n=5,k=4

我们可以把1放第一个,第二个为1+4=5,第三个是5-3=2,第四个是2+2=4,第五个是4-1=3。这样刚好用了n个数不重复。

所以我们可以想到,前面的我们用递增的序列,保证前面差值均为1,后面再从差值为n-1开始往后按照上面的发现来构造,就一定能构造出这样的序列来。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn=1e5+5;
int a[maxn];
int main()
{
    int n,k;
    while(~scanf("%d%d",&n,&k))
    {
        int remain=k;
        int i;
        int f=1;
        for(i=1;i<=n-k;i++)
        {
            a[i]=i;
        }
        for(;i<=n;i++)
        {
            if(f)
            {
                f=0;
                a[i]=a[i-1]+remain;
                remain--;
            }
            else
            {
                f=1;
                a[i]=a[i-1]-remain;
                remain--;
            }
        }
        for(int i=1;i<=n;i++)
        {
            if(i==n)
                printf("%d\n",a[i]);
            else
                printf("%d ",a[i]);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/timeclimber/article/details/80940122