File size: 1,489 Bytes
ab396f0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
// Jack's Candy Shop
// Solution by Adel Aly
#include <algorithm>
#include <vector>
#include <queue>
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
const int MAXN = 2e5 + 10;
const int MAXM = 1e6 + 10;
int cands[MAXN], qIdx[MAXN];
long long ans;
priority_queue<int> Q[MAXN];
vector<int> 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);
}
|