Post

[BaekJoon] 35308번 - PPPP [Java][C++]

[BaekJoon] 35308번 - PPPP [Java][C++]

문제 링크


1. 문제 풀이


주어진 조건을 보면 $P_1 = K$ 이므로 $P_{P_1} = P_K = P_2$ 다. $1$ 부터 $N$ 까지 서로 다른 정수로 만들어지는 수열이려면 $K = 2$ 여야 한다. $P_2 = a$ 라고 두면 $P_{P_{P_1}} = P_{P_2} = P_a = P_3$ 이다. $1$ 부터 $N$ 까지 서로 다른 정수로 만들어지는 수열이려면 $a = 3$ 이며 이런 과정을 반복하면 $[2, 3, 4, …, N, 1]$ 꼴의 수열이어야 함을 볼 수 있다. 이때 $N = 1$ 이면서 $K = 1$ 인 경우도 해당 조건을 만족한다. 따라서 위 조건에 따라 분기처리를 해주면 된다.


2. 코드


1. 풀이 [Java]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        StringTokenizer st;

        int t = Integer.parseInt(br.readLine());
        while (t-- > 0) {
            st = new StringTokenizer(br.readLine());
            int n = Integer.parseInt(st.nextToken());
            int k = Integer.parseInt(st.nextToken());

            if (n == 1 && k == 1) {
                sb.append("1\n");
            } else if (k != 2) {
                sb.append("-1\n");
            } else {
                for (int i = 2; i <= n; i++) {
                    sb.append(i).append(" ");
                }
                sb.append("1\n");
            }
        }

        System.out.println(sb);
    }
}


2. 풀이 [C++]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    int t;
    cin >> t;

    while (t--) {
        int n, k;
        cin >> n >> k;

        if (n == 1 && k == 1) {
            cout << 1 << '\n';
        } else if (k != 2) {
            cout << -1 << '\n';
        } else {
            for (int i = 2; i <= n; i++) {
                cout << i << ' ';
            }
            cout << 1 << '\n';
        }
    }
}

This post is licensed under CC BY 4.0 by the author.