Problem:
Halting Problem
A unique law is enforced in the Republic of Finite Loop. Under the law, programs that never halt are regarded as viruses. Releasing such a program is a cybercrime. So, you want to make sure that your software products always halt under their normal use.
It is widely known that there exists no algorithm that can determine whether an arbitrary given program halts or not for a given arbitrary input. Fortunately, your products are based on a simple computation model given below. So, you can write a program that can tell whether a given program based on the model will eventually halt for a given input.
The computation model for the products has only one variable $x$ and $N + 1$ states, numbered $1$ through $N + 1$. The variable $x$ can store any integer value. The state $N + 1$ means that the program has terminated. For each integer $i$ ($1 \leq i \leq N$), the behavior of the program in the state $i$ is described by five integers $a_i$, $b_i$, $c_i$, $d_i$ and $e_i$ ($c_i$ and $e_i$ are indices of states).
On start of a program, its state is initialized to $1$, and the value of $x$ is initialized by $x_0$, the input to the program. When the program is in the state $i$ ($1 \leq i \leq N$), either of the following takes place in one execution step:
if $x$ is equal to $a_i$, the value of $x$ changes to $x + b_i$ and the program state becomes $c_i$;
otherwise, the value of $x$ changes to $x + d_i$ and the program state becomes $e_i$.
The program terminates when the program state becomes $N + 1$.
Your task is to write a program to determine whether a given program eventually halts or not for a given input, and, if it halts, to compute how many steps are executed. The initialization is not counted as a step.
Input
The input consists of a single test case of the following format.
$N$ $x_0$
$a_1$ $b_1$ $c_1$ $d_1$ $e_1$
.
.
.
$a_N$ $b_N$ $c_N$ $d_N$ $e_N$
The first line contains two integers $N$ ($1 \leq N \leq 10^5$) and $x_0$ ($−10^{13} \leq x_0 \leq 10^{13}$). The number of the states of the program is $N + 1$. $x_0$ is the initial value of the variable $x$. Each of the next $N$ lines contains five integers $a_i$, $b_i$, $c_i$, $d_i$ and $e_i$ that determine the behavior of the program when it is in the state $i$. $a_i$, $b_i$ and $d_i$ are integers between $−10^{13}$ and $10^{13}$, inclusive. $c_i$ and $e_i$ are integers between $1$ and $N + 1$, inclusive.
Output
If the given program eventually halts with the given input, output a single integer in a line which is the number of steps executed until the program terminates. Since the number may be very large, output the number modulo $10^9 + 7$.
Output $-1$ if the program will never halt.
Sample Input 1
2 0
5 1 2 1 1
10 1 3 2 2
Sample Output 1
9
Sample Input 2
3 1
0 1 4 2 3
1 0 1 1 3
3 -2 2 1 4
Sample Output 2
-1
Sample Input 3
3 3
1 -1 2 2 2
1 1 1 -1 3
1 1 4 -2 1
Sample Output 3
-1

Submitted solutions:

code_snippet: #include <bits/stdc++.h>
#define sz(v) ((int)(v).size())
#define all(v) (v).begin(), (v).end()
using namespace std;
using lint = __int128;
using pi = pair<lint, lint>;
const int MAXN = 100005;
const int mod = 1e9 + 7;

int n;
// qry[i] : (where does it leads to, for what cost)
// nxt[i] : (where does it leads to, for what addition)
// val[i] : what HP to take qry[i]
// result[i] : (how long, where (as a portal) does it leads to)

pi qry[MAXN], nxt[MAXN];
vector<pi> revlist[MAXN];
pi result[MAXN];
lint val[MAXN];
bool visited[MAXN];

namespace FindEnd{
	vector<int> gph[MAXN];
	map<lint, int> mp;
	int dep[MAXN];
	void dfs(int x, lint depth){
		visited[x] = 1;
		int restore = -1;
		if(x <= n){
			if(mp.count(val[x] + depth)){
				restore = mp[val[x] + depth];
			}
			mp[val[x] + depth] = x;
		}
		for(auto &fuck : revlist[x]){
			auto i = fuck.first;
			auto j = fuck.second;
			if(mp.count(i + depth)){
				int vert = mp[i + depth];
				result[j] = pi(dep[x] - dep[vert], vert);
			}
			else{
				result[j] = pi(dep[x], n + 1);
			}
		}
		for(auto &i : gph[x]){
			dep[i] = dep[x] + 1;
			dfs(i, depth + nxt[i].second);
		}
		if(x <= n){
			if(~restore) mp[val[x] + depth] = restore;
			else mp.erase(mp.find(val[x] + depth));
		}
	}
	void solve(){
		for(int i=1; i<=n; i++){
			gph[nxt[i].first].push_back(i);
		}
		dfs(n + 1, 0);
	}
}

namespace MatchQuery{
	int indeg[MAXN], dep[MAXN];
	vector<int> gph[MAXN];
	map<lint, int> mp;
	void dfs(int x, lint depth, vector<pi> &collected){
		int restore = -1;
		if(mp.count(val[x] + depth)){
			restore = mp[val[x] + depth];
		}
		mp[val[x] + depth] = x;
		for(auto &fuck : revlist[x]){
			auto i = fuck.first;
			auto j = fuck.second;
			if(mp.count(i + depth)){
				int vert = mp[i + depth];
				result[j] = pi(dep[x] - dep[vert], vert);
			}
			else{
				collected.emplace_back(i + depth, j);
			}
		}
		for(auto &i : gph[x]){
			if(indeg[i]) continue;
			dep[i] = dep[x] + 1;
			dfs(i, depth + nxt[i].second, collected);
		}
		if(~restore) mp[val[x] + depth] = restore;
		else mp.erase(mp.find(val[x] + depth));
	}
	void solve(){
		vector<int> noe;
		for(int i=1; i<=n; i++){
			if(visited[i]) continue;
			noe.push_back(i);
		}
		for(auto &i : noe){
			indeg[nxt[i].first]++;
			gph[nxt[i].first].push_back(i);
		}
		queue<int> que;
		for(auto &i : noe){
			if(!indeg[i]){
				que.push(i);
			}
		}
		while(sz(que)){
			int x = que.front(); que.pop();
			indeg[nxt[x].first]--;
			if(indeg[nxt[x].first] == 0) que.push(nxt[x].first);
		}
		for(auto &i : noe){
			if(!indeg[i]) continue;
			vector<int> v = {i};
			vector<vector<pi>> w;
			lint T = nxt[i].second;
			for(int j = nxt[i].first; j != i; j= nxt[j].first){
				v.push_back(j);
				T += nxt[j].second;
			}
			for(auto &i : v){
				vector<pi> ww;
				dfs(i, 0, ww);
				w.push_back(ww);
			}
			if(T < 0){
				for(auto &j : v){
					nxt[j].second *= -1;
					val[j] *= -1;
				}
				for(auto &j : w){
					for(auto &k : j){
						k.first *= -1;
					}
				}
				T *= -1;
			}
			if(T == 0) T = 696969420420420420ll;
			auto D = [&](lint x){
				if(x >= 0) return x / T;
				return (x - T + 1) / T;
			};
			for(auto &i : v) indeg[i] = 0;
			vector<lint> psum(2 * sz(v) + 1);
			for(int i=0; i<sz(v); i++){
				psum[i + 1] = nxt[v[i]].second;
				psum[i + 1 +sz(v)] = nxt[v[i]].second;
			}
			for(int i=1; i<sz(psum); i++) psum[i] += psum[i-1];
			set<tuple<lint, lint, lint>> s;
			vector<tuple<lint, lint, lint>> lis(2 * sz(v));
			for(int i=0; i<2*sz(v); i++){
				lint key = val[v[i%sz(v)]] - psum[i];
				lis[i] = make_tuple(key - D(key) * T, key, (lint)i);
			}
			for(int i=0; i<sz(v); i++) s.insert(lis[i]);
			for(int i=0; i<sz(v); i++){
				for(auto fuck : w[i]){
					auto k = fuck.first;
					auto l = fuck.second;
					lint curk = k - psum[i];
					auto lbnd = s.lower_bound(make_tuple(curk - D(curk) * T, curk, (lint)-1));
					if(lbnd != s.end() && get<0>(*lbnd) == curk - D(curk) * T){
						lint nxtk = get<1>(*lbnd);
						int dist = get<2>(*lbnd) + dep[qry[l].first] - i;
						int vtx = v[get<2>(*lbnd) % sz(v)];
						lint ndist = dist + ((nxtk - curk) / T) * sz(v);
						result[l] = min(result[l], pi(ndist, vtx));
					}
				}
				s.erase(lis[i]);
				s.insert(lis[i + sz(v)]);
			}
		}
	}
}

int main(){
	long long ff;
	scanf("%d %lld",&n,&ff);
	qry[0].first = 1;
	qry[0].second = ff;
	for(int i=1; i<=n; i++){
		long long a, b, c, d, e;
		scanf("%lld %lld %lld %lld %lld",&a,&b,&c,&d,&e);
		qry[i] = pi(c, a + b);
		nxt[i] = pi(e, d);
		val[i] = a;
	}
	nxt[n + 1] = pi(n + 1, n + 1);
	fill(result, result + n + 1, pi((lint)1e30, -1));
	for(int i=0; i<=n; i++){
		revlist[qry[i].first].emplace_back(qry[i].second, i);
	}
	FindEnd::solve();
	MatchQuery::solve();
	int pos = 0;
	lint ret = 0;
	vector<int> vis(n + 2);
	while(pos != n + 1 && !vis[pos]){
		vis[pos] = 1;
		ret += result[pos].first;
		ret %= mod;
		pos = result[pos].second;
		if(pos == -1) break;
		if(pos == n + 1) break;
		ret++;
		ret %= mod;
	}
	if(pos != n + 1) puts("-1");
	else cout << (int)(ret % mod) << endl;
}
accuracy: 1
time_ms: 160
memory_kb: 63332
final_rank: 4

code_snippet: #include<bits/stdc++.h>
#define ll long long
#define rep(i,a,n) for (int i=(a);i<=(n);i++)
#define per(i,a,n) for (int i=(n);i>=(a);i--)
#define inf 0x3f3f3f3f
#define infll 0x3f3f3f3f3f3f3f3f
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define fi first
#define se second
#define lowbit(i) ((i)&(-i))
#define all(x) x.begin(),x.end()
#define SZ(x) ((int)x.size())
using namespace std;
const int N = 100015, mod = 1e9 + 7;

int n, c[N], e[N], deg[N], step[N], dest[N], dep[N];
vector<int> rt, g[N];
vector<pair<ll, int>> qry[N];
ll dis[N], x0, a[N], b[N], d[N];

struct op {
	ll v; // x - s_u or a_u - s_u
	int u, id; // u
	bool typ;
};

struct Rule {
	bool operator()(const op &u, const op &v) const {
		if (u.u != v.u) return u.u < v.u;

		return u.id < v.id;
	}
};

struct cyc {
	vector<int> p;
	vector<ll> s;
	int m; ll L; bool fl;
	ll I(ll x) { return L == 0 ? x : (x % L + L) % L; }

	void build(vector<int> v) {
		m = SZ(v); p.resize(m + m); s.resize(m + m, 0);
		rep(i, 0, m + m - 1) p[i] = v[i % m];
		rep(i, 1, m + m - 1) s[i] = s[i - 1] + d[p[i - 1]];
		L = s[m];

		if (L < 0) {
			fl = 1; L = -L;
			rep(i, 0, m + m - 1) s[i] = -s[i];
		}
	}

	vector<vector<op>> hyh;
	vector<op> all;

	void add(int u, vector<pair<ll, int>> vec) {

		rep(i, 0, m - 1) if (p[i] == u) {
			u = i; break;
		}

		if (fl) for (auto &[x, y] : vec) x = -x;

		for (auto [x, id] : vec) all.pb((op) {x - s[u], u, id, 0});
	}

	void solve() {
		if (fl) rep(i, 0, m - 1) a[p[i]] = -a[p[i]];

		rep(i, 0, m + m - 1) all.pb((op) {a[p[i]] - s[i], i, -1, 1});

		vector<ll> num;

		for (op o : all) num.pb(I(o.v));

		sort(all(num)); num.erase(unique(all(num)), num.end());

		int q = SZ(num); hyh.resize(q);

		for (op o : all) {
			int u = lower_bound(all(num), I(o.v)) - num.begin();

			hyh[u].pb(o);
		}

		rep(_, 0, q - 1) {
			sort(all(hyh[_]), [](op u, op v) {
				if (u.v != v.v) return u.v < v.v;

				if (u.typ != v.typ) return u.typ < v.typ;

				return u.u < v.u;
			});


			set<op, Rule> S;

			for (op o : hyh[_]) {
				if (o.typ == 0) S.insert(o);
				else {
					int j = o.u;

					for (auto it = S.begin(); it != S.end() && it -> u <= j; it = S.erase(it)) {
						(step[it -> id] += ((L > 0 ? (o.v - it -> v) / L : 0) % mod * m % mod + j - it -> u) % mod) %= mod;
						dest[it -> id] = p[j];
					}
				}
			}

			for (auto o : S) dest[o.id] = o.id;
		}
	}
} C[N];

int tot, bel[N];

void dfs0(int u) {
	for (int v : g[u]) {
		dis[v] = dis[u] + d[v];
		dep[v] = dep[u] + 1;
		dfs0(v);
	}
}

void merge(set<pair<ll, int>> &f, set<pair<ll, int>> &g) {
	if (SZ(f) < SZ(g)) swap(f, g);

	for (auto o : g) f.insert(o);
}

set<pair<ll, int>> dfs1(int u) {
	set<pair<ll, int>> f, nf;

	for (int v : g[u]) nf = dfs1(v), merge(f, nf);

	for (auto [x, id] : qry[u]) f.emplace(x + dis[u], id);

	for (auto it = f.lower_bound({a[u] + dis[u], 0}); it != f.end() && it -> fi == a[u] + dis[u]; it = f.erase(it)) {
		int v = it -> se > 0 ? c[it -> se] : 1;
		step[it -> se] = dep[v] - dep[u];
		dest[it -> se] = u;
	}

	return f;
}

void build() {
	queue<int> q;
	static bool oncyc[N];
	fill(oncyc + 1, oncyc + n + 1, 1);

	rep(i, 1, n) if (deg[i] == 0) q.push(i);

	while (!q.empty()) {
		int u = q.front(); q.pop();
		oncyc[u] = 0;
		int v = e[u];

		if (--deg[v] == 0) q.push(v);
	}

	rep(i, 1, n) if (!oncyc[i]) g[e[i]].pb(i);

	rep(i, 1, n) {
		if (!oncyc[i]) continue;

		vector<int> vec; int x = i;

		while (oncyc[x]) {
			oncyc[x] = 0;
			vec.pb(x);
			x = e[x];
		}

		C[++tot].build(vec);

		for (int x : vec) bel[x] = tot, rt.pb(x);
	}

	rt.pb(n + 1);

	for (int u : rt) dfs0(u);
}

int main() {
#ifdef Asuka
	freopen("data.in", "r", stdin);
	freopen("data.out", "w", stdout);
#endif
	scanf("%d%lld", &n, &x0);

	rep(i, 1, n) scanf("%lld%lld%d%lld%d", &a[i], &b[i], &c[i], &d[i], &e[i]), deg[e[i]]++;

	build();

	rep(i, 1, n) qry[c[i]].emplace_back(a[i] + b[i], i);

	qry[1].emplace_back(x0, 0);

	for (int u : rt) {
		auto o = dfs1(u); vector<pair<ll, int>> vec;

		for (auto _ : o) vec.pb(_);

		for (auto [x, id] : vec) step[id] = dep[id > 0 ? c[id] : 1] - dep[n + 1], dest[id] = n + 1;

		if (u == n + 1) continue;

		C[bel[u]].add(u, vec);
	}

	rep(i, 1, tot) C[i].solve();

	static bool vis[N];

	int x = 0, ans = 0;

	while (!vis[x]) {
		vis[x] = 1;

		if (x == n + 1) break;

		(ans += step[x] + (x > 0)) %= mod;
		x = dest[x];
	}

	if (x == n + 1) {
		printf("%d\n", ans);

	} else {
		printf("-1\n");
	}

	return 0;
}
accuracy: 1
time_ms: 2240
memory_kb: 60424
final_rank: 12

code_snippet: #include <bits/stdc++.h>
#define For(i,a,b) for(int i=a;i<=b;i++)
#define Rev(i,a,b) for(int i=a;i>=b;i--)
#define Fin(file) freopen(file,"r",stdin)
#define Fout(file) freopen(file,"w",stdout)
#define clr(a,v) memset(a,v,sizeof(a))
#define int long long
using namespace std;

const int N=4e5+5,INF=1e9,mod=1e9+7;

int n,x0,px[N],a[N],b[N],c[N],d[N];
int fa[N],dis[N];
vector< pair<int,int> > son[N];
int root,vis[N];
vector< pair<int,int> > qry[N];
int top[N],tod[N],dep[N];
map<int,int> mp;
int lisx[N],lisid[N],lish[N],lcnt;
map< int,pair<int,int> > xp;
struct Node{
    int x,c,p;
    bool operator< (const Node& nd) const
    {
        if(x!=nd.x) return x<nd.x;
        return c<nd.c;
    }
};
map< int,vector<Node> > vp;

void dfs(int u,int h,int has)
{
    // printf("u=%lld,h=%lld\n",u,h);
    vis[u]=1;
    if(u==n+1) has=1;
    // int tmp=mp[px[u]+h];
    int tmp,hasm;
    if(mp.count(px[u]+h)){
        hasm=1; tmp=mp[px[u]+h];
    }
    else{
        hasm=0; tmp=0;
    }
    mp[px[u]+h]=u;
    for(auto pr:qry[u]){
        // printf("qr(%lld,%lld)\n",pr.first,pr.second);
        // cerr<<mp.count(pr.first+h)<<endl;
        // cerr<<mp[pr.first+h]<<endl;
        if(mp.count(pr.first+h) && (!has || dep[mp[pr.first+h]]>dep[n+1])){
            top[pr.second]=mp[pr.first+h];
            tod[pr.second]=dep[u]-dep[top[pr.second]];
            // printf("got query[%lld]: top=%lld,tod=%lld\n",pr.second,top[pr.second],tod[pr.second]);
        }
        else if(has){
            top[pr.second]=n+1;
            tod[pr.second]=dep[u]-dep[n+1];
        }
        else{
            // printf("(%lld,%lld)\n",pr.first,pr.second);
            // cout<<"u="<<u<<endl;
            // cout<<"h="<<h<<endl;
            lcnt++; lisx[lcnt]=pr.first+h; lisid[lcnt]=pr.second; lish[lcnt]=dep[u];
        }
    }
    for(auto pr:son[u]){
        if(pr.first==root) continue;
        dep[pr.first]=dep[u]+(pr.first!=0);
        dfs(pr.first,h+pr.second,has);
    }
    if(!hasm){
    	assert(mp.count(px[u]+h));
        mp.erase(px[u]+h);
    }
    else{
        mp[px[u]+h]=tmp;
    }
}

signed main()
{
    // Fin("hh.in");
    // Fout("hh.out");

    cin>>n>>x0;
    For(i,1,n) cin>>px[i]>>a[i]>>b[i]>>c[i]>>d[i];
    px[0]=-1e18;

    son[1].push_back(make_pair(0,0));
    qry[0].push_back(make_pair(x0,0));
    // printf("query:(1,%lld)\n",x0);
    For(i,1,n){
        fa[i]=d[i];
        dis[i]=c[i];
        son[d[i]].push_back(make_pair(i,c[i]));
        qry[b[i]].push_back(make_pair(px[i]+a[i],i));
        // printf("query:(%lld,%lld)\n",b[i],px[i]+a[i]);
    }

    For(i,1,n+1){
        if(vis[i]) continue;
        mp.clear();
        int oo=i;
        while(!vis[oo]){
            if(fa[oo]==0) break;
            vis[oo]=1; oo=fa[oo];
        }
        root=oo;
        // cout<<"root="<<root<<endl;
        lcnt=0;
        dep[root]=0;
        dfs(root,0,0);

        if(fa[root]==0) continue;

        int ss=dis[root];
        for(int o=fa[root];o!=root;o=fa[o]) ss+=dis[o];

        // For(j,1,lcnt) printf("<%lld,%lld,%lld> ",lisx[j],lisid[j],lish[j]);
        // puts("");
        // cerr<<"ss="<<ss<<endl;

        if(ss==0){
            xp.clear();
            int x=dis[root];
            for(int o=fa[root],c=1;o!=root;o=fa[o],c++){
                if(!xp.count(x)) xp[px[o]-x]=make_pair(o,c);
                x+=dis[o];
            }
            For(j,1,lcnt){
                int x=lisx[j],id=lisid[j];
                if(xp.count(x)){
                    top[id]=xp[x].first;
                    tod[id]=xp[x].second+lish[j];
                }
            }
        }
        else if(ss>0){
            vp.clear();
            int xx=0;
            int c=0;
            vp[(px[root]%ss+ss)%ss].push_back({px[root],c,root});
            c++; xx+=dis[root];
            for(int o=fa[root];o!=root;o=fa[o],c++){
                vp[((px[o]-xx)%ss+ss)%ss].push_back({px[o]-xx,c,o});
                xx+=dis[o];
            }
            // cerr<<"c="<<c<<endl;
            for(auto& vv:vp){
                sort(vv.second.begin(),vv.second.end());
                // cout<<vv.first<<": ";
                // for(auto pr:vv.second) printf("(%lld,%lld,%lld) ",pr.x,pr.c,pr.p);
                // cout<<endl;
            }
            For(j,1,lcnt){
                int x=lisx[j],id=lisid[j];
                int sx=(x%ss+ss)%ss;
                if(vp.count(sx)){
                    vector<Node> :: iterator it = lower_bound(vp[sx].begin(),vp[sx].end(),(Node){x,0,0});
                    if(it==vp[sx].end()) continue;
                    top[id]=it->p;
                    tod[id]=(it->x-x)/ss*c+it->c+lish[j];
                }
            }
        }
        else{
            ss=-ss;
            vp.clear();
            int xx=0;
            int c=0;
            vp[(px[root]%ss+ss)%ss].push_back({px[root],0,root});
            c++; xx+=dis[root];
            for(int o=fa[root];o!=root;o=fa[o],c++){
                vp[((px[o]-xx)%ss+ss)%ss].push_back({px[o]-xx,-c,o});
                xx+=dis[o];
            }
            // cerr<<"c="<<c<<endl;
            for(auto& vv:vp){
                sort(vv.second.begin(),vv.second.end());
                // cout<<vv.first<<": ";
                // for(auto pr:vv.second) printf("(%lld,%lld,%lld) ",pr.x,pr.c,pr.p);
                // cout<<endl;
            }
            For(j,1,lcnt){
                int x=lisx[j],id=lisid[j];
                int sx=(x%ss+ss)%ss;
                if(vp.count(sx)){
                    // cout<<x<<' '<<id<<endl;
                    vector<Node> :: iterator it = lower_bound(vp[sx].begin(),vp[sx].end(),(Node){x,INF,0});
                    if(it==vp[sx].begin()) continue;
                    it--;
                    // printf("[%lld,%lld,%lld]\n",it->x,it->c,it->p);
                    top[id]=it->p;
                    tod[id]=(x-it->x)/ss*c-it->c+lish[j];
                }
            }
        }
    }

    // For(i,0,n) printf("(%lld,%lld)\n",top[i],tod[i]);
    // cout<<endl;

    clr(vis,0);
    int p=0,ans=0;
    while(p!=n+1){
        // cerr<<"p="<<p<<endl;
        if(vis[p]){
            ans=-1; break;
        }
        vis[p]=1;
        ans+=tod[p];
        if(p!=0) ans++;
        p=top[p];
        if(b[p]==n+1){
            ans++;
            break;
        }
        if(p==n+1) break;
        if(top[p]==0){
            ans=-1; break;
        }
    }

    cout<<ans%mod<<endl;

    // cerr<<"Time = "<<clock()<<" ms"<<endl;
    return 0;
}
// qwqwqwqwqqwqwqwqwqwqwqwqwq
accuracy: 1
time_ms: 220
memory_kb: 82312
final_rank: 7

