A - Mobilint Tensor Scheduling (REGULUS)

Time Limit: 2 sec / Memory Limit: 1024 MiB

表示言語

/ /

Score : 100 points

Problem Statement

Zye is writing AI inference code to run on REGULUS using Mobilint's SDK. Since Zye is a developer who is not very good at coding, the code he writes can compute only tree-shaped graphs.

Using this code, Zye wants to compute a rooted tree-shaped computation graph consisting of N tensors. The root of the tree is node 1. Node i of the tree represents a tensor of size w_i MiB.

A tensor represented by a leaf node is called an input tensor, and a tensor represented by a non-leaf node is called a result tensor. Input tensors already exist in memory in the initial state. The memory usage in the initial state is at most M MiB.

To compute the result tensor represented by node i, all tensors represented by the children of i must currently exist in memory. When computing the result tensor represented by node i, first the result tensor of size w_i MiB is allocated in memory. After the computation is finished, all tensors represented by the children of i are removed from memory.

The memory usage at a certain moment is defined as the sum of the sizes of all tensors that exist in memory at that moment.

Zye wants to choose the computation order so that the peak memory usage while computing the tensor represented by the root node is minimized. The peak memory usage is the maximum memory usage over the initial state and all moments during the computation.

The memory limit of the computer is M MiB. During the computation, the memory usage must always be at most M MiB.

Find the minimum peak memory usage needed to compute the result tensor represented by the root node.

Constraints

  • 2 \leq N \leq 5\,000
  • M = 8\,192
  • w_i = 1
  • 1 \leq p_i \leq N
  • The given graph is a rooted tree with root node 1.
  • All input values are integers.

Input

The input is given from Standard Input in the following format:

N M
w_1 w_2 \dots w_N
p_2 p_3 \dots p_N

Here, p_i denotes the parent of node i.

Output

If it is possible to compute the result tensor represented by the root node so that the peak memory usage is at most M MiB, output the minimum possible peak memory usage.

Otherwise, output OOM instead.


Sample Input 1

8 8192
1 1 1 1 1 1 1 1
1 1 2 2 4 3 3

Sample Output 1

5

In the initial state, the tensors that exist in memory are the input tensors represented by leaf nodes 5,6,7,8. Therefore, the memory usage is 1+1+1+1=4 MiB.

For example, the result tensors can be computed in the following order.

  1. Compute the result tensor represented by node 4. The maximum memory usage during this step is 4+1=5 MiB.
  2. Compute the result tensor represented by node 3. The maximum memory usage during this step is 4+1=5 MiB.
  3. Compute the result tensor represented by node 2. The maximum memory usage during this step is 3+1=4 MiB.
  4. Compute the result tensor represented by node 1. The maximum memory usage during this step is 2+1=3 MiB.

The peak memory usage for this computation order is 5 MiB. It is impossible to make the peak memory usage at most 4 MiB, so the answer is 5.

表示言語

/ /

Score : 100 points

문제

자이는 모빌린트의 SDK를 사용하여 REGULUS에서 실행할 AI 추론 코드를 작성하려고 한다. 자이는 코딩을 잘 하지 못하는 개발자이기 때문에 자이가 작성한 코드로는 트리 모양의 그래프만 계산할 수 있다.

자이는 이 코드로 텐서 N개로 이루어진 루트가 있는 트리 모양의 계산 그래프를 계산하려고 한다. 트리의 루트는 1번 노드이다. 트리의 i번 노드는 크기가 w_i MiB인 텐서를 가리킨다.

리프 노드가 가리키는 텐서를 입력 텐서, 리프가 아닌 노드가 가리키는 텐서를 결과 텐서라고 하자. 입력 텐서는 초기 상태에서 이미 메모리에 존재한다. 초기 상태의 메모리 사용량은 M MiB 이하이다.

i번 노드가 가리키는 결과 텐서를 계산하려면 i의 모든 자식 노드가 가리키는 텐서가 현재 메모리에 있어야 한다. i번 노드가 가리키는 결과 텐서를 계산할 때는 먼저 크기가 w_i MiB인 결과 텐서를 메모리에 할당하고, 계산이 끝나면 i의 모든 자식 노드가 가리키는 텐서를 메모리에서 제거한다.

어떤 시점의 메모리 사용량은 그 시점에 메모리에 존재하는 모든 텐서 크기의 합이다.

자이는 계산 순서를 적절히 조정해 루트 노드가 가리키는 텐서를 계산할 때의 피크 메모리 사용량을 최소화하려고 한다. 피크 메모리 사용량은 초기 상태와 모든 계산 과정에서의 메모리 사용량의 최댓값이다.

사용할 컴퓨터의 메모리 한도는 M MiB이다. 계산 과정에서 메모리 사용량은 항상 M MiB 이하여야 한다.

루트 노드가 가리키는 결과 텐서를 계산하는 데 필요한 피크 메모리 사용량의 최솟값을 구해 보자.

제한

  • 2 \leq N \leq 5\,000
  • M = 8\,192
  • w_i = 1
  • 1 \leq p_i \leq N
  • 주어지는 그래프는 루트가 1번인 트리이다.
  • 입력으로 주어지는 수는 모두 정수이다.

입력

입력은 다음 형식으로 표준 입력으로 주어진다.

N M
w_1 w_2 \dots w_N
p_2 p_3 \dots p_N

p_ii번 노드의 부모이다.

출력

피크 메모리 사용량이 M MiB 이하가 되도록 루트 노드가 가리키는 결과 텐서를 계산할 수 있다면 가능한 피크 메모리 사용량의 최솟값을 출력한다.

그렇지 않다면 대신 OOM을 출력한다.


입력 예 1

8 8192
1 1 1 1 1 1 1 1
1 1 2 2 4 3 3

출력 예 1

5

초기 상태에서 메모리에 존재하는 텐서는 5번, 6번, 7번, 8번 리프 노드가 가리키는 입력 텐서이다. 이때 메모리 사용량은 1+1+1+1=4 MiB이다.

예를 들어 다음 순서로 결과 텐서를 계산할 수 있다.

  1. 4번 노드가 가리키는 결과 텐서를 계산한다. 메모리 사용량의 최댓값은 4+1=5 MiB가 된다.
  2. 3번 노드가 가리키는 결과 텐서를 계산한다. 메모리 사용량의 최댓값은 4+1=5 MiB가 된다.
  3. 2번 노드가 가리키는 결과 텐서를 계산한다. 메모리 사용량의 최댓값은 3+1=4 MiB가 된다.
  4. 1번 노드가 가리키는 결과 텐서를 계산한다. 메모리 사용량의 최댓값은 2+1=3 MiB가 된다.

이 순서에서 피크 메모리 사용량은 5 MiB이다. 피크 메모리 사용량을 4 MiB 이하로 만드는 것은 불가능하므로 정답은 5이다.

表示言語

/ /

配点 : 100

問題文

ザイは Mobilint の SDK を用いて,REGULUS 上で実行する AI 推論コードを書こうとしています.ザイはコーディングがあまり得意でない開発者なので,ザイが書いたコードでは木状のグラフしか計算できません.

ザイはこのコードで,N 個のテンソルからなる根付き木状の計算グラフを計算します.木の根は頂点 1 です.木の頂点 i は,サイズが w_i MiB であるテンソルを表します.

葉が表すテンソルを入力テンソル,葉でない頂点が表すテンソルを結果テンソルと呼びます.入力テンソルは初期状態ですでにメモリ上に存在します.初期状態でのメモリ使用量は M MiB 以下です.

頂点 i が表す結果テンソルを計算するためには,i のすべての子が表すテンソルが現在メモリ上に存在している必要があります.頂点 i が表す結果テンソルを計算するときは,まずサイズ w_i MiB の結果テンソルをメモリ上に確保します.その計算が完了した直後に,i のすべての子が表すテンソルをメモリから削除します.

ある時点でのメモリ使用量を,その時点でメモリ上に存在するすべてのテンソルのサイズの総和と定義します.

ザイは計算順序を適切に選ぶことで,根が表すテンソルを計算するときのピークメモリ使用量を最小化したいです.ピークメモリ使用量とは,初期状態および計算過程のすべての時点におけるメモリ使用量の最大値です.

使用するコンピュータのメモリ上限は M MiB です.計算中のどの時点においても,メモリ使用量は M MiB 以下でなければなりません.

根が表す結果テンソルを計算するために必要なピークメモリ使用量の最小値を求めてください.

制約

  • 2 \leq N \leq 5\,000
  • M = 8\,192
  • w_i = 1
  • 1 \leq p_i \leq N
  • 与えられるグラフは頂点 1 を根とする根付き木である.
  • 入力される数値はすべて整数

入力

入力は以下の形式で標準入力から与えられる.

N M
w_1 w_2 \dots w_N
p_2 p_3 \dots p_N

ここで,p_i は頂点 i の親を表す.

出力

ピークメモリ使用量が M MiB 以下となるように根が表す結果テンソルを計算できるならば,可能なピークメモリ使用量の最小値を出力する.

そうでなければ,代わりに OOM を出力する.


入力例 1

8 8192
1 1 1 1 1 1 1 1
1 1 2 2 4 3 3

出力例 1

5

初期状態では,葉である頂点 5,6,7,8 が表す入力テンソルがメモリ上に存在します.したがって,このときのメモリ使用量は 1+1+1+1=4 MiB です.

例えば,次の順序で結果テンソルを計算できます.

  1. 頂点 4 が表す結果テンソルを計算する.このステップ中のメモリ使用量の最大値は 4+1=5 MiB である.
  2. 頂点 3 が表す結果テンソルを計算する.このステップ中のメモリ使用量の最大値は 4+1=5 MiB である.
  3. 頂点 2 が表す結果テンソルを計算する.このステップ中のメモリ使用量の最大値は 3+1=4 MiB である.
  4. 頂点 1 が表す結果テンソルを計算する.このステップ中のメモリ使用量の最大値は 2+1=3 MiB である.

この計算順序におけるピークメモリ使用量は 5 MiB です.ピークメモリ使用量を 4 MiB 以下にすることはできないため,答えは 5 です.

B - SCSC Card Game

Time Limit: 2 sec / Memory Limit: 1024 MiB

表示言語

/ /

Score : 100 points

Problem Statement

SCSC has N members. Each member has one spade card and one club card. Member i's spade card has integer S_i written on it, and their club card has integer C_i written on it.

