#include <bits/stdc++.h>
using namespace std;
 
#define long long ll
const int N = 1e5;
vector<int> adj[N];
int dfs(int node, vector<pair<int,int>>& job, vector<bool>& vis, int& ans){
    vis[node] = true;
    for(auto i : adj[node]){
        if(!vis[i]){
            ans += job[i].first;
            if(i != 0) dfs(i,job,vis,ans);
        }
    }
    return ans;
}
 
int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
 
    int t;
    cin >> t;
 
    while(t--){
        int n, s;
        cin >> n >> s;
        vector<pair<int,int>> job(n);
        for(int i=0; i<n; ++i){
            cin >> job[i].first >> job[i].second;
            if(job[i].second != 0){
                adj[i].push_back(job[i].second - 1);
            } else {
                adj[i].push_back(job[i].second);
            }
        }
        vector<int> dp(n,0); 
        vector<bool> vis(n,false);
        dp[0] = max(job[0].first + s, s);
        if(dp[0] == job[0].first + s) vis[0] = true;
        for(int i=1; i<n; ++i){
            if(job[i].second == 0){
                dp[i] = max(dp[i-1], dp[i-1] + job[i].first);
            } else {
                if(!vis[job[i].second - 1]){
                    int ans = 0;
                    dp[i] = dp[i-1] + dfs(i,job,vis,ans);
                    dp[i] = max(dp[i-1], dp[i] + job[i].first);
                } else {
                    dp[i] = max(dp[i-1], dp[i-1] + job[i].first);
                }
            }
            if(dp[i] != dp[i-1]) vis[i] = true;
        }
        cout << dp[n-1] - s << endl;
        for (int i = 0; i < n; ++i) {
            adj[i].clear();
        }
    }
 
    return 0;
}
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... |