// Jack's Candy Shop // Solution by Adel Aly #include #include #include #include #include #include using namespace std; const int MAXN = 2e5 + 10; const int MAXM = 1e6 + 10; int cands[MAXN], qIdx[MAXN]; long long ans; priority_queue Q[MAXN]; vector adj[MAXN]; void solve(int n) { int myIdx = n, otherIdx; if (adj[n].size() > 0) { solve(adj[n][0]); myIdx = qIdx[adj[n][0]]; for (int j = 1; j < adj[n].size(); ++j) { solve(adj[n][j]); otherIdx = qIdx[adj[n][j]]; if (Q[otherIdx].size() > Q[myIdx].size()) { swap(otherIdx, myIdx); } while (!Q[otherIdx].empty()) { Q[myIdx].push(Q[otherIdx].top()); Q[otherIdx].pop(); } } } qIdx[n] = myIdx; Q[myIdx].push(n); while ((cands[n]--) && (!Q[myIdx].empty())) { ans += Q[myIdx].top(); Q[myIdx].pop(); } } int main() { int T, N, M, A, B, p; cin >> T; for (int tt = 1; tt <= T; ++tt) { ans = 0; cin >> N >> M >> A >> B; memset(cands, 0, MAXN * sizeof(int)); ans = 0; for (int i = 0; i < N; i++) { adj[i].clear(); while (!Q[i].empty()) { Q[i].pop(); } } for (int i = 1; i < N; i++) { cin >> p; adj[p].push_back(i); } for (int i = 0; i < M; i++) { long long x = (1LL * A * i + B) % N; ++cands[x]; } solve(0); cout << "Case #" << tt << ": " << ans << endl; } return (0); }