#P14193. [ICPC 2024 Hangzhou R] Gathering Mushrooms

[ICPC 2024 Hangzhou R] Gathering Mushrooms

题目描述

BaoBao is picking mushrooms in a forest. There are nn locations in the forest, and in the ii-th location there grows an infinite amount of mushrooms of type tit_i. Each location also has a wooden sign. The sign of the ii-th location points to location aia_i (it is possible that ai=ia_i = i).

As it is very foggy in the forest, BaoBao decides to move between locations according to the signs just for safety. Starting from location ss with an empty basket, each time BaoBao walks into a location cc (including the starting location c=sc = s, and regardless of whether he has visited location cc before), he will pick one mushroom of type tct_c into his basket and move to location aca_c.

Given an integer kk, for each 1sn1 \le s \le n, determine the first type of mushroom that appears at least kk times in the basket.

输入格式

There are multiple test cases. The first line of the input contains an integer TT (1T1041 \le T \le 10^4) indicating the number of test cases. For each test case:

The first line contains two integers nn and kk (1n2×1051 \le n \le 2 \times 10^5, 1k1091 \le k \le 10^9) indicating the number of locations and the required times of appearance of mushrooms.

The second line contains nn integers t1,t2,,tnt_1, t_2, \cdots, t_n (1tin1 \le t_i \le n), where tit_i is the type of mushroom growing in location ii.

The third line contains nn integers a1,a2,,ana_1, a_2, \cdots, a_n (1ain1 \le a_i \le n), where aia_i is the location pointed to by the sign in location ii.

It's guaranteed that the sum of nn of all test cases will not exceed 2×1052 \times 10^5.

输出格式

To decrease the size of output, for each test case, output one line containing one integer indicating i=1n(i×vi)\sum\limits_{i = 1}^n (i \times v_i), where viv_i is the answer for s=is = i.

3
5 3
2 2 1 3 3
2 5 1 2 4
5 4
2 2 1 3 3
2 5 1 2 4
3 10
1 2 3
1 3 2
41
45
14

提示

For the first sample test case, v1=2v_1 = 2, v2=3v_2 = 3, v3=2v_3 = 2, v4=3v_4 = 3, v5=3v_5 = 3, so you should output $1 \times 2 + 2 \times 3 + 3 \times 2 + 4 \times 3 + 5 \times 3 = 41$. Consider s=3s = 3, the types of mushrooms BaoBao picks in order are {1,2,2,3,3,2,}\{1, 2, 2, 3, 3, 2, \cdots\}, so mushrooms of type 22 is the very first type which appears at least 33 times in the basket.