题解:P12457 [JOI2025 预选赛 R2] 台球
Yi_chen123 · · 题解
思路
既然出现了先打另一个球,才能打这一个球的约束条件,不难想到拓扑排序,对所有
最后从
代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
int a[314514];
int p[314514];
int s[314514];
inline int rd(){
int k = 0, f = 1;
char c = getchar();
while(!isdigit(c)){
if(c == '-') f = -1;
c = getchar();
}
while(isdigit(c)){
k = (k << 3) + (k << 1) + c - '0';
c = getchar();
}
return k * f;
}
void toposort(int x, const vector<vector<int> > &g){ //拓扑排序
if(p[x] > 0) s[x] = a[x] + s[p[x]]; //转移方程
else s[x] = a[x];
for(int i = 0; i < g[x].size(); ++i){ //递归深入
toposort(g[x][i], g);
}
}
signed main(){
int n = rd(), x = rd();
vector<vector<int> > G(n + 1); //记得多加一个空间,不然 RE!
for(int i = 1; i <= n; ++i) a[i] = rd();
for(int i = 1; i <= n; ++i){
p[i] = rd();
if(p[i] > 0){ //建边
G[p[i]].push_back(i);
}
}
for(int i = 1; i <= n; ++i){
if(p[i] == -1) toposort(i, G);
}
for(int i = n; i >= 1; --i){
if(s[i] <= x && s[i]) return cout << i, 0; //找到答案
}
cout << -1; //报告无解
return 0;
}