倍增板子。开两个二维数组,一个算桶会被传到哪里,一个算桶在传到那里后装了多少水。查询的时候把 拆成二进制,模拟即可。
时间复杂度为 。
Code
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using ull = unsigned long long;
using i128 = __int128;
using PII = pair<int, int>;
using PLL = pair<ll, ll>;
constexpr ll inf = (1ll << 62);
constexpr int N = 2e5 + 10;
void solve() {
int n, q;
cin >> n >> q;
vector<int> p(n);
vector<array<ll, 32>> to(n), w(n);
for (int i = 0; i < n; i++) {
cin >> p[i];
p[i]--;
to[i][0] = p[i];
w[i][0] = i + 1;
}
for (int i = 1; i < 32; i++) {
for (int j = 0; j < n; j++) {
to[j][i] = to[to[j][i - 1]][i - 1];
w[j][i] = w[j][i - 1] + w[to[j][i - 1]][i - 1];
}
}
while (q--) {
int t, u;
cin >> t >> u;
u--;
ll cur = 0;
for (int i = 0; i < 32; i++) {
if ((1 << i) & t) {
cur += w[u][i];
u = to[u][i];
}
}
cout << cur << "\n";
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t = 1;
// cin >> t;
while (t--) {
solve();
}
return 0;
}