The members of SCSC are standing in a line in the order from member 1 to member N to play the SCSC card game. Terra, the host of the game, must choose two adjacent members and make them play one of the following two duels.

  • The two members each reveal the spade card with the smallest integer among their spade cards. The member who reveals the card with the larger integer wins. The losing member gives all of their club cards to the winning member and leaves.

  • The two members each reveal the club card with the smallest integer among their club cards. The member who reveals the card with the larger integer wins. The losing member gives all of their spade cards to the winning member and leaves.

Any cards that the leaving member does not give to the winning member are no longer used in the game. If there were members on both sides of the leaving member, those two members become adjacent to each other.

After N-1 duels, exactly one member remains.

The last remaining member gives Terra one card with the smallest integer among their spade cards and one card with the smallest integer among their club cards, then leaves.

Let S_{\mathrm{sum}} be the sum of the integers written on all spade cards initially held by all members, and let C_{\mathrm{sum}} be the sum of the integers written on all club cards initially held by all members. Let S_f be the integer written on the spade card Terra receives at the end, and let C_f be the integer written on the club card Terra receives at the end. Then Terra's final score is (S_{\mathrm{sum}} - S_f)(C_{\mathrm{sum}} - C_f).

Terra wants the final score to be as small as possible. Find the minimum possible score Terra can obtain.

Constraints

  • 1 \leq N \leq 5\,000
  • 1 \leq S_i, C_i \leq 50\,000
  • For all 1 \leq i < j \leq N, S_i \neq S_j and C_i \neq C_j.
  • All given numbers are integers.

Input

The input is given from Standard Input in the following format:

N
S_1 C_1
S_2 C_2
\vdots
S_N C_N

Output

Output the minimum possible score Terra can obtain.


Sample Input 1

2
3 4
4 5

Sample Output 1

15

表示言語

/ /

Score : 100 points

문제

SCSC에는 N명의 부원이 있다. 각 부원은 스페이드 카드클로버 카드를 한 장씩 가지고 있다. i번 부원이 가진 스페이드 카드에는 정수 S_i, 클로버 카드에는 정수 C_i가 적혀 있다.

SCSC 부원들은 SCSC 카드 놀이를 하기 위해 1번부터 N번까지 순서대로 서 있다. 게임의 진행자인 테라는 인접하게 서 있는 두 부원을 골라 다음 두 가지 대결 중 하나를 시켜야 한다.

  • 두 부원이 각자 자신이 가진 스페이드 카드 중 적힌 수가 가장 작은 카드를 공개한다. 더 큰 수가 적힌 카드를 공개한 부원이 승리한다. 패배한 부원은 자신이 가진 클로버 카드를 모두 승리한 부원에게 넘겨주고 퇴장한다.

  • 두 부원이 각자 자신이 가진 클로버 카드 중 적힌 수가 가장 작은 카드를 공개한다. 더 큰 수가 적힌 카드를 공개한 부원이 승리한다. 패배한 부원은 자신이 가진 스페이드 카드를 모두 승리한 부원에게 넘겨주고 퇴장한다.

퇴장한 부원이 승리한 부원에게 넘겨주지 않은 카드는 더 이상 게임에 사용되지 않는다. 퇴장한 부원의 양옆에 부원이 모두 있었다면 그 두 부원은 새로 인접하게 된다.

N-1번 대결을 하고 나면 마지막에 단 한 명의 부원만 남는다.

마지막에 남은 부원은 자신이 가진 스페이드 카드 중 적힌 수가 가장 작은 카드 한 장과 클로버 카드 중 적힌 수가 가장 작은 카드 한 장을 테라에게 주고 퇴장한다.

처음 모든 부원이 가진 스페이드 카드에 적힌 정수의 합을 S_{\mathrm{sum}}, 클로버 카드에 적힌 정수의 합을 C_{\mathrm{sum}}이라고 하자. 마지막에 테라가 받은 스페이드 카드에 적힌 수를 S_f, 클로버 카드에 적힌 수를 C_f라고 하면, 테라의 최종 점수는 (S_{\mathrm{sum}} - S_f)(C_{\mathrm{sum}} - C_f)가 된다.

테라는 마지막에 얻게 되는 점수를 최소화하고자 한다. 테라가 얻을 수 있는 점수의 최솟값을 구해 보자.

제한

  • 1 \leq N \leq 5\,000
  • 1 \leq S_i, C_i \leq 50\,000
  • 모든 1 \leq i < j \leq N에 대해 S_i \neq S_j이고 C_i \neq C_j이다.
  • 입력으로 주어지는 수는 모두 정수이다.

입력

입력은 다음 형식으로 표준 입력으로 주어진다.

N
S_1 C_1
S_2 C_2
\vdots
S_N C_N

출력

테라가 얻을 수 있는 점수의 최솟값을 출력한다.


입력 예 1

2
3 4
4 5

출력 예 1

15

表示言語

/ /

配点 : 100

問題文

SCSC には N 人の部員がいる.各部員は スペードカードクラブカード1 枚ずつ持っている.部員 i が持つスペードカードには整数 S_i が,クラブカードには整数 C_i が書かれている.

SCSC の部員たちは,SCSC カードゲームをするために 1 番から N 番まで順番に一列に並んでいる.ゲームの進行役であるテラは,隣り合う 2 人の部員を選び,次の 2 種類の対戦のうち一方をさせなければならない.

  • 2 人の部員がそれぞれ,自分が持つスペードカードのうち書かれている整数が最も小さいカードを公開する.より大きい整数が書かれたカードを公開した部員が勝利する.敗北した部員は自分が持つクラブカードをすべて勝利した部員に渡して退場する.

  • 2 人の部員がそれぞれ,自分が持つクラブカードのうち書かれている整数が最も小さいカードを公開する.より大きい整数が書かれたカードを公開した部員が勝利する.敗北した部員は自分が持つスペードカードをすべて勝利した部員に渡して退場する.

退場した部員が勝利した部員に渡さなかったカードは,以後ゲームでは使用されない.退場した部員の両隣に部員がともに存在した場合,その 2 人の部員は新たに隣り合うことになる.

N-1 回の対戦を行うと,最後にはただ 1 人の部員だけが残る.

最後に残った部員は,自分が持つスペードカードのうち書かれている整数が最も小さいカード 1 枚と,クラブカードのうち書かれている整数が最も小さいカード 1 枚をテラに渡して退場する.

最初にすべての部員が持つスペードカードに書かれた整数の合計を S_{\mathrm{sum}},クラブカードに書かれた整数の合計を C_{\mathrm{sum}} とする.最後にテラが受け取ったスペードカードに書かれた整数を S_f,クラブカードに書かれた整数を C_f とすると,テラの最終得点は (S_{\mathrm{sum}} - S_f)(C_{\mathrm{sum}} - C_f) となる.

テラは最後に得られる得点をできるだけ小さくしたい.テラが得られる得点の最小値を求めよ.

制約

  • 1 \leq N \leq 5\,000
  • 1 \leq S_i, C_i \leq 50\,000
  • すべての 1 \leq i < j \leq N について,S_i \neq S_j かつ C_i \neq C_j である.
  • 入力される数値はすべて整数である.

入力

入力は以下の形式で標準入力から与えられる.

N
S_1 C_1
S_2 C_2
\vdots
S_N C_N

出力

テラが得られる得点の最小値を出力せよ.


入力例 1

2
3 4
4 5

出力例 1

15
C - Rearrangement

Time Limit: 2 sec / Memory Limit: 1024 MiB

表示言語

/ /

Score : 100 points

Problem Statement

You are given an integer array A=[A_1,\dots,A_N] of length N and an integer array B=[B_1,\dots,B_M] of length M.

Find a rearrangement of A in which the number of occurrences of B as a contiguous subsequence is maximized. Here, a rearrangement of A means an array A' satisfying the following condition.

  • A' is an integer array of length N, and there exists a permutation P of 1,\dots,N such that A'_i=A_{P_i}(1 \le i \le N).
What is a contiguous subsequence? A contiguous subsequence of a sequence is a sequence obtained by taking elements from consecutive positions of the original sequence, in the same order. For example, in the sequence [1,2,3,4], [2,3] is a contiguous subsequence, but [1,3] is not. Multiple contiguous subsequences may overlap with each other in the same sequence. For example, in the sequence [1,2,1,2,1], [1,2,1] appears a total of 2 times.
What is a permutation? A permutation of length N is a sequence that contains each integer from 1 to N exactly once. For example, [2,1,4,3] is a permutation, but [4,2,1,1] and [1,2,3,5] are not.

Constraints

  • 1 \le M \le N \le 1\,000\,000
  • 0 \le A_i, B_i \le 1\,000\,000
  • All given numbers are integers.

Input

The input is given from Standard Input in the following format:

N M
A_1 A_2 \dots A_N
B_1 B_2 \dots B_M

Output

Output the elements of a rearrangement of A that maximizes the number of occurrences of B as a contiguous subsequence, separated by spaces. If there are multiple such rearrangements, output any one of them.


Sample Input 1

4 2
1 2 3 4
2 1

Sample Output 1

2 1 3 4 

Sample Input 2

4 2
1 2 1 2
2 1

Sample Output 2

2 1 2 1 

表示言語

/ /

점수 : 100

문제

길이가 N인 정수 배열 A=[A_1,\dots,A_N], 길이가 M인 정수 배열 B=[B_1,\dots,B_M]가 주어진다.

A의 재배열 중 B가 연속 부분 수열로 등장하는 횟수가 최대가 되는 배열을 구하시오. 이때 A재배열이란 다음을 만족하는 배열 A'을 의미한다.

  • A'은 길이가 N인 정수 배열이고, A'_i=A_{P_i}(1 \le i \le N)인 길이 N인 순열 P가 존재한다.
연속 부분 수열이란 어떤 수열의 연속 부분 수열은 원래 수열에서 연속한 위치의 원소들을 순서대로 가져온 수열이다. 예를 들어 수열 [1, 2, 3, 4]에서 [2, 3]은 연속 부분 수열이지만, [1, 3]은 연속 부분 수열이 아니다. 같은 수열 안에서 여러 연속 부분 수열이 서로 겹쳐서 등장할 수도 있다. 예를 들어 수열 [1, 2, 1, 2, 1]에서 [1, 2, 1]은 총 2회 등장한다.
순열이란 길이가 N순열1부터 N까지의 정수가 정확히 한 번씩 등장하는 수열이다. 예를 들어 [2,1,4,3]은 순열이지만 [4,2,1,1]이나 [1,2,3,5]는 순열이 아니다.

제한

  • 1 \le M \le N \le 10^6
  • 0 \le A_i, B_i \le 10^6
  • 입력으로 주어지는 수는 모두 정수이다.

입력

입력은 다음 형식으로 표준 입력으로 주어진다.

