题目
A. Array and Peaks
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
A sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.
Given two integers n and k, construct a permutation a of numbers from 1 to n which has exactly k peaks. An index i of an array a of size n is said to be a peak if 1<iai−1 and ai>ai+1. If such permutation is not possible, then print −1.
Input
The first line contains an integer t (1≤t≤100) — the number of test cases.
Then t lines follow, each containing two space-separated integers n (1≤n≤100) and k (0≤k≤n) — the length of an array and the required number of peaks.
Output
Output t lines. For each test case, if there is no permutation with given length and number of peaks, then print −1. Otherwise print a line containing n space-separated integers which forms a permutation of numbers from 1 to n and contains exactly k peaks.
If there are multiple answers, print any.
Example
inputCopy
5
1 0
5 2
6 6
2 1
6 1
outputCopy
1
2 4 1 5 3
-1
-1
1 3 6 5 4 2
Note
In the second test case of the example, we have array a=[2,4,1,5,3]. Here, indices i=2 and i=4 are the peaks of the array. This is because (a2>a1, a2>a3) and (a4>a3, a4>a5).
代码
以下是我拙劣的代码,若有错误,欢迎指正
//LMY
#include<bits/stdc++.h>
using namespace std;
int main() {
int t,n,mid,k,flag,j,i;
int a[500]= {0},b[500];
scanf("%d",&t);
while(t--) {
flag=0;
scanf("%d%d",&n,&k);
if(n%2==0) {
mid=(n-2)/2;
}
if(n%2==1) {
mid=(n-1)/2;
}
if(k>mid) {
flag=1;
}
for(int i=1; i<=n; i++) {
a[i]=i;
}
if(n==1&&k==0) {
printf("1\n");
}
if(n==1&&k>0) {
printf("-1\n");
}
if(n==2&&k!=0) {
printf("-1\n");
}
if(n==2&&k==0) {
printf("1 2\n");
}
if(n>2&&flag==1) {
printf("-1\n");
}
if(n>2&&flag==0) {
int x=n;
int ans=0,m=1;
for(i=1; i<=k; i++) {
a[n-i*2+1]=x;
x--;
b[i]=n-i*2+1;
}
for(i=1; i<=n; i++) {
ans=0;
for(j=1; j<=k; j++) {
if(i==b[j]) {
ans=1;
break;
}
}
if(ans==0) {
a[i]=m;
m++;
}
}
for(i=1; i<=n; i++) {
printf("%d ",a[i]);
}
printf("\n");
}
}
return 0;
}