Cerinta completa

We define to be a permutation of the first natural numbers in the range . Let denote the value at position in permutation using -based indexing.

is considered to be an absolute permutation if holds true for every .

Given and , print the lexicographically smallest absolute permutation . If no absolute permutation exists, print -1.

Example

Create an array of elements from to , . Using based indexing, create a permutation where every . It can be rearranged to so that all of the absolute differences equal :

pos[i]  i   |pos[i] - i|
  3     1        2
  4     2        2
  1     3        2
  2     4        2

Function Description

Complete the absolutePermutation function in the editor below.

absolutePermutation has the following parameter(s):

  • int n: the upper bound of natural numbers to consider, inclusive
  • int k: the absolute difference between each element’s value and its index

Returns

  • int[n]: the lexicographically smallest permutation, or if there is none

Input Format

The first line contains an integer , the number of queries.
Each of the next lines contains space-separated integers, and .

Constraints

Sample Input

STDIN   Function
-----   --------
3       t = 3 (number of queries)
2 1     n = 2, k = 1
3 0     n = 3, k = 0
3 2     n = 3, k = 2

Sample Output

2 1
1 2 3
-1

Explanation

Test Case 0:

Test Case 1:

Test Case 2:
No absolute permutation exists, so we print -1 on a new line.


Limbajul de programare folosit: java8

Cod:

import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Solution {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		int T = sc.nextInt();
		for (int tc = 0; tc < T; tc++) {
			int N = sc.nextInt();
			int K = sc.nextInt();

			int[] result = solve(N, K);
			System.out.println(result == null ? -1
					: String.join(" ", Arrays.stream(result).mapToObj(String::valueOf).collect(Collectors.toList())));
		}

		sc.close();
	}

	static int[] solve(int N, int K) {
		if (K > 0 && N % (2 * K) != 0) {
			return null;
		}

		int[] original = IntStream.range(1, N + 1).toArray();
		boolean[] used = new boolean[original.length];

		int[] result = new int[original.length];
		for (int i = 0; i < original.length; i++) {
			if (!used[i]) {
				result[i] = original[i + K];
				result[i + K] = original[i];

				used[i] = true;
				used[i + K] = true;
			}
		}
		return result;
	}
}

Scor obtinut: 1.0

Submission ID: 464602642

Link challenge: https://www.hackerrank.com/challenges/absolute-permutation/problem

Absolute Permutation