N M
A_1 A_2 \dots A_N
B_1 B_2 \dots B_M

출력

B가 연속 부분 수열로 등장하는 횟수가 최대화되는 A의 재배열의 원소를 순서대로 공백으로 구분하여 출력한다.

조건을 만족하는 재배열이 여러 가지라면 그중 아무거나 출력한다.


입력 예 1

4 2
1 2 3 4
2 1

출력 예 1

2 1 3 4 

입력 예 2

4 2
1 2 1 2
2 1

출력 예 2

2 1 2 1 

表示言語

/ /

配点 : 100

問題文

長さ N の整数配列 A=[A_1,\dots,A_N] と,長さ M の整数配列 B=[B_1,\dots,B_M] が与えられる.

A の並べ替えのうち,B が連続部分列として現れる回数が最大になる配列を求めよ.ここで,A並べ替えとは,次の条件を満たす配列 A' を意味する.

  • A' は長さ N の整数配列であり,A'_i=A_{P_i}(1 \le i \le N) となる 1,\dots,N の順列 P が存在する.
連続部分列とは ある数列の 連続部分列 とは,元の数列から連続した位置の要素を順番に取り出してできる数列である.例えば,数列 [1,2,3,4] において [2,3] は連続部分列であるが,[1,3] は連続部分列ではない. 同じ数列の中で,複数の連続部分列が互いに重なって現れることもある.例えば,数列 [1,2,1,2,1] において [1,2,1] は合計 2 回現れる.
順列とは 長さ N順列 とは,1 から N までの整数をちょうど一度ずつ含む数列である.例えば [2,1,4,3] は順列であるが,[4,2,1,1][1,2,3,5] は順列ではない.

制約

  • 1 \le M \le N \le 1\,000\,000
  • 0 \le A_i, B_i \le 1\,000\,000
  • 入力される数値はすべて整数

入力

入力は以下の形式で標準入力から与えられる.

N M
A_1 A_2 \dots A_N
B_1 B_2 \dots B_M

出力

B が連続部分列として現れる回数が最大になる A の並べ替えの要素を,順に空白区切りで出力せよ.

条件を満たす並べ替えが複数存在する場合,そのうちどれを出力してもよい.


入力例 1

4 2
1 2 3 4
2 1

出力例 1

2 1 3 4 

入力例 2

4 2
1 2 1 2
2 1

出力例 2

2 1 2 1 
D - Coloring

Time Limit: 2 sec / Memory Limit: 1024 MiB

表示言語

/ /

Score : 100 points

Problem Statement

Lulu and Terra are playing with red, green, and blue paints.

Lulu and Terra want to paint a picture consisting of N square cells arranged in a row. Terra first painted part of the picture and then handed the rest over to Lulu. The picture painted by Terra can be represented by a string S of length N consisting of R, G, B, and X. If the i-th character of S is R, the i-th cell is painted red; if it is G, it is painted green; if it is B, it is painted blue; and if it is X, it is an unpainted empty cell.

Lulu does not like the picture Terra painted, so Lulu decided to cut out a certain interval of the picture and make that interval into a perfect picture. According to Lulu, a perfect picture is a picture satisfying the following two conditions.

  1. Every cell must be painted one of red, green, and blue.

  2. Lulu likes colorful things, so any two adjacent cells must always have different colors.

Lulu can paint empty cells that Terra did not paint in any desired color, and can also repaint cells Terra has already painted in a different color.

The interval Lulu cuts out is represented by two integers l and r, meaning the consecutive interval from the l-th cell to the r-th cell from the left. For each of the Q ways to cut out a certain interval, tell Lulu the minimum number of cells that must be repainted to make the interval a perfect picture.

Constraints

  • 1 \leq N, Q \leq 300\,000
  • The string S consists only of uppercase letters R, G, B, and X.
  • For each query, 1 \leq l_i \leq r_i \leq N.
  • All given numbers are integers.

Input

The input is given from Standard Input in the following format:

N Q
S
l_1 r_1
l_2 r_2
\vdots
l_Q r_Q

Output

Print Q lines. For each case, print one line containing the minimum number of cells Lulu must repaint to complete the perfect picture.


Sample Input 1

8 3
RRXGGGBR
1 8
4 5
2 7

Sample Output 1

2
1
1

表示言語

/ /

Score : 100 points

문제

루루와 테라는 빨간색, 초록색, 파란색 물감을 가지고 색칠 놀이를 하고 있다.

루루와 테라는 N개의 정사각형 칸이 일렬로 연결된 그림을 색칠하려 한다. 테라가 먼저 그림의 일부를 칠한 뒤 남은 부분을 루루에게 넘겨주었다. 테라가 칠한 그림은 R, G, B, X로 이루어진 길이 N의 문자열 S로 표현할 수 있다. 문자열 Si번째 문자가 R이면 빨간색, G이면 초록색, B이면 파란색, X이면 칠해지지 않은 빈칸을 의미한다.

루루는 테라가 칠해 놓은 그림이 마음에 들지 않아 그림의 특정 구간을 잘라내어 구간을 완벽한 그림으로 만들기로 했다. 루루가 생각한 완벽한 그림은 다음 두 조건을 만족하는 그림이다.

  1. 모든 칸은 빨간색, 초록색, 파란색 중 하나로 칠해져야 한다.

  2. 루루는 알록달록한 것을 좋아하기 때문에 인접한 두 칸의 색은 항상 달라야 한다.

루루는 테라가 칠하지 않은 비어 있는 칸을 원하는 색으로 칠할 수 있고 테라가 칠했던 칸의 색을 다른 색으로 덧칠할 수도 있다.

루루가 잘라낼 구간은 두 정수 lr로 표현되며, 이는 왼쪽에서 l번째 칸부터 r번째 칸까지의 연속한 구간을 의미한다. 특정 구간을 잘라내는 Q가지 경우에 대해 루루가 최소 몇 번 덧칠을 해야 완벽한 그림을 만들 수 있는지 알아내 보자.

제한

  • 1 \leq N, Q \leq 300\,000
  • 문자열 S는 대문자 R, G, B, X로만 이루어져 있다.
  • 1 \leq l_i \leq r_i \leq N
  • 입력으로 주어지는 수는 모두 정수이다.

입력

입력은 다음 형식으로 표준 입력으로 주어진다.

N Q
S
l_1 r_1
l_2 r_2
\vdots
l_Q r_Q

출력

Q개의 줄에 걸쳐 각 경우마다 루루가 완벽한 그림을 완성하는 데 필요한 덧칠의 최소 횟수를 한 줄에 하나씩 출력한다.


입력 예 1

8 3
RRXGGGBR
1 8
4 5
2 7

출력 예 1

2
1
1

表示言語

/ /

配点 : 100

問題文

ルルとテラは赤色,緑色,青色の絵の具で塗り絵をしている.

ルルとテラは N 個の正方形のマスが一列につながった絵を塗ろうとしている.テラが先に絵の一部を塗った後,残りの部分をルルに渡した.テラが塗った絵は R, G, B, X からなる長さ N の文字列 S で表される.文字列 Si 番目の文字が R なら赤色,G なら緑色,B なら青色,X なら塗られていない空のマスを表す.

ルルはテラが塗った絵が気に入らず,絵の特定の区間を切り出して,その区間を 完璧な絵 にすることにした.ルルが考える 完璧な絵 とは,次の 2 つの条件を満たす絵である.

  1. すべてのマスは赤色,緑色,青色のいずれかで塗られていなければならない.

  2. ルルは色とりどりなものが好きなので,隣り合う 2 つのマスの色は常に異ならなければならない.

ルルは,テラが塗っていない空のマスを好きな色で塗ることができ,テラがすでに塗ったマスの色を別の色に塗り直すこともできる.

ルルが切り出す区間は 2 つの整数 lr で表され,これは左から l 番目のマスから r 番目のマスまでの連続した区間を意味する.特定の区間を切り出す Q 通りの場合について,ルルが 完璧な絵 を作るために塗り直す必要があるマスの最小個数を求めよ.

制約

  • 1 \leq N, Q \leq 300\,000
  • 文字列 S は英大文字 R, G, B, X のみからなる.
  • 各クエリについて,1 \leq l_i \leq r_i \leq N
  • 入力される数値はすべて整数である.

入力

入力は以下の形式で標準入力から与えられる.

N Q
S
l_1 r_1
l_2 r_2
\vdots
l_Q r_Q

出力

Q 行にわたり,各場合について,ルルが 完璧な絵 を完成させるために塗り直す必要があるマスの最小個数を 1 行に出力せよ.


入力例 1

8 3
RRXGGGBR
1 8
4 5
2 7

出力例 1

2
1
1
E - Opening Magical Box

Time Limit: 2 sec / Memory Limit: 1024 MiB

表示言語

/ /

Score : 100 points

Problem Statement

Lulu found a magical box containing treasure. The box has N distinct spells cast on it, one of each type, and it can be opened only by dispelling all of them in the correct order. Lulu, a genius magician, has identified all N types of spells on the box, but does not know the correct order in which they must be dispelled.

To open the box, Lulu attempts the following procedure.

  1. Lulu chooses one spell that is still cast on the box among the N spells and tries to dispel it. When Lulu tries to dispel the i-th spell, M_i magic power is consumed.

  2. If the attempted spell is the correct spell in the order, the dispelling succeeds. If it is not the correct spell in the order, the box returns to the state where all N spells are cast on it. Lulu can immediately tell whether the dispelling attempt succeeded. The order required for dispelling the spells does not change.

  3. Once all N spells are dispelled, the box opens.

Given N and the magic power cost M_i of each spell, find the expected total amount of magic power Lulu will consume if Lulu opens the box using an optimal strategy. The correct order of spells is one of the N! possible orders, and all possible orders are equally likely.

Constraints

  • 1 \leq N \leq 100\,000
  • 1 \leq M_i \leq 100\,000
  • All given numbers are integers.

Input

The input is given from Standard Input in the following format:

N
M_1 M_2 \dots M_N

Output

Output the expected total amount of magic power Lulu will consume. An absolute or relative error of at most 10^{-6} is accepted.


Sample Input 1

1
10

Sample Output 1

10

Sample Input 2

2
10 20

Sample Output 2

35

表示言語

/ /

Score : 100 points

문제

루루는 보물이 담긴 마법의 상자를 발견했다. 상자에는 서로 다른 N가지의 마법이 한 번씩 걸려 있으며, 이를 정확한 순서대로 모두 해제해야만 상자를 열 수 있다. 천재 마법사인 루루는 상자에 걸려 있는 N가지 마법의 종류는 전부 알아냈지만 해제해야 할 올바른 순서는 알지 못한다.