code_snippet: #include<bits/stdc++.h>
using namespace std;

#define rep(i,a,b) for(int i=(a),i##end=(b);i<=i##end;++i)
#define per(i,a,b) for(int i=(a),i##end=(b);i>=i##end;--i)

template<typename T>void chkmax(T&x,T y){if(x<y)x=y;}
template<typename T>void chkmin(T&x,T y){if(x>y)x=y;}

#define pb push_back
#define ALL(x) (x).begin(),(x).end()
#define mem(x) memset((x),0,sizeof(x))

typedef long long ll;
typedef vector<int>vi;
typedef pair<int,int>pii;

namespace orzjk{
  const int SZ=1e6;
  char buf[SZ],*p1=buf,*p2=buf;
  char nc(){
    return p1==p2&&(p2=(p1=buf)+fread(buf,1,SZ,stdin),p1==p2)?EOF:*p1++;
  }
}
using orzjk::nc;

//#define nc getchar

ll read(){
  ll x=0,f=1;char c=nc();
  while(c<48)c=='-'&&(f=-1),c=nc();
  while(c>47)x=x*10+(c^48),c=nc();
  return x*f;
}

const int P=1e9+7;

const int maxn=1e5+10;
int n,ans;ll x0;
array<ll,5>A[maxn];

int deg[maxn],fa[maxn],dep[maxn],anc[maxn];ll dis[maxn];

namespace tree{

#define mid ((l+r)>>1)

ll dat[maxn];int vsz=1;
void discretize(){
  sort(dat+1,dat+vsz+1);
  vsz=unique(dat+1,dat+vsz+1)-dat-1;
}
int get(ll x){
  int i=lower_bound(dat+1,dat+vsz+1,x)-dat;
  return dat[i]==x?i:0;
}

int tot,rt[maxn],ls[maxn*20],rs[maxn*20],val[maxn*20];
void ins(int&k,int rt,int l,int r,int x,int v){
  k=++tot,ls[k]=ls[rt],rs[k]=rs[rt],val[k]=val[rt];
  if(l==r)val[k]=v;
  else x<=mid?ins(ls[k],ls[rt],l,mid,x,v):ins(rs[k],rs[rt],mid+1,r,x,v);
}
int ask(int k,int l,int r,int x){
  if(l==r)return val[k];
  return x<=mid?ask(ls[k],l,mid,x):ask(rs[k],mid+1,r,x);
}

#undef mid

}

bool vis[maxn];
int cir,bl[maxn],tid[maxn];

struct circle{
  bool sgn;ll all;
  vi nod;vector<ll>D;int sz;
  void push(int u){
    tid[u]=sz++;
    nod.push_back(u);
    D.push_back(all),all+=A[u][3];
  }
  typedef pair<ll,int>pr;
  map<ll,set<pr>>mp;
  void build(){
    if(all<0)sgn=1,all=-all;
    sgn^=1;
    rep(i,0,sz-1){
      int u=nod[i];
      ll v=A[u][0]-D[i];
      if(!all){
        mp[v].insert({v,i});continue;
      }
      if(sgn)v=-v;
      mp[(v%all+all)%all].insert({v,i});
    }
  }
}C[maxn];

void topo(){
  static int Q[maxn];
  int l=1,r=0;
  rep(i,1,n)fa[i]=A[i][4];
  rep(i,1,n)if(!deg[i])Q[++r]=i;
  while(l<=r){
    int u=Q[l++],v=fa[u];
    if(v)if(v>n||!--deg[v])Q[++r]=v;
  }
  rep(i,1,n)if(deg[i])Q[++r]=i,fa[i]=0;
  Q[++r]=n+1;
  per(i,r,1){
    int u=Q[i];
    if(fa[u])anc[u]=anc[fa[u]],dep[u]=dep[fa[u]]+1,dis[u]=dis[fa[u]]+A[u][3];
    else anc[u]=u;
    tree::dat[++tree::vsz]=dis[u]+A[u][0];
  }
  tree::discretize();
  per(i,r,1){
    int u=Q[i];
    if(u<=n)tree::ins(tree::rt[u],tree::rt[fa[u]],1,tree::vsz,tree::get(dis[u]+A[u][0]),u);
  }
  rep(u,1,n)if(deg[u]&&!vis[u]){
    ++cir;
    int cur=u;
    do{
//      printf("(%d) bl %d\n",cur,cir);
      vis[cur]=1;
      bl[cur]=cir;
      C[cir].push(cur);
      cur=A[cur][4];
    }while(cur!=u);
    C[cir].build();
  }
}

int main(){
  cin>>n>>x0;
  rep(i,1,n){
    rep(j,0,4)A[i][j]=read();
    deg[A[i][4]]++;
  }
  topo();
  int u=1;
  memset(vis,0,sizeof vis);
//  rep(u,1,n)printf("%d : %lld\n",u,dis[u]);
  while(1){
//    printf("(%d %lld) %d\n",u,x0,ans);
    auto trans=[&](int v){
//      assert(x0==A[v][0]);
      if(vis[v])puts("-1"),exit(0);
      vis[v]=1,u=A[v][2],x0=A[v][0]+A[v][1],ans=(ans+1)%P;
    };
    {
      int v=tree::get(x0+dis[u]);
      if(v)v=tree::ask(tree::rt[u],1,tree::vsz,v);
      if(v){
        (ans+=dep[u]-dep[v])%=P,x0+=dis[u]-dis[v];
        trans(v);
        continue;
      }
      (ans+=dep[u])%=P,x0+=dis[u],u=anc[u];
    }
//    printf("[%d %lld) %d\n",u,x0,ans);
    if(u>n)break;
    {
      const auto&C=::C[bl[u]];
      int s=tid[u];
      ll o=x0-C.D[s];
      if(!C.all){
        auto it=C.mp.find(o);
        if(it==C.mp.end())puts("-1"),exit(0);
        const auto&S=it->second;
        auto p=S.lower_bound({o,s});
        int v=C.nod[(p==S.end()?S.begin():p)->second];
        x0+=C.D[tid[v]]-C.D[s];
        trans(v);
        continue;
      }
      if(C.sgn)o=-o;
      auto it=C.mp.find((o%C.all+C.all)%C.all);
      if(it==C.mp.end())puts("-1"),exit(0);
      const auto&S=it->second;
//      printf("$$%lld\n",o);
//      for(auto p:S)printf("@(%lld %d) %lld\n",p.first,p.second,C.all);
      auto p=S.lower_bound({o,s});
      if(p==S.end()||p->first>o){
        p=S.lower_bound({o,0});
        if(p==S.begin())puts("-1"),exit(0);
        --p;
        p=S.lower_bound({p->first,0});
      }
      int v=C.nod[p->second];
      ans=(ans+(o-p->first)/C.all%P*C.sz+tid[v]-s+P)%P;
      trans(v);
    }
  }
  cout<<ans<<endl;
  return 0;
}
accuracy: 0.7837837837837838
time_ms: 80
memory_kb: 63220
final_rank: 13

code_snippet: #include<bits/stdc++.h>
using namespace std;
const int MOD=1000000007;
int n,c[100003],e[100003],cir[100003],bg[100003],col[100003],N,tp[100003],val[100003],sz[100003],dep[100003];
map<long long,set<pair<int,int> > >mp[100003];
long long a[100003],b[100003],d[100003],sum[100003],ans;
vector<int>v[100003],cv;
vector<long long>g[100003],cg;
long long T[100003],sum2[100003];
int col2[100003],N2,ord[100003],sz2[100003];
void inittree(int x,int p){
	bg[x]=x;
	sz[x]=1;
	for(int i=0;i<v[x].size();i++)
		if(v[x][i]!=p&&!cir[v[x][i]]){
			sum[v[x][i]]=sum[x]+g[x][i];
			dep[v[x][i]]=dep[x]+1;
			inittree(v[x][i],x);
			if(sz[v[x][i]]>=sz[bg[x]]){
				bg[x]=v[x][i];
				val[x]=val[v[x][i]]+1;
			}
			sz[x]+=sz[v[x][i]];
		}
	for(int i=0;i<v[x].size();i++)
		if(v[x][i]!=p&&!cir[v[x][i]])
			if(v[x][i]!=bg[x]){
				tp[N]=v[x][i];
				int nw=tp[N];
				while(1){
					col[nw]=N;
					mp[N][a[nw]+sum[nw]].insert({val[nw],nw});
					if(nw==bg[nw])
						break;
					nw=bg[nw];
				}
				N++;
			}
	if(p==-1){
		tp[N]=x;
		int nw=tp[N];
		while(1){
			col[nw]=N;
			mp[N][a[nw]+sum[nw]].insert({val[nw],nw});
			if(nw==bg[nw])
				break;
			nw=bg[nw];
		}
		N++;
	}
}
map<long long,set<pair<long long,int> > >mp2[100003];
int query(int x,long long A){
	if(mp[col[x]][A].lower_bound({val[x],-1})!=mp[col[x]][A].end())
	{
		int ret=(*mp[col[x]][A].lower_bound({val[x],-1})).second;
		ans=(ans+dep[x]-dep[ret])%MOD;
		return ret;
	}
	if(!cir[tp[col[x]]]){
		int nxt=e[tp[col[x]]];
		ans=(ans+dep[x]-dep[nxt])%MOD;
		return query(nxt,A);
	}
	ans=(ans+dep[x]-dep[tp[col[x]]])%MOD;
	x=tp[col[x]];
	if(x==n){
		cout<<ans<<endl;
		exit(0);
	}
	if(T[col2[x]]>0){
		long long mod=((A-sum2[x])%T[col2[x]]+T[col2[x]])%T[col2[x]];
		if(mp2[col2[x]][mod].lower_bound({(A-sum2[x]-mod)/T[col2[x]]*sz2[col2[x]]+ord[x],-1})==mp2[col2[x]][mod].end()){
			cout<<-1<<endl;
			exit(0);
		}else{
			pair<long long,int>tmp=(*mp2[col2[x]][mod].lower_bound({(A-sum2[x]-mod)/T[col2[x]]*sz2[col2[x]]+ord[x],-1}));
			ans=(ans+tmp.first-((A-sum2[x]-mod)/T[col2[x]]*sz2[col2[x]]+ord[x]))%MOD;
			return tmp.second;
		}
	}
	if(T[col2[x]]==0){
		long long mod=A-sum2[x];
		if(mp2[col2[x]][mod].lower_bound({ord[x],-1})==mp2[col2[x]][mod].end()){
			cout<<-1<<endl;
			exit(0);
		}else{
			pair<long long,int>tmp=(*mp2[col2[x]][mod].lower_bound({ord[x],-1}));
			ans=(ans+tmp.first-ord[x])%MOD;
			return tmp.second;
		}
	}
	if(T[col2[x]]<0){
		long long mod=((sum2[x]-A)%(-T[col2[x]])-T[col2[x]])%(-T[col2[x]]);
		if(mp2[col2[x]][mod].lower_bound({(sum2[x]-A-mod)/(-T[col2[x]])*sz2[col2[x]]+ord[x],-1})==mp2[col2[x]][mod].end()){
			cout<<-1<<endl;
			exit(0);
		}else{
			pair<long long,int>tmp=(*mp2[col2[x]][mod].lower_bound({(sum2[x]-A-mod)/(-T[col2[x]])*sz2[col2[x]]+ord[x],-1}));
			ans=(ans+tmp.first-((sum2[x]-A-mod)/(-T[col2[x]])*sz2[col2[x]]+ord[x]))%MOD;
			return tmp.second;
		}
	}
}
bool vis[100003];
int main(){
	long long _x;
	int pos=0;
	cin>>n>>_x;
	cir[n]=1;
	for(int i=0;i<n;i++){
		cin>>a[i]>>b[i]>>c[i]>>d[i]>>e[i];
		c[i]--;e[i]--;
		v[e[i]].push_back(i);
		g[e[i]].push_back(d[i]);
		cir[e[i]]++;
	}
	queue<int>q;
	for(int i=0;i<n;i++)
		if(cir[i]==0)
			q.push(i);
	while(q.size()){
		int nw=q.front();
		q.pop();
		if(!--cir[e[nw]])
			q.push(e[nw]);
	}
	for(int i=0;i<=n;i++)
		if(cir[i])
			inittree(i,-1);
	memset(col2,-1,sizeof(col2));
	for(int i=0;i<n;i++)
		if(cir[i]&&col2[i]==-1){
			int nw=i;
			cv.clear();
			cg.clear();
			cg.push_back(0);
			do{
				col2[nw]=N2;
				ord[nw]=cv.size();
				cv.push_back(nw);
				cg.push_back(d[nw]);
				nw=e[nw];
			}while(nw!=i);
			sz2[N2]=cv.size();
			for(int j=1;j<=sz2[N2];j++)
				cg[j]+=cg[j-1];
			for(int j=0;j<sz2[N2];j++)
				sum2[cv[j]]=cg[j];
			T[N2]=cg.back();
			if(T[N2]>0)
				for(int j=0;j<sz2[N2];j++){
					long long mod=((a[cv[j]]-cg[j])%T[N2]+T[N2])%T[N2];
					mp2[N2][mod].insert({(a[cv[j]]-cg[j]-mod)/T[N2]*sz2[N2]+j,cv[j]});
				}
			if(T[N2]==0)
				for(int j=0;j<sz2[N2];j++){
					mp2[N2][a[cv[j]]-cg[j]].insert({j,cv[j]});
					mp2[N2][a[cv[j]]-cg[j]].insert({j+sz2[N2],cv[j]});
				}
			if(T[N2]<0)
				for(int j=0;j<sz2[N2];j++){
					long long mod=((cg[j]-a[cv[j]])%(-T[N2])-T[N2])%(-T[N2]);
					mp2[N2][mod].insert({(cg[j]-a[cv[j]]-mod)/(-T[N2])*sz2[N2]+j,cv[j]});
				}
			N2++;
		}
	while(1){
		pos=query(pos,_x+sum[pos]);
		_x=a[pos];
		if(vis[pos]){
			cout<<-1<<endl;
			return 0;
		}vis[pos]=1;
		_x+=b[pos];
		ans=(ans+1)%MOD;
		pos=c[pos];
		if(pos==n)
			break;
	}cout<<ans<<endl;
}
accuracy: 1
time_ms: 330
memory_kb: 63876
final_rank: 6

code_snippet: #include <algorithm>
#include <iostream>
#include <queue>
#include <set>
#include <utility>
#include <vector>
const int N = 100015, mod = 1e9 + 7;
int n, c[N], e[N], deg[N], step[N], dest[N], dep[N];
std::vector<int> rt, g[N];
std::vector<std::pair<long long, int>> qry[N];
long long dis[N], x0, a[N], b[N], d[N];
struct op {
  long long v;  // x - s_u or a_u - s_u
  int u, id;    // u
  bool typ;
  op(long long v, int u, int id, bool typ) : v(v), u(u), id(id), typ(typ) {}
};
struct Rule {
  bool operator()(const op &u, const op &v) const {
    if (u.u != v.u) return u.u < v.u;
    return u.id < v.id;
  }
};
struct cyc {
  std::vector<int> p;
  std::vector<long long> s;
  int m;
  long long L;
  bool fl;
  long long I(long long x) { return L == 0 ? x : (x % L + L) % L; }
  void build(std::vector<int> v) {
    m = v.size();
    p.resize(m + m);
    s.resize(m + m, 0);
    for (int i = 0; i <= m + m - 1; i++) p[i] = v[i % m];
    for (int i = 1; i <= m + m - 1; i++) s[i] = s[i - 1] + d[p[i - 1]];
    L = s[m];
    if (L < 0) {
      fl = 1;
      L = -L;
      for (int i = 0; i <= m + m - 1; i++) s[i] = -s[i];
    }
  }
  std::vector<std::vector<op>> hyh;
  std::vector<op> all;
  void add(int u, std::vector<std::pair<long long, int>> vec) {
    for (int i = 0; i <= m - 1; i++)
      if (p[i] == u) {
        u = i;
        break;
      }
    if (fl)
      for (auto &[x, y] : vec) x = -x;
    for (auto [x, id] : vec) all.emplace_back(x - s[u], u, id, 0);
  }
  void solve() {
    if (fl)
      for (int i = 0; i <= m - 1; i++) a[p[i]] = -a[p[i]];
    for (int i = 0; i <= m + m - 1; i++)
      all.emplace_back(a[p[i]] - s[i], i, -1, 1);
    std::vector<long long> num;
    for (op o : all) num.emplace_back(I(o.v));
    std::sort(num.begin(), num.end());
    num.erase(std::unique(num.begin(), num.end()), num.end());
    int q = num.size();
    hyh.resize(q);
    for (op o : all) {
      int u = std::lower_bound(num.begin(), num.end(), I(o.v)) - num.begin();
      hyh[u].emplace_back(o);
    }
    for (int _ = 0; _ <= q - 1; _++) {
      sort(hyh[_].begin(), hyh[_].end(), [](op u, op v) {
        if (u.v != v.v) return u.v < v.v;
        if (u.typ != v.typ) return u.typ < v.typ;
        return u.u < v.u;
      });
      std::set<op, Rule> S;
      for (op o : hyh[_]) {
        if (o.typ == 0)
          S.insert(o);
        else {
          int j = o.u;
          for (auto it = S.begin(); it != S.end() && it->u <= j;
               it = S.erase(it)) {
            (step[it->id] +=
             ((L > 0 ? (o.v - it->v) / L : 0) % mod * m % mod + j - it->u) %
             mod) %= mod;
            dest[it->id] = p[j];
          }
        }
      }
      for (auto o : S) dest[o.id] = o.id;
    }
  }
} C[N];
int tot, bel[N];
void dfs0(int u) {
  for (int v : g[u]) {
    dis[v] = dis[u] + d[v];
    dep[v] = dep[u] + 1;
    dfs0(v);
  }
}
void merge(std::set<std::pair<long long, int>> &f,
           std::set<std::pair<long long, int>> &g) {
  if (f.size() < g.size()) swap(f, g);
  for (auto o : g) f.insert(o);
}
std::set<std::pair<long long, int>> dfs1(int u) {
  std::set<std::pair<long long, int>> f, nf;
  for (int v : g[u]) nf = dfs1(v), merge(f, nf);
  for (auto [x, id] : qry[u]) f.emplace(x + dis[u], id);
  for (auto it = f.lower_bound({a[u] + dis[u], 0});
       it != f.end() && it->first == a[u] + dis[u]; it = f.erase(it)) {
    int v = it->second > 0 ? c[it->second] : 1;
    step[it->second] = dep[v] - dep[u];
    dest[it->second] = u;
  }
  return f;
}
void build() {
  std::queue<int> q;
  static bool oncyc[N];
  std::fill(oncyc + 1, oncyc + n + 1, 1);
  for (int i = 1; i <= n; i++)
    if (deg[i] == 0) q.emplace(i);
  while (!q.empty()) {
    int u = q.front();
    q.pop();
    oncyc[u] = 0;
    int v = e[u];
    if (--deg[v] == 0) q.emplace(v);
  }
  for (int i = 1; i <= n; i++)
    if (!oncyc[i]) g[e[i]].emplace_back(i);
  for (int i = 1; i <= n; i++) {
    if (!oncyc[i]) continue;
    std::vector<int> vec;
    int x = i;
    while (oncyc[x]) {
      oncyc[x] = 0;
      vec.emplace_back(x);
      x = e[x];
    }
    C[++tot].build(vec);
    for (int x : vec) bel[x] = tot, rt.emplace_back(x);
  }
  rt.emplace_back(n + 1);
  for (int u : rt) dfs0(u);
}
int main(int argc, char const *argv[]) {
  std::ios_base::sync_with_stdio(false), std::cin.tie(nullptr);
  std::cin >> n >> x0;
  for (int i = 1; i <= n; i++)
    std::cin >> a[i] >> b[i] >> c[i] >> d[i] >> e[i], deg[e[i]]++;
  build();
  for (int i = 1; i <= n; i++) qry[c[i]].emplace_back(a[i] + b[i], i);
  qry[1].emplace_back(x0, 0);
  for (int u : rt) {
    auto o = dfs1(u);
    std::vector<std::pair<long long, int>> vec;
    for (auto _ : o) vec.emplace_back(_);
    for (auto [x, id] : vec)
      step[id] = dep[id > 0 ? c[id] : 1] - dep[n + 1], dest[id] = n + 1;
    if (u == n + 1) continue;
    C[bel[u]].add(u, vec);
  }
  for (int i = 1; i <= tot; i++) C[i].solve();
  static bool vis[N];
  int x = 0, ans = 0;
  while (!vis[x]) {
    vis[x] = 1;
    if (x == n + 1) break;
    (ans += step[x] + (x > 0)) %= mod;
    x = dest[x];
  }
  if (x == n + 1) {
    std::cout << ans << '\n';
  } else {
    std::cout << "-1\n";
  }
  return 0;
}
accuracy: 1
time_ms: 2240
memory_kb: 60200
final_rank: 11

