Datasets:

Modalities:
Image
Text
Formats:
parquet
Size:
< 1K
Tags:
code
Libraries:
Datasets
pandas
License:
hackercup / 2018 /round2 /jacks_candy_shop.cpp
wjomlex's picture
2018 Problems
ab396f0 verified
raw
history blame
1.49 kB
// 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);
}