루루는 상자를 열기 위해 아래와 같은 방법으로 상자 열기를 시도한다.

  1. 루루는 N가지 마법 중 아직 상자에 걸려 있는 마법 하나를 선택하여 해제를 시도한다. i번째 마법을 해제 시도할 때 M_i의 마력이 소모된다.

  2. 만약 해제 시도한 마법이 순서에 맞는 마법이라면 해제에 성공한다. 순서에 맞지 않는 마법이라면 N가지 마법이 모두 걸린 상태로 되돌아간다. 해제 시도가 성공했는지 바로 알 수 있다. 해제하는 데 필요한 마법의 순서는 바뀌지 않는다.

  3. N개의 마법이 모두 해제되면 상자가 열린다.

N과 각 마법의 소모 마력 M_i가 주어질 때 루루가 최적의 전략으로 상자를 연다면 소모하게 될 마력 합의 기댓값을 구해 보자. 상자를 여는 올바른 마법의 순서는 N!가지 중 하나이며, 모든 가능한 순서가 올바른 순서일 확률은 동일하다.

제한

  • 1 \leq N \leq 100\,000
  • 1 \leq M_i \leq 100\,000
  • 입력으로 주어지는 수는 모두 정수이다.

입력

입력은 다음 형식으로 표준 입력으로 주어진다.

N
M_1 M_2 \dots M_N

출력

루루가 소모하게 될 마력 합의 기댓값을 출력한다. 절대/상대 오차는 10^{-6}까지 허용한다.


입력 예 1

1
10

출력 예 1

10

입력 예 2

2
10 20

출력 예 2

35

表示言語

/ /

配点 : 100

問題文

ルルは宝物が入った魔法の箱を見つけた.箱には互いに異なる N 種類の魔法が 1 回ずつかけられており,それらを正しい順序ですべて解除しなければ箱を開けることができない.天才魔法使いであるルルは,箱にかけられている N 種類の魔法の種類はすべて特定したが,解除すべき正しい順序は知らない.

ルルは箱を開けるため,次の方法で箱を開けようとする.

  1. ルルは N 種類の魔法のうち,まだ箱にかかっている魔法を 1 つ選び,解除を試みる.i 番目の魔法の解除を試みると,M_i の魔力が消費される.

  2. 解除を試みた魔法が順序に合う魔法なら解除に成功する.順序に合わない魔法なら,N 種類の魔法がすべてかかった状態に戻る.解除の試みが成功したかどうかはすぐに分かる.解除に必要な魔法の順序は変わらない.

  3. N 個の魔法がすべて解除されると箱が開く.

N と各魔法の消費魔力 M_i が与えられる.ルルが最適な戦略で箱を開けるとき,消費する魔力の合計の期待値を求めよ.箱を開ける正しい魔法の順序は N! 通りのうちの 1 つであり,すべての順序が正解である確率は等しい.

制約

  • 1 \leq N \leq 100\,000
  • 1 \leq M_i \leq 100\,000
  • 入力される数値はすべて整数である.

入力

入力は以下の形式で標準入力から与えられる.

N
M_1 M_2 \dots M_N

出力

ルルが消費する魔力の合計の期待値を出力せよ.絶対誤差または相対誤差は 10^{-6} まで許容される.


入力例 1

1
10

出力例 1

10

入力例 2

2
10 20

出力例 2

35
F - The Kth Smallest Number

Time Limit: 2 sec / Memory Limit: 1024 MiB

表示言語

/ /

Score : 100 points

Problem Statement

An infinite sequence (a_n) satisfies the following property.

  • For every positive integer i satisfying i>N, a_i is equal to the K-th element of a_{i-N},a_{i-N+1},\dots,a_{i-1} after these values are sorted in nondecreasing order.

Once the values of a_1,\dots,a_N are determined, the values of a_{N+1},a_{N+2},\dots are uniquely determined.

You are given the values of N, K, M and a_1,\dots,a_N. Find a_M.

Constraints

  • 1 \leq K \leq N \leq 300\,000
  • 1 \leq M \leq 10^{18}
  • -10^9 \leq a_i \leq 10^9
  • All input values are integers.

Input

The input is given from Standard Input in the following format:

N K M
a_1 a_2 \dots a_N

Output

Output the answer.


Sample Input 1

8 6 9
2 0 2 6 0 5 1 6

Sample Output 1

5

Sorting [2,0,2,6,0,5,1,6] in nondecreasing order, we have [0,0,1,2,2,5,6,6]. Since K=6, we have a_9=5.


Sample Input 2

1 1 1
1

Sample Output 2

1

表示言語

/ /

점수 : 100

문제

수열 (a_n)은 다음 성질을 만족하는 무한 수열이다.

  • i>N을 만족하는 모든 양의 정수 i에 대하여 a_{i-N},a_{i-N+1},\dots,a_{i-1}을 오름차순으로 정렬할 때 K번째에 오는 수가 a_i와 같다.

a_1,\dots,a_N의 값이 결정되면 a_{N+1},a_{N+2},\dots의 값은 유일하게 결정된다.

N, K, Ma_1,\dots, a_N의 값이 주어질 때 a_M의 값을 구해 보자.

제한

  • 1 \leq K \leq N \leq 300\,000
  • 1 \leq M \leq 10^{18}
  • -10^9 \leq a_i \leq 10^9
  • 입력으로 주어지는 수는 모두 정수이다.

입력

입력은 다음 형식으로 표준 입력으로 주어진다.

N K M
a_1 a_2 \dots a_N

출력

a_M을 출력한다.


입력 예 1

8 6 9
2 0 2 6 0 5 1 6

출력 예 1

5

[2,0,2,6,0,5,1,6]을 오름차순으로 나열하면 [0,0,1,2,2,5,6,6]이고 K=6이므로 a_9=5이다.


입력 예 2

1 1 1
1

출력 예 2

1

表示言語

/ /

配点 : 100

問題文

無限数列 (a_n) は次の性質を満たします.

  • i>N を満たすすべての正整数 i に対し,a_ia_{i-N},a_{i-N+1},\dots,a_{i-1} を昇順に並べたときの K 番目の数に等しい.

a_1,\dots,a_N の値が決まると,a_{N+1},a_{N+2},\dots の値は一意に決まります.

N, K, Ma_1,\dots,a_N の値が与えられます.a_M の値を求めてください.

制約

  • 1 \leq K \leq N \leq 300\,000
  • 1 \leq M \leq 10^{18}
  • -10^9 \leq a_i \leq 10^9
  • 入力はすべて整数

入力

入力は以下の形式で標準入力から与えられる.

N K M
a_1 a_2 \dots a_N

出力

a_M を出力せよ.


入力例 1

8 6 9
2 0 2 6 0 5 1 6

出力例 1

5

[2,0,2,6,0,5,1,6] を昇順に並べると [0,0,1,2,2,5,6,6] になります.K=6 なので,a_9=5 です.


入力例 2

1 1 1
1

出力例 2

1

G - SCSC Game

Time Limit: 2 sec / Memory Limit: 1024 MiB

表示言語

/ /

Score : 100 points

Problem Statement

This year, FuriosaAI officially announced mass production of RNGD, its second-generation AI accelerator. RNGD is specialized for processing language models and multimodal models, and provides powerful computing performance even with low power consumption.

At SCSC, AI agents Lulu and Terra were created using RNGD chips, and SCSC had them play the SCSC game for performance testing.

The SCSC game is played with a string S consisting of uppercase letters S and C that does not contain SCSC as a substring. Lulu and Terra take turns, with Terra going first. On each turn, the current player chooses one character from the string and removes it. If, after the removal, the string contains SCSC as a substring, that player wins and the other player loses. If the current player can no longer choose any character to remove, that player loses and the other player wins.

Thanks to the powerful computing performance of the RNGD chips, Lulu and Terra have become able to always find optimal moves to win. Given the string S, determine which agent wins the game if both Lulu and Terra play optimally.

What is a substring? A substring of a string is a contiguous part of the original string. For example, `bc` is a substring of `abcd`, but `ac` is not. Multiple substrings may overlap within the same string. For example, `aba` appears a total of 2 times in `ababa`.

Constraints

  • 1 \leq T \leq 10\,000
  • 1 \leq |S| \leq 200\,000
  • S consists only of uppercase letters S and C, and does not contain SCSC as a substring.
  • The sum of |S| over all test cases does not exceed 200\,000.

Input

The input is given from Standard Input in the following format:

T
\mathrm{case}_1
\mathrm{case}_2
\vdots
\mathrm{case}_T

Each test case is given in the following format:

S

Output

For each test case, output Terra if Terra wins, and Lulu if Lulu wins, one per line.


Sample Input 1

2
SCSSCCS
SSSS

Sample Output 1

Terra
Lulu

表示言語

/ /

Score : 100 points

문제

FuriosaAI는 올해 공식적으로 2세대 AI 가속기 RNGD의 대량 생산을 발표했다. RNGD는 언어 모델 및 멀티모달 모델 처리에 특화된 제품으로, 적은 전력으로도 강력한 연산 성능을 제공한다.

SCSC에서는 RNGD 칩을 이용해 AI 에이전트 루루와 테라를 제작하고 성능 테스트를 위해 SCSC 게임을 플레이하도록 했다.

SCSC 게임은 알파벳 대문자 SC로 이루어진 문자열 중 SCSC를 부분문자열로 가지지 않는 문자열 S를 가지고 진행하는 게임이다. 루루와 테라는 테라부터 시작해 번갈아 가며 S의 문자 하나를 선택해 제거한다. 제거한 뒤 SSCSC를 부분문자열로 가지면 해당 에이전트가 승리하고 상대방이 패배한다. 만약 더 이상 문자를 선택해 제거할 수 없으면 해당 에이전트가 패배하고 상대방이 승리한다.

RNGD 칩의 강력한 연산 성능으로 루루와 테라는 항상 이기기 위한 최선의 행동을 찾아낼 수 있게 되었다. 문자열 S가 주어질 때 루루와 테라가 모두 최선의 행동을 하면 어느 에이전트가 게임에서 승리할지 구해 보자.

부분문자열이란 어떤 문자열의 부분문자열은 원래 문자열의 연속된 일부이다. 예를 들어 문자열 `abcd`에서 `bc`는 부분문자열이지만, `ac`는 부분문자열이 아니다. 같은 문자열 안에서 여러 부분문자열이 서로 겹쳐서 등장할 수도 있다. 예를 들어 문자열 `ababa`에서 `aba`는 총 2회 등장한다.

