直接倍增就好了。。。。。
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #define maxv 100500 #define inf 0x7f7f7f7f7f7f7f7fLL using namespace std; long long n,k,anc[maxv][35],mn[maxv][35],w[maxv][35],table[35]; int main() { table[0]=1;for (long long i=1;i<=34;i++) table[i]=table[i-1]*2; scanf("%I64d%I64d",&n,&k); for (long long i=0;i<n;i++) scanf("%I64d",&anc[i][0]); for (long long i=0;i<n;i++) {scanf("%I64d",&mn[i][0]);w[i][0]=mn[i][0];} for (long long e=1;e<=34;e++) for (long long i=0;i<n;i++) { anc[i][e]=anc[anc[i][e-1]][e-1]; mn[i][e]=min(mn[i][e-1],mn[anc[i][e-1]][e-1]); w[i][e]=w[i][e-1]+w[anc[i][e-1]][e-1]; } for (long long i=0;i<n;i++) { long long ret1=0,ret2=inf,ret3=k,now=i; for (long long e=34;e>=0;e--) { if (ret3>=table[e]) { ret3-=table[e]; ret1+=w[now][e];ret2=min(ret2,mn[now][e]); now=anc[now][e]; } } printf("%I64d %I64d\n",ret1,ret2); } return 0; }
时间: 2024-10-12 21:15:45