#6413. [ICPC 2024 Hangzhou R] Gathering Mushrooms

[ICPC 2024 Hangzhou R] Gathering Mushrooms

[ICPC 2024 Hangzhou R] Gathering Mushrooms

题目描述

BaoBao is picking mushrooms in a forest. There are $n$ locations in the forest, and in the $i$-th location there grows an infinite amount of mushrooms of type $t_i$. Each location also has a wooden sign. The sign of the $i$-th location points to location $a_i$ (it is possible that $a_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 1≤s≤n1 \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 $T$ ($1 \le T \le 10^4$) indicating the number of test cases. For each test case:

The first line contains two integers nn and kk (1≤n≤2×1051 \le n \le 2 \times 10^5, 1≤k≤1091 \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 (1≤ti≤n1 \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 (1≤ai≤n1 \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 $\sum\limits_{i = 1}^n (i \times v_i)$, where $v_i$ is the answer for $s = 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, $v_1 = 2$, $v_2 = 3$, $v_3 = 2$, $v_4 = 3$, $v_5 = 3$, so you should output $1 \times 2 + 2 \times 3 + 3 \times 2 + 4 \times 3 + 5 \times 3 = 41$. Consider $s = 3$, the types of mushrooms BaoBao picks in order are $\{1, 2, 2, 3, 3, 2, \cdots\}$, so mushrooms of type $2$ is the very first type which appears at least $3$ times in the basket. 标签: P14193|2024|ICPC|杭州

来源

P14193|[ICPC 2024 Hangzhou R] Gathering Mushrooms