제한

  • 1 \leq T \leq 10\,000
  • 1 \leq |S| \leq 200\,000
  • S는 대문자 SC로만 이루어져 있으며, SCSC를 부분문자열로 가지지 않는다.
  • 모든 테스트 케이스의 |S|의 합은 200\,000을 넘지 않는다.

입력

입력은 다음 형식으로 표준 입력으로 주어진다.

T
\mathrm{case}_1
\mathrm{case}_2
\vdots
\mathrm{case}_T

각 테스트 케이스는 다음 형식으로 주어진다.

S

출력

각 테스트 케이스마다 테라가 이기면 Terra, 루루가 이기면 Lulu를 한 줄에 하나씩 출력한다.


입력 예 1

2
SCSSCCS
SSSS

출력 예 1

Terra
Lulu

表示言語

/ /

配点 : 100

問題文

FuriosaAI は今年,第 2 世代 AI アクセラレータである RNGD の大量生産を正式に発表した.RNGD は言語モデルおよびマルチモーダルモデルの処理に特化した製品であり,少ない電力でも強力な演算性能を提供する.

SCSC では RNGD チップを用いて AI エージェントのルルとテラを作成し,性能テストのために SCSC ゲームをプレイさせた.

SCSC ゲームは,英大文字 SC からなる文字列のうち,SCSC を部分文字列として含まない文字列 S を用いて行うゲームである. ルルとテラはテラを先手として,交互に文字列の文字を 1 つ選んで削除する. 削除した後,文字列が SCSC を部分文字列として含むなら,そのプレイヤーが勝利し,相手が敗北する. もしこれ以上文字を選んで削除できなければ,そのプレイヤーが敗北し,相手が勝利する.

RNGD チップの強力な演算性能により,ルルとテラは常に勝つための最善の行動を見つけられるようになった. 文字列 S が与えられたとき,ルルとテラがともに最善の行動をとるなら,どちらのエージェントがゲームに勝利するか求めよ.

部分文字列とは ある文字列の 部分文字列 とは,元の文字列の連続した一部分である.例えば,文字列 `abcd` において `bc` は部分文字列であるが,`ac` は部分文字列ではない. 同じ文字列の中で,複数の部分文字列が互いに重なって現れることもある.例えば,文字列 `ababa` において `aba` は合計 2 回現れる.

制約

  • 1 \leq T \leq 10\,000
  • 1 \leq |S| \leq 200\,000
  • S は英大文字 SC のみからなり,SCSC を部分文字列として含まない.
  • すべてのテストケースにおける |S| の総和は 200\,000 を超えない.

入力

入力は以下の形式で標準入力から与えられる.

T
\mathrm{case}_1
\mathrm{case}_2
\vdots
\mathrm{case}_T

各テストケースは次の形式で与えられる.

S

出力

各テストケースについて,テラが勝つなら Terra,ルルが勝つなら Lulu1 行に出力せよ.


入力例 1

2
SCSSCCS
SSSS

出力例 1

Terra
Lulu
H - CUBRID HA Load Balance

Time Limit: 2 sec / Memory Limit: 1024 MiB

表示言語

/ /

Score : 100 points

Problem Statement

A CUBRID HA cluster is a system consisting of N servers. The servers are numbered from 1 to N.

Jank has become the server administrator of SCSC and wants to choose some of the servers in the CUBRID HA cluster to use. Jank turns on the servers he chooses and turns off the servers he does not choose.

Jank, who rules SCSC, chooses whether each chosen server operates as a Master or as a Slave when turning it on. A Master server can process RW requests and RO requests, and a Slave server can process RO requests and SO requests. Each server can process at most one request at the same time.

If there is no Master server among the currently turned-on servers and at least one Slave server is currently turned on, the currently turned-on Slave server with the smallest number immediately becomes a Master server.

Jank, who rules SCSC, must process Q queries of the following two types in order.

  • 1 i: Turn off server i. If it is already turned off, ignore this query.
  • 2 a b c: a RW requests, b RO requests, and c SO requests arrive simultaneously.

The requests that arrive in a type-2 query must all be processed using only the servers that are currently turned on. Each request must be assigned to a server that can process that request, and at most one request can be assigned to each server. A request that is not assigned when the query is given cannot be processed.

When all requests have been assigned, each server processes its assigned request and discards the processed request. A server with no remaining request becomes ready to process another request again.

Find the minimum number of servers Jank, who rules SCSC, must choose initially in order to process all requests. If it is impossible to process all requests by any method, output -1 instead.

Constraints

  • 1 \leq N,Q \leq 2\,000
  • 1 \leq i \leq N
  • 0 \leq a,b,c \leq N
  • There is at least one query of the second type.
  • All input values are integers.

Input

The input is given from Standard Input in the following format:

N Q
\mathrm{query}_1
\mathrm{query}_2
\vdots
\mathrm{query}_Q

Each query is in one of the following two formats:

1 i
2 a b c

Output

Output the minimum number of servers Jank, who rules SCSC, must choose initially in order to process all requests. If it is impossible to process all requests by any method, output -1 instead.


Sample Input 1

3 4
2 2 0 0
1 1
2 0 0 1
2 1 0 1

Sample Output 1

3

表示言語

/ /

Score : 100 points

문제

CUBRID HA 클러스터는 N개의 서버로 구성된 시스템이다. 서버는 1번부터 N번까지 번호가 붙어 있다.

SCSC의 서버 관리자로 취임한 Jank는 CUBRID HA 클러스터의 서버 중 몇 대를 선택해 사용하려고 한다. Jank는 선택한 서버를 켜고 선택하지 않은 서버를 끈다.

SCSC를 지배하는 Jank는 선택한 각 서버를 켤 때 Master 또는 Slave 중 하나를 선택해 작동시킨다. Master 서버는 RW 요청과 RO 요청을 처리할 수 있고, Slave 서버는 RO 요청과 SO 요청을 처리할 수 있다. 각 서버는 최대 한 개의 요청만 동시에 처리할 수 있다.

만약 현재 켜져 있는 서버 중 Master 서버가 하나도 없고 현재 켜져 있는 Slave 서버가 하나 이상 있다면, 그중 번호가 가장 작은 서버가 즉시 Master 서버가 된다.

SCSC를 지배하는 Jank는 아래 두 종류의 쿼리 Q개를 순서대로 처리해야 한다.

  • 1 i: i번 서버를 끈다. 이미 꺼져 있는 서버라면 무시한다.
  • 2 a b c: RW 요청 a개, RO 요청 b개, SO 요청 c개가 동시에 들어온다.

2번 쿼리로 들어온 요청은 현재 켜져 있는 서버만 사용해 모두 처리해야 한다. 각 요청은 요청을 처리할 수 있는 서버에 배정되어야 하며, 하나의 서버에는 최대 한 개의 요청만 배정할 수 있다. 쿼리가 주어질 때 배정하지 못한 요청은 처리할 수 없다.

모든 요청이 배정되면 각 서버는 요청을 처리하고 처리한 요청을 버린다. 남은 요청이 없는 서버는 다시 다른 요청을 처리할 수 있는 상태가 된다.

SCSC를 지배하는 Jank가 모든 요청을 처리할 수 있도록 처음에 선택해야 하는 서버 수의 최솟값을 구하여라. 어떤 방법으로도 모든 요청을 처리할 수 없다면 대신 -1을 출력한다.

제한

  • 1 \leq N,Q \leq 2\,000
  • 1 \leq i \leq N
  • 0 \leq a,b,c \leq N
  • 2번 쿼리가 하나 이상 주어진다.
  • 입력으로 주어지는 수는 모두 정수이다.

입력

입력은 다음 형식으로 표준 입력으로 주어진다.

N Q
\mathrm{query}_1
\mathrm{query}_2
\vdots
\mathrm{query}_Q

각 쿼리는 다음 두 형식 중 하나이다.

1 i
2 a b c

출력

SCSC를 지배하는 Jank가 모든 요청을 처리할 수 있도록 처음에 선택해야 하는 서버 수의 최솟값을 출력한다. 어떤 방법으로도 모든 요청을 처리할 수 없다면 대신 -1을 출력한다.


입력 예 1

3 4
2 2 0 0
1 1
2 0 0 1
2 1 0 1

출력 예 1

3

表示言語

/ /

配点 : 100

問題文

CUBRID HA クラスタは N 台のサーバからなるシステムです.サーバには 1 番から N 番までの番号が付いています.

SCSC のサーバ管理者に就任した Jank は,CUBRID HA クラスタのサーバのうちいくつかを選んで使おうとしています.Jank は選んだサーバを起動し,選ばないサーバを停止します.

SCSC を支配する Jank は,選んだ各サーバを起動するとき,Master または Slave のどちらとして動作させるかを選びます.Master サーバは RW リクエストと RO リクエストを処理でき,Slave サーバは RO リクエストと SO リクエストを処理できます.各サーバは同時に高々 1 個のリクエストしか処理できません.

現在起動しているサーバの中に Master サーバが 1 台も存在せず,現在起動している Slave サーバが 1 台以上存在する場合,現在起動している Slave サーバのうち番号が最も小さいサーバがただちに Master サーバになります.

SCSC を支配する Jank は,以下の 2 種類のクエリを Q 個,順に処理しなければなりません.

  • 1 i: サーバ i を停止する.すでに停止しているサーバなら無視する.
  • 2 a b c: RW リクエスト a 個,RO リクエスト b 個,SO リクエスト c 個が同時に到着する.

2 番目の形式のクエリで到着したリクエストは,現在起動しているサーバだけを使ってすべて処理しなければなりません.各リクエストは,そのリクエストを処理できるサーバに割り当てる必要があり,1 台のサーバには高々 1 個のリクエストしか割り当てられません.クエリが与えられた時点で割り当てられなかったリクエストは処理できません.

すべてのリクエストが割り当てられると,各サーバはリクエストを処理し,処理したリクエストを破棄します.残っているリクエストがないサーバは,再び他のリクエストを処理できる状態になります.

SCSC を支配する Jank がすべてのリクエストを処理するためには,最初に選ぶ必要があるサーバの最小個数を求めてください.どのような方法でもすべてのリクエストを処理できない場合は,代わりに -1 を出力してください.

制約

  • 1 \leq N,Q \leq 2\,000
  • 1 \leq i \leq N
  • 0 \leq a,b,c \leq N
  • 2 番目の形式のクエリが少なくとも 1 個与えられる
  • 入力される数値はすべて整数

入力

入力は以下の形式で標準入力から与えられる.

N Q
\mathrm{query}_1
\mathrm{query}_2
\vdots
\mathrm{query}_Q

各クエリは以下の 2 種類のいずれかの形式で与えられる.