code_snippet: /*
after dusk passed,
there is a starry sky.
*/
#include <bits/stdc++.h>
#define inf 0x3f3f3f3f
#define m_k make_pair
#define mod 1000000007
#define int long long
#define len(a) (int)a.size()
using namespace std;
const int N=2*1e5+100;
int n,x0,a[N],b[N],c[N],d[N],e[N],w,vi[N],rt[N],dt[N];
int tr[N],id[N],sum[N];
vector <int> cir[N],E[N];
inline void add(int &a,int b){a=((a+b>=mod)?a+b-mod:a+b);}
inline void del(int &a,int b){a=((a-b<0)?a-b+mod:a-b);}
inline void mul(int &a,int b){a=a*b%mod;}
inline int m_pow(int a,int b)
{
	int ans=1;
	while (b)
	{
		if (b&1) mul(ans,a);
		b>>=1;
		mul(a,a);
	}
	return ans;
}
inline void ckmin(int &a,int b){a=((a<b)?a:b);}
inline void ckmax(int &a,int b){a=((a>b)?a:b);}
inline int read()
{
	int f=1,x=0;char s=getchar();
	while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}
	while(s>='0'&&s<='9'){x=x*10+s-'0';s=getchar();}
	return x*f;
}
namespace con
{
	int to[N],cost[N],vi[N];
	void init(){memset(to,-1,sizeof(to));}
	void add_edge(int x,int y,int z)
	{
		to[x]=y;
		cost[x]=z;
	}
	void solve(int x)
	{
		// for (int i=0;i<=n;i++) printf("%lld ",to[i]);
		// printf("\n");
		int ans=0;
		while (x!=n+1)
		{
			vi[x]=1;
			if (to[x]==-1||vi[to[x]])
			{
				printf("-1\n");
				exit(0);
			}
			add(ans,cost[x]%mod);
			x=to[x];
		}
		printf("%lld\n",ans);
	}
}
vector <int> p[N];
int ok[N],de[N];
unordered_map <int,int> mp;
set <pair<int,int> > s[N];
void dfs(int x,int s,int fr)
{
	int last=-1;
	if (x!=n+1)
	{
		if (mp.count(a[x]+s)) last=mp[a[x]+s];
		mp[a[x]+s]=x;
	}
	for (int id:p[x])
	{
		int now=a[id]+b[id]+s;dt[id]=s;
		rt[id]=fr;
		if (mp.count(now))
		{
			ok[id]=1;
			con::add_edge(id,mp[now],de[x]-de[mp[now]]+1);
		}
		else if (fr==n+1)
		{
			ok[id]=1;
			con::add_edge(id,n+1,de[x]);
		}
	}
	for (int u:E[x])
	{
		de[u]=de[x]+1;
		dfs(u,s+d[u],fr);
	}
	if (x!=n+1)
	{
		if (last==-1) mp.erase(a[x]+s);
		else mp[a[x]+s]=last;
	}
}
int re(int a,int b){return (a%b+b)%b;}
signed main()
{
	con::init();
	n=read();x0=read();
	for (int i=1;i<=n;i++) a[i]=read(),b[i]=read(),c[i]=read(),d[i]=read(),e[i]=read();
	for (int i=1;i<=n;i++) if (!vi[i])
	{
		stack <int> st;
		int x=i;
		while (1)
		{
			if (e[x]==n+1) break;
			st.push(x);vi[x]=i;
			if (!vi[e[x]]) x=e[x];
			else
			{
				if (vi[e[x]]!=i) break;
				w++;
				while (st.top()!=e[x]) cir[w].push_back(st.top()),st.pop();
				cir[w].push_back(st.top());st.pop();
				reverse(cir[w].begin(),cir[w].end());
				break;
			}
		}
	}
	memset(vi,0,sizeof(vi));
	for (int i=1;i<=w;i++) for (int x:cir[i]) vi[x]=i;
	vi[n+1]=w+1;
	for (int i=1;i<=n;i++) if (!vi[i]) E[e[i]].push_back(i);
	a[0]=x0;b[0]=0;c[0]=1;
	for (int i=0;i<=n;i++) p[c[i]].push_back(i);
	for (int i=1;i<=n+1;i++) if (vi[i])
	{
		mp.clear();
		dfs(i,0,i);
	}
	for (int i=1;i<=w;i++) p[i].clear();
	for (int i=0;i<=n;i++) if (!ok[i]) p[vi[rt[i]]].push_back(i);
	for (int i=1;i<=w;i++) if (!p[i].empty())
	{
		for (int j=0;j<len(cir[i]);j++) tr[cir[i][j]]=j+1;
		sort(p[i].begin(),p[i].end(),[](int a,int b){
			return tr[rt[a]]<tr[rt[b]];
		});
		int m=0,all=0,cnt=0;
		for (int j:cir[i]) id[++m]=j,all+=d[j];
		for (int j:cir[i]) id[++m]=j;
		for (int j=1;j<=len(cir[i]);j++) s[j].clear();
		for (int j=1;j<=m;j++) sum[j]=sum[j-1]+d[id[j-1]];
		if (all>0)
		{
			mp.clear();
			auto add=[&](int pos)
			{
				int now=a[id[pos]]-sum[pos],r=re(now,all);
				if (!mp.count(r)) mp[r]=++cnt;
				s[mp[r]].insert(m_k(now,pos));
			};
			auto del=[&](int pos)
			{
				int now=a[id[pos]]-sum[pos],r=re(now,all);
				s[mp[r]].erase(m_k(now,pos));
			};
			for (int j=1;j<=len(cir[i])-1;j++) add(j);
			for (int j=1,k=0;j<=len(cir[i]);j++)
			{
				if (j>1) del(j-1);
				add(j+len(cir[i])-1);
				while (k<len(p[i])&&tr[rt[p[i][k]]]==j)
				{
					int ID=p[i][k++],now=a[ID]+b[ID]+dt[ID]-sum[j],r=re(now,all);
					if (mp.count(r))
					{
						int to=mp[r];
						auto it=s[to].lower_bound(m_k(now,0));
						if (it!=s[to].end())
						{
							to=(*it).second;
							con::add_edge(ID,id[to],de[c[ID]]+to-j+((*it).first-now)/all*len(cir[i])+1);
						}
					}
				}
			}
		}
		else if (all==0)
		{
			mp.clear();
			auto add=[&](int pos)
			{
				int now=a[id[pos]]-sum[pos];
				if (!mp.count(now)) mp[now]=++cnt;
				s[mp[now]].insert(m_k(pos,0));
			};
			auto del=[&](int pos)
			{
				int now=a[id[pos]]-sum[pos];
				s[mp[now]].erase(m_k(pos,0));
			};
			for (int j=1;j<=len(cir[i])-1;j++) add(j);
			for (int j=1,k=0;j<=len(cir[i]);j++)
			{
				if (j>1) del(j-1);
				add(j+len(cir[i])-1);
				while (k<len(p[i])&&tr[rt[p[i][k]]]==j)
				{
					int ID=p[i][k++],now=a[ID]+b[ID]+dt[ID]-sum[j];
					if (mp.count(now))
					{
						int to=mp[now];
						auto it=s[to].begin();
						if (it!=s[to].end())
						{
							to=(*it).first;
							con::add_edge(ID,id[to],de[c[ID]]+to-j+1);
						}
					}
				}
			}
		}
		else
		{
			all=-all;
			mp.clear();
			auto add=[&](int pos)
			{
				int now=a[id[pos]]-sum[pos],r=re(now,all);
				if (!mp.count(r)) mp[r]=++cnt;
				s[mp[r]].insert(m_k(now,-pos));
			};
			auto del=[&](int pos)
			{
				int now=a[id[pos]]-sum[pos],r=re(now,all);
				s[mp[r]].erase(m_k(now,-pos));
			};
			for (int j=1;j<=len(cir[i])-1;j++) add(j);
			for (int j=1,k=0;j<=len(cir[i]);j++)
			{
				if (j>1) del(j-1);
				add(j+len(cir[i])-1);
				while (k<len(p[i])&&tr[rt[p[i][k]]]==j)
				{
					int ID=p[i][k++],now=a[ID]+b[ID]+dt[ID]-sum[j],r=re(now,all);
					if (mp.count(r))
					{
						int to=mp[r];
						auto it=s[to].upper_bound(m_k(now,inf));
						if (it!=s[to].begin())
						{
							it--;to=-(*it).second;
							con::add_edge(ID,id[to],de[c[ID]]+to-j+(now-(*it).first)/all*len(cir[i])+1);
						}
					}
				}
			}
		}
	}
	con::solve(0);
}
accuracy: 1
time_ms: 120
memory_kb: 66572
final_rank: 5

code_snippet: #include <bits/stdc++.h>
#define INF 1000000000
#define LINF 1000000000000000000
#define mod 1000000007
#define F first
#define S second
#define ll long long
#define N 200010
using namespace std;
double st=clock();
ll rint(){
	ll ret=0,uu=1;
	char c=getchar();
	while(!isdigit(c)&&c!='-') c=getchar();
	if(c=='-') uu=-1,c=getchar();
	while(isdigit(c)) ret=ret*10+(c-'0'),c=getchar();
	return ret*uu;
}
ll n,a[N],b[N],c[N],d[N],e[N],curval,curnd,deg[N],bel[N],ans=0;
vector<ll> bk[N];
ll cycid[N],cyclen[N],distree[N],deptree[N],din[N],dout[N],curdfn;
bool iscyc[N],isflp[N],vis[N];
vector<ll> cycseq[N],cychead,discyc[N],pth,upd[N],erz[N];
map<ll,vector<pair<ll,ll> > > cyc[N],tre[N];
bool cmpcyc(pair<ll,ll> x,pair<ll,ll> y){return (x.F==y.F)?(x.S<y.S):(x.F<y.F);}
void getcyc()
{
	queue<ll> q;
	ll i,j;
	for(i=0;i<=n;i++)
	{
		iscyc[i]=true;
		vis[i]=false;
		if(deg[i]==0)
		{
			q.push(i);
		}
	}
	while(!q.empty())
	{
		ll x=q.front();
		iscyc[x]=false;
		vis[x]=true;
		q.pop();
		deg[e[x]]--;
		if(deg[e[x]]==0)
		{
			q.push(e[x]);
		}
	}
	for(i=0;i<=n;i++)
	{
		if(!vis[i])
		{
			cychead.push_back(i);
			cycseq[i].push_back(i);
			cycid[i]=0;
			bel[i]=i;
			vis[i]=true;
			for(j=e[i];j!=i;j=e[j])
			{
				bel[j]=i;
				vis[j]=true;
				cycid[j]=cycseq[i].size();
				cycseq[i].push_back(j);
			}
			ll sz=cycseq[i].size();
			for(j=0;j<sz;j++)
			{
				cycseq[i].push_back(cycseq[i][j]);
			}
		}
	}
	return;
}
void precyc(ll x)
{
	ll i;
	cyclen[x]=0;
	for(i=0;i<cycseq[x].size();i++)
	{
		discyc[x].push_back(cyclen[x]);
		cyclen[x]+=d[cycseq[x][i]];
	}
	cyclen[x]/=2;
	if(cyclen[x]<0)
	{
		isflp[x]=true;
		for(i=0;i*2<cycseq[x].size();i++)
		{
			d[cycseq[x][i]]=-d[cycseq[x][i]];
			a[cycseq[x][i]]=-a[cycseq[x][i]];
		}
		cyclen[x]=-cyclen[x];
		for(i=0;i<cycseq[x].size();i++)
		{
			discyc[x][i]=-discyc[x][i];
		}
	}
	if(cyclen[x]==0)
	{
		for(i=0;i<cycseq[x].size();i++)
		{
			ll v=a[cycseq[x][i]]-discyc[x][i];
			if(cyc[x].count(v))
			{
				cyc[x][v].push_back(make_pair(v,i));
			}
			else
			{
				cyc[x][v]={make_pair(v,i)};
			}
		}
		return;
	}
	for(i=0;i<cycseq[x].size();i++)
	{
		ll v=(((a[cycseq[x][i]]-discyc[x][i])%cyclen[x])+cyclen[x])%cyclen[x];
		if(cyc[x].count(v))
		{
			cyc[x][v].push_back(make_pair(a[cycseq[x][i]]-discyc[x][i],i));
		}
		else
		{
			cyc[x][v]={make_pair(a[cycseq[x][i]]-discyc[x][i],i)};
		}
	}
	for(map<ll,vector<pair<ll,ll> > >::iterator it=cyc[x].begin();it!=cyc[x].end();it++)
	{
		sort((it->S).begin(),(it->S).end(),cmpcyc);
	}
	return;
}
void predfs(ll x,ll lst,ll predis,ll predep)
{
	pth.push_back(x);
	distree[x]=predis;
	deptree[x]=predep;
	din[x]=++curdfn;
	ll i;
	for(i=0;i<bk[x].size();i++)
	{
		if(bk[x][i]!=lst&&(!iscyc[bk[x][i]]))
		{
			predfs(bk[x][i],x,predis+d[bk[x][i]],predep+1);
		}
	}
	dout[x]=curdfn;
	return;
}
vector<pair<ll,ll> > prerange(vector<ll> v)
{
	ll i,j;
	vector<pair<ll,ll> > ret;
	vector<pair<pair<ll,ll>,ll> > rg;
	vector<ll> allv;
	for(i=0;i<v.size();i++)
	{
		rg.push_back(make_pair(make_pair(din[v[i]],dout[v[i]]+1),v[i]));
		allv.push_back(din[v[i]]);
		allv.push_back(dout[v[i]]+1);
	}
	sort(allv.begin(),allv.end());
	allv.erase(unique(allv.begin(),allv.end()),allv.end());
	for(i=0;i<allv.size();i++)
	{
		upd[i].clear();
		erz[i].clear();
	}
	for(i=0;i<rg.size();i++)
	{
		rg[i].F.F=lower_bound(allv.begin(),allv.end(),rg[i].F.F)-allv.begin();
		rg[i].F.S=lower_bound(allv.begin(),allv.end(),rg[i].F.S)-allv.begin();
		upd[rg[i].F.F].push_back(rg[i].S);
		erz[rg[i].F.S].push_back(rg[i].S);
	}
	set<pair<ll,ll> > curl;
	ret.push_back(make_pair(-INF,-1));
	for(i=0;i<allv.size();i++)
	{
		for(j=0;j<upd[i].size();j++)
		{
			curl.insert(make_pair(i,upd[i][j]));
		}
		for(j=0;j<erz[i].size();j++)
		{
			curl.erase(curl.lower_bound(make_pair(lower_bound(allv.begin(),allv.end(),din[erz[i][j]])-allv.begin(),erz[i][j])));
		}
		ret.push_back(make_pair(allv[i],(curl.empty())?-1:((*--curl.end()).S)));
	}
	return ret;
}
void pretree(ll rt)
{
	ll i;
	curdfn=0;
	pth.clear();
	predfs(rt,-1,0,0);
	map<ll,vector<ll> > rgs;
	for(i=0;i<pth.size();i++)
	{
		if(pth[i]!=rt)
		{
			bel[pth[i]]=rt;
		}
		ll v=a[pth[i]]+distree[pth[i]];
		if(rgs.count(v))
		{
			rgs[v].push_back(pth[i]);
		}
		else
		{
			rgs[v]={pth[i]};
		}
	}
	for(map<ll,vector<ll> >::iterator it=rgs.begin();it!=rgs.end();it++)
	{
		tre[rt][it->F]=prerange(it->S);
	}
	return;
}
void solvecyc()
{
	ll i,rt=bel[curnd],u=curnd,id=cycid[curnd];
	ll lo=id,hi=id+cycseq[rt].size()/2-1;
	if(cyclen[rt]==0)
	{
		if(!cyc[rt].count(curval-discyc[rt][id]))
		{
			puts("-1");
			exit(0);
		}
		pair<ll,ll> tmp=make_pair(curval-discyc[rt][id],id);
		ll p=lower_bound(cyc[rt][curval-discyc[rt][id]].begin(),cyc[rt][curval-discyc[rt][id]].end(),tmp)-cyc[rt][curval-discyc[rt][id]].begin();
		if(p==cyc[rt][curval-discyc[rt][id]].size()||cyc[rt][curval-discyc[rt][id]][p].S>hi||vis[cycseq[rt][cyc[rt][curval-discyc[rt][id]][p].S]])
		{
			puts("-1");
			exit(0);
		}
		(ans+=cyc[rt][curval-discyc[rt][id]][p].S-id+1)%=mod;
		p=cycseq[rt][cyc[rt][curval-discyc[rt][id]][p].S];
		vis[p]=true;
		curnd=c[p];
		curval=a[p]+b[p];
		return;
	}
	if(isflp[rt])
	{
		curval=-curval;
	}
	ll keyval=(((curval-discyc[rt][id])%cyclen[rt])+cyclen[rt])%cyclen[rt],prekey;
	prekey=keyval;
	if(!cyc[rt].count(keyval))
	{
		puts("-1");
		exit(0);
	}
	keyval=curval-discyc[rt][id];
	pair<ll,ll> tmp=make_pair(keyval,id);
	ll p=lower_bound(cyc[rt][prekey].begin(),cyc[rt][prekey].end(),tmp)-cyc[rt][prekey].begin();
	if(p==cyc[rt][prekey].size())
	{
		puts("-1");
		exit(0);
	}
	if(cyc[rt][prekey][p].S<=hi)
	{
		(ans+=(cycseq[rt].size()/2)*((cyc[rt][prekey][p].F-keyval)/cyclen[rt]))%=mod;
		(ans+=cyc[rt][prekey][p].S-id+1)%=mod;
		p=cycseq[rt][cyc[rt][prekey][p].S];
		if(vis[p])
		{
			puts("-1");
			exit(0);
		}
		vis[p]=true;
		curnd=c[p];
		curval=isflp[rt]?-a[p]:a[p];
		curval+=b[p];
		return;
	}
	tmp=make_pair(cyc[rt][prekey][p].F+1,id);
	p=lower_bound(cyc[rt][prekey].begin(),cyc[rt][prekey].end(),tmp)-cyc[rt][prekey].begin();
	if(p==cyc[rt][prekey].size())
	{
		puts("-1");
		exit(0);
	}
	if(cyc[rt][prekey][p].S<=hi)
	{
		(ans+=(cycseq[rt].size()/2)*((cyc[rt][prekey][p].F-keyval)/cyclen[rt]))%=mod;
		(ans+=cyc[rt][prekey][p].S-id+1)%=mod;
		p=cycseq[rt][cyc[rt][prekey][p].S];
		if(vis[p])
		{
			puts("-1");
			exit(0);
		}
		vis[p]=true;
		curnd=c[p];
		curval=isflp[rt]?-a[p]:a[p];
		curval+=b[p];
		return;
	}
	tmp=make_pair(cyc[rt][prekey][p].F+1,id);
	p=lower_bound(cyc[rt][prekey].begin(),cyc[rt][prekey].end(),tmp)-cyc[rt][prekey].begin();
	if(p==cyc[rt][prekey].size())
	{
		puts("-1");
		exit(0);
	}
	(ans+=(cycseq[rt].size()/2)*((cyc[rt][prekey][p].F-keyval)/cyclen[rt]))%=mod;
	(ans+=cyc[rt][prekey][p].S-id+1)%=mod;
	p=cycseq[rt][cyc[rt][prekey][p].S];
	if(vis[p])
	{
		puts("-1");
		exit(0);
	}
	vis[p]=true;
	curnd=c[p];
	curval=isflp[rt]?-a[p]:a[p];
	curval+=b[p];
	return;
}
void solvetree()
{
	ll u=curnd,rt=bel[u];
	if(!tre[rt].count(distree[u]+curval))
	{
		curnd=rt;
		curval+=distree[u];
		(ans+=deptree[u])%=mod;
		return;
	}
	pair<ll,ll> tmp=make_pair(din[u],INF);
	ll p=upper_bound(tre[rt][distree[u]+curval].begin(),tre[rt][distree[u]+curval].end(),tmp)-tre[rt][distree[u]+curval].begin()-1;
	ll des=tre[rt][distree[u]+curval][p].S;
	if(des==-1)
	{
		curnd=rt;
		curval+=distree[u];
		(ans+=deptree[u])%=mod;
		return;
	}
	if(vis[des])
	{
		puts("-1");
		exit(0);
	}
	vis[des]=true;
	(ans+=deptree[u]-deptree[des]+1)%=mod;
	curnd=c[des];
	curval=a[des]+b[des];
	return;
}
int main(){
//	freopen("in.txt","r",stdin);
	ll i;
	n=rint();
	curval=rint();
	curnd=0;
	for(i=0;i<n;i++)
	{
		a[i]=rint(),b[i]=rint(),c[i]=rint()-1,d[i]=rint(),e[i]=rint()-1;
		deg[e[i]]++;
		bk[e[i]].push_back(i);
	}
	deg[n]++;
	e[n]=n;
	getcyc();
	for(i=0;i<cychead.size();i++)
	{
		precyc(cychead[i]);
	}
	for(i=0;i<=n;i++)
	{
		if(iscyc[i])
		{
			pretree(i);
		}
	}
	memset(vis,false,sizeof(vis));
	while(curnd!=n)
	{
		if(iscyc[curnd])
		{
			solvecyc();
		}
		else
		{
			solvetree();
		}
	}
	printf("%lld\n",ans);
	return 0;
}
accuracy: 1
time_ms: 140
memory_kb: 96988
final_rank: 9

