A. Array and Peaks | #714 Div.2

LONGNEW·2021년 7월 22일
0

CP

목록 보기
55/155

https://codeforces.com/contest/1513/problem/A
시간 1초, 메모리 256MB

input :

  • t (1 ≤ t ≤ 100)
  • n k(1 ≤ n ≤ 100)(0 <= k <= n)

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.
    t개의 줄을 출력합니다. 각 테스트 케이스에서 조건에 맞는 배열을 만들 수 없다면 -1을 출력합니다. 그렇지 않은 경우에는 공백을 포함해서 배열을 출력합니다.

조건 :

  • 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 < i < n and ai > ai−1 and ai > ai+1. If such permutation is not possible, then print −1.
    두 정수 n, k가 입력됩니다. 1 ~ n까지의 수를 이용해서 k개의 peak를 가지는 배열을 만듭니다. i를 기준으로 peak는 ai > ai−1 와 ai > ai+1를 만족해야 합니다. 이러한 배열을 만들 수 없다면 -1을 출력하시오.

결국 k개만큼의 큰 수를 자리를 지정하고 그 외의 숫자들을 나열할 수 있는지를 묻는 것이다.
입력해야 하는 수가 1 ~ n까지이니까 k개의 수만큼 짝수 위치에 n에서부터 감소하면서 위치를 지정하고 그 외의 숫자들은 빈 자리에 넣어주는 방식을 사용했다.

예외

결국 peak를 만들려면 자기보다 작은 2개의 수가 필요하다.
그러나, 가지고 있는 수의 개수가 이보다 적으면 불가능이기에 -1을 출력하도록 해야 한다.

(길이 + 1) // 2를 한 것과 k를 비교해서 같거나 k가 크다면 불가능의 경우이다.

import sys

t = int(sys.stdin.readline())
for _ in range(t):
    n, k = map(int, sys.stdin.readline().split())

    if (n + 1) // 2 <= k:
        print(-1)
        continue

    ans = [0] * n
    idx = 1
    for i in range(k):
        ans[idx] = n
        idx += 2
        n -= 1

    for i in range(len(ans)):
        if ans[i] == 0:
            ans[i] = n
            n -= 1

    print(*ans)

0개의 댓글