1 i
2 a b c

出力

SCSC を支配する Jank がすべてのリクエストを処理するために最初に選ぶ必要があるサーバの最小個数を出力せよ.どのような方法でもすべてのリクエストを処理できない場合は,代わりに -1 を出力せよ.


入力例 1

3 4
2 2 0 0
1 1
2 0 0 1
2 1 0 1

出力例 1

3
I - Sum and Difference

Time Limit: 2 sec / Memory Limit: 1024 MiB

表示言語

/ /

Score : 100 points

Problem Statement

Terra is studying how to transform pairs of integers using sums and differences. The transformation method Terra is studying uses the following two operations.

Operation 1: (A, B) \rightarrow (A+B, A-B)

Operation 2: (A, B) \rightarrow (B-A, A+B)

Each transformation process can be represented as a string according to the order in which the operations are used. If the i-th character is 1, operation 1 was chosen as the i-th operation; if it is 2, operation 2 was chosen. A transformation process in which no operation is performed is represented by the empty string, and the length of the string is equal to the number of operations applied.

Terra wants to list all transformation processes that turn (A, B) into (C, D) in order. When each transformation process is represented as a string, strings of shorter length come first, and among strings of the same length, lexicographically smaller strings come first.

The number of test cases T is given, and for each test case, (A, B), (C, D), and P are given. Find the string of the P-th transformation process in this order among the transformation processes that turn (A, B) into (C, D). If the P-th string does not exist in this order, output -1; if the P-th string is the empty string, output EMPTY.

Constraints

  • 1 \leq T \leq 100\,000
  • -10^9 \leq A, B, C, D \leq 10^9
  • 1 \leq P \leq 10^9
  • All given numbers are integers.

Input

The input is given from Standard Input in the following format:

T
A_1 B_1 C_1 D_1 P_1
A_2 B_2 C_2 D_2 P_2
\vdots
A_T B_T C_T D_T P_T

Output

For each test case, output one line containing the string of the P-th transformation process when the transformations that turn (A, B) into (C, D) are listed in order. If the P-th string does not exist, output -1; if the P-th transformation process is represented by the empty string, output EMPTY.


Sample Input 1

3
1 0 1 0 1
1 0 0 1 1
1 0 2 0 2

Sample Output 1

EMPTY
-1
22

In the first test case, the shortest transformation that turns (1,0) into (1,0) is to do nothing, so EMPTY should be output.

In the second test case, there is no transformation that turns (1,0) into (0,1), so -1 should be output.

表示言語

/ /

Score : 100 points

문제

테라는 합과 차를 이용해 정수 쌍을 변환하는 방법에 대해 연구하고 있다. 테라가 연구 중인 변환 방법은 아래의 두 연산을 사용하는 것이다.

연산 1: (A, B) \rightarrow (A+B, A-B)

연산 2: (A, B) \rightarrow (B-A, A+B)

각 변환은 연산을 사용한 순서에 따라 문자열로 표현할 수 있다. i번째 문자가 1이면 i번째 연산으로 연산 1, 2이면 연산 2를 선택했음을 나타낸다. 어떤 변환 과정도 문자열로 표현할 수 있다. 문자열의 길이만큼 연산을 적용했다는 사실이나 연산을 한 번도 하지 않으면 문자열의 길이가 0이 된다는 것도 쉽게 알 수 있다.

테라는 (A, B)(C, D)로 만드는 변환을 순서대로 나열하려고 한다. 문자열로 나타냈을 때 길이가 짧은 문자열이 먼저 오며 길이가 같다면 사전 순으로 앞서는 문자열이 먼저 온다.

테스트 케이스의 개수 T가 주어지며, 각 테스트 케이스마다 (A, B), (C, D), P가 주어진다. (A, B)(C, D)로 만들 수 있는 변환을 순서대로 나열할 때 P번째로 오는 변환의 문자열을 구해 보자.

제한

  • 1 \leq T \leq 100\,000
  • -10^9 \leq A_i, B_i, C_i, D_i \leq 10^9
  • 1 \leq P_i \leq 10^9
  • 주어지는 모든 수는 정수이다.

입력

입력은 다음 형식으로 표준 입력으로 주어진다.

T
A_1 B_1 C_1 D_1 P_1
A_2 B_2 C_2 D_2 P_2
\vdots
A_T B_T C_T D_T P_T

출력

각 테스트 케이스마다 (A, B)(C, D)로 만들 수 있는 변환을 순서대로 나열할 때 P번째로 오는 변환의 문자열을 한 줄에 하나씩 출력한다. P번째 문자열이 존재하지 않는다면 -1, P번째로 오는 변환의 문자열이 빈 문자열이라면 EMPTY를 출력한다.


입력 예 1

3
1 0 1 0 1
1 0 0 1 1
1 0 2 0 2

출력 예 1

EMPTY
-1
22

첫 번째 테스트 케이스에서 (1,0)(1,0)로 만드는 가장 짧은 변환은 아무것도 하지 않는 것이므로 EMPTY를 출력해야 한다.

두 번째 테스트 케이스에서 (1,0)(0,1)로 만드는 변환이 없으므로 -1을 출력해야 한다.

表示言語

/ /

配点 : 100

問題文

テラは和と差を用いて整数の組を変換する方法について研究している.テラが研究している変換方法では,次の 2 つの操作を使う.

操作 1: (A, B) \rightarrow (A+B, A-B)

操作 2: (A, B) \rightarrow (B-A, A+B)

各変換過程は,操作を使用した順序に従って文字列で表すことができる.i 文字目が 1 なら i 番目の操作として操作 1 を,2 なら操作 2 を選んだことを表す.操作を一度も行わない変換過程は空文字列で表され,文字列の長さは適用した操作の回数に等しい.

テラは (A, B)(C, D) にするすべての変換過程を順に並べようとしている.各変換過程を文字列で表したとき,長さが短い文字列が先に来て,長さが同じなら辞書順で小さい文字列が先に来る.

テストケースの数 T が与えられ,各テストケースごとに (A, B)(C, D)P が与えられる.(A, B)(C, D) にする変換過程をこの順に並べたとき,P 番目に来る変換過程の文字列を求めよう.この順序において P 番目の文字列が存在しないなら -1P 番目の文字列が空文字列なら EMPTY を出力する.

制約

  • 1 \leq T \leq 100\,000
  • -10^9 \leq A, B, C, D \leq 10^9
  • 1 \leq P \leq 10^9
  • 入力される数値はすべて整数である.

入力

入力は以下の形式で標準入力から与えられる.

T
A_1 B_1 C_1 D_1 P_1
A_2 B_2 C_2 D_2 P_2
\vdots
A_T B_T C_T D_T P_T

出力

各テストケースについて,(A, B)(C, D) にする変換過程を順に並べたとき P 番目に来る変換過程の文字列を 1 行に出力せよ.P 番目の文字列が存在しないなら -1P 番目に来る変換過程の文字列が空文字列なら EMPTY を出力せよ.


入力例 1

3
1 0 1 0 1
1 0 0 1 1
1 0 2 0 2

出力例 1

EMPTY
-1
22

1 番目のテストケースでは,(1,0)(1,0) にする最短の変換は何もしないことであるため,EMPTY を出力する必要がある.

2 番目のテストケースでは,(1,0)(0,1) にする変換が存在しないため,-1 を出力する必要がある.

J - DETOX

Time Limit: 2 sec / Memory Limit: 1024 MiB

表示言語

/ /

Score : 100 points

Problem Statement

N students, numbered from 1 to N, are seated in a circle in numerical order. Each student wears a name tag marked with either O or X. Each student can see the name tags of N-1 students, excluding their own. No three or more students sitting next to each other have name tags with the same letter, and all students are aware of this fact.

The game continues until every student has correctly guessed the letter on their own name tag. The rules of the game are as follows:

  • In each round, all students who are certain of the letter on their name tag raise their hands at the same time.
  • Once all students have confirmed which students raised their hands in this round, the next round begins.

During the game, no student may exchange name tags with others, remove their name tag, or change the letter on their name tag.

You are given T test cases. For each test case, determine in which round each student will raise their hand for the first time.

Constraints

  • 1 \le T \le 100\,000
  • 3 \le N \le 100\,000
  • S is a string of length N consisting only of O and X.
    • The ith character of S is the character written on the name tag of the ith student.
  • None of the three students sitting consecutively are wearing name tags with the same characters written on them.
  • The sum of N over all test cases is at most 300\,000.
  • All input numbers are integers.

Input

The input is given from Standard Input in the following format:

T
case_1
case_2
\vdots
case_T

Each test case is given in the following format:

N
S

Output

Output N non-negative integers, separated by spaces, on a single line for each test case. The ith integer, r_i, indicates the r_ith round in which student i first raises their hand. If there is a student who cannot raise their hand no matter how long the game continues, output -1 instead.


Sample Input 1

4
4
XOXO
3
OOX
3
OXX
6
OXOOXX

Sample Output 1

1 1 1 1 
2 2 1 
1 2 2 
1 1 2 1 1 2 

In the first test case, four students are seated in a circle, each wearing a name tag labeled X, O, X, and O, respectively.

In the first round, Student 2 observes that both Student 1 and Student 3 are wearing name tags labeled X. If Student 2 were wearing a badge marked with X, then Students 2, 3, and 4 would all be wearing badges marked with X, which contradicts the rule that three students sitting consecutively cannot all have badges marked with the same character.

Therefore, Student 2 cannot be wearing a name tag marked with an X and can be certain that they are wearing a name tag marked with an O, so they raise their hand in the first round. The other students also raise their hands in the first round based on the same reasoning.

表示言語

/ /

점수 : 100

문제

1번부터 N번까지 N명의 학생이 번호 순으로 원형으로 둘러앉아 있다. 각 학생은 O 또는 X가 적힌 명찰을 달고 있다. 각 학생은 자신의 명찰을 제외한 N-1명의 학생의 명찰을 볼 수 있다. 같은 문자가 적힌 명찰을 달고 있는 학생이 셋 이상 연속해서 앉아 있지 않으며 모든 학생은 이 사실을 알고 있다.

모든 학생이 자신의 명찰에 적힌 문자를 맞힐 때까지 게임을 진행한다. 게임의 규칙은 다음과 같다.

  • 매 라운드마다 자신의 명찰에 적힌 문자를 확신할 수 있는 모든 학생이 동시에 거수한다.
  • 이번 라운드에 어느 학생들이 거수했는지 모든 학생이 확인한 뒤 다음 라운드를 시작한다.