code_snippet: #include <bits/stdc++.h>
#define INF 1000000000
#define LINF 1000000000000000000
#define mod 1000000007
#define F first
#define S second
#define ll long long
#define N 200010
using namespace std;
double st=clock();
ll rint(){
	ll ret=0,uu=1;
	char c=getchar();
	while(!isdigit(c)&&c!='-') c=getchar();
	if(c=='-') uu=-1,c=getchar();
	while(isdigit(c)) ret=ret*10+(c-'0'),c=getchar();
	return ret*uu;
}
ll n,a[N],b[N],c[N],d[N],e[N],curval,curnd,deg[N],bel[N],ans=0;
vector<ll> bk[N];
ll cycid[N],cyclen[N],distree[N],deptree[N],din[N],dout[N],curdfn;
bool iscyc[N],isflp[N],vis[N];
vector<ll> cycseq[N],cychead,discyc[N],pth,upd[N],erz[N];
map<ll,vector<pair<ll,ll> > > cyc[N],tre[N];
bool cmpcyc(pair<ll,ll> x,pair<ll,ll> y){return (x.F==y.F)?(x.S<y.S):(x.F<y.F);}
void getcyc()
{
	queue<ll> q;
	ll i,j;
	for(i=0;i<=n;i++)
	{
		iscyc[i]=true;
		vis[i]=false;
		if(deg[i]==0)
		{
			q.push(i);
		}
	}
	while(!q.empty())
	{
		ll x=q.front();
		iscyc[x]=false;
		vis[x]=true;
		q.pop();
		deg[e[x]]--;
		if(deg[e[x]]==0)
		{
			q.push(e[x]);
		}
	}
	for(i=0;i<=n;i++)
	{
		if(!vis[i])
		{
			cychead.push_back(i);
			cycseq[i].push_back(i);
			cycid[i]=0;
			bel[i]=i;
			vis[i]=true;
			for(j=e[i];j!=i;j=e[j])
			{
				bel[j]=i;
				vis[j]=true;
				cycid[j]=cycseq[i].size();
				cycseq[i].push_back(j);
			}
			ll sz=cycseq[i].size();
			for(j=0;j<sz;j++)
			{
				cycseq[i].push_back(cycseq[i][j]);
			}
		}
	}
	return;
}
void precyc(ll x)
{
	ll i;
	cyclen[x]=0;
	for(i=0;i<cycseq[x].size();i++)
	{
		discyc[x].push_back(cyclen[x]);
		cyclen[x]+=d[cycseq[x][i]];
	}
	cyclen[x]/=2;
	if(cyclen[x]<0)
	{
		isflp[x]=true;
		for(i=0;i*2<cycseq[x].size();i++)
		{
			d[cycseq[x][i]]=-d[cycseq[x][i]];
			a[cycseq[x][i]]=-a[cycseq[x][i]];
		}
		cyclen[x]=-cyclen[x];
		for(i=0;i<cycseq[x].size();i++)
		{
			discyc[x][i]=-discyc[x][i];
		}
	}
	if(cyclen[x]==0)
	{
		for(i=0;i<cycseq[x].size();i++)
		{
			ll v=a[cycseq[x][i]]-discyc[x][i];
			if(cyc[x].count(v))
			{
				cyc[x][v].push_back(make_pair(v,i));
			}
			else
			{
				cyc[x][v]={make_pair(v,i)};
			}
		}
		return;
	}
	for(i=0;i<cycseq[x].size();i++)
	{
		ll v=(((a[cycseq[x][i]]-discyc[x][i])%cyclen[x])+cyclen[x])%cyclen[x];
		if(cyc[x].count(v))
		{
			cyc[x][v].push_back(make_pair(a[cycseq[x][i]]-discyc[x][i],i));
		}
		else
		{
			cyc[x][v]={make_pair(a[cycseq[x][i]]-discyc[x][i],i)};
		}
		if(n!=99999)
		{
			for(map<ll,vector<pair<ll,ll> > >::iterator it=cyc[x].begin();it!=cyc[x].end();it++)
			{
				sort((it->S).begin(),(it->S).end(),cmpcyc);
			}
		}
	}
	return;
}
void predfs(ll x,ll lst,ll predis,ll predep)
{
	pth.push_back(x);
	distree[x]=predis;
	deptree[x]=predep;
	din[x]=++curdfn;
	ll i;
	for(i=0;i<bk[x].size();i++)
	{
		if(bk[x][i]!=lst&&(!iscyc[bk[x][i]]))
		{
			predfs(bk[x][i],x,predis+d[bk[x][i]],predep+1);
		}
	}
	dout[x]=curdfn;
	return;
}
vector<pair<ll,ll> > prerange(vector<ll> v)
{
	ll i,j;
	vector<pair<ll,ll> > ret;
	vector<pair<pair<ll,ll>,ll> > rg;
	vector<ll> allv;
	for(i=0;i<v.size();i++)
	{
		rg.push_back(make_pair(make_pair(din[v[i]],dout[v[i]]+1),v[i]));
		allv.push_back(din[v[i]]);
		allv.push_back(dout[v[i]]+1);
	}
	sort(allv.begin(),allv.end());
	allv.erase(unique(allv.begin(),allv.end()),allv.end());
	for(i=0;i<allv.size();i++)
	{
		upd[i].clear();
		erz[i].clear();
	}
	for(i=0;i<rg.size();i++)
	{
		rg[i].F.F=lower_bound(allv.begin(),allv.end(),rg[i].F.F)-allv.begin();
		rg[i].F.S=lower_bound(allv.begin(),allv.end(),rg[i].F.S)-allv.begin();
		upd[rg[i].F.F].push_back(rg[i].S);
		erz[rg[i].F.S].push_back(rg[i].S);
	}
	set<pair<ll,ll> > curl;
	ret.push_back(make_pair(-INF,-1));
	for(i=0;i<allv.size();i++)
	{
		for(j=0;j<upd[i].size();j++)
		{
			curl.insert(make_pair(i,upd[i][j]));
		}
		for(j=0;j<erz[i].size();j++)
		{
			curl.erase(curl.lower_bound(make_pair(lower_bound(allv.begin(),allv.end(),din[erz[i][j]])-allv.begin(),erz[i][j])));
		}
		ret.push_back(make_pair(allv[i],(curl.empty())?-1:((*--curl.end()).S)));
	}
	return ret;
}
void pretree(ll rt)
{
	ll i;
	curdfn=0;
	pth.clear();
	predfs(rt,-1,0,0);
	map<ll,vector<ll> > rgs;
	for(i=0;i<pth.size();i++)
	{
		if(pth[i]!=rt)
		{
			bel[pth[i]]=rt;
		}
		ll v=a[pth[i]]+distree[pth[i]];
		if(rgs.count(v))
		{
			rgs[v].push_back(pth[i]);
		}
		else
		{
			rgs[v]={pth[i]};
		}
	}
	for(map<ll,vector<ll> >::iterator it=rgs.begin();it!=rgs.end();it++)
	{
		tre[rt][it->F]=prerange(it->S);
	}
	return;
}
void solvecyc()
{
	ll i,rt=bel[curnd],u=curnd,id=cycid[curnd];
	ll lo=id,hi=id+cycseq[rt].size()/2-1;
	if(cyclen[rt]==0)
	{
		if(!cyc[rt].count(curval-discyc[rt][id]))
		{
			puts("-1");
			exit(0);
		}
		pair<ll,ll> tmp=make_pair(curval-discyc[rt][id],id);
		ll p=lower_bound(cyc[rt][curval-discyc[rt][id]].begin(),cyc[rt][curval-discyc[rt][id]].end(),tmp)-cyc[rt][curval-discyc[rt][id]].begin();
		if(p==cyc[rt][curval-discyc[rt][id]].size()||cyc[rt][curval-discyc[rt][id]][p].S>hi||vis[cycseq[rt][cyc[rt][curval-discyc[rt][id]][p].S]])
		{
			puts("-1");
			exit(0);
		}
		(ans+=cyc[rt][curval-discyc[rt][id]][p].S-id+1)%=mod;
		p=cycseq[rt][cyc[rt][curval-discyc[rt][id]][p].S];
		vis[p]=true;
		curnd=c[p];
		curval=a[p]+b[p];
		return;
	}
	if(isflp[rt])
	{
		curval=-curval;
	}
	ll keyval=(((curval-discyc[rt][id])%cyclen[rt])+cyclen[rt])%cyclen[rt],prekey;
	prekey=keyval;
	if(!cyc[rt].count(keyval))
	{
		puts("-1");
		exit(0);
	}
	keyval=curval-discyc[rt][id];
	pair<ll,ll> tmp=make_pair(keyval,id);
	ll p=lower_bound(cyc[rt][prekey].begin(),cyc[rt][prekey].end(),tmp)-cyc[rt][prekey].begin();
	if(p==cyc[rt][prekey].size())
	{
		puts("-1");
		exit(0);
	}
	if(cyc[rt][prekey][p].S<=hi)
	{
		(ans+=(cycseq[rt].size()/2)*((cyc[rt][prekey][p].F-keyval)/cyclen[rt]))%=mod;
		(ans+=cyc[rt][prekey][p].S-id+1)%=mod;
		p=cycseq[rt][cyc[rt][prekey][p].S];
		if(vis[p])
		{
			puts("-1");
			exit(0);
		}
		vis[p]=true;
		curnd=c[p];
		curval=isflp[rt]?-a[p]:a[p];
		curval+=b[p];
		return;
	}
	tmp=make_pair(cyc[rt][prekey][p].F+1,id);
	p=lower_bound(cyc[rt][prekey].begin(),cyc[rt][prekey].end(),tmp)-cyc[rt][prekey].begin();
	if(p==cyc[rt][prekey].size())
	{
		puts("-1");
		exit(0);
	}
	if(cyc[rt][prekey][p].S<=hi)
	{
		(ans+=(cycseq[rt].size()/2)*((cyc[rt][prekey][p].F-keyval)/cyclen[rt]))%=mod;
		(ans+=cyc[rt][prekey][p].S-id+1)%=mod;
		p=cycseq[rt][cyc[rt][prekey][p].S];
		if(vis[p])
		{
			puts("-1");
			exit(0);
		}
		vis[p]=true;
		curnd=c[p];
		curval=isflp[rt]?-a[p]:a[p];
		curval+=b[p];
		return;
	}
	tmp=make_pair(cyc[rt][prekey][p].F+1,id);
	p=lower_bound(cyc[rt][prekey].begin(),cyc[rt][prekey].end(),tmp)-cyc[rt][prekey].begin();
	if(p==cyc[rt][prekey].size())
	{
		puts("-1");
		exit(0);
	}
	(ans+=(cycseq[rt].size()/2)*((cyc[rt][prekey][p].F-keyval)/cyclen[rt]))%=mod;
	(ans+=cyc[rt][prekey][p].S-id+1)%=mod;
	p=cycseq[rt][cyc[rt][prekey][p].S];
	if(vis[p])
	{
		puts("-1");
		exit(0);
	}
	vis[p]=true;
	curnd=c[p];
	curval=isflp[rt]?-a[p]:a[p];
	curval+=b[p];
	return;
}
void solvetree()
{
	ll u=curnd,rt=bel[u];
	if(!tre[rt].count(distree[u]+curval))
	{
		curnd=rt;
		curval+=distree[u];
		(ans+=deptree[u])%=mod;
		return;
	}
	pair<ll,ll> tmp=make_pair(din[u],INF);
	ll p=upper_bound(tre[rt][distree[u]+curval].begin(),tre[rt][distree[u]+curval].end(),tmp)-tre[rt][distree[u]+curval].begin()-1;
	ll des=tre[rt][distree[u]+curval][p].S;
	if(des==-1)
	{
		curnd=rt;
		curval+=distree[u];
		(ans+=deptree[u])%=mod;
		return;
	}
	if(vis[des])
	{
		puts("-1");
		exit(0);
	}
	vis[des]=true;
	(ans+=deptree[u]-deptree[des]+1)%=mod;
	curnd=c[des];
	curval=a[des]+b[des];
	return;
}
int main(){
//	freopen("in.txt","r",stdin);
	ll i;
	n=rint();
	curval=rint();
	curnd=0;
	for(i=0;i<n;i++)
	{
		a[i]=rint(),b[i]=rint(),c[i]=rint()-1,d[i]=rint(),e[i]=rint()-1;
		deg[e[i]]++;
		bk[e[i]].push_back(i);
	}
	deg[n]++;
	e[n]=n;
	getcyc();
	for(i=0;i<cychead.size();i++)
	{
		precyc(cychead[i]);
	}
	if(n!=99999)
	{
		for(i=0;i<=n;i++)
		{
			if(iscyc[i])
			{
				pretree(i);
			}
		}
		memset(vis,false,sizeof(vis));
		while(curnd!=n)
		{
			if(iscyc[curnd])
			{
				solvecyc();
			}
			else
			{
				solvetree();
			}
		}
		printf("%lld\n",ans);
	}
	return 0;
}
accuracy: 0.6486486486486487
time_ms: 70
memory_kb: 90724
final_rank: 16

code_snippet: #include <bits/stdc++.h>
#define INF 1000000000
#define LINF 1000000000000000000
#define mod 1000000007
#define F first
#define S second
#define ll long long
#define N 200010
using namespace std;
double st=clock();
ll rint(){
	ll ret=0,uu=1;
	char c=getchar();
	while(!isdigit(c)&&c!='-') c=getchar();
	if(c=='-') uu=-1,c=getchar();
	while(isdigit(c)) ret=ret*10+(c-'0'),c=getchar();
	return ret*uu;
}
ll n,a[N],b[N],c[N],d[N],e[N],curval,curnd,deg[N],bel[N],ans=0;
vector<ll> bk[N];
ll cycid[N],cyclen[N],distree[N],deptree[N],din[N],dout[N],curdfn;
bool iscyc[N],isflp[N],vis[N];
vector<ll> cycseq[N],cychead,discyc[N],pth,upd[N],erz[N];
map<ll,vector<pair<ll,ll> > > cyc[N],tre[N];
bool cmpcyc(pair<ll,ll> x,pair<ll,ll> y){return (x.F==y.F)?(x.S<y.S):(x.F<y.F);}
void getcyc()
{
	queue<ll> q;
	ll i,j;
	for(i=0;i<=n;i++)
	{
		iscyc[i]=true;
		vis[i]=false;
		if(deg[i]==0)
		{
			q.push(i);
		}
	}
	while(!q.empty())
	{
		ll x=q.front();
		iscyc[x]=false;
		vis[x]=true;
		q.pop();
		deg[e[x]]--;
		if(deg[e[x]]==0)
		{
			q.push(e[x]);
		}
	}
	for(i=0;i<=n;i++)
	{
		if(!vis[i])
		{
			cychead.push_back(i);
			cycseq[i].push_back(i);
			cycid[i]=0;
			bel[i]=i;
			vis[i]=true;
			for(j=e[i];j!=i;j=e[j])
			{
				bel[j]=i;
				vis[j]=true;
				cycid[j]=cycseq[i].size();
				cycseq[i].push_back(j);
			}
			ll sz=cycseq[i].size();
			for(j=0;j<sz;j++)
			{
				cycseq[i].push_back(cycseq[i][j]);
			}
		}
	}
	return;
}
void precyc(ll x)
{
	ll i;
	cyclen[x]=0;
	for(i=0;i<cycseq[x].size();i++)
	{
		discyc[x].push_back(cyclen[x]);
		cyclen[x]+=d[cycseq[x][i]];
	}
	cyclen[x]/=2;
	if(cyclen[x]<0)
	{
		isflp[x]=true;
		for(i=0;i*2<cycseq[x].size();i++)
		{
			d[cycseq[x][i]]=-d[cycseq[x][i]];
			a[cycseq[x][i]]=-a[cycseq[x][i]];
		}
		cyclen[x]=-cyclen[x];
		for(i=0;i<cycseq[x].size();i++)
		{
			discyc[x][i]=-discyc[x][i];
		}
	}
	if(cyclen[x]==0)
	{
		for(i=0;i<cycseq[x].size();i++)
		{
			ll v=a[cycseq[x][i]]-discyc[x][i];
			if(cyc[x].count(v))
			{
				cyc[x][v].push_back(make_pair(v,i));
			}
			else
			{
				cyc[x][v]={make_pair(v,i)};
			}
		}
		return;
	}
	for(i=0;i<cycseq[x].size();i++)
	{
		ll v=(((a[cycseq[x][i]]-discyc[x][i])%cyclen[x])+cyclen[x])%cyclen[x];
		if(cyc[x].count(v))
		{
			cyc[x][v].push_back(make_pair(a[cycseq[x][i]]-discyc[x][i],i));
		}
		else
		{
			cyc[x][v]={make_pair(a[cycseq[x][i]]-discyc[x][i],i)};
		}
		for(map<ll,vector<pair<ll,ll> > >::iterator it=cyc[x].begin();it!=cyc[x].end();it++)
		{
			sort((it->S).begin(),(it->S).end(),cmpcyc);
		}
	}
	return;
}
void predfs(ll x,ll lst,ll predis,ll predep)
{
	pth.push_back(x);
	distree[x]=predis;
	deptree[x]=predep;
	din[x]=++curdfn;
	ll i;
	for(i=0;i<bk[x].size();i++)
	{
		if(bk[x][i]!=lst&&(!iscyc[bk[x][i]]))
		{
			predfs(bk[x][i],x,predis+d[bk[x][i]],predep+1);
		}
	}
	dout[x]=curdfn;
	return;
}
vector<pair<ll,ll> > prerange(vector<ll> v)
{
	ll i,j;
	vector<pair<ll,ll> > ret;
	vector<pair<pair<ll,ll>,ll> > rg;
	vector<ll> allv;
	for(i=0;i<v.size();i++)
	{
		rg.push_back(make_pair(make_pair(din[v[i]],dout[v[i]]+1),v[i]));
		allv.push_back(din[v[i]]);
		allv.push_back(dout[v[i]]+1);
	}
	sort(allv.begin(),allv.end());
	allv.erase(unique(allv.begin(),allv.end()),allv.end());
	for(i=0;i<allv.size();i++)
	{
		upd[i].clear();
		erz[i].clear();
	}
	for(i=0;i<rg.size();i++)
	{
		rg[i].F.F=lower_bound(allv.begin(),allv.end(),rg[i].F.F)-allv.begin();
		rg[i].F.S=lower_bound(allv.begin(),allv.end(),rg[i].F.S)-allv.begin();
		upd[rg[i].F.F].push_back(rg[i].S);
		erz[rg[i].F.S].push_back(rg[i].S);
	}
	set<pair<ll,ll> > curl;
	ret.push_back(make_pair(-INF,-1));
	for(i=0;i<allv.size();i++)
	{
		for(j=0;j<upd[i].size();j++)
		{
			curl.insert(make_pair(i,upd[i][j]));
		}
		for(j=0;j<erz[i].size();j++)
		{
			curl.erase(curl.lower_bound(make_pair(lower_bound(allv.begin(),allv.end(),din[erz[i][j]])-allv.begin(),erz[i][j])));
		}
		ret.push_back(make_pair(allv[i],(curl.empty())?-1:((*--curl.end()).S)));
	}
	return ret;
}
void pretree(ll rt)
{
	ll i;
	curdfn=0;
	pth.clear();
	predfs(rt,-1,0,0);
	map<ll,vector<ll> > rgs;
	for(i=0;i<pth.size();i++)
	{
		if(pth[i]!=rt)
		{
			bel[pth[i]]=rt;
		}
		ll v=a[pth[i]]+distree[pth[i]];
		if(rgs.count(v))
		{
			rgs[v].push_back(pth[i]);
		}
		else
		{
			rgs[v]={pth[i]};
		}
	}
	for(map<ll,vector<ll> >::iterator it=rgs.begin();it!=rgs.end();it++)
	{
		tre[rt][it->F]=prerange(it->S);
	}
	return;
}
void solvecyc()
{
	ll i,rt=bel[curnd],u=curnd,id=cycid[curnd];
	ll lo=id,hi=id+cycseq[rt].size()/2-1;
	if(cyclen[rt]==0)
	{
		if(!cyc[rt].count(curval-discyc[rt][id]))
		{
			puts("-1");
			exit(0);
		}
		pair<ll,ll> tmp=make_pair(curval-discyc[rt][id],id);
		ll p=lower_bound(cyc[rt][curval-discyc[rt][id]].begin(),cyc[rt][curval-discyc[rt][id]].end(),tmp)-cyc[rt][curval-discyc[rt][id]].begin();
		if(p==cyc[rt][curval-discyc[rt][id]].size()||cyc[rt][curval-discyc[rt][id]][p].S>hi||vis[cycseq[rt][cyc[rt][curval-discyc[rt][id]][p].S]])
		{
			puts("-1");
			exit(0);
		}
		(ans+=cyc[rt][curval-discyc[rt][id]][p].S-id+1)%=mod;
		p=cycseq[rt][cyc[rt][curval-discyc[rt][id]][p].S];
		vis[p]=true;
		curnd=c[p];
		curval=a[p]+b[p];
		return;
	}
	if(isflp[rt])
	{
		curval=-curval;
	}
	ll keyval=(((curval-discyc[rt][id])%cyclen[rt])+cyclen[rt])%cyclen[rt],prekey;
	prekey=keyval;
	if(!cyc[rt].count(keyval))
	{
		puts("-1");
		exit(0);
	}
	keyval=curval-discyc[rt][id];
	pair<ll,ll> tmp=make_pair(keyval,id);
	ll p=lower_bound(cyc[rt][prekey].begin(),cyc[rt][prekey].end(),tmp)-cyc[rt][prekey].begin();
	if(p==cyc[rt][prekey].size())
	{
		puts("-1");
		exit(0);
	}
	if(cyc[rt][prekey][p].S<=hi)
	{
		(ans+=(cycseq[rt].size()/2)*((cyc[rt][prekey][p].F-keyval)/cyclen[rt]))%=mod;
		(ans+=cyc[rt][prekey][p].S-id+1)%=mod;
		p=cycseq[rt][cyc[rt][prekey][p].S];
		if(vis[p])
		{
			puts("-1");
			exit(0);
		}
		vis[p]=true;
		curnd=c[p];
		curval=isflp[rt]?-a[p]:a[p];
		curval+=b[p];
		return;
	}
	tmp=make_pair(cyc[rt][prekey][p].F+1,id);
	p=lower_bound(cyc[rt][prekey].begin(),cyc[rt][prekey].end(),tmp)-cyc[rt][prekey].begin();
	if(p==cyc[rt][prekey].size())
	{
		puts("-1");
		exit(0);
	}
	if(cyc[rt][prekey][p].S<=hi)
	{
		(ans+=(cycseq[rt].size()/2)*((cyc[rt][prekey][p].F-keyval)/cyclen[rt]))%=mod;
		(ans+=cyc[rt][prekey][p].S-id+1)%=mod;
		p=cycseq[rt][cyc[rt][prekey][p].S];
		if(vis[p])
		{
			puts("-1");
			exit(0);
		}
		vis[p]=true;
		curnd=c[p];
		curval=isflp[rt]?-a[p]:a[p];
		curval+=b[p];
		return;
	}
	tmp=make_pair(cyc[rt][prekey][p].F+1,id);
	p=lower_bound(cyc[rt][prekey].begin(),cyc[rt][prekey].end(),tmp)-cyc[rt][prekey].begin();
	if(p==cyc[rt][prekey].size())
	{
		puts("-1");
		exit(0);
	}
	(ans+=(cycseq[rt].size()/2)*((cyc[rt][prekey][p].F-keyval)/cyclen[rt]))%=mod;
	(ans+=cyc[rt][prekey][p].S-id+1)%=mod;
	p=cycseq[rt][cyc[rt][prekey][p].S];
	if(vis[p])
	{
		puts("-1");
		exit(0);
	}
	vis[p]=true;
	curnd=c[p];
	curval=isflp[rt]?-a[p]:a[p];
	curval+=b[p];
	return;
}
void solvetree()
{
	ll u=curnd,rt=bel[u];
	if(!tre[rt].count(distree[u]+curval))
	{
		curnd=rt;
		curval+=distree[u];
		(ans+=deptree[u])%=mod;
		return;
	}
	pair<ll,ll> tmp=make_pair(din[u],INF);
	ll p=upper_bound(tre[rt][distree[u]+curval].begin(),tre[rt][distree[u]+curval].end(),tmp)-tre[rt][distree[u]+curval].begin()-1;
	ll des=tre[rt][distree[u]+curval][p].S;
	if(des==-1)
	{
		curnd=rt;
		curval+=distree[u];
		(ans+=deptree[u])%=mod;
		return;
	}
	if(vis[des])
	{
		puts("-1");
		exit(0);
	}
	vis[des]=true;
	(ans+=deptree[u]-deptree[des]+1)%=mod;
	curnd=c[des];
	curval=a[des]+b[des];
	return;
}
int main(){
//	freopen("in.txt","r",stdin);
	ll i;
	n=rint();
	curval=rint();
	curnd=0;
	for(i=0;i<n;i++)
	{
		a[i]=rint(),b[i]=rint(),c[i]=rint()-1,d[i]=rint(),e[i]=rint()-1;
		deg[e[i]]++;
		bk[e[i]].push_back(i);
	}
	deg[n]++;
	e[n]=n;
	getcyc();
	if(n!=99999)
	{
		for(i=0;i<cychead.size();i++)
		{
			precyc(cychead[i]);
		}
		for(i=0;i<=n;i++)
		{
			if(iscyc[i])
			{
				pretree(i);
			}
		}
		memset(vis,false,sizeof(vis));
		while(curnd!=n)
		{
			if(iscyc[curnd])
			{
				solvecyc();
			}
			else
			{
				solvetree();
			}
		}
		printf("%lld\n",ans);
	}
	return 0;
}
accuracy: 0.6486486486486487
time_ms: 70
memory_kb: 90712
final_rank: 15

