QOJ.ac

QOJ

Time Limit: 2.0 s Memory Limit: 256 MB Total points: 100 Hackable ✓

#14096. 彩色排列排序

Statistics

給定由 $1$ 到 $n$ 的整數組成的排列 $p_1,p_2,\ldots,p_n$。從 $1$ 到 $n$ 的每個位置都被塗上 $k$ 種顏色之一。我們想將排列排序,為此可以執行任意次以下類型的操作:

  • 交換任意兩個元素。此操作花費 $S$ 枚硬幣;
  • 選擇任意顏色 $i$,任意重排顏色為 $i$ 的位置上的元素。此操作花費 $C_i$ 枚硬幣。

注意,被塗色的是位置,而不是元素,因此交換兩個元素時,位置的顏色不會改變。

求將排列排序所需花費的最少硬幣數。

輸入格式

輸入第一行包含一個整數 $T$($1\le T\le10^3$),表示需要處理的獨立測試案例數。接下來是各測試案例的描述。

每個測試案例的第一行包含兩個整數 $n,k$($1\le n\le10^5$,$1\le k\le5$),表示排列的大小和顏色數。

每個測試案例的第二行包含 $k+1$ 個整數 $S,C_1,C_2,\ldots,C_k$($0\le S,C_i\le10^9$),表示操作的費用。

每個測試案例的第三行包含 $n$ 個整數 $p_1,p_2,\ldots,p_n$($1\le p_i\le n$,所有 $p_i$ 互不相同),表示排列。

每個測試案例的第四行包含 $n$ 個整數 $col_i$($1\le col_i\le k$),表示各位置的顏色。

同一輸入檔案中所有測試案例的 $n$ 之和不超過 $10^5$。

輸出格式

對每個測試案例輸出一個整數,表示將排列排序所需花費的最少硬幣數。

範例

輸入格式 1

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

輸出格式 1

3
1
12
0

說明

在第一個測試案例中,我們可以執行 3 次「交換」操作,將排列排序:$(2,3,4,1)\to(4,3,2,1)\to(4,2,3,1)\to(1,2,3,4)$。這樣將花費 3 枚硬幣。

另一種排序方式是重排所有顏色為 $1$ 的位置上的元素,但這將花費 10 枚硬幣,而我們可以用更低的費用完成。

然而,在第二個測試案例中(它和第一個案例只有操作費用不同),只要花費 1 枚硬幣重排所有顏色為 $1$ 的位置上的元素,會更加便宜。

在第三個測試案例中,一個最優的操作序列如下:

  • 重排顏色為 $2$ 的位置上的元素,得到排列 $(5,2,4,3,1,6)$。此操作花費 1 枚硬幣。
  • 交換元素 $p_3,p_4$。此時排列為 $(5,2,3,4,1,6)$。此操作花費 10 枚硬幣。
  • 重排顏色為 $1$ 的位置上的元素,得到排列 $(1,2,3,4,5,6)$。此操作花費 1 枚硬幣。

總共花費了 12 枚硬幣。

在第四個測試案例中,排列已經有序,因此不需要花費任何硬幣。

Discussions

About Discussions

The discussion section is only for posting: General Discussions (problem-solving strategies, alternative approaches), and Off-topic conversations.

This is NOT for reporting issues! If you want to report bugs or errors, please use the Issues section below.

Open Discussions 0
No discussions in this category.

Issues

About Issues

If you find any issues with the problem (statement, scoring, time/memory limits, test cases, etc.), you may submit an issue here. A problem moderator will review your issue.

Guidelines:

  1. This is not a place to publish discussions, editorials, or requests to debug your code. Issues are only visible to you and problem moderators.
  2. Do not submit duplicated issues.
  3. Issues must be filed in English or Chinese only.
Active Issues 0
No issues in this category.
Closed/Resolved Issues 0
No issues in this category.