게임을 진행하는 동안 모든 학생은 명찰을 서로 교환하거나 명찰을 떼거나 명찰에 적힌 글자를 바꿀 수 없다.

T개의 테스트 케이스가 주어진다. 각 테스트 케이스마다 각 학생이 몇 번째 라운드에 처음으로 거수할지 알아내 보자.

제한

  • 1 \le T \le 100\,000
  • 3 \le N \le 100\,000
  • SOX로만 이루어진 길이 N의 문자열이다.
    • Si번째 문자는 i번 학생의 명찰에 적힌 문자이다.
  • 연속해 앉은 어느 세 학생도 같은 문자가 적힌 명찰을 달고 있지 않다.
  • 모든 테스트 케이스에 주어지는 N의 합은 300\,000을 넘지 않는다.
  • 입력으로 주어지는 수는 모두 정수이다.

입력

입력은 다음 형식으로 표준 입력으로 주어진다.

T
case_1
case_2
\vdots
case_T

각 테스트 케이스는 다음 형식으로 주어진다.

N
S

출력

테스트 케이스마다 N개의 음이 아닌 정수를 공백으로 구분하여 출력한다. i번째 정수 r_ii번 학생이 r_i번째 라운드에 처음으로 거수함을 의미한다. 만약 게임을 영원히 진행해도 거수할 수 없는 학생이 있다면 대신 -1을 출력한다.


입력 예 1

4
4
XOXO
3
OOX
3
OXX
6
OXOOXX

출력 예 1

1 1 1 1 
2 2 1 
1 2 2 
1 1 2 1 1 2 

첫 번째 테스트 케이스에서는 네 명의 학생이 각각 X, O, X, O가 적힌 명찰을 달고 둘러앉아 있다.

첫 번째 라운드에 2번 학생은 1번 학생과 3번 학생이 모두 X가 적힌 명찰을 달고 있는 걸 확인한다. 이때 2번 학생이 X가 적힌 명찰을 달고 있다면 2번, 3번, 4번 학생이 모두 X가 적힌 명찰을 달고 있으니 연속해 앉은 세 학생이 같은 문자가 적힌 명찰을 달고 있지 않다는 정보와 맞지 않는다.

이로부터 2번 학생은 자신이 X가 적힌 명찰을 달고 있을 수 없고, 따라서 O가 적힌 명찰을 달고 있다고 확신할 수 있으므로 첫 번째 라운드에 거수한다. 다른 학생들도 같은 근거로 모두 첫 번째 라운드에 거수한다.

表示言語

/ /

配点 : 100

問題文

1番からN番までのN人の生徒が、番号順に円形に座っている。各生徒は、OまたはXと書かれた名札を付けている。各生徒は、自分の名札を除くN-1人の生徒の名札を見ることができる。同じ文字が書かれた名札をつけた生徒が3人以上連続して座っていることはなく、すべての生徒はこの事実を知っている。

すべての生徒が自分の名札に書かれた文字を当てるまでゲームを進める。ゲームのルールは以下の通りである。

  • 各ラウンドごとに、自分の名札に書かれた文字に確信が持てる生徒全員が同時に手を上げる。
  • 今回のラウンドでどの生徒が挙手したかを全員が確認した後次のラウンドを始める。

ゲームの進行中、すべての生徒は名札を互いに交換したり、名札を外したり、名札に書かれた文字を変更したりすることはできない。

T個のテストケースが与えられる。各テストケースにおいて、各生徒が何番目のラウンドで初めて手を上げるかを求めよ。

制約

  • 1 \le T \le 100\,000
  • 3 \le N \le 100\,000
  • SOXのみで構成される長さNの文字列である
    • Si番目の文字は、i番目の生徒の名札に書かれた文字である
  • どの並んで座っている3人の学生も同じ文字が書かれた名札をつけていない
  • すべてのテストケースで与えられるNの合計は300\,000を超えない
  • 入力される数値はすべて整数

入力

入力は以下の形式で標準入力から与えられる.

T
case_1
case_2
\vdots
case_T

各テストケースは以下の形式で与えられる。

N
S

出力

N個の非負の整数をスペースで区切り、テストケースごとに1行に出力する。そのうちi番目の整数r_iは、i番目の生徒がr_i番目のラウンドで初めて挙手することを意味する。もしゲームをいつまでも続けても挙手できない生徒がいるなら、代わりに -1 を出力する。


入力例 1

4
4
XOXO
3
OOX
3
OXX
6
OXOOXX

出力例 1

1 1 1 1 
2 2 1 
1 2 2 
1 1 2 1 1 2 

最初のテストケースでは、4人の生徒がそれぞれXOXOと書かれた名札をつけて円になって座っている。

第1ラウンドで、2番の生徒は1番の生徒と3番の生徒がともにXと書かれた名札をつけていることを確認する。このとき、2番の学生がXと書かれた名札をつけているとすると、2番、3番、4番の学生が全員Xと書かれた名札をつけていることになり、隣り合って座っている3人の学生が同じ文字が書かれた名札をつけていないという情報と矛盾する。

したがって、2番の生徒は自分がXと書かれた名札をつけていることはあり得ず、したがってOと書かれた名札をつけていると確信できるため、第1ラウンドで挙手する。他の生徒たちも同様の根拠から、全員第1ラウンドで挙手する。

K - Cosmic Playground

Time Limit: 2 sec / Memory Limit: 1024 MiB

表示言語

/ /

Score : 100 points

Problem Statement

While exploring the galaxy, Navi and Hyeongtae discovered a cosmic playground! The cosmic playground consists of N points and N-1 bidirectional passages. Each point in the cosmic playground is numbered from 1 to N. The ith passage connects points u_i and v_i in both directions. It is always possible to travel between any two distinct points using only the passages. In other words, the cosmic playground has a tree structure.

Each point is connected to a single slide. For a permutation P=[P_1, P_2, \dots, P_N] of length N, sliding down the slide at point i moves you to point P_i.

Navi wants to slide down the slides non-stop to enjoy the thrill of speed. On the other hand, Hyeongtae is worried that if Navi travels too far, Navi might get lost in space. After much deliberation, Navi and Hyeongtae defined the risk level f(r) of point r as follows:

  • The distance between points a and b is the minimum number of passages one must traverse to reach point b from point a using only the passages.
  • Navi starts at point s and continues moving using only slides, while Hyeongtae watches Navi from point r. The maximum distance between point r and any point Navi can reach is defined as the maximum distance d(r, s).
  • The risk level f(r) when Hyeongtae remains at point r is the sum of the maximum distances \sum\limits_{s = 1}^{N}{d(r, s)} when Navi starts from each point.

Hyeongtae wants to stay at the point where the risk level is minimized. Let us help Hyeongtae by calculating the risk level for each point.

What is a permutation? A permutation of length N is a sequence that contains exactly one of each integer from 1 to N. For example, [2,1,4,3] is a permutation, but [4, 2, 1, 1] and [1, 2, 3, 5] are not.

Constraints

  • 3 \le N \le 100\,000
  • 1 \le u_i < v_i \le N
  • The given graph is a tree.
  • P is a permutation.
  • All input values are integers.

Input

The input is given from Standard Input in the following format:

N
P_1 P_2 \dots P_N
u_1 v_1
u_2 v_2
\vdots
u_{N-1} v_{N-1}

Output

Output N integers f(1), f(2), \dots, f(N), separated by spaces, where each integer represents the risk level of each point.


Sample Input 1

6
3 1 2 4 6 5
1 3
2 3
3 4
4 5
4 6

Sample Output 1

14 14 8 8 14 14 

表示言語

/ /

점수 : 100

문제

은하계를 탐방하던 나비와 형태는 우주 놀이터를 발견했다! 우주 놀이터에는 N개의 포인트와 N-1개의 양방향 통로가 있다. 우주 놀이터의 각 포인트에는 1번부터 N번까지 번호가 순서대로 매겨져 있다. i번째 통로u_i번 포인트와 v_i번 포인트를 양방향으로 연결한다. 임의의 서로 다른 두 포인트를 통로만을 이용해 항상 오갈 수 있다. 즉 우주 놀이터는 트리 구조이다.

각 포인트에는 미끄럼틀이 하나씩 연결되어 있다. 길이 N의 순열 P = [P_1, P_2, \dots, P_N]에 대해 i번 포인트에서 미끄럼틀을 타면 P_i번 포인트로 이동한다.

나비는 속도감을 즐기기 위해 끊임없이 미끄럼틀을 타고 싶어 한다. 반면 형태는 너무 멀리 있는 포인트까지 이동했다가는 우주 미아가 될까 걱정이다. 나비와 형태는 열심히 고민한 결과 r번 포인트의 위험도 f(r)을 다음과 같이 정의했다.

  • a번 포인트와 b번 포인트 사이의 거리a번 포인트에서 통로만을 이용해 b번 포인트로 이동하기 위해 지나야 하는 통로의 최소 개수이다.
  • 나비는 s번 포인트에서 출발해 미끄럼틀만을 이용해 계속 이동하고, 형태는 r번 포인트에서 나비를 지켜본다. 이때 r번 포인트와 나비가 도달할 수 있는 포인트 사이의 거리 중 최댓값을 최대 거리 d(r, s)라고 한다.
  • 형태가 r번 포인트에 남아 있을 때의 위험도 f(r)은 나비가 각 포인트에서 출발했을 때의 최대 거리의 합 \sum\limits_{s = 1}^{N}{d(r, s)}이다.

형태는 위험도가 최소가 되는 포인트에 남아 있고자 한다. 형태를 도와 각 포인트의 위험도를 계산해 보자.

순열이란 길이가 N순열1부터 N까지의 정수가 정확히 한 번씩 등장하는 수열이다. 예를 들어 [2,1,4,3]은 순열이지만 [4,2,1,1]이나 [1,2,3,5]는 순열이 아니다.

제한

  • 3 \le N \le 100\,000
  • 1 \le u_i < v_i \le N
  • 주어지는 그래프는 트리 구조이다.
  • P는 순열이다.
  • 주어지는 모든 수는 정수이다.

입력

입력은 다음 형식으로 표준 입력으로 주어진다.

N
P_1 P_2 \dots P_N
u_1 v_1
u_2 v_2
\vdots
u_{N-1} v_{N-1}

출력

각 포인트의 위험도를 나타내는 N개의 정수 f(1), f(2), \dots, f(N)을 공백으로 구분하여 출력한다.


입력 예 1

6
3 1 2 4 6 5
1 3
2 3
3 4
4 5
4 6

출력 예 1

14 14 8 8 14 14 

表示言語

/ /

配点 : 100

問題文