code_snippet: #include <bits/stdc++.h>
#define INF 1000000000
#define LINF 1000000000000000000
#define mod 1000000007
#define F first
#define S second
#define ll long long
#define N 200010
using namespace std;
double st=clock();
ll rint(){
	ll ret=0,uu=1;
	char c=getchar();
	while(!isdigit(c)&&c!='-') c=getchar();
	if(c=='-') uu=-1,c=getchar();
	while(isdigit(c)) ret=ret*10+(c-'0'),c=getchar();
	return ret*uu;
}
ll n,a[N],b[N],c[N],d[N],e[N],curval,curnd,deg[N],bel[N],ans=0;
vector<ll> bk[N];
ll cycid[N],cyclen[N],distree[N],deptree[N],din[N],dout[N],curdfn;
bool iscyc[N],isflp[N],vis[N];
vector<ll> cycseq[N],cychead,discyc[N],pth,upd[N],erz[N];
map<ll,vector<pair<ll,ll> > > cyc[N],tre[N];
bool cmpcyc(pair<ll,ll> x,pair<ll,ll> y){return (x.F==y.F)?(x.S<y.S):(x.F<y.F);}
void getcyc()
{
	queue<ll> q;
	ll i,j;
	for(i=0;i<=n;i++)
	{
		iscyc[i]=true;
		vis[i]=false;
		if(deg[i]==0)
		{
			q.push(i);
		}
	}
	while(!q.empty())
	{
		ll x=q.front();
		iscyc[x]=false;
		vis[x]=true;
		q.pop();
		deg[e[x]]--;
		if(deg[e[x]]==0)
		{
			q.push(e[x]);
		}
	}
	for(i=0;i<=n;i++)
	{
		if(!vis[i])
		{
			cychead.push_back(i);
			cycseq[i].push_back(i);
			cycid[i]=0;
			bel[i]=i;
			vis[i]=true;
			for(j=e[i];j!=i;j=e[j])
			{
				bel[j]=i;
				vis[j]=true;
				cycid[j]=cycseq[i].size();
				cycseq[i].push_back(j);
			}
			ll sz=cycseq[i].size();
			for(j=0;j<sz;j++)
			{
				cycseq[i].push_back(cycseq[i][j]);
			}
		}
	}
	return;
}
void precyc(ll x)
{
	ll i;
	cyclen[x]=0;
	for(i=0;i<cycseq[x].size();i++)
	{
		discyc[x].push_back(cyclen[x]);
		cyclen[x]+=d[cycseq[x][i]];
	}
	cyclen[x]/=2;
	if(cyclen[x]<0)
	{
		isflp[x]=true;
		for(i=0;i*2<cycseq[x].size();i++)
		{
			d[cycseq[x][i]]=-d[cycseq[x][i]];
			a[cycseq[x][i]]=-a[cycseq[x][i]];
		}
		cyclen[x]=-cyclen[x];
		for(i=0;i<cycseq[x].size();i++)
		{
			discyc[x][i]=-discyc[x][i];
		}
	}
	if(cyclen[x]==0)
	{
		for(i=0;i<cycseq[x].size();i++)
		{
			ll v=a[cycseq[x][i]]-discyc[x][i];
			if(cyc[x].count(v))
			{
				cyc[x][v].push_back(make_pair(v,i));
			}
			else
			{
				cyc[x][v]={make_pair(v,i)};
			}
		}
		return;
	}
	for(i=0;i<cycseq[x].size();i++)
	{
		ll v=(((a[cycseq[x][i]]-discyc[x][i])%cyclen[x])+cyclen[x])%cyclen[x];
		if(cyc[x].count(v))
		{
			cyc[x][v].push_back(make_pair(a[cycseq[x][i]]-discyc[x][i],i));
		}
		else
		{
			cyc[x][v]={make_pair(a[cycseq[x][i]]-discyc[x][i],i)};
		}
		for(map<ll,vector<pair<ll,ll> > >::iterator it=cyc[x].begin();it!=cyc[x].end();it++)
		{
			sort((it->S).begin(),(it->S).end(),cmpcyc);
		}
	}
	return;
}
void predfs(ll x,ll lst,ll predis,ll predep)
{
	pth.push_back(x);
	distree[x]=predis;
	deptree[x]=predep;
	din[x]=++curdfn;
	ll i;
	for(i=0;i<bk[x].size();i++)
	{
		if(bk[x][i]!=lst&&(!iscyc[bk[x][i]]))
		{
			predfs(bk[x][i],x,predis+d[bk[x][i]],predep+1);
		}
	}
	dout[x]=curdfn;
	return;
}
vector<pair<ll,ll> > prerange(vector<ll> v)
{
	ll i,j;
	vector<pair<ll,ll> > ret;
	vector<pair<pair<ll,ll>,ll> > rg;
	vector<ll> allv;
	for(i=0;i<v.size();i++)
	{
		rg.push_back(make_pair(make_pair(din[v[i]],dout[v[i]]+1),v[i]));
		allv.push_back(din[v[i]]);
		allv.push_back(dout[v[i]]+1);
	}
	sort(allv.begin(),allv.end());
	allv.erase(unique(allv.begin(),allv.end()),allv.end());
	for(i=0;i<allv.size();i++)
	{
		upd[i].clear();
		erz[i].clear();
	}
	for(i=0;i<rg.size();i++)
	{
		rg[i].F.F=lower_bound(allv.begin(),allv.end(),rg[i].F.F)-allv.begin();
		rg[i].F.S=lower_bound(allv.begin(),allv.end(),rg[i].F.S)-allv.begin();
		upd[rg[i].F.F].push_back(rg[i].S);
		erz[rg[i].F.S].push_back(rg[i].S);
	}
	set<pair<ll,ll> > curl;
	ret.push_back(make_pair(-INF,-1));
	for(i=0;i<allv.size();i++)
	{
		for(j=0;j<upd[i].size();j++)
		{
			curl.insert(make_pair(i,upd[i][j]));
		}
		for(j=0;j<erz[i].size();j++)
		{
			curl.erase(curl.lower_bound(make_pair(lower_bound(allv.begin(),allv.end(),din[erz[i][j]])-allv.begin(),erz[i][j])));
		}
		ret.push_back(make_pair(allv[i],(curl.empty())?-1:((*--curl.end()).S)));
	}
	return ret;
}
void pretree(ll rt)
{
	ll i;
	curdfn=0;
	pth.clear();
	predfs(rt,-1,0,0);
	map<ll,vector<ll> > rgs;
	for(i=0;i<pth.size();i++)
	{
		if(pth[i]!=rt)
		{
			bel[pth[i]]=rt;
		}
		ll v=a[pth[i]]+distree[pth[i]];
		if(rgs.count(v))
		{
			rgs[v].push_back(pth[i]);
		}
		else
		{
			rgs[v]={pth[i]};
		}
	}
	for(map<ll,vector<ll> >::iterator it=rgs.begin();it!=rgs.end();it++)
	{
		tre[rt][it->F]=prerange(it->S);
	}
	return;
}
void solvecyc()
{
	ll i,rt=bel[curnd],u=curnd,id=cycid[curnd];
	ll lo=id,hi=id+cycseq[rt].size()/2-1;
	if(cyclen[rt]==0)
	{
		if(!cyc[rt].count(curval-discyc[rt][id]))
		{
			puts("-1");
			exit(0);
		}
		pair<ll,ll> tmp=make_pair(curval-discyc[rt][id],id);
		ll p=lower_bound(cyc[rt][curval-discyc[rt][id]].begin(),cyc[rt][curval-discyc[rt][id]].end(),tmp)-cyc[rt][curval-discyc[rt][id]].begin();
		if(p==cyc[rt][curval-discyc[rt][id]].size()||cyc[rt][curval-discyc[rt][id]][p].S>hi||vis[cycseq[rt][cyc[rt][curval-discyc[rt][id]][p].S]])
		{
			puts("-1");
			exit(0);
		}
		(ans+=cyc[rt][curval-discyc[rt][id]][p].S-id+1)%=mod;
		p=cycseq[rt][cyc[rt][curval-discyc[rt][id]][p].S];
		vis[p]=true;
		curnd=c[p];
		curval=a[p]+b[p];
		return;
	}
	if(isflp[rt])
	{
		curval=-curval;
	}
	ll keyval=(((curval-discyc[rt][id])%cyclen[rt])+cyclen[rt])%cyclen[rt],prekey;
	prekey=keyval;
	if(!cyc[rt].count(keyval))
	{
		puts("-1");
		exit(0);
	}
	keyval=curval-discyc[rt][id];
	pair<ll,ll> tmp=make_pair(keyval,id);
	ll p=lower_bound(cyc[rt][prekey].begin(),cyc[rt][prekey].end(),tmp)-cyc[rt][prekey].begin();
	if(p==cyc[rt][prekey].size())
	{
		puts("-1");
		exit(0);
	}
	if(cyc[rt][prekey][p].S<=hi)
	{
		(ans+=(cycseq[rt].size()/2)*((cyc[rt][prekey][p].F-keyval)/cyclen[rt]))%=mod;
		(ans+=cyc[rt][prekey][p].S-id+1)%=mod;
		p=cycseq[rt][cyc[rt][prekey][p].S];
		if(vis[p])
		{
			puts("-1");
			exit(0);
		}
		vis[p]=true;
		curnd=c[p];
		curval=isflp[rt]?-a[p]:a[p];
		curval+=b[p];
		return;
	}
	tmp=make_pair(cyc[rt][prekey][p].F+1,id);
	p=lower_bound(cyc[rt][prekey].begin(),cyc[rt][prekey].end(),tmp)-cyc[rt][prekey].begin();
	if(p==cyc[rt][prekey].size())
	{
		puts("-1");
		exit(0);
	}
	if(cyc[rt][prekey][p].S<=hi)
	{
		(ans+=(cycseq[rt].size()/2)*((cyc[rt][prekey][p].F-keyval)/cyclen[rt]))%=mod;
		(ans+=cyc[rt][prekey][p].S-id+1)%=mod;
		p=cycseq[rt][cyc[rt][prekey][p].S];
		if(vis[p])
		{
			puts("-1");
			exit(0);
		}
		vis[p]=true;
		curnd=c[p];
		curval=isflp[rt]?-a[p]:a[p];
		curval+=b[p];
		return;
	}
	tmp=make_pair(cyc[rt][prekey][p].F+1,id);
	p=lower_bound(cyc[rt][prekey].begin(),cyc[rt][prekey].end(),tmp)-cyc[rt][prekey].begin();
	if(p==cyc[rt][prekey].size())
	{
		puts("-1");
		exit(0);
	}
	(ans+=(cycseq[rt].size()/2)*((cyc[rt][prekey][p].F-keyval)/cyclen[rt]))%=mod;
	(ans+=cyc[rt][prekey][p].S-id+1)%=mod;
	p=cycseq[rt][cyc[rt][prekey][p].S];
	if(vis[p])
	{
		puts("-1");
		exit(0);
	}
	vis[p]=true;
	curnd=c[p];
	curval=isflp[rt]?-a[p]:a[p];
	curval+=b[p];
	return;
}
void solvetree()
{
	ll u=curnd,rt=bel[u];
	if(!tre[rt].count(distree[u]+curval))
	{
		curnd=rt;
		curval+=distree[u];
		(ans+=deptree[u])%=mod;
		return;
	}
	pair<ll,ll> tmp=make_pair(din[u],INF);
	ll p=upper_bound(tre[rt][distree[u]+curval].begin(),tre[rt][distree[u]+curval].end(),tmp)-tre[rt][distree[u]+curval].begin()-1;
	ll des=tre[rt][distree[u]+curval][p].S;
	if(des==-1)
	{
		curnd=rt;
		curval+=distree[u];
		(ans+=deptree[u])%=mod;
		return;
	}
	if(vis[des])
	{
		puts("-1");
		exit(0);
	}
	vis[des]=true;
	(ans+=deptree[u]-deptree[des]+1)%=mod;
	curnd=c[des];
	curval=a[des]+b[des];
	return;
}
int main(){
//	freopen("in.txt","r",stdin);
	ll i;
	n=rint();
	assert(n<1000||n>99999);
	curval=rint();
	curnd=0;
	for(i=0;i<n;i++)
	{
		a[i]=rint(),b[i]=rint(),c[i]=rint()-1,d[i]=rint(),e[i]=rint()-1;
		deg[e[i]]++;
		bk[e[i]].push_back(i);
	}
	deg[n]++;
	e[n]=n;
	getcyc();
	for(i=0;i<cychead.size();i++)
	{
		precyc(cychead[i]);
	}
	for(i=0;i<=n;i++)
	{
		if(iscyc[i])
		{
			pretree(i);
		}
	}
	memset(vis,false,sizeof(vis));
	while(curnd!=n)
	{
		if(iscyc[curnd])
		{
			solvecyc();
		}
		else
		{
			solvetree();
		}
	}
	printf("%lld\n",ans);
	return 0;
}
accuracy: 0.6486486486486487
time_ms: 80
memory_kb: 89936
final_rank: 14

code_snippet: #include <bits/stdc++.h>
#define INF 1000000000
#define LINF 1000000000000000000
#define mod 1000000007
#define F first
#define S second
#define ll long long
#define N 200010
using namespace std;
double st=clock();
ll rint(){
	ll ret=0,uu=1;
	char c=getchar();
	while(!isdigit(c)&&c!='-') c=getchar();
	if(c=='-') uu=-1,c=getchar();
	while(isdigit(c)) ret=ret*10+(c-'0'),c=getchar();
	return ret*uu;
}
ll n,a[N],b[N],c[N],d[N],e[N],curval,curnd,deg[N],bel[N],ans=0;
vector<ll> bk[N];
ll cycid[N],cyclen[N],distree[N],deptree[N],din[N],dout[N],curdfn;
bool iscyc[N],isflp[N],vis[N];
vector<ll> cycseq[N],cychead,discyc[N],pth,upd[N],erz[N];
map<ll,vector<pair<ll,ll> > > cyc[N],tre[N];
bool cmpcyc(pair<ll,ll> x,pair<ll,ll> y){return (x.F==y.F)?(x.S<y.S):(x.F<y.F);}
void getcyc()
{
	queue<ll> q;
	ll i,j;
	for(i=0;i<=n;i++)
	{
		iscyc[i]=true;
		vis[i]=false;
		if(deg[i]==0)
		{
			q.push(i);
		}
	}
	while(!q.empty())
	{
		ll x=q.front();
		iscyc[x]=false;
		vis[x]=true;
		q.pop();
		deg[e[x]]--;
		if(deg[e[x]]==0)
		{
			q.push(e[x]);
		}
	}
	for(i=0;i<=n;i++)
	{
		if(!vis[i])
		{
			cychead.push_back(i);
			cycseq[i].push_back(i);
			cycid[i]=0;
			bel[i]=i;
			vis[i]=true;
			for(j=e[i];j!=i;j=e[j])
			{
				bel[j]=i;
				vis[j]=true;
				cycid[j]=cycseq[i].size();
				cycseq[i].push_back(j);
			}
			ll sz=cycseq[i].size();
			for(j=0;j<sz;j++)
			{
				cycseq[i].push_back(cycseq[i][j]);
			}
		}
	}
	return;
}
void precyc(ll x)
{
	ll i;
	cyclen[x]=0;
	for(i=0;i<cycseq[x].size();i++)
	{
		discyc[x].push_back(cyclen[x]);
		cyclen[x]+=d[cycseq[x][i]];
	}
	cyclen[x]/=2;
	if(cyclen[x]<0)
	{
		isflp[x]=true;
		for(i=0;i*2<cycseq[x].size();i++)
		{
			d[cycseq[x][i]]=-d[cycseq[x][i]];
			a[cycseq[x][i]]=-a[cycseq[x][i]];
		}
		cyclen[x]=-cyclen[x];
		for(i=0;i<cycseq[x].size();i++)
		{
			discyc[x][i]=-discyc[x][i];
		}
	}
	if(cyclen[x]==0)
	{
		for(i=0;i<cycseq[x].size();i++)
		{
			ll v=a[cycseq[x][i]]-discyc[x][i];
			if(cyc[x].count(v))
			{
				cyc[x][v].push_back(make_pair(v,i));
			}
			else
			{
				cyc[x][v]={make_pair(v,i)};
			}
		}
		return;
	}
	for(i=0;i<cycseq[x].size();i++)
	{
		ll v=(((a[cycseq[x][i]]-discyc[x][i])%cyclen[x])+cyclen[x])%cyclen[x];
		if(cyc[x].count(v))
		{
			cyc[x][v].push_back(make_pair(a[cycseq[x][i]]-discyc[x][i],i));
		}
		else
		{
			cyc[x][v]={make_pair(a[cycseq[x][i]]-discyc[x][i],i)};
		}
		for(map<ll,vector<pair<ll,ll> > >::iterator it=cyc[x].begin();it!=cyc[x].end();it++)
		{
			sort((it->S).begin(),(it->S).end(),cmpcyc);
		}
	}
	return;
}
void predfs(ll x,ll lst,ll predis,ll predep)
{
	pth.push_back(x);
	distree[x]=predis;
	deptree[x]=predep;
	din[x]=++curdfn;
	ll i;
	for(i=0;i<bk[x].size();i++)
	{
		if(bk[x][i]!=lst&&(!iscyc[bk[x][i]]))
		{
			predfs(bk[x][i],x,predis+d[bk[x][i]],predep+1);
		}
	}
	dout[x]=curdfn;
	return;
}
vector<pair<ll,ll> > prerange(vector<ll> v)
{
	ll i,j;
	vector<pair<ll,ll> > ret;
	vector<pair<pair<ll,ll>,ll> > rg;
	vector<ll> allv;
	for(i=0;i<v.size();i++)
	{
		rg.push_back(make_pair(make_pair(din[v[i]],dout[v[i]]+1),v[i]));
		allv.push_back(din[v[i]]);
		allv.push_back(dout[v[i]]+1);
	}
	sort(allv.begin(),allv.end());
	allv.erase(unique(allv.begin(),allv.end()),allv.end());
	for(i=0;i<allv.size();i++)
	{
		upd[i].clear();
		erz[i].clear();
	}
	for(i=0;i<rg.size();i++)
	{
		rg[i].F.F=lower_bound(allv.begin(),allv.end(),rg[i].F.F)-allv.begin();
		rg[i].F.S=lower_bound(allv.begin(),allv.end(),rg[i].F.S)-allv.begin();
		upd[rg[i].F.F].push_back(rg[i].S);
		erz[rg[i].F.S].push_back(rg[i].S);
	}
	set<pair<ll,ll> > curl;
	ret.push_back(make_pair(-INF,-1));
	for(i=0;i<allv.size();i++)
	{
		for(j=0;j<upd[i].size();j++)
		{
			curl.insert(make_pair(i,upd[i][j]));
		}
		for(j=0;j<erz[i].size();j++)
		{
			curl.erase(curl.lower_bound(make_pair(lower_bound(allv.begin(),allv.end(),din[erz[i][j]])-allv.begin(),erz[i][j])));
		}
		ret.push_back(make_pair(allv[i],(curl.empty())?-1:((*--curl.end()).S)));
	}
	return ret;
}
void pretree(ll rt)
{
	ll i;
	curdfn=0;
	pth.clear();
	predfs(rt,-1,0,0);
	map<ll,vector<ll> > rgs;
	for(i=0;i<pth.size();i++)
	{
		if(pth[i]!=rt)
		{
			bel[pth[i]]=rt;
		}
		ll v=a[pth[i]]+distree[pth[i]];
		if(rgs.count(v))
		{
			rgs[v].push_back(pth[i]);
		}
		else
		{
			rgs[v]={pth[i]};
		}
	}
	for(map<ll,vector<ll> >::iterator it=rgs.begin();it!=rgs.end();it++)
	{
		tre[rt][it->F]=prerange(it->S);
	}
	return;
}
void solvecyc()
{
	ll i,rt=bel[curnd],u=curnd,id=cycid[curnd];
	ll lo=id,hi=id+cycseq[rt].size()/2-1;
	if(cyclen[rt]==0)
	{
		if(!cyc[rt].count(curval-discyc[rt][id]))
		{
			puts("-1");
			exit(0);
		}
		pair<ll,ll> tmp=make_pair(curval-discyc[rt][id],id);
		ll p=lower_bound(cyc[rt][curval-discyc[rt][id]].begin(),cyc[rt][curval-discyc[rt][id]].end(),tmp)-cyc[rt][curval-discyc[rt][id]].begin();
		if(p==cyc[rt][curval-discyc[rt][id]].size()||cyc[rt][curval-discyc[rt][id]][p].S>hi||vis[cycseq[rt][cyc[rt][curval-discyc[rt][id]][p].S]])
		{
			puts("-1");
			exit(0);
		}
		(ans+=cyc[rt][curval-discyc[rt][id]][p].S-id+1)%=mod;
		p=cycseq[rt][cyc[rt][curval-discyc[rt][id]][p].S];
		vis[p]=true;
		curnd=c[p];
		curval=a[p]+b[p];
		return;
	}
	if(isflp[rt])
	{
		curval=-curval;
	}
	ll keyval=(((curval-discyc[rt][id])%cyclen[rt])+cyclen[rt])%cyclen[rt],prekey;
	prekey=keyval;
	if(!cyc[rt].count(keyval))
	{
		puts("-1");
		exit(0);
	}
	keyval=curval-discyc[rt][id];
	pair<ll,ll> tmp=make_pair(keyval,id);
	ll p=lower_bound(cyc[rt][prekey].begin(),cyc[rt][prekey].end(),tmp)-cyc[rt][prekey].begin();
	if(p==cyc[rt][prekey].size())
	{
		puts("-1");
		exit(0);
	}
	if(cyc[rt][prekey][p].S<=hi)
	{
		(ans+=(cycseq[rt].size()/2)*((cyc[rt][prekey][p].F-keyval)/cyclen[rt]))%=mod;
		(ans+=cyc[rt][prekey][p].S-id+1)%=mod;
		p=cycseq[rt][cyc[rt][prekey][p].S];
		if(vis[p])
		{
			puts("-1");
			exit(0);
		}
		vis[p]=true;
		curnd=c[p];
		curval=isflp[rt]?-a[p]:a[p];
		curval+=b[p];
		return;
	}
	tmp=make_pair(cyc[rt][prekey][p].F+1,id);
	p=lower_bound(cyc[rt][prekey].begin(),cyc[rt][prekey].end(),tmp)-cyc[rt][prekey].begin();
	if(p==cyc[rt][prekey].size())
	{
		puts("-1");
		exit(0);
	}
	if(cyc[rt][prekey][p].S<=hi)
	{
		(ans+=(cycseq[rt].size()/2)*((cyc[rt][prekey][p].F-keyval)/cyclen[rt]))%=mod;
		(ans+=cyc[rt][prekey][p].S-id+1)%=mod;
		p=cycseq[rt][cyc[rt][prekey][p].S];
		if(vis[p])
		{
			puts("-1");
			exit(0);
		}
		vis[p]=true;
		curnd=c[p];
		curval=isflp[rt]?-a[p]:a[p];
		curval+=b[p];
		return;
	}
	tmp=make_pair(cyc[rt][prekey][p].F+1,id);
	p=lower_bound(cyc[rt][prekey].begin(),cyc[rt][prekey].end(),tmp)-cyc[rt][prekey].begin();
	if(p==cyc[rt][prekey].size())
	{
		puts("-1");
		exit(0);
	}
	(ans+=(cycseq[rt].size()/2)*((cyc[rt][prekey][p].F-keyval)/cyclen[rt]))%=mod;
	(ans+=cyc[rt][prekey][p].S-id+1)%=mod;
	p=cycseq[rt][cyc[rt][prekey][p].S];
	if(vis[p])
	{
		puts("-1");
		exit(0);
	}
	vis[p]=true;
	curnd=c[p];
	curval=isflp[rt]?-a[p]:a[p];
	curval+=b[p];
	return;
}
void solvetree()
{
	ll u=curnd,rt=bel[u];
	if(!tre[rt].count(distree[u]+curval))
	{
		curnd=rt;
		curval+=distree[u];
		(ans+=deptree[u])%=mod;
		return;
	}
	pair<ll,ll> tmp=make_pair(din[u],INF);
	ll p=upper_bound(tre[rt][distree[u]+curval].begin(),tre[rt][distree[u]+curval].end(),tmp)-tre[rt][distree[u]+curval].begin()-1;
	ll des=tre[rt][distree[u]+curval][p].S;
	if(des==-1)
	{
		curnd=rt;
		curval+=distree[u];
		(ans+=deptree[u])%=mod;
		return;
	}
	if(vis[des])
	{
		puts("-1");
		exit(0);
	}
	vis[des]=true;
	(ans+=deptree[u]-deptree[des]+1)%=mod;
	curnd=c[des];
	curval=a[des]+b[des];
	return;
}
int main(){
//	freopen("in.txt","r",stdin);
	ll i;
	n=rint();
	assert(n<1000||n==100000);
	curval=rint();
	curnd=0;
	for(i=0;i<n;i++)
	{
		a[i]=rint(),b[i]=rint(),c[i]=rint()-1,d[i]=rint(),e[i]=rint()-1;
		deg[e[i]]++;
		bk[e[i]].push_back(i);
	}
	deg[n]++;
	e[n]=n;
	getcyc();
	for(i=0;i<cychead.size();i++)
	{
		precyc(cychead[i]);
	}
	for(i=0;i<=n;i++)
	{
		if(iscyc[i])
		{
			pretree(i);
		}
	}
	memset(vis,false,sizeof(vis));
	while(curnd!=n)
	{
		if(iscyc[curnd])
		{
			solvecyc();
		}
		else
		{
			solvetree();
		}
	}
	printf("%lld\n",ans);
	return 0;
}
accuracy: 0.6486486486486487
time_ms: 80
memory_kb: 91088
final_rank: 17

