The n n n stages an their mutual pathways can be intuitively seen as graph, with stages as nodes, and the pathways as edges.
The problem seems to solvable by some clever greedy algorithm due to the semi tree-like structure of the n n n stages. However, an ad-hoc dijkstra shortest path can easily solve the problem with O ( n log n ) \mathcal O(n \log n) O(nlogn) time complexity.
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<cstring>
using namespace std;
const long long Maxn=2e5+10;
const long long inf=(1ll<<60);
struct node{
long long pos,dis;
bool operator <(const node &x)const
{
return x.dis<dis;
}
};
struct edge{
long long v,len;
};
vector <edge> e[Maxn];
bool vis[Maxn];
long long dis[Maxn];
long long n;
inline long long read()
{
long long s=0,w=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
while(ch>='0' && ch<='9')s=(s<<3)+(s<<1)+(ch^48),ch=getchar();
return s*w;
}
void work()
{
priority_queue <node> q;
fill(dis+2,dis+1+n,inf);
dis[1]=0;
q.push(node{1,0});
while(q.size())
{
long long x=q.top().pos;
q.pop();
if(x==n)return;
if(vis[x])continue;
vis[x]=1;
for(long long i=0;i<e[x].size();++i)
{
long long y=e[x][i].v,len=e[x][i].len;
if(dis[y]>dis[x]+len)
{
dis[y]=dis[x]+len;
q.push(node{y,dis[y]});
}
}
}
}
int main()
{
// freopen("in.txt","r",stdin);
n=read();
for(long long i=1;i<n;++i)
{
long long a=read(),b=read(),x=read();
e[i].push_back(edge{i+1,a});
if(x!=i)
e[i].push_back(edge{x,b});
}
work();
printf("%lld\n",dis[n]);
return 0;
}