銀河を旅していたナビとヒョンテは,宇宙の遊び場を発見した!宇宙の遊び場には,N個のポイントとN-1個の双方向通路がある.宇宙の遊び場の各ポイントには,1番からN番までの番号が振られている.i番目の通路は,u_i番目のポイントとv_i番目のポイントを双方向に結んでいる.任意の異なる2つのポイントは,通路のみを利用して常に行き来することができる.つまり,宇宙の遊び場は木構造である.

各ポイントには,1つずつ滑り台が接続されている.長さNの順列P = [P_1, P_2, \dots, P_N]について,i番目のポイントから滑り台を滑ると,P_i番目のポイントへ移動する.

ナビはスピード感を味わうために,途切れることなく滑り台を滑り続けたいと思っている.一方,ヒョンテは,ナビがあまりにも遠いポイントまで移動してしまうと,宇宙で迷子になってしまうのではないかと心配している.ナビとヒョンテは一生懸命考えた結果,r番ポイントの危険度 f(r)を次のように定義した.

  • a番ポイントとb番ポイントの間の距離は,a番ポイントから通路のみを利用してb番ポイントへ移動するために通らなければならない通路の最小個数である.
  • ナビはs番目のポイントから出発し,滑り台のみを利用して移動を続け,ヒョンテはr番目のポイントからナビを見守る.このとき,r番目のポイントとナビが到達可能なポイントとの間の距離のうち,最大値を最大距離 d(r, s)と呼ぶ.
  • ヒョンテがr番ポイントに残っているときの危険度f(r)は,ナビが各ポイントから出発したときの最大距離の和 \sum\limits_{s = 1}^{N}{d(r, s)}である.

ヒョンテは危険度が最小になるポイントに残りたいと考えている.ヒョンテを助けて,各ポイントの危険度を計算してみよう.

順列とは 長さが N順列とは、1 から N までの整数を、それぞれちょうど一つずつ含む数列である。例えば、[2,1,4,3] は順列だが、[4, 2, 1, 1][1, 2, 3, 5] は順列ではない。

制約

  • 3 \le N \le 100\,000
  • 1 \le u_i < v_i \le N
  • 与えられるグラフは木構造
  • Pは順列
  • 入力される数値はすべて整数

入力

入力は以下の形式で標準入力から与えられる.

N
P_1 P_2 \dots P_N
u_1 v_1
u_2 v_2
\vdots
u_{N-1} v_{N-1}

出力

各ポイントの危険度を表すN個の整数f(1), f(2), \dots, f(N)を空白区切りで出力せよ.


入力例 1

6
3 1 2 4 6 5
1 3
2 3
3 4
4 5
4 6

出力例 1

14 14 8 8 14 14 
L - ChannelTalk Workflow

Time Limit: 2 sec / Memory Limit: 1024 MiB

表示言語

/ /

Score : 100 points

Problem Statement

ChannelTalk, an all-in-one AI messenger that facilitates real-time communication with customers, offers a workflow feature that allows anyone to easily create chatbots. Using ChannelTalk Workflow, you can combine triggers and actions like building blocks based on the customer and the situation to automate the entire process from the start to the end of a consultation. Additionally, frequently used functions can be created as modules and reused multiple times.

Ino intends to build a chatbot using ChannelTalk Workflow to handle N different types of questions. Each question is assigned a unique number from 1 to N.

Ino wants to add M modules to the workflow and number them from 0 to M-1 in the order they are added. Since Ino cannot manage too many modules, at most 2\,048 modules can be used.

When question x is entered, module i operates as follows.

  • If x = i, it answers the question and ends the consultation.
  • If x \neq i, it enters question x to module L_i if x \le F_i, and module G_i if x \gt F_i.

When a question is received, it is first input to module 0, and executing each module takes 1 second. That is, the time taken to process question i is equal to the total number of modules passed through, including module 0 and module i, until the consultation ends. If the same module is passed through multiple times, it is counted as many times as it was passed through.

Ino wants to ensure that the consultation ends in exactly K seconds regardless of which question from 1 to N is asked. Given the number of question types N and the ending time K, choose the number of modules M and the values of F_i, L_i, and G_i for each module so that the consultation always ends exactly at K seconds using at most 2\,048 modules. Note that M does not need to be minimized.

Constraints

  • 2 \le K \le N \le 1\,000
  • All input values are integers.

Input

The input is given from Standard Input in the following format:

N K

Output

On the first line, output the number of modules M to use. (1 \le M \le 2\,048)

From the second line, output M lines. On the (i+2)-th line, output three integers F_i, L_i, and G_i representing module i, separated by spaces. (0 \le F_i \le N;\ 0 \le L_i, G_i < M)

If no solution exists, output -1 instead.


Sample Input 1

6 6

Sample Output 1

11
1 7 1
2 7 2
3 7 3
4 7 4
5 5 6
4 0 0
5 0 0
3 8 4
2 9 3
1 10 2
0 0 1

表示言語

/ /

점수 : 100

문제

고객과의 실시간 소통을 편리하게 해주는 올인원 AI 메신저 채널톡은 누구나 쉽게 챗봇을 만들 수 있도록 워크플로우 기능을 제공한다. 채널톡 워크플로우를 이용해 고객과 상황에 따라 필요한 트리거와 액션을 블록처럼 조합해 상담 시작부터 끝까지 전 과정을 자동화할 수 있다. 또한 반복적으로 필요한 기능은 모듈로 만들어 여러 번 재활용할 수도 있다.

이노는 채널톡 워크플로우를 이용해 N종류의 서로 다른 질문을 처리하는 챗봇을 제작하려 한다. 각 질문에는 1번부터 N번까지의 서로 다른 번호가 매겨져 있다.

이노는 워크플로우에 M개의 모듈을 추가하고 추가한 순서대로 0번부터 M-1번까지 번호를 매기고자 한다. 이노는 너무 많은 모듈을 관리할 능력이 없기 때문에 최대 2\,048개의 모듈만 사용할 수 있다.

i번 모듈은 x번 질문이 입력되었을 때 다음과 같이 작동한다.

  • x = i인 경우 해당 질문에 답변한 뒤 상담을 종료한다.
  • x \neq i인 경우 x \le F_iL_i번 모듈, x \gt F_iG_i번 모듈에 x번 질문을 입력한다.

질문이 들어오면 처음에 0번 모듈에 입력되며, 각 모듈을 실행하는 데에는 1초가 걸린다. 즉, i번 질문을 처리하는 데 걸리는 시간은 0번 모듈과 i번 모듈을 포함해 상담을 종료할 때까지 거쳐간 모듈의 총 개수와 같다. 같은 모듈을 여러 번 거쳐간 경우 거쳐간 횟수만큼 중복해 센다.

이노는 1번부터 N번까지 중 어느 질문을 해도 정확히 K초만에 상담이 종료되도록 만들고자 한다. 질문의 종류 N과 종료 시간 K가 주어질 때 모듈의 수 M과 각 모듈의 F_i, L_i, G_i를 적절히 정해 2\,048개 이하의 모듈로 항상 정확히 K초만에 상담이 끝나도록 만들어 보자. M을 최소화할 필요는 없음에 유의하라.

제한

  • 2 \le K \le N \le 1\,000
  • 입력으로 주어지는 수는 모두 정수이다.

입력

입력은 다음 형식으로 표준 입력으로 주어진다.

N K

출력

첫 번째 줄에 사용할 모듈의 수 M을 출력한다. (1 \le M \le 2\,048)

두 번째 줄부터 M개의 줄에 걸쳐, i+2번째 줄에 i번 모듈의 규칙을 나타내는 세 정수 F_i, L_i, G_i를 공백으로 구분하여 출력한다. (0 \le F_i \le N;\ 0 \le L_i, G_i < M)

가능한 방법이 존재하지 않는 경우 대신 -1을 출력한다.


입력 예 1

6 6

출력 예 1

11
1 7 1
2 7 2
3 7 3
4 7 4
5 5 6
4 0 0
5 0 0
3 8 4
2 9 3
1 10 2
0 0 1

表示言語

/ /

配点 : 100

問題文

顧客とのリアルタイムなコミュニケーションを便利にするオールインワン AI メッセンジャー ChannelTalk は,誰でも簡単にチャットボットを作れるようにワークフロー機能を提供している.ChannelTalk Workflow を利用すると,顧客や状況に応じて必要なトリガーとアクションをブロックのように組み合わせ,相談の開始から終了までの全過程を自動化できる.また,繰り返し必要な機能はモジュールとして作り,何度も再利用できる.

イノは ChannelTalk Workflow を利用して,N 種類の互いに異なる質問を処理するチャットボットを作ろうとしている.各質問には 1 番から N 番までの互いに異なる番号が付いている.

イノはワークフローに M 個のモジュールを追加し,追加した順に 0 番から M-1 番までの番号を付けたいと考えている.イノはあまり多くのモジュールを管理する能力がないため,最大 2\,048 個のモジュールしか使用できない.

i 番モジュールは x 番質問が入力されたとき次のように動作する.

  • x = i の場合,その質問に回答した後,相談を終了する.
  • x \neq i の場合,x \le F_i なら L_i 番モジュールに,x \gt F_i なら G_i 番モジュールに x 番質問を入力する.

質問が入力されると,最初に 0 番モジュールに入力され,各モジュールの実行には 1 秒かかる.すなわち,i 番の質問を処理するのにかかる時間は,0 番モジュールと i 番モジュールを含め,相談が終了するまでに通過したモジュールの総数に等しい.同じモジュールを複数回通過した場合は,通過した回数だけ重複して数える.

イノは,1 番から N 番までのどの質問が来ても,相談が 正確に K 秒で終了するようにしたい.質問の種類 N と終了時間 K が与えられるので,モジュールの数 M と各モジュールの F_i, L_i, G_i を適切に定め,2\,048 個以下のモジュールで常に正確に K 秒で相談が終わるようにしよう.M を最小化する必要はない.

制約

  • 2 \le K \le N \le 1\,000
  • 入力される数値はすべて整数

入力

入力は以下の形式で標準入力から与えられる.

N K

出力

1行目に使用するモジュール数 M を出力する.(1 \le M \le 2\,048)

2行目から M 行にわたり,i+2 行目に i 番モジュールを表す 3 つの整数 F_i, L_i, G_i を空白区切りで出力する.(0 \le F_i \le N;\ 0 \le L_i, G_i < M)

可能な方法が存在しない場合は,代わりに -1 を出力する.


入力例 1

6 6

出力例 1

11
1 7 1
2 7 2
3 7 3
4 7 4
5 5 6
4 0 0
5 0 0
3 8 4
2 9 3
1 10 2
0 0 1