code_snippet: #include <bits/stdc++.h>
#define INF 1000000000
#define LINF 1000000000000000000
#define mod 1000000007
#define F first
#define S second
#define ll long long
#define N 200010
using namespace std;
ll rint(){
	ll ret=0,uu=1;
	char c=getchar();
	while(!isdigit(c)&&c!='-') c=getchar();
	if(c=='-') uu=-1,c=getchar();
	while(isdigit(c)) ret=ret*10+(c-'0'),c=getchar();
	return ret*uu;
}
ll n,a[N],b[N],c[N],d[N],e[N],curval,curnd,deg[N],bel[N],ans=0;
vector<ll> bk[N];
ll cycid[N],cyclen[N],distree[N],deptree[N],din[N],dout[N],curdfn;
bool iscyc[N],isflp[N],vis[N];
vector<ll> cycseq[N],cychead,discyc[N],pth,upd[N],erz[N];
map<ll,vector<pair<ll,ll> > > cyc[N],tre[N];
bool cmpcyc(pair<ll,ll> x,pair<ll,ll> y){return (x.F==y.F)?(x.S<y.S):(x.F<y.F);}
void getcyc()
{
	queue<ll> q;
	ll i,j;
	for(i=0;i<=n;i++)
	{
		iscyc[i]=true;
		vis[i]=false;
		if(deg[i]==0)
		{
			q.push(i);
		}
	}
	while(!q.empty())
	{
		ll x=q.front();
		iscyc[x]=false;
		vis[x]=true;
		q.pop();
		deg[e[x]]--;
		if(deg[e[x]]==0)
		{
			q.push(e[x]);
		}
	}
	for(i=0;i<=n;i++)
	{
		if(!vis[i])
		{
			cychead.push_back(i);
			cycseq[i].push_back(i);
			cycid[i]=0;
			bel[i]=i;
			vis[i]=true;
			for(j=e[i];j!=i;j=e[j])
			{
				bel[j]=i;
				vis[j]=true;
				cycid[j]=cycseq[i].size();
				cycseq[i].push_back(j);
			}
			ll sz=cycseq[i].size();
			for(j=0;j<sz;j++)
			{
				cycseq[i].push_back(cycseq[i][j]);
			}
		}
	}
	return;
}
void precyc(ll x)
{
	ll i;
	cyclen[x]=0;
	for(i=0;i<cycseq[x].size();i++)
	{
		discyc[x].push_back(cyclen[x]);
		cyclen[x]+=d[cycseq[x][i]];
	}
	cyclen[x]/=2;
	if(cyclen[x]<0)
	{
		isflp[x]=true;
		for(i=0;i*2<cycseq[x].size();i++)
		{
			d[cycseq[x][i]]=-d[cycseq[x][i]];
			a[cycseq[x][i]]=-a[cycseq[x][i]];
		}
		cyclen[x]=-cyclen[x];
		for(i=0;i<cycseq[x].size();i++)
		{
			discyc[x][i]=-discyc[x][i];
		}
	}
	if(cyclen[x]==0)
	{
		for(i=0;i<cycseq[x].size();i++)
		{
			ll v=a[cycseq[x][i]]-discyc[x][i];
			if(cyc[x].count(v))
			{
				cyc[x][v].push_back(make_pair(v,i));
			}
			else
			{
				cyc[x][v]={make_pair(v,i)};
			}
		}
		return;
	}
	for(i=0;i<cycseq[x].size();i++)
	{
		ll v=(((a[cycseq[x][i]]-discyc[x][i])%cyclen[x])+cyclen[x])%cyclen[x];
		if(cyc[x].count(v))
		{
			cyc[x][v].push_back(make_pair(a[cycseq[x][i]]-discyc[x][i],i));
		}
		else
		{
			cyc[x][v]={make_pair(a[cycseq[x][i]]-discyc[x][i],i)};
		}
		for(map<ll,vector<pair<ll,ll> > >::iterator it=cyc[x].begin();it!=cyc[x].end();it++)
		{
			sort((it->S).begin(),(it->S).end(),cmpcyc);
		}
	}
	return;
}
void predfs(ll x,ll lst,ll predis,ll predep)
{
	pth.push_back(x);
	distree[x]=predis;
	deptree[x]=predep;
	din[x]=++curdfn;
	ll i;
	for(i=0;i<bk[x].size();i++)
	{
		if(bk[x][i]!=lst&&(!iscyc[bk[x][i]]))
		{
			predfs(bk[x][i],x,predis+d[bk[x][i]],predep+1);
		}
	}
	dout[x]=curdfn;
	return;
}
vector<pair<ll,ll> > prerange(vector<ll> v)
{
	ll i,j;
	vector<pair<ll,ll> > ret;
	vector<pair<pair<ll,ll>,ll> > rg;
	vector<ll> allv;
	for(i=0;i<v.size();i++)
	{
		rg.push_back(make_pair(make_pair(din[v[i]],dout[v[i]]+1),v[i]));
		allv.push_back(din[v[i]]);
		allv.push_back(dout[v[i]]+1);
	}
	sort(allv.begin(),allv.end());
	allv.erase(unique(allv.begin(),allv.end()),allv.end());
	for(i=0;i<allv.size();i++)
	{
		upd[i].clear();
		erz[i].clear();
	}
	for(i=0;i<rg.size();i++)
	{
		rg[i].F.F=lower_bound(allv.begin(),allv.end(),rg[i].F.F)-allv.begin();
		rg[i].F.S=lower_bound(allv.begin(),allv.end(),rg[i].F.S)-allv.begin();
		upd[rg[i].F.F].push_back(rg[i].S);
		erz[rg[i].F.S].push_back(rg[i].S);
	}
	set<pair<ll,ll> > curl;
	ret.push_back(make_pair(-INF,-1));
	for(i=0;i<allv.size();i++)
	{
		for(j=0;j<upd[i].size();j++)
		{
			curl.insert(make_pair(i,upd[i][j]));
		}
		for(j=0;j<erz[i].size();j++)
		{
			curl.erase(curl.lower_bound(make_pair(lower_bound(allv.begin(),allv.end(),din[erz[i][j]])-allv.begin(),erz[i][j])));
		}
		ret.push_back(make_pair(allv[i],(curl.empty())?-1:((*--curl.end()).S)));
	}
	return ret;
}
void pretree(ll rt)
{
	ll i;
	curdfn=0;
	pth.clear();
	predfs(rt,-1,0,0);
	map<ll,vector<ll> > rgs;
	for(i=0;i<pth.size();i++)
	{
		if(pth[i]!=rt)
		{
			bel[pth[i]]=rt;
		}
		ll v=a[pth[i]]+distree[pth[i]];
		if(rgs.count(v))
		{
			rgs[v].push_back(pth[i]);
		}
		else
		{
			rgs[v]={pth[i]};
		}
	}
	for(map<ll,vector<ll> >::iterator it=rgs.begin();it!=rgs.end();it++)
	{
		tre[rt][it->F]=prerange(it->S);
	}
	return;
}
void solvecyc()
{
	ll i,rt=bel[curnd],u=curnd,id=cycid[curnd];
	ll lo=id,hi=id+cycseq[rt].size()/2-1;
	if(cyclen[rt]==0)
	{
		if(!cyc[rt].count(curval-discyc[rt][id]))
		{
			puts("-1");
			exit(0);
		}
		vector<pair<ll,ll> > vals=cyc[rt][curval-discyc[rt][id]];
		pair<ll,ll> tmp=make_pair(curval-discyc[rt][id],id);
		ll p=lower_bound(vals.begin(),vals.end(),tmp)-vals.begin();
		if(p==vals.size()||vals[p].S>hi||vis[cycseq[rt][vals[p].S]])
		{
			puts("-1");
			exit(0);
		}
		(ans+=vals[p].S-id+1)%=mod;
		p=cycseq[rt][vals[p].S];
		vis[p]=true;
		curnd=c[p];
		curval=a[p]+b[p];
		return;
	}
	if(isflp[rt])
	{
		curval=-curval;
	}
	ll keyval=(((curval-discyc[rt][id])%cyclen[rt])+cyclen[rt])%cyclen[rt];
	if(!cyc[rt].count(keyval))
	{
		puts("-1");
		exit(0);
	}
	vector<pair<ll,ll> > vals=cyc[rt][keyval];
	keyval=curval-discyc[rt][id];
	pair<ll,ll> tmp=make_pair(keyval,id);
	ll p=lower_bound(vals.begin(),vals.end(),tmp)-vals.begin();
	if(p==vals.size())
	{
		puts("-1");
		exit(0);
	}
	if(vals[p].S<=hi)
	{
		(ans+=(cycseq[rt].size()/2)*((vals[p].F-keyval)/cyclen[rt]))%=mod;
		(ans+=vals[p].S-id+1)%=mod;
		p=cycseq[rt][vals[p].S];
		if(vis[p])
		{
			puts("-1");
			exit(0);
		}
		vis[p]=true;
		curnd=c[p];
		curval=isflp[rt]?-a[p]:a[p];
		curval+=b[p];
		return;
	}
	tmp=make_pair(vals[p].F+1,id);
	p=lower_bound(vals.begin(),vals.end(),tmp)-vals.begin();
	if(p==vals.size())
	{
		puts("-1");
		exit(0);
	}
	if(vals[p].S<=hi)
	{
		(ans+=(cycseq[rt].size()/2)*((vals[p].F-keyval)/cyclen[rt]))%=mod;
		(ans+=vals[p].S-id+1)%=mod;
		p=cycseq[rt][vals[p].S];
		if(vis[p])
		{
			puts("-1");
			exit(0);
		}
		vis[p]=true;
		curnd=c[p];
		curval=isflp[rt]?-a[p]:a[p];
		curval+=b[p];
		return;
	}
	tmp=make_pair(vals[p].F+1,id);
	p=lower_bound(vals.begin(),vals.end(),tmp)-vals.begin();
	if(p==vals.size())
	{
		puts("-1");
		exit(0);
	}
	(ans+=(cycseq[rt].size()/2)*((vals[p].F-keyval)/cyclen[rt]))%=mod;
	(ans+=vals[p].S-id+1)%=mod;
	p=cycseq[rt][vals[p].S];
	if(vis[p])
	{
		puts("-1");
		exit(0);
	}
	vis[p]=true;
	curnd=c[p];
	curval=isflp[rt]?-a[p]:a[p];
	curval+=b[p];
	return;
}
void solvetree()
{
	ll u=curnd,rt=bel[u];
	if(!tre[rt].count(distree[u]+curval))
	{
		curnd=rt;
		curval+=distree[u];
		(ans+=deptree[u])%=mod;
		return;
	}
	vector<pair<ll,ll> > vals=tre[rt][distree[u]+curval];
	pair<ll,ll> tmp=make_pair(din[u],INF);
	ll p=upper_bound(vals.begin(),vals.end(),tmp)-vals.begin()-1;
	ll des=vals[p].S;
	if(des==-1)
	{
		curnd=rt;
		curval+=distree[u];
		(ans+=deptree[u])%=mod;
		return;
	}
	if(vis[des])
	{
		puts("-1");
		exit(0);
	}
	vis[des]=true;
	(ans+=deptree[u]-deptree[des]+1)%=mod;
	curnd=c[des];
	curval=a[des]+b[des];
	return;
}
int main(){
//	freopen("in.txt","r",stdin);
	ll i;
	n=rint();
	curval=rint();
	curnd=0;
	for(i=0;i<n;i++)
	{
		a[i]=rint(),b[i]=rint(),c[i]=rint()-1,d[i]=rint(),e[i]=rint()-1;
		deg[e[i]]++;
		bk[e[i]].push_back(i);
	}
	deg[n]++;
	e[n]=n;
	getcyc();
	for(i=0;i<cychead.size();i++)
	{
		precyc(cychead[i]);
	}
	for(i=0;i<=n;i++)
	{
		if(iscyc[i])
		{
			pretree(i);
		}
	}
	memset(vis,false,sizeof(vis));
	i=0;
	while(i<5000&&curnd!=n)
	{
		i++;
		if(iscyc[curnd])
		{
			solvecyc();
		}
		else
		{
			solvetree();
		}
	}
	printf("%lld\n",ans);
	return 0;
}
accuracy: 0.6351351351351351
time_ms: 680
memory_kb: 93556
final_rank: 19

