#include using namespace std; typedef long long ll; bool active[5001]; bool cycle[5001]; int root[5001]; int p[5001]; int cost[5001][5001]; int dfs(int x){ if (active[x]){ root[x]=x; }else if (root[p[x]]!=-1){ root[x]=root[p[x]]; }else{ active[x]=true; root[x]=dfs(p[x]); if (active[root[x]]) cycle[x]=true; active[x]=false; } return root[x]; } int main(){ int n; cin>>n; ++n; ll res=0; for (int i=1; i>p[i]>>t; res+=t; for (int j=0; j>cost[j][i]; cost[j][i]-=t; } } memset(root,-1,sizeof root); for (int i=n; i--;) if (root[i]==-1) root[i]=dfs(i); for (int i=1; i distance(n,(1ll<<62ll)); priority_queue,vector>,greater>> todo; todo.emplace(distance[0]=0ll,0); while (not todo.empty()){ int x=todo.top().second; ll w=todo.top().first; todo.pop(); if (active[x]) continue; else active[x]=true; for (int y=n; y--;) if (w+cost[x][y]