Diverse Permutation
Time Limit:1000MS Memory Limit:262144KB 64bit IO Format:%I64d & %I64u
Description
Permutationp is an ordered set of integers p1, p2, …, pn, consisting of n distinct positive integers not larger than n. We’ll denote as n the 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 n, k (1 ≤ k < n ≤ 105).
Output
Print n integers forming the permutation. If there are multiple answers, print any of them.
Sample Input
Input
3 2
Output
1 3 2
Input
3 1
Output
1 2 3
Input
5 2
Output
1 3 2 4 5
Hint
By |x| we denote the absolute value of number x.
题意:有一个p1, p2, …, pn(代表1–n)的序列,将里面的序列重新排列,使其满足 |p1 - p2|, |p2 - p3|, …, |pn - 1 - pn|出现k种植,k种值的意思就是所有的|pi - pi-1|的值必须包含1–k种的每一个值。
这下就可以想如果要出现k,就可以用k+1减去1,要得k-1,用k+1减去2,因为是绝对值,所以可以写成,1,k+1,2。得到k-2就用2减去k(绝对值不用管顺序),就变成1,k+1,2,k,重复这个过程就能得到满足要求的序列。相当于在1到k+1,从左边1和右边k+1开始,一边取一个数字重新排成一个序列,1,k+1, 2 , k , 3 , k-1 …… 然后后面还有n-k-1个数字,因为已经满足题目所给要求,所以只需要顺序输出(相邻的数字差值为1)。
#include"stdio.h"
#include"iostream"
#include"algorithm"
#include"string.h"
using namespace std;
bool vis[100010];
int main(void)
{
int n,k;
while(scanf("%d%d",&n,&k) !=EOF)
{
memset(vis,false,sizeof(vis));
printf("1");
int x = 1;
int t = 1;
for(int i = k;i > 0;i--)
{
if(t == 1)
{
printf(" %d",x+i);
x = x+i;
}
else
{
printf(" %d",x-i);
x = x-i;
}
t = 1-t;
}
for(int i = k+2;i <= n;i++)
printf(" %d",i);
printf("\n");
}
return 0;
}