code_snippet: #include <bits/stdc++.h>
#define INF 1000000000
#define LINF 1000000000000000000
#define mod 1000000007
#define F first
#define S second
#define ll long long
#define N 200010
using namespace std;
ll rint(){
	ll ret=0,uu=1;
	char c=getchar();
	while(!isdigit(c)&&c!='-') c=getchar();
	if(c=='-') uu=-1,c=getchar();
	while(isdigit(c)) ret=ret*10+(c-'0'),c=getchar();
	return ret*uu;
}
ll n,a[N],b[N],c[N],d[N],e[N],curval,curnd,deg[N],bel[N],ans=0;
vector<ll> bk[N];
ll cycid[N],cyclen[N],distree[N],deptree[N],din[N],dout[N],curdfn;
bool iscyc[N],isflp[N],vis[N];
vector<ll> cycseq[N],cychead,discyc[N],pth,upd[N],erz[N];
map<ll,vector<pair<ll,ll> > > cyc[N],tre[N];
bool cmpcyc(pair<ll,ll> x,pair<ll,ll> y){return (x.F==y.F)?(x.S<y.S):(x.F<y.F);}
void getcyc()
{
	queue<ll> q;
	ll i,j;
	for(i=0;i<=n;i++)
	{
		iscyc[i]=true;
		vis[i]=false;
		if(deg[i]==0)
		{
			q.push(i);
		}
	}
	while(!q.empty())
	{
		ll x=q.front();
		iscyc[x]=false;
		vis[x]=true;
		q.pop();
		deg[e[x]]--;
		if(deg[e[x]]==0)
		{
			q.push(e[x]);
		}
	}
	for(i=0;i<=n;i++)
	{
		if(!vis[i])
		{
			cychead.push_back(i);
			cycseq[i].push_back(i);
			cycid[i]=0;
			bel[i]=i;
			vis[i]=true;
			for(j=e[i];j!=i;j=e[j])
			{
				bel[j]=i;
				vis[j]=true;
				cycid[j]=cycseq[i].size();
				cycseq[i].push_back(j);
			}
			ll sz=cycseq[i].size();
			for(j=0;j<sz;j++)
			{
				cycseq[i].push_back(cycseq[i][j]);
			}
		}
	}
	return;
}
void precyc(ll x)
{
	ll i;
	cyclen[x]=0;
	for(i=0;i<cycseq[x].size();i++)
	{
		discyc[x].push_back(cyclen[x]);
		cyclen[x]+=d[cycseq[x][i]];
	}
	cyclen[x]/=2;
	if(cyclen[x]<0)
	{
		isflp[x]=true;
		for(i=0;i*2<cycseq[x].size();i++)
		{
			d[cycseq[x][i]]=-d[cycseq[x][i]];
			a[cycseq[x][i]]=-a[cycseq[x][i]];
		}
		cyclen[x]=-cyclen[x];
		for(i=0;i<cycseq[x].size();i++)
		{
			discyc[x][i]=-discyc[x][i];
		}
	}
	if(cyclen[x]==0)
	{
		for(i=0;i<cycseq[x].size();i++)
		{
			ll v=a[cycseq[x][i]]-discyc[x][i];
			if(cyc[x].count(v))
			{
				cyc[x][v].push_back(make_pair(v,i));
			}
			else
			{
				cyc[x][v]={make_pair(v,i)};
			}
		}
		return;
	}
	for(i=0;i<cycseq[x].size();i++)
	{
		ll v=(((a[cycseq[x][i]]-discyc[x][i])%cyclen[x])+cyclen[x])%cyclen[x];
		if(cyc[x].count(v))
		{
			cyc[x][v].push_back(make_pair(a[cycseq[x][i]]-discyc[x][i],i));
		}
		else
		{
			cyc[x][v]={make_pair(a[cycseq[x][i]]-discyc[x][i],i)};
		}
		for(map<ll,vector<pair<ll,ll> > >::iterator it=cyc[x].begin();it!=cyc[x].end();it++)
		{
			sort((it->S).begin(),(it->S).end(),cmpcyc);
		}
	}
	return;
}
void predfs(ll x,ll lst,ll predis,ll predep)
{
	pth.push_back(x);
	distree[x]=predis;
	deptree[x]=predep;
	din[x]=++curdfn;
	ll i;
	for(i=0;i<bk[x].size();i++)
	{
		if(bk[x][i]!=lst&&(!iscyc[bk[x][i]]))
		{
			predfs(bk[x][i],x,predis+d[bk[x][i]],predep+1);
		}
	}
	dout[x]=curdfn;
	return;
}
vector<pair<ll,ll> > prerange(vector<ll> v)
{
	ll i,j;
	vector<pair<ll,ll> > ret;
	vector<pair<pair<ll,ll>,ll> > rg;
	vector<ll> allv;
	for(i=0;i<v.size();i++)
	{
		rg.push_back(make_pair(make_pair(din[v[i]],dout[v[i]]+1),v[i]));
		allv.push_back(din[v[i]]);
		allv.push_back(dout[v[i]]+1);
	}
	sort(allv.begin(),allv.end());
	allv.erase(unique(allv.begin(),allv.end()),allv.end());
	for(i=0;i<allv.size();i++)
	{
		upd[i].clear();
		erz[i].clear();
	}
	for(i=0;i<rg.size();i++)
	{
		rg[i].F.F=lower_bound(allv.begin(),allv.end(),rg[i].F.F)-allv.begin();
		rg[i].F.S=lower_bound(allv.begin(),allv.end(),rg[i].F.S)-allv.begin();
		upd[rg[i].F.F].push_back(rg[i].S);
		erz[rg[i].F.S].push_back(rg[i].S);
	}
	set<pair<ll,ll> > curl;
	ret.push_back(make_pair(-INF,-1));
	for(i=0;i<allv.size();i++)
	{
		for(j=0;j<upd[i].size();j++)
		{
			curl.insert(make_pair(i,upd[i][j]));
		}
		for(j=0;j<erz[i].size();j++)
		{
			curl.erase(curl.lower_bound(make_pair(lower_bound(allv.begin(),allv.end(),din[erz[i][j]])-allv.begin(),erz[i][j])));
		}
		ret.push_back(make_pair(allv[i],(curl.empty())?-1:((*--curl.end()).S)));
	}
	return ret;
}
void pretree(ll rt)
{
	ll i;
	curdfn=0;
	pth.clear();
	predfs(rt,-1,0,0);
	map<ll,vector<ll> > rgs;
	for(i=0;i<pth.size();i++)
	{
		if(pth[i]!=rt)
		{
			bel[pth[i]]=rt;
		}
		ll v=a[pth[i]]+distree[pth[i]];
		if(rgs.count(v))
		{
			rgs[v].push_back(pth[i]);
		}
		else
		{
			rgs[v]={pth[i]};
		}
	}
	for(map<ll,vector<ll> >::iterator it=rgs.begin();it!=rgs.end();it++)
	{
		tre[rt][it->F]=prerange(it->S);
	}
	return;
}
void solvecyc()
{
	ll i,rt=bel[curnd],u=curnd,id=cycid[curnd];
	ll lo=id,hi=id+cycseq[rt].size()/2-1;
	if(cyclen[rt]==0)
	{
		if(!cyc[rt].count(curval-discyc[rt][id]))
		{
			puts("-1");
			exit(0);
		}
		vector<pair<ll,ll> > vals=cyc[rt][curval-discyc[rt][id]];
		pair<ll,ll> tmp=make_pair(curval-discyc[rt][id],id);
		ll p=lower_bound(vals.begin(),vals.end(),tmp)-vals.begin();
		if(p==vals.size()||vals[p].S>hi||vis[cycseq[rt][vals[p].S]])
		{
			puts("-1");
			exit(0);
		}
		(ans+=vals[p].S-id+1)%=mod;
		p=cycseq[rt][vals[p].S];
		vis[p]=true;
		curnd=c[p];
		curval=a[p]+b[p];
		return;
	}
	if(isflp[rt])
	{
		curval=-curval;
	}
	ll keyval=(((curval-discyc[rt][id])%cyclen[rt])+cyclen[rt])%cyclen[rt];
	if(!cyc[rt].count(keyval))
	{
		puts("-1");
		exit(0);
	}
	vector<pair<ll,ll> > vals=cyc[rt][keyval];
	keyval=curval-discyc[rt][id];
	pair<ll,ll> tmp=make_pair(keyval,id);
	ll p=lower_bound(vals.begin(),vals.end(),tmp)-vals.begin();
	if(p==vals.size())
	{
		puts("-1");
		exit(0);
	}
	if(vals[p].S<=hi)
	{
		(ans+=(cycseq[rt].size()/2)*((vals[p].F-keyval)/cyclen[rt]))%=mod;
		(ans+=vals[p].S-id+1)%=mod;
		p=cycseq[rt][vals[p].S];
		if(vis[p])
		{
			puts("-1");
			exit(0);
		}
		vis[p]=true;
		curnd=c[p];
		curval=isflp[rt]?-a[p]:a[p];
		curval+=b[p];
		return;
	}
	tmp=make_pair(vals[p].F+1,id);
	p=lower_bound(vals.begin(),vals.end(),tmp)-vals.begin();
	if(p==vals.size())
	{
		puts("-1");
		exit(0);
	}
	if(vals[p].S<=hi)
	{
		(ans+=(cycseq[rt].size()/2)*((vals[p].F-keyval)/cyclen[rt]))%=mod;
		(ans+=vals[p].S-id+1)%=mod;
		p=cycseq[rt][vals[p].S];
		if(vis[p])
		{
			puts("-1");
			exit(0);
		}
		vis[p]=true;
		curnd=c[p];
		curval=isflp[rt]?-a[p]:a[p];
		curval+=b[p];
		return;
	}
	tmp=make_pair(vals[p].F+1,id);
	p=lower_bound(vals.begin(),vals.end(),tmp)-vals.begin();
	if(p==vals.size())
	{
		puts("-1");
		exit(0);
	}
	(ans+=(cycseq[rt].size()/2)*((vals[p].F-keyval)/cyclen[rt]))%=mod;
	(ans+=vals[p].S-id+1)%=mod;
	p=cycseq[rt][vals[p].S];
	if(vis[p])
	{
		puts("-1");
		exit(0);
	}
	vis[p]=true;
	curnd=c[p];
	curval=isflp[rt]?-a[p]:a[p];
	curval+=b[p];
	return;
}
void solvetree()
{
	ll u=curnd,rt=bel[u];
	if(!tre[rt].count(distree[u]+curval))
	{
		curnd=rt;
		curval+=distree[u];
		(ans+=deptree[u])%=mod;
		return;
	}
	vector<pair<ll,ll> > vals=tre[rt][distree[u]+curval];
	pair<ll,ll> tmp=make_pair(din[u],INF);
	ll p=upper_bound(vals.begin(),vals.end(),tmp)-vals.begin()-1;
	ll des=vals[p].S;
	if(des==-1)
	{
		curnd=rt;
		curval+=distree[u];
		(ans+=deptree[u])%=mod;
		return;
	}
	if(vis[des])
	{
		puts("-1");
		exit(0);
	}
	vis[des]=true;
	(ans+=deptree[u]-deptree[des]+1)%=mod;
	curnd=c[des];
	curval=a[des]+b[des];
	return;
}
int main(){
//	freopen("in.txt","r",stdin);
	ll i;
	n=rint();
	curval=rint();
	curnd=0;
	for(i=0;i<n;i++)
	{
		a[i]=rint(),b[i]=rint(),c[i]=rint()-1,d[i]=rint(),e[i]=rint()-1;
		deg[e[i]]++;
		bk[e[i]].push_back(i);
	}
	deg[n]++;
	e[n]=n;
	getcyc();
	for(i=0;i<cychead.size();i++)
	{
		precyc(cychead[i]);
	}
	for(i=0;i<=n;i++)
	{
		if(iscyc[i])
		{
			pretree(i);
		}
	}
	if(n<50000)
	{
		memset(vis,false,sizeof(vis));
		while(curnd!=n)
		{
			if(iscyc[curnd])
			{
				solvecyc();
			}
			else
			{
				solvetree();
			}
		}
		printf("%lld\n",ans);
	}
	return 0;
}
accuracy: 0.6351351351351351
time_ms: 60
memory_kb: 90260
final_rank: 18

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define mit map<ll,int>::iterator
#define sit set<int>::iterator
#define itrm(g,x) for(mit g=x.begin();g!=x.end();g++)
#define itrs(g,x) for(sit g=x.begin();g!=x.end();g++)
#define ltype int
#define rep(i,j,k) for(ltype(i)=(j);(i)<=(k);(i)++)
#define rap(i,j,k) for(ltype(i)=(j);(i)<(k);(i)++)
#define per(i,j,k) for(ltype(i)=(j);(i)>=(k);(i)--)
#define pii pair<int,int>
#define fi first
#define se second
#define mpr make_pair
#define pb push_back
#define fastio ios::sync_with_stdio(false)
#define check(x) if(x>=mod) x-=mod
const int inf=0x3f3f3f3f,mod=1000000007;
const double pi=3.1415926535897932,eps=1e-6;
void chmax(int &x,int y){if(x < y) x = y;}
void chmin(int &x,int y){if(x > y) x = y;}
int n;ll x0;
int c[100005],e[100005],en[100005],dep[100005],at[100005],xd[100005];ll a[100005],b[100005],d[100005],P[100005];
int id[100005],totc,tt[100005],tick;
vector<int> cyc[100005],path;vector<ll> pre[100005];bool on[100005],vis[100005];
ll sumc[100005];//555
bool walk2[100005];
vector<int> r[100005];
void dfs(int x){
    if(x == n + 1) {path.clear();return;}
    if(tt[x]) {
        if(on[x] || vis[x]){path.clear();return;}
        rap(i,tt[x]-1,path.size()) cyc[totc].pb(path[i]),on[path[i]] = vis[path[i]] = 1,at[path[i]]=totc,xd[path[i]] = i-tt[x]+1;
        path.clear();
        totc++;
        en[x] = x;
        return;
    }
    tt[x] = ++tick;
    path.pb(x);
    dfs(e[x]);
    if(!on[e[x]]) P[x] = P[e[x]];
    P[x] += d[x], en[x] = en[e[x]];
    if(on[x]) en[x] = x;
    vis[x] = 1;//completed
}
map<ll,int> vals;
int rt[400005];
struct segtree{
    int dat[10500000],ls[10500000],rs[10500000],n,top,num;
    void build(int nn)
    {
        n=1;
        while(n<=nn) n<<=1;
        for(int i=0;i<2*n-1;i++) {
            if(i<n-1) ls[i]=(i<<1)+1,rs[i]=(i<<1)+2;
            else ls[i] = rs[i] = -1;
        }
        top = 2 * n - 2;
    }
    int clone(int x){
        top++;
        dat[top] = dat[x];
        ls[top] = ls[x];
        rs[top] = rs[x];
        return top;
    }
    void update(int x,int k){
        num++;
        rt[num] = top + 1;
        update(rt[num-1],0,n,x,k);
    }
    int update(int k,int l,int r,int a,int x){
        k = clone(k);
        if(r - l == 1) {
            dat[k] = x;
            return k;
        }
        if(a < ((l + r) >> 1)) {ls[k] = update(ls[k],l,(l+r)>>1,a,x);}
        else {rs[k] = update(rs[k],(l+r)>>1,r,a,x);}
        return k;
    }
    int query(int l,int r,int x){
        return query(l,r+1,rt[x],0,n);
    }
    int query(int a,int b,int k,int l,int r){
        if(r<=a||b<=l) return inf;
        if(a<=l&&r<=b) return dat[k];
        return min(query(a,b,ls[k],l,(l+r)>>1),query(a,b,rs[k],(l+r)>>1,r));
    }
}seg;
int jiyi[100005],Cnt;
void deal(int x,int fa){
    int ps = vals[P[x] + a[x]];
    int pr = seg.query(ps, ps, seg.num);
    seg.update(ps, x);
    jiyi[x] = seg.num;
    for(int to : r[x]) {
        if(to == fa) continue;
        dep[to] = dep[x] + 1;
        deal(to, x);
    }
    seg.update(ps, pr);
}
void fail(){puts("-1");exit(0);}
map<pair<int,ll>,int> ID;vector<pair<ll,int>> duliu[200005],wtf[200005];
bool cmp(pair<ll,int> x,pair<ll,int> y){if(x.fi != y.fi) return x.fi > y.fi;return x.se < y.se;}
int dis(int x,int y,int l){return x > y ? l - x + y : y - x;}
void mark(int x){if(walk2[x])fail();walk2[x]=1;}
int main()
{
    scanf("%d%lld",&n,&x0);
    rep(i,1,n) {
        scanf("%lld%lld%d%lld%d",a+i,b+i,c+i,d+i,e+i);
        r[e[i]].pb(i);
    }
    rep(i,1,n){
        if(!tt[i]){tick=0;dfs(i);}
    }
    int asdf = 0;
    rap(i,0,totc) {
        pre[i].pb(0);
        rap(j,0,(int)cyc[i].size()-1) {
            pre[i].pb(d[cyc[i][j]]);
            pre[i][j + 1] += pre[i][j];
        }//for(int x : cyc[i]) printf("%d ",x);puts("");
        //for(ll x : pre[i]) printf("%lld ",x);puts("");
        ll sum = pre[i].back() + d[cyc[i].back()];
        sumc[i] = sum;
        sum = abs(sum);
        if(sum)
        rap(j,0,cyc[i].size()) {
            ID[mpr(i, ((-pre[i][j]+a[cyc[i][j]]) % sum + sum) % sum)] = 0;
        }
        else{ID[mpr(i, 0x3f3f3f3f3f3f3f3f)] = 0;}
    }
    for(auto it = ID.begin();it != ID.end();it++) it->se = ++asdf;
    rap(i,0,totc) {
        ll sum = abs(sumc[i]);
        rap(j,0,cyc[i].size()) {
            int id;
            if(sum){id = ID[mpr(i, ((-pre[i][j]+a[cyc[i][j]]) % sum + sum) % sum)];
            duliu[id].pb(mpr(-pre[i][j]+a[cyc[i][j]],j));}
            id = ID[mpr(i, 0x3f3f3f3f3f3f3f3f)];
            duliu[id].pb(mpr(-pre[i][j]+a[cyc[i][j]],j));
        }
    }
    rep(i,1,asdf) sort(duliu[i].begin(),duliu[i].end());
    rep(i,1,asdf) {wtf[i] = duliu[i];sort(wtf[i].begin(),wtf[i].end(),cmp);}

    int CNT = 0;
    rep(i,1,n) if(!on[i]) {
        vals[P[i] + a[i]] = 0;
    }
    itrm(it, vals) it->se = ++CNT;

    seg.build(n);
    rep(i,1,n+1) if(!en[i]) en[i] = n + 1;
    rep(i,1,n + 1) if(on[i] || i == n + 1) {
        for(int to : r[i]) {
            if(!on[to]) {
                deal(to, i);
            }
        }
    }
    int pos = 1;int ans = 0;
    while(1) {
        if(pos == n + 1) break;
        if(!on[pos]) {
            ll qwq = x0 + P[pos];
            if(vals[qwq]) {
                int res = seg.query(vals[qwq],vals[qwq],jiyi[pos]);
                if(res > 0) {
                    mark(res);
                    ans += dep[pos] - dep[res] + 1;
                    check(ans);
                    x0 += P[pos] - P[res] + b[res];
                    pos = c[res];
                    continue;
                }
            }
            ans += dep[pos] + 1;
            check(ans);
            x0 += P[pos];
            pos = en[pos];
        }
        if(pos == n + 1) break;
        int id = at[pos];ll &pr = pre[id][xd[pos]];
        ll sum = sumc[id];
        if(!sum) {
            int g = ID[mpr(id,0x3f3f3f3f3f3f3f3f)];
            int fuck = lower_bound(duliu[g].begin(),duliu[g].end(),mpr(x0 - pr,xd[pos])) - duliu[g].begin();
            if(fuck == duliu[g].size() || duliu[g][fuck].fi != x0 - pr) {
                fuck = lower_bound(duliu[g].begin(),duliu[g].end(),mpr(x0 - pr,0)) - duliu[g].begin();
                if(fuck == duliu[g].size() || duliu[g][fuck].fi != x0 - pr) fail();
            }
            int pos0 = duliu[g][fuck].se;
            mark(cyc[id][pos0]);
            ans += dis(xd[pos], pos0, duliu[g].size()) + 1;
            check(ans);
            pos0 = cyc[id][pos0];
            x0 = a[pos0] + b[pos0];
            pos = c[pos0];
            continue;
        }
        int g = ID[mpr(id,((x0 - pr)% abs(sum) + abs(sum)) % abs(sum))];
        if(!g || duliu[g].empty()) fail();
        if(sum > 0) {
            int fuck = lower_bound(duliu[g].begin(),duliu[g].end(),mpr(x0 - pr,xd[pos])) - duliu[g].begin();
            if(fuck == duliu[g].size()) {
                fail();
            }
            pair<ll,int> &pir = duliu[g][fuck];
            ll nums = (pir.fi - x0 + pr) / sum;
            ans += ((ll)pre[id].size() * nums + pir.se - xd[pos]) % mod;check(ans);
            pos = cyc[id][pir.se];
            x0 = a[pos];
        }
        else if(sum < 0){
            int fuck = lower_bound(wtf[g].begin(),wtf[g].end(),mpr(x0 - pr,xd[pos]),cmp) - wtf[g].begin();
            if(fuck == wtf[g].size()) {
                fail();
            }
            pair<ll,int> &pir = wtf[g][fuck];
            ll nums = (x0 - pr - pir.fi) / abs(sum);
            ans += ((ll)pre[id].size() * nums + pir.se - xd[pos]) % mod;check(ans);
            pos = cyc[id][pir.se];
            x0 = a[pos];
        }
        ans++;check(ans);
        mark(pos);
        x0 += b[pos];
        pos = c[pos];
        if(pos == n + 1)break;
    }//ohhhhhhhhhhhhhhhh
    printf("%d\n",ans);
    return 0;
}
accuracy: 1
time_ms: 200
memory_kb: 111304
final_rank: 10

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define fi first
#define se second
const int M=1e9+7;
int n,c[100004],e[100004];
ll x,a[100004],b[100004],d[100004];
vector<pair<ll,int> >ask[100004];
vector<pair<ll,int> >tr[100004];
bool vis[100004];
vector<int>sta,cir;
vector<pair<ll,pair<int,int> > >v[100004];
int h[100004],m;
ll p[100004];
map<ll,int>mp;
int nxt[100004],dep[100004],val[100004];
int tot;
map<ll,int>MP[100004];
void dfs(int x,int rt,int pa,ll d){
	vis[x]=1;
	int lst;
	if(x!=n+1){
		lst=mp[a[x]+d];
		mp[a[x]+d]=x;
	}
	for(auto z:ask[x]){
		ll t=z.fi;int i=z.se;
		if(mp[d+t]!=0)nxt[i]=mp[d+t],val[i]=dep[x]-dep[nxt[i]]+1;
		else v[rt].push_back({t+d,{dep[x],i}});
	}
	for(auto y:tr[x])if(y.se!=pa)
		dep[y.se]=dep[x]+1,dfs(y.se,rt,-1,d+y.fi);
	if(x!=n+1)mp[a[x]+d]=lst;
}
int main(){
	scanf("%d%lld",&n,&x),ask[1].push_back({x,0});
	for(int i=0;i<=n+1;i++)nxt[i]=-1;
	for(int i=1;i<=n;i++){
		scanf("%lld%lld%d%lld%d",&a[i],&b[i],&c[i],&d[i],&e[i]);
		if(c[i]!=n+1)ask[c[i]].push_back({a[i]+b[i],i});
		else nxt[i]=n+1,val[i]=0;
		tr[e[i]].push_back({d[i],i});
	}
	for(int t=1;t<=n+1;t++)if(!vis[t]){
		sta.clear(),cir.clear();
		int cur=t;
		for(;;){
			vis[cur]=1,sta.push_back(cur);
			if(cur==n+1)break;
			cur=e[cur];if(vis[cur])break;
		}
		if(cur==n+1)cir.push_back(n+1);
		else{
			bool exi=0;
			for(auto x:sta){
				if(x==cur)exi=1;
				if(exi)cir.push_back(x);
			}
		}
		m=cir.size();
		for(int i=0;i<m;i++)h[i]=cir[i];
		h[m]=cir[0];
		for(int i=1;i<=m;i++){
			for(auto x:tr[h[i]])
				if(x.se==h[i-1])p[i]=x.fi;
			mp.clear();
			dfs(h[i],h[i],h[i-1],0);		
		}
		if(h[1]==n+1){
			for(auto x:v[n+1])nxt[x.se.se]=n+1,val[x.se.se]=x.se.fi;
			continue;
		}
		ll all=0;
		vector<pair<ll,pair<int,int> > >vec;
		mp.clear();
		for(int i=m;i;i--){
			for(auto z:v[h[i]]){
				ll w=z.fi+all;
				if(mp[w]>0){
					nxt[z.se.se]=h[mp[w]];
					val[z.se.se]=z.se.fi+mp[w]-i+1;
				}else vec.push_back({w,{z.se.fi+m-i,z.se.se}});
			}
			mp[a[h[i]]+all]=i,all+=p[i];
		}
		mp.clear();ll pre=0;
		for(int i=1;i<=m;i++){
			pre+=p[i];
			ll T,t=a[h[i]]-pre;
			if(all==0)T=t;
			else{
				ll q=abs(all);
				T=(t%q+q)%q;
			}
			if(!mp[T])mp[T]=++tot,MP[tot].clear();
			int id=mp[T];
			if(!MP[id].count(t))MP[id][t]=i;
		}
		for(auto x:vec){
			ll T,t=x.fi;
			if(all==0)T=t;
			else{
				ll q=abs(all);
				T=(t%q+q)%q;
			}
			if(!mp.count(T))continue;
			int id=mp[T];
			if(all==0)nxt[x.se.se]=id,val[x.se.se]=x.se.fi+id+1;
			if(all<0){
				auto it=MP[id].upper_bound(t);
				if(it==MP[id].begin())continue;--it;
				int ps=(*it).se;ll tm=(*it).fi;
				int g=(tm-t)/all%M;g=(ll)g*m%M;(g+=ps)%=M;
				nxt[x.se.se]=h[ps],val[x.se.se]=(x.se.fi+g+1)%M;
			}
			if(all>0){
				auto it=MP[id].lower_bound(t);
				if(it==MP[id].end())continue;
				int ps=(*it).se;ll tm=(*it).fi;
				int g=(tm-t)/all%M;g=(ll)g*m%M;(g+=ps)%=M;
				nxt[x.se.se]=h[ps],val[x.se.se]=(x.se.fi+g+1)%M;
			}
		}
	}
	int cur=0,ans=0,cnt=0;
	for(;;){
		cnt++;
		if(cnt>n+5||cur<0){
			puts("-1");return 0;
		}
		(ans+=val[cur])%=M,cur=nxt[cur];
		if(cur==n+1)break;
	}
	printf("%d\n",ans);
}
accuracy: 1
time_ms: 140
memory_kb: 41952
final_rank: 2

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define fi first
#define se second
const int M=1e9+7;
int n,c[100004],e[100004];
ll x,a[100004],b[100004],d[100004];
vector<pair<ll,int> >ask[100004];
vector<pair<ll,int> >tr[100004];
bool vis[100004];
vector<int>sta,cir;
vector<pair<ll,pair<int,int> > >v[100004];
int h[100004],m;
ll p[100004];
map<ll,int>mp;
int nxt[100004],dep[100004],val[100004];
int tot;
map<ll,int>MP[100004];
void dfs(int x,int rt,int pa,ll d){
	vis[x]=1;
	int lst;
	if(x!=n+1){
		lst=mp[a[x]+d];
		mp[a[x]+d]=x;
	}
	for(auto z:ask[x]){
		ll t=z.fi;int i=z.se;
		if(mp[d+t]!=0)nxt[i]=mp[d+t],val[i]=dep[x]-dep[nxt[i]]+1;
		else v[rt].push_back({t+d,{dep[x],i}});
	}
	for(auto y:tr[x])if(y.se!=pa)
		dep[y.se]=dep[x]+1,dfs(y.se,rt,-1,d+y.fi);
	if(x!=n+1)mp[a[x]+d]=lst;
}
int main(){
	scanf("%d%lld",&n,&x),ask[1].push_back({x,0});
	for(int i=0;i<=n+1;i++)nxt[i]=-1;
	for(int i=1;i<=n;i++){
		scanf("%lld%lld%d%lld%d",&a[i],&b[i],&c[i],&d[i],&e[i]);
		if(c[i]!=n+1)ask[c[i]].push_back({a[i]+b[i],i});
		else nxt[i]=n+1,val[i]=0;
		tr[e[i]].push_back({d[i],i});
	}
	for(int t=1;t<=n+1;t++)if(!vis[t]){
		sta.clear(),cir.clear();
		int cur=t;
		for(;;){
			vis[cur]=1,sta.push_back(cur);
			if(cur==n+1)break;
			cur=e[cur];if(vis[cur])break;
		}
		if(cur==n+1)cir.push_back(n+1);
		else{
			bool exi=0;
			for(auto x:sta){
				if(x==cur)exi=1;
				if(exi)cir.push_back(x);
			}
		}
		m=cir.size();
		for(int i=0;i<m;i++)h[i]=cir[i];
		h[m]=cir[0];
		for(int i=1;i<=m;i++){
			for(auto x:tr[h[i]])
				if(x.se==h[i-1])p[i]=x.fi;
			mp.clear();
			dfs(h[i],h[i],h[i-1],0);		
		}
//		cout<<m<<"\n";
//		for(int i=1;i<=m;i++)cout<<h[i]<<" "<<p[i]<<"\n";
//		break;
//		return 0;
		if(h[1]==n+1){
			for(auto x:v[n+1])nxt[x.se.se]=n+1,val[x.se.se]=x.se.fi;
			continue;
		}
		ll all=0;
		vector<pair<ll,pair<int,int> > >vec;
		mp.clear();
		for(int i=m;i;i--){
			for(auto z:v[h[i]]){
				ll w=z.fi+all;
				if(mp[w]>0){
					nxt[z.se.se]=h[mp[w]];
					val[z.se.se]=z.se.fi+mp[w]-i+1;
				}else vec.push_back({w,{z.se.fi+m-i,z.se.se}});
			}
			mp[a[h[i]]+all]=i,all+=p[i];
		}
//		cout<<m<<" "<<all<<"\n";
//		for(int i=1;i<=m;i++)cout<<h[i]<<" "<<p[i]<<"\n";
//		for(auto x:vec)cout<<x.fi<<" "<<x.se.fi<<" "<<x.se.se<<"?\n";
//		puts("");
//		return 0;
//		continue;
		mp.clear();ll pre=0;
		for(int i=1;i<=m;i++){
			pre+=p[i];
			ll T,t=a[h[i]]-pre;
			if(all==0)T=t;
			else{
				ll q=abs(all);
				T=(t%q+q)%q;
			}
			if(!mp[T])mp[T]=++tot,MP[tot].clear();
			int id=mp[T];
//			cout<<T<<" "<<t<<" "<<i<<"!\n";
			if(!MP[id].count(t))MP[id][t]=i;
		}
//		puts("");
		for(auto x:vec){
			ll T,t=x.fi;
			if(all==0)T=t;
			else{
				ll q=abs(all);
				T=(t%q+q)%q;
			}
			if(!mp.count(T))continue;
			int id=mp[T];
			if(all==0)nxt[x.se.se]=id,val[x.se.se]=x.se.fi+id+1;
			if(all<0){
				auto it=MP[id].upper_bound(t);
				if(it==MP[id].begin())continue;--it;
				int ps=(*it).se;ll tm=(*it).fi;
				int g=(tm-t)/all%M;g=(ll)g*m%M;(g+=ps)%=M;
				nxt[x.se.se]=h[ps],val[x.se.se]=(x.se.fi+g+1)%M;
			}
			if(all>0){
				auto it=MP[id].lower_bound(t);
				if(it==MP[id].end())continue;
				int ps=(*it).se;ll tm=(*it).fi;
//				cout<<ps<<" "<<tm<<" "<<x.se.se<<"\n";
//				cout<<tm<<" "<<t<<" "<<all<<"\n";
				int g=(tm-t)/all%M;g=(ll)g*m%M;(g+=ps)%=M;
				nxt[x.se.se]=h[ps],val[x.se.se]=(x.se.fi+g+1)%M;
			}
		}
//		break;
//		return 0;
	}
//	for(int i=0;i<=n;i++)cout<<nxt[i]<<" "<<val[i]<<"\n";
//	return 0;
	int cur=0,ans=0,cnt=0;
	for(;;){
		cnt++;
		if(cnt>n+5||cur<0){
			puts("-1");return 0;
		}
		(ans+=val[cur])%=M,cur=nxt[cur];
		if(cur==n+1)break;
	}
//	return 0;
	printf("%d\n",ans);
}
accuracy: 1
time_ms: 140
memory_kb: 41884
final_rank: 1

code_snippet: #include<bits/stdc++.h>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
#define int long long
#define lb long double
#define gmax(x,y) x=max(x,y)
#define gmin(x,y) x=min(x,y)
#define F first
#define S second
#define P pair
#define FOR(i,a,b) for(int i=a;i<=b;i++)
#define rep(i,a,b) for(int i=a;i<b;i++)
#define V vector
#define RE return
#define ALL(a) a.begin(),a.end()
#define MP make_pair
#define PB emplace_back
#define PF emplace_front
#define FILL(a,b) memset(a,b,sizeof(a))
#define lwb lower_bound
#define upb upper_bound
#define lc (x<<1)
#define rc ((x<<1)^1)
#define y1 yyyy1111
using namespace std;
using namespace __gnu_pbds;
int to[100005],add[100005],a[100005],b[100005],c[100005],n,in[100005],to2[100005];
int dis[100005],d[100005];
int out[100005];
V<P<int,int> > q1[100005],q2[100005];
V<int> v[100005],node[100005];
int vis[100005],adddis[100005];
int fa[100005];
int val[100005],rt[100005],s1[100005],s2[100005];
int get(int x){
	RE (fa[x]==x)?x:(fa[x]=get(fa[x]));
}
int dep[100005];
#define mod 1000000007
map<int,V<int> > mp;
void dfs(int x,int root){
	mp[dep[x]+a[x]].PB(x);
	for(auto u:q1[x]){
		if(mp.count(dep[x]+u.S)&&!mp[dep[x]+u.S].empty()){
			to2[u.F]=mp[dep[x]+u.S].back();
			dis[u.F]=d[x]-d[to2[u.F]];
		}else {
			q2[root].PB(MP(u.F,u.S+dep[x])),adddis[u.F]=d[x];
		}
	}
	for(auto u:v[x])dep[u]=dep[x]+add[u],d[u]=d[x]+1,dfs(u,root);
	mp[dep[x]+a[x]].pop_back();
}
int nd[100005];
map<int,set<P<int,int> > > mp2;
signed main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	int st;
	cin>>n>>st;
	q1[1].PB(MP(0,st));
	FOR(i,1,n)fa[i]=i;
	FOR(i,1,n){
		cin>>a[i]>>b[i]>>c[i]>>add[i]>>to[i];
		if(to[i]<=n)in[to[i]]++,fa[i]=to[i];
		else out[i]=1;
	}
	queue<int> q;
	FOR(i,1,n)if(!in[i])q.emplace(i);
	while(!q.empty()){
		int x=q.front();q.pop();
		if(to[x]<=n){
			v[to[x]].PB(x);
			if(--in[to[x]]==0)q.emplace(to[x]);
		}
	}
	int len=0;
	FOR(i,1,n)if(in[i]&&!vis[i]){
		int x=i;
		x=to[x];
		++len;
		node[i].PB(i);
		vis[i]=1;
		val[i]+=add[i];
		fa[i]=i;
		while(x!=i){
			val[i]+=add[x];
			vis[x]=1;fa[x]=i;
			node[i].PB(x);
			x=to[x];
		}
	}
	FOR(i,1,n){
		if(c[i]<=n)q1[c[i]].PB(MP(i,a[i]+b[i]));
		else to2[i]=n+1,dis[i]=0;
	}
	FOR(i,1,n)if(to[i]>n||in[i]){
		rt[i]=1;
		dfs(i,i);
	}
	FOR(i,1,n)if(rt[i]){
		if(to[i]>n){
			for(auto u:q2[i])to2[u.F]=n+1,dis[u.F]=0;
		}else if(get(i)==i){
			len=0;
			for(auto u:node[i])nd[++len]=u;
			FOR(j,1,len){
				s1[j]=s1[j-1]+add[nd[j]];
			}
			s2[len+1]=0;
			for(int j=len;j>=1;j--){
				s2[j]=s2[j+1]+add[nd[j]];
			}
			if(val[i]<0){
				FOR(j,1,len){
					s1[j]=-s1[j],s2[j]=-s2[j];a[nd[j]]=-a[nd[j]];add[nd[j]]=-add[nd[j]];
					for(auto &u:q2[nd[j]])u.S=-u.S;
				}
				val[i]=-val[i];
			}
			if(val[i]>0){
//				FOR(j,1,len){
//					for(auto u:q2[nd[j]]){
//						int cnt=0;
//						FOR(k,j,len){
//							if(u.S<=a[nd[k]]&&(a[nd[k]]-u.S)%val[i]==0){
//								if((a[nd[k]]-u.S)/val[i]*len+cnt<dis[u.F]||to2[u.F]==0){
//									to2[u.F]=nd[k];
//									dis[u.F]=(a[nd[k]]-u.S)/val[i]*len+cnt;
//								}
//							}
//							cnt++;u.S+=add[nd[k]];
//						}
//						rep(k,1,j){
//							if(u.S<=a[nd[k]]&&(a[nd[k]]-u.S)%val[i]==0){
//								if((a[nd[k]]-u.S)/val[i]*len+cnt<dis[u.F]||to2[u.F]==0){
//									to2[u.F]=nd[k];
//									dis[u.F]=(a[nd[k]]-u.S)/val[i]*len+cnt;
//								}
//							}
//							cnt++;u.S+=add[nd[k]];
//						}
//					}
//				}
//				continue;
				mp2.clear();
				for(int j=len;j>=1;j--){
					mp2[((a[nd[j]]+s2[j])%val[i]+val[i])%val[i]].emplace(MP(a[nd[j]]+s2[j],j));
					for(auto u:q2[nd[j]]){
						int nowval=u.S+s2[j];
						if(mp2.count((nowval%val[i]+val[i])%val[i])){
							set<P<int,int> >  &ts=mp2[(nowval%val[i]+val[i])%val[i]];
							auto iter=ts.lower_bound(MP(nowval,j));
							if(iter!=ts.end()){
								to2[u.F]=nd[(*iter).S];
								dis[u.F]=((*iter).S-j+((*iter).F-nowval)/val[i]*len);
							}
						}
					}
				}
				mp2.clear();
				FOR(j,1,len){
					mp2[((a[nd[j]]-s1[j-1])%val[i]+val[i])%val[i]].emplace(MP(a[nd[j]]-s1[j-1],j));
					for(auto u:q2[nd[j]]){
						int nowval=u.S+s2[j];
						if(mp2.count((nowval%val[i]+val[i])%val[i])){
							set<P<int,int> >  &ts=mp2[(nowval%val[i]+val[i])%val[i]];
							auto iter=ts.lower_bound(MP(nowval,0));
							if(iter!=ts.end()&&(to2[u.F]==0||((*iter).S-j+len+((*iter).F-nowval)/val[i]*len)<dis[u.F])){
								to2[u.F]=nd[(*iter).S];
								dis[u.F]=((*iter).S-j+len+((*iter).F-nowval)/val[i]*len);
							}
						}
					}
				}
			}else{
//				val[i]=1;
//				FOR(j,1,len){
//					for(auto u:q2[nd[j]]){
//						int cnt=0;
//						FOR(k,j,len){
//							if(u.S==a[nd[k]]&&(a[nd[k]]-u.S)%val[i]==0){
//								if((a[nd[k]]-u.S)/val[i]*len+cnt<dis[u.F]||to2[u.F]==0){
//									to2[u.F]=nd[k];
//									dis[u.F]=(a[nd[k]]-u.S)/val[i]*len+cnt;
//								}
//							}
//							cnt++;u.S+=add[nd[k]];
//						}
//						rep(k,1,j){
//							if(u.S==a[nd[k]]&&(a[nd[k]]-u.S)%val[i]==0){
//								if((a[nd[k]]-u.S)/val[i]*len+cnt<dis[u.F]||to2[u.F]==0){
//									to2[u.F]=nd[k];
//									dis[u.F]=(a[nd[k]]-u.S)/val[i]*len+cnt;
//								}
//							}
//							cnt++;u.S+=add[nd[k]];
//						}
//					}
//				}
//				continue;
				mp2.clear();
				for(int j=len;j>=1;j--){
					mp2[a[nd[j]]+s2[j]].emplace(MP(a[nd[j]]+s2[j],j));
					for(auto u:q2[nd[j]]){
						int nowval=u.S+s2[j];
						if(mp2.count(nowval)){
							set<P<int,int> > &ts=mp2[nowval];
							auto iter=ts.lower_bound(MP(nowval,j));
							if(iter!=ts.end()){
								to2[u.F]=nd[(*iter).S];
								dis[u.F]=(*iter).S-j;
							}
						}
					}
				}
				mp2.clear();
				FOR(j,1,len){
					mp2[a[nd[j]]-s1[j-1]].emplace(MP(a[nd[j]]-s1[j-1],j));
					for(auto u:q2[nd[j]]){
						int nowval=u.S+s2[j];
						if(mp2.count(nowval)){
							set<P<int,int> > &ts=mp2[nowval];
							auto iter=ts.lower_bound(MP(nowval,0));
							if(iter!=ts.end()&&(to2[u.F]==0||(*iter).S+len-j<dis[u.F])){
								to2[u.F]=nd[(*iter).S];
								dis[u.F]=(*iter).S-j+len;
							}
						}
					}
				}
			}
		}
	}
	FILL(vis,0);
	int sum=0,now=0;
	do{
		sum+=dis[now]+1+adddis[now];
		sum%=mod;
		now=to2[now];
		if(now==0||vis[now]){
			cout<<-1<<'\n';RE 0;
		}
		vis[now]=1;
	}while(c[now]<=n&&now<=n);
	cout<<sum<<'\n';
	RE 0;
}
accuracy: 1
time_ms: 190
memory_kb: 50608
final_rank: 3

code_snippet: #include<bits/stdc++.h>
#define rep(i,a,b) for(int i = (a); i <= (b); i++)
#define per(i,b,a) for(int i = (b); i >= (a); i--)
#define N 101000
#define ll long long
#define mod 1000000007
#define fr first
#define sc second
using namespace std;

int n, c[N], e[N];
ll x, a[N], b[N], d[N];
vector<ll> rev[N], A[N];
ll ans;

int deg[N], circ[N], dep[N], dfn[N], r[N], root[N], loc[N];
int cnt, num;
bool oncyc[N]; map<ll, bool> vis[N];
map<int, ll> acc[N];
vector<int> node, vec, son[N];
vector<vector<int> > circle;
map<ll, map<ll, vector<int> > > cycle[N];
ll s1[N], s2[N];
ll sum[N];

void topo(){
    queue<int> q;
    rep(i,1,n+1){ oncyc[i] = true; if(!deg[i]) q.push(i); }
    while(!q.empty()){
        int x = q.front(); q.pop();
        oncyc[x] = false;
        if(!(--deg[e[x]])) q.push(e[x]);
    }
}

void dfs(int x){
    node.push_back(x);
    dfn[x] = ++num;
    for(int y : rev[x]) if(!oncyc[y])
        s1[y] = s1[x] + d[y], dep[y] = dep[x]+1, dfs(y);
    r[x] = num;
}

void build(int l, int r, int f){
    son[f].clear();
    if(l > r) return;
    int it = l;
    while(it <= r){
        int x = node[vec[it]-1];
        son[f].push_back(x);
        int ti = upper_bound(vec.begin(), vec.end(), ::r[x]) - vec.begin();
        build(it+1, ti-1, x);
        it = ti;
    }
}

void getacc(int x, int pre, ll C){
    if(x != n+1 && a[x]+s1[x] == C) pre = x;
    acc[x][C-s1[x]] = pre;
    for(int y : son[x]) getacc(y, pre, C);
}

void work(int root){
    map<ll, vector<int> > C;
    s1[root] = d[root], num = 0;
    node.clear(), dfs(root);
    for(int x : node){
        sort(A[x].begin(), A[x].end());
        A[x].erase(unique(A[x].begin(), A[x].end()), A[x].end());
        C[a[x]+s1[x]].push_back(dfn[x]);
        for(ll k : A[x]) if(k != a[x]) C[k+s1[x]].push_back(dfn[x]);
        ::root[x] = root;
    }
    for(pair<ll, vector<int> > p : C){
        vec = p.sc;
        build(0, (int)vec.size()-1, 0);
        getacc(0, 0, p.fr);
    }
}

void getcirc(int x){
    circle.back().push_back(x);
    circ[x] = circle.size();
    if(!circ[e[x]]) getcirc(e[x]);
}

int main(){
    ios::sync_with_stdio(false);
    cin>>n>>x;
    rep(i,1,n){
        cin>>a[i]>>b[i]>>c[i]>>d[i]>>e[i];
        deg[e[i]]++, rev[e[i]].push_back(i);
        A[c[i]].push_back(a[i] + b[i]);
    }
    A[1].push_back(x);

    topo();
    rep(i,1,n+1) if(oncyc[i] || i == n+1){
        work(i);
        if(i == n+1 || circ[i]) continue;
        circle.push_back({}), getcirc(i);
        int id = circle.size();
        ll pre = 0;
        for(int x : circle.back()) s2[x] = pre, pre = s2[x] + d[x];
        sum[id] = pre;
        rep(i,0,(int)circle.back().size()-1){
            int x = circle.back()[i];
            ll v = a[x]-s2[x], md = abs(sum[id]), rem = md ? (v%md + md) % md : 0;
            if(md) cycle[id][rem][(v-rem)/sum[id]].push_back(i);
            else cycle[id][v][v].push_back(i);
            loc[x] = i;
        }
    }

    int cur = 1, num = 0;
    while(cur != n+1){
        assert(num <= 1000);
        if(vis[cur][x]) break;
        vis[cur][x] = true;
        if(acc[cur][x]){ 
            int nxt = acc[cur][x];
            ans += dep[cur] - dep[nxt], cur = nxt;
        } 
        else if(root[cur] == n+1){ (ans += dep[cur]) %= mod, cur = n+1; break; }
        else{
            (ans += dep[cur]) %= mod;
            int rt = root[cur]; 
            ll val = x + s1[cur] - d[rt], md = abs(sum[circ[rt]]), v = val-s2[rt];
            ll i1 = circ[rt], i2 = md ? (v%md + md) % md : v, i3 = md ? (v-i2)/sum[i1] : v;
            if(cycle[i1][i2].empty()) break;
            auto it = cycle[i1][i2].lower_bound(i3);
            if(it == cycle[i1][i2].end()) break;
            if(it->fr == i3 && loc[rt] > it->sc.back() && ++it == cycle[i1][i2].end()) break;
            int nloc = loc[rt] < it->sc.front() || it->fr == i3 ? *lower_bound(it->sc.begin(), it->sc.end(), loc[rt]) : it->sc.front();
            (ans += (it->fr - i3) * (circle[i1-1].size()) + nloc - loc[rt]) %= mod;
            cur = circle[i1-1][nloc];
        }
        x = a[cur] + b[cur], cur = c[cur];
        (ans += 1) %= mod;
    }
    cout<< (cur == n+1 ? ans : -1) <<endl;
    return 0;
}
accuracy: 1
time_ms: 270
memory_kb: 83852
final_rank: 8

code_snippet: #include<iostream>
#include<fstream>
#include<cassert>
#define rep(i,a,b) for(int i = (a); i <= (b); i++)
#define per(i,b,a) for(int i = (b); i >= (a); i--)
#define N 202200
using namespace std;

int n, x;
int a[N], b[N], c[N], d[N], e[N];

int main(){
	// freopen("data.in", "r", stdin);
	// freopen("correct.out", "w", stdout);
	ios::sync_with_stdio(false);
	cin>>n>>x;
	int mx = 0;
	rep(i,1,n){
	    cin>>a[i]>>b[i]>>c[i]>>d[i]>>e[i];
	    mx = max(mx, a[i]);
	    mx = max(mx, b[i]);
	    mx = max(mx, d[i]);
	}
	if(n >= 150){
		assert(false);
		cout<<"-1\n";
		return 0;
	}

	int ans = 0, cur = 1;
	for(int _ = 1; _ <= 2000000000 && cur != n+1; _++){
		if(x == a[cur]) x += b[cur], cur = c[cur];
		else x += d[cur], cur = e[cur];
		ans++;
		// cout<<cur<<" "<<x<<endl;
	}
	cout<< (cur == n+1 ? ans % 1000000007 : -1) <<endl;
	return 0;
}
accuracy: 0.013513513513513514
time_ms: 2930
memory_kb: 3124
final_rank: 20