#include<iostream>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<stdio.h>
using namespace std;
const int bound=40;
const double eps=1e-9,inf=1e9+9,pi=acos(-1.0);
double ans,r,h,xa,ya,za,xb,yb,zb,la,ra,mxa,mya,lb,rb,mxb,myb,lv,rv,lz,rz;
double dtheta;
double dist(double x1,double y1,double z1,double x2,double y2,double z2)
{
	return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)+(z1-z2)*(z1-z2));
}
void norm(double &theta)
{
	while(theta<-eps)
	   theta+=2*pi;
    while(theta>2*pi-eps)
       theta-=2*pi;
}
double solve(double x1,double y1,double z1,double x2,double y2,double z2)
{
	double l1,l2,l,cj,alpha,dj,theta,res;
	if(fabs(z1)<eps&&fabs(z2)<eps)
	    return dist(x1,y1,z1,x2,y2,z2);
	l1=dist(x1,y1,z1,0,0,h);
	l2=dist(x2,y2,z2,0,0,h);
	alpha=atan2(y2,x2)-atan2(y1,x1);
	norm(alpha);
	if(alpha>pi)
	   alpha=2*pi-alpha;
	l=alpha*r;
	cj=sqrt(r*r+h*h);
	theta=l/cj;
	double u1,v1,u2,v2;
	u1=0;
	v1=l1;
	u2=l2*sin(theta);
	v2=l2*cos(theta);
	res=sqrt((u1-u2)*(u1-u2)+(v1-v2)*(v1-v2));
    theta=2*pi-theta;
  	u1=0;
	v1=l1;
	u2=l2*sin(theta);
	v2=l2*cos(theta);
	res=min(res,sqrt((u1-u2)*(u1-u2)+(v1-v2)*(v1-v2)));
    return res;
}
double compute(double alpha,double beta)
{
	return solve(xa,ya,za,r*cos(alpha),r*sin(alpha),0)+solve(xb,yb,zb,r*cos(beta),r*sin(beta),0)+dist(r*cos(alpha),r*sin(alpha),0,r*cos(beta),r*sin(beta),0);
}
double compute(double alpha)
{
	double theta,vl,ch,ret=inf;
	for(theta=0;theta<2*pi;theta+=dtheta)
	{
		vl=compute(alpha,theta);
		if(ret>vl)
		{
			ret=vl;
			ch=theta;
		}
	}
	lb=max(0.,ch-dtheta);
	rb=min(2*pi,ch+dtheta);
	while(lb<rb)
	{
		mxb=0.5*(lb+rb);
		myb=mxb+eps;
		if(compute(alpha,mxb)>compute(alpha,myb))
		    lb=mxb+eps;
        else
            rb=mxb-eps;
	}
	vl=compute(alpha,0.5*(lb+rb));
	if(ret>vl)
	   ret=vl;
    return ret;
}
int main()
{
	int i,j,s,p,q,it1,it2;
	scanf("%lf%lf",&r,&h);
	scanf("%lf%lf%lf%lf%lf%lf",&xa,&ya,&za,&xb,&yb,&zb);
	ans=inf;
	if(fabs(za)>eps&&fabs(zb)>eps)
	   ans=min(ans,solve(xa,ya,za,xb,yb,zb));
	if(fabs(za)<eps&&fabs(zb)<eps)
	   ans=min(ans,dist(xa,ya,za,xb,yb,zb));
	if(fabs(zb)<eps)
	{
	    swap(xa,xb);
	    swap(ya,yb);
	    swap(za,zb);
	}
	double theta,vl,ch,mi=inf;
	dtheta=2*pi/bound;
	mi=inf;
	for(theta=0;theta<2*pi;theta+=dtheta)
	{
		vl=solve(xa,ya,za,r*cos(theta),r*sin(theta),0)+solve(xb,yb,zb,r*cos(theta),r*sin(theta),0);
		if(mi>vl)
		{
			mi=vl;
			ch=theta;
		}
		if(ans>vl)
		   ans=vl;
	}
	la=max(0.,ch-dtheta);
	ra=min(2*pi,ch+dtheta);
	while(la<ra)
	{
		mxa=0.5*(la+ra);
		mya=mxa+eps;
		lv=solve(xa,ya,za,r*cos(mxa),r*sin(mxa),0)+solve(xb,yb,zb,r*cos(mxa),r*sin(mxa),0);
        rv=solve(xa,ya,za,r*cos(mya),r*sin(mya),0)+solve(xb,yb,zb,r*cos(mya),r*sin(mya),0);
		if(lv>rv)
		   la=mxa+eps;
		else
		   ra=mxa-eps;
	}
	vl=solve(xa,ya,za,r*cos(0.5*(la+ra)),r*sin(0.5*(la+ra)),0)+solve(xb,yb,zb,r*cos(0.5*(la+ra)),r*sin(0.5*(la+ra)),0);
	if(ans>vl)
	   ans=vl;
	mi=inf;
	for(theta=0;theta<2*pi;theta+=dtheta)
	{
		vl=compute(theta);
		if(mi>vl)
        {
        	mi=vl;
        	ch=theta;
        }
        if(ans>vl)
           ans=vl;
	}
    la=max(0.,ch-dtheta);
    ra=min(2*pi,ch+dtheta);
    while(la<ra)
    {
        mxa=0.5*(la+ra);
        mya=mxa+eps;
		if(compute(mxa)>compute(mya))
    	    la=mxa+eps;
	    else
	        ra=mxa-eps;
    }
    vl=compute(0.5*(la+ra));
    if(ans>vl)
       ans=vl;
    printf("%.20f\n",ans);
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
const int bound=40;
const double eps=1e-9,inf=1e9+9,pi=acos(-1.0);
double ans,r,h,xa,ya,za,xb,yb,zb,la,ra,mxa,mya,lb,rb,mxb,myb,lv,rv,lz,rz;
double dtheta;
double dist(double x1,double y1,double z1,double x2,double y2,double z2)
{
	return sqrt(((x1-x2)*(x1-x2))+((y1-y2)*(y1-y2))+((z1-z2)*(z1-z2)));
}
void norm(double &theta)
{
	while(theta<-eps)
	{
		theta+=2*pi;
	}
	while(theta>2*pi-eps)
	theta-=2*pi;
}
void solve(double x1,double y1,double z1,double x2,double y2,double z2)
{
	double l1,l2 ,l,cj,alpha,dj,theta,res;
	if(fabs(z1)<eps&&fabs(z2)<eps)
		return dist(x1,y1,z1,x2,y2,z2);
		l1=dist(x1,y1,z1,0,0,h);
		l2=dist(x2,y2,z2,0,0,h);
		alpha=atan2(y2,x2)-atan2(y1,x1);
		norm(alpha);
	if(alpha>pi)
	alpha=2*pi-alpha;
	l=alpha*r;
	cj=sqrt(r*r+h*h);
	theta=l/cj;
	double u1,v1,u2,v2;
	u1=-;
	v1=l1;
	u2=l2*sin(theta);
	v2=l2*cos(theta);
	res=sqrt((u1-u2)*(u1-u2)+(v1-v2)*(v1-v2));
	theta=2*pi-theta;
	  	u1=0;
	v1=l1;
	u2=l2*sin(theta);
	v2=l2*cos(theta);
	res=min(res,sqrt((u1-u2)*(u1-u2)+(v1-v2)*(v1-v2)));
    return res;
	v1=l1;
	u2=l2*sin(theta);
	v2=l2*cos(theta);
	res=min(res,sqrt((u1-u2)*(u1-u2)+(v1-v2)*(v1-v2)));
	return res;
}
double compute(double alpha,double beta)
{
	return solve(xa,ya,za,r*cos(alpha),r*sin(alpha),0)+solve(xb,yb,zb,r*cos(beta),r*sin(beta),0)+dist(r*cos(alpha),r*sin(alpha),0,r*cos(beta),r*sin(beta),0);
}
double compute(double alpha)
{
	double theta,vl,ch,ret=inf;
	for(theta=0;theta<2*pi;theta+=dtheta)
	{
		vl=compute(alpha,theta);
		if(ret>vl)
		{
			ret=vl;
			ch=theta;
		}
	}
	lb=max(0.,ch-dtheta);
	rb=min(2*pi,ch+dtheta);
	while(lb<rb)
	{
		mxb=0.5*(lb+rb);
		myb=mxb+eps;
		if(compute(alpha,mxb)>compute(alpha,myb))
		lb=mxb+eps;
		else
		rb=mxb-eps;
	}
	vl=compute(alpha,0.5*(lb+rb));
	if(ret>vl)
	ret=vl;
	return ret;
}
int main()
{
	int i,j,s,p,q,it1,it2;
	scanf("%lf%lf",&r,&h);
	scanf("%lf%lf%lf%lf%lf%lf",&xa,&ya,&za,&xb,&yb,&zb);
	ans=inf;
	if(fabs(za)>eps&&fabs(zb)>eps)
	ans=min(ans,solve(xa,ya,za,xb,yb,zb));
	if(fabs(za)<eps&&fabs(zb)<eps)
	ans=min(ans,dist(xa,ya,za,xb,yb,zb));
	if(fabs(zb)<eps)
	{
		swap(xa,xb);
		swap(ya,yb);
		swap(za,zb);
	}
	double theta,vl,ch,mi=inf;
	dtheta=2*pi/bound;
	mi-inf;
	for(theta=0;theta<2*pi;theta+=dtheta)
	{
		vl=solve(xa,ya,za,r*cos(theta),r*sin(theta),0)+solve(xb,yb,zb,r*cos(theta),r*sin(theta),0);
		if(mi>vl)
		{
			mi=vl;
			ch=theta;
		}
		if(ans>vl)
		ans=vl;
	}
	la=max(0.ch-dtheta);
	ra=min(2*pi,ch+dtheta);
	while(la<ra)
	{
		mxa=0.5*(la+ra);
		mya=mxa+eps;
		lv=solve(xa,ya,za,r*cos(mxa),r*sin(mxa),0)+solve(xb,yb,zb,r*cos(mxa),r*sin(mxa),0);
		rv=solve(xa,ya,za,r*cos(mya),r*sin(mya),0)+solve(xb,yb,zb,r*cos(mya),r*sin(mya),0);
		if(lv>rv)
		la=mxa+eps;
		else
		ra=mxa-eps;

	}
	vl=solve(xa,ya,za,r*cos(0.5*(la+ra)),r*sin(0.5*(la+ra)),0)+solve(xb,yb,zb,r*cos(0.5*(la+ra)),r*sin(0.5*(la+ra)),0);
	if(ans>vl)
	ans=vl;
	mi-inf;
	for(theta=0;theta<2*pi;theta+=dtheta)
	{
		vl=compute(theta);
		if(mi>vl)
	{
		mi=vl;
		ch=theta;
	}
	        if(ans>vl)
           ans=vl;
	}
    la=max(0.,ch-dtheta);
    ra=min(2*pi,ch+dtheta);
	while(la<ra)
	{
	mxa=0.5*(la+ra);
	mya=mxa+eps;
	if(compute(mxa)>compute(mya))
	la=mxa+eps;
	else
	ra=mxa-eps;
	}
	vl=compute(0.5*(l1+ra));
	if(ans>vl)
	ans=vl;
	printf("%.20f\n",ans);
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
const int bound=40;
const double eps=1e-9,inf=1e9+9,pi=acos(-1.0);
double ans,r,h,xa,ya,za,xb,yb,zb,la,ra,mxa,mya,lb,rb,mxb,myb,lv,rv,lz,rz;
double dtheta;
double dist(double x1,double y1,double z1,double x2,double y2,double z2)
{
	return sqrt(((x1-x2)*(x1-x2))+((y1-y2)*(y1-y2))+((z1-z2)*(z1-z2)))
}
void norm(double &theta)
{
	while(theta<-eps)
	{
		theta+=2*pi;
	}
	while(theta>2*pi-eps)
	theta-=2*pi;
}
void solve(double x1,double y1,double z1,double x2,double y2,double z2)
{
	double l1,l2 ,l,cj,alpha,dj,theta,res;
	if(fabs(z1)<eps&&fabs(z2)<eps)
		return dist(x1,y1,z1,x2,y2,z2);
		l1=dist(x1,y1,z1,0,0,h);
		l2=dist(x2,y2,z2,0,0,h);
		alpha=atan2(y2,x2)-atan2(y1,x1);
		norm(alpha);
	if(alpha>pi)
	alpha=2*pi-alpha;
	l=alpha*r;
	cj=sqrt(r*r+h*h);
	theta=l/cj;
	double u1,v1,u2,v2;
	u1=-;
	v1=l1;
	u2=l2*sin(theta);
	v2=l2*cos(theta);
	res=sqrt((u1-u2)*(u1-u2)+(v1-v2)*(v1-v2));
	theta=2*pi-theta;
	  	u1=0;
	v1=l1;
	u2=l2*sin(theta);
	v2=l2*cos(theta);
	res=min(res,sqrt((u1-u2)*(u1-u2)+(v1-v2)*(v1-v2)));
    return res;
	v1=l1;
	u2=l2*sin(theta);
	v2=l2*cos(theta);
	res=min(res,sqrt((u1-u2)*(u1-u2)+(v1-v2)*(v1-v2)));
	return res;
}
double compute(double alpha,double beta)
{
	return solve(xa,ya,za,r*cos(alpha),r*sin(alpha),0)+solve(xb,yb,zb,r*cos(beta),r*sin(beta),0)+dist(r*cos(alpha),r*sin(alpha),0,r*cos(beta),r*sin(beta),0);
}
double compute(double alpha)
{
	double theta,vl,ch,ret=inf;
	for(theta=0;theta<2*pi;theta+=dtheta)
	{
		vl=compute(alpha,theta);
		if(ret>vl)
		{
			ret=vl;
			ch=theta;
		}
	}
	lb=max(0.,ch-dtheta);
	rb=min(2*pi,ch+dtheta);
	while(lb<rb)
	{
		mxb=0.5*(lb+rb);
		myb=mxb+eps;
		if(compute(alpha,mxb)>compute(alpha,myb))
		lb=mxb+eps;
		else
		rb=mxb-eps;
	}
	vl=compute(alpha,0.5*(lb+rb));
	if(ret>vl)
	ret=vl;
	return ret;
}
int main()
{
	int i,j,s,p,q,it1,it2;
	scanf("%lf%lf",&r,&h);
	scanf("%lf%lf%lf%lf%lf%lf",&xa,&ya,&za,&xb,&yb,&zb);
	ans=inf;
	if(fabs(za)>eps&&fabs(zb)>eps)
	ans=min(ans,solve(xa,ya,za,xb,yb,zb));
	if(fabs(za)<eps&&fabs(zb)<eps)
	ans=min(ans,dist(xa,ya,za,xb,yb,zb));
	if(fabs(zb)<eps)
	{
		swap(xa,xb);
		swap(ya,yb);
		swap(za,zb);
	}
	double theta,vl,ch,mi=inf;
	dtheta=2*pi/bound;
	mi-inf;
	for(theta=0;theta<2*pi;theta+=dtheta)
	{
		vl=solve(xa,ya,za,r*cos(theta),r*sin(theta),0)+solve(xb,yb,zb,r*cos(theta),r*sin(theta),0);
		if(mi>vl)
		{
			mi=vl;
			ch=theta;
		}
		if(ans>vl)
		ans=vl;
	}
	la=max(0.ch-dtheta);
	ra=min(2*pi,ch+dtheta);
	while(la<ra)
	{
		mxa=0.5*(la+ra);
		mya=mxa+eps;
		lv=solve(xa,ya,za,r*cos(mxa),r*sin(mxa),0)+solve(xb,yb,zb,r*cos(mxa),r*sin(mxa),0);
		rv=solve(xa,ya,za,r*cos(mya),r*sin(mya),0)+solve(xb,yb,zb,r*cos(mya),r*sin(mya),0);
		if(lv>rv)
		la=mxa+eps;
		else
		ra=mxa-eps;

	}
	vl=solve(xa,ya,za,r*cos(0.5*(la+ra)),r*sin(0.5*(la+ra)),0)+solve(xb,yb,zb,r*cos(0.5*(la+ra)),r*sin(0.5*(la+ra)),0);
	if(ans>vl)
	ans=vl;
	mi-inf;
	for(theta=0;theta<2*pi;theta+=dtheta)
	{
		vl=compute(theta);
		if(mi>vl)
	{
		mi=vl;
		ch=theta;
	}
	        if(ans>vl)
           ans=vl;
	}
    la=max(0.,ch-dtheta);
    ra=min(2*pi,ch+dtheta);
	while(la<ra)
	{
	mxa=0.5*(la+ra);
	mya=mxa+eps;
	if(compute(mxa)>compute(mya))
	la=mxa+eps;
	else
	ra=mxa-eps;
	}
	vl=compute(0.5*(l1+ra));
	if(ans>vl)
	ans=vl;
	printf("%.20f\n",ans);
	return 0;
}


#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <bitset>
#include <sstream>
#include <algorithm>
#include <functional>
#include <numeric>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <cassert>

using namespace std;

#define forn(i, n) for(int i = 0; i < int(n); ++i)
#define for1(i, n) for(int i = 1; i <= int(n); ++i)
#define ford(i, n) for(int i = int(n) - 1; i >= 0; --i)
#define fore(i, l, r) for(int i = int(l); i < int(r); ++i)
#define sz(v) int((v).size())
#define all(v) (v).begin(), (v).end()
#define pb push_back
#define X first
#define Y second
#define mp make_pair
#define debug(x) {cerr << #x << " = " << x << endl;}
template<typename T> inline T abs(T a){ return ((a < 0) ? -a : a); }
template<typename T> inline T sqr(T a){ return a * a; }

typedef long long li;
typedef long double ld;
typedef pair<int, int> pt;

const int INF = (int)1E9 + 7;
const ld EPS = 1E-9;
const ld PI = 3.1415926535897932384626433832795;

const int NMAX = 300000;

int n;
vector<int> a[NMAX];
vector<int> ls[NMAX];
int it[NMAX], git[NMAX];

int main() {
    #ifdef myproject
    freopen("input.txt", "rt", stdin);
    //freopen("output.txt", "wt", stdout);
    #endif

    scanf("%d", &n);

    int ans = 0;

    int sumk = 0;

    forn(i, n){
        int k, a0, x, y, m;
        scanf("%d%d%d%d%d", &k, &a0, &x, &y, &m);
//        cerr << "x = " << x << endl;

        assert(k > 0);

        a[i].pb(a0);
        forn(j, k-1){
            int na = (li(a[i].back() * 1LL * x) + y) % m;
            a[i].pb(na);
        }

        forn(j, k){
            int t = j;
            while(t+1 < sz(a[i]) && a[i][t] <= a[i][t+1])
                t++;

            ls[i].pb(t);

            j = t;
        }

        ans = max(ans, sz(ls[i]) - 1);
//        cerr << endl;

        sumk += k;
    }

    set<pt> s, qs;

    forn(i, n)
        s.insert(mp(a[i][0], i));

    printf("%d\n", ans);

    if(sumk > 200000) exit(0);

    while(!s.empty()){
//        qs.clear();

        while(!s.empty()){

            int i = s.begin()->Y;
            int v = s.begin()->X;
            s.erase(s.begin());

            printf("%d %d\n", v, i+1);

            if(it[i] != ls[i][git[i]]){
                it[i]++;
                s.insert(mp(a[i][it[i]], i));
            }else{
                if(it[i] != sz(a[i]) - 1){
                    it[i]++, git[i]++;
                    qs.insert(mp(a[i][it[i]], i));
                }
            }
        }

        s = qs;
        qs.clear();
    }

    return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cassert>
#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <deque>
#include <map>
#include <set>

using namespace std;

#define eprintf(...) fprintf(stderr, __VA_ARGS__)
#define pb push_back
#define mp make_pair
#define sz(x) ((int)(x).size())

typedef long long ll;
typedef vector<ll> vll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<bool> vb;
typedef vector<vb> vvb;
typedef pair<int, int> pii;

int main() {
  #ifdef DEBUG
  freopen("std.in", "r", stdin);
  freopen("std.out", "w", stdout);
  #endif

  int n;
  while (scanf("%d", &n) >= 1) {
    vvi cs(n);
    vector<vector<pii> > bs(n);
    int scnt = 0;

    vi tmp;
    for (int i = 0; i < n; i++) {
      int k, a, x, y, m;
      scanf("%d%d%d%d%d", &k, &a, &x, &y, &m);

      cs[i] = vi(k);
      for (int i2 = 0; i2 < k; i2++) {
        cs[i][i2] = a;
        a = (ll(a) * x + y) % m;
      }
      int pr = -1;
      int st = 0;
      for (int i2 = 0; i2 <= k; i2++) {
        if (i2 >= k || pr > cs[i][i2]) {
          bs[i].pb(mp(st, i2));
          st = i2;
        }
        if (i2 < k)
          pr = cs[i][i2];
      }
      scnt += k;
    }
    bool needOut = scnt <= 200000;

    int ans = 0;
    vector<pii> ord;
    vi ptrs(n, 0);

    for (int bptr = 0;; bptr++) {
      vector<pii> curs;
      bool cont = false;
      for (int i = 0; i < n; i++)
        if (sz(bs[i]) > bptr) {
          cont = true;
          if (needOut) {
            for (int i2 = bs[i][bptr].first; i2 < bs[i][bptr].second; i2++)
              curs.pb(mp(cs[i][i2], i));
          }
        }
      if (!cont) break;
      if (needOut) {
        sort(curs.begin(), curs.end());
        ord.insert(ord.end(), curs.begin(), curs.end());
      }

      if (bptr > 0) ans++;
    }

    printf("%d\n", ans);
    if (needOut) {
      for (int i = 0; i < sz(ord); i++)
        printf("%d %d\n", ord[i].first, ord[i].second + 1);
    }
  }
  return 0;
}


#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
#include <vector>
#include <set>
#include <map>

typedef long long LL;
typedef unsigned long long ULL;

#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))

using namespace std;

vector<int> a[5555];
int n, k[5555], x, y, m, gn[5555];
vector< pair<int, int> > pool[222222];

int main() {
//	freopen(".in", "r", stdin);
//	freopen(".out", "w", stdout);

	cin >> n;
	int ans = 0;
	int total = 0;
	for (int i = 0; i < n; i++) {
		cin >> k[i];
		a[i].resize(k[i]);
		total += k[i];
		cin >> a[i][0];
		cin >> x >> y >> m;
		for (int j = 1; j < k[i]; j++) a[i][j] = (LL(a[i][j-1]) * x + y) % m;
		gn[i] = 0;
		for (int j = 1; j < k[i]; j++) {
			pool[gn[i]].push_back(make_pair(a[i][j - 1], i + 1));
			if (a[i][j] < a[i][j - 1]) ++gn[i];
		}
		if (k[i]) {
			pool[gn[i]].push_back(make_pair(a[i][k[i] - 1], i + 1));
			++gn[i];
		}
		ans = max(ans, gn[i] - 1);
	}
	cout << ans << endl;

	if (total <= 200000) {
		for (int i = 0; i <= ans; i++) {
			sort(pool[i].begin(), pool[i].end());
			for (int j = 0; j < pool[i].size(); j++) cout << pool[i][j].first << " " << pool[i][j].second << endl;
		}
	}

	return 0;
}


#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
#include <vector>
#include <set>
#include <map>

typedef long long LL;
typedef unsigned long long ULL;

#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))

using namespace std;

vector<int> a[5555], g[5555];
int n, k[5555], x, y, m, gn[5555];
vector< pair<int, int> > pool[5555];

int main() {
//	freopen(".in", "r", stdin);
//	freopen(".out", "w", stdout);

	cin >> n;
	int ans = 0;
	int total = 0;
	for (int i = 0; i < n; i++) {
		cin >> k[i];
		a[i].resize(k[i]);
		total += k[i];
		cin >> a[i][0];
		cin >> x >> y >> m;
		for (int j = 1; j < k[i]; j++) a[i][j] = (LL(a[i][j-1]) * x + y) % m;
		gn[i] = 0;
		g[i].resize(k[i]);
		for (int j = 1; j < k[i]; j++) {
			pool[gn[i]].push_back(make_pair(a[i][j - 1], i + 1));

			if (a[i][j] < a[i][j-1]) {
				g[i][++gn[i]] = j - 1;
			}
		}
		if (k[i]) {
			pool[gn[i]].push_back(make_pair(a[i][k[i] - 1], i + 1));
			g[i][++gn[i]] = k[i] - 1;
		}
		ans = max(ans, gn[i] - 1);
	}
	cout << ans << endl;

	if (total <= 200000) {
		for (int i = 0; i <= ans; i++) {
			sort(pool[i].begin(), pool[i].end());
			for (int j = 0; j < pool[i].size(); j++) cout << pool[i][j].first << " " << pool[i][j].second << endl;
		}
	}

	return 0;
}


#include <bits/stdc++.h>

using namespace std;

template <typename T>
T inverse(T a, T m) {
  T u = 0, v = 1;
  while (a != 0) {
    T t = m / a;
    m -= t * a; swap(a, m);
    u -= t * v; swap(u, v);
  }
  assert(m == 1);
  return u;
}

template <typename T>
class Modular {
 public:
  using Type = typename decay<decltype(T::value)>::type;

  constexpr Modular() : value() {}
  template <typename U>
  Modular(const U& x) {
    value = normalize(x);
  }

  template <typename U>
  static Type normalize(const U& x) {
    Type v;
    if (-mod() <= x && x < mod()) v = static_cast<Type>(x);
    else v = static_cast<Type>(x % mod());
    if (v < 0) v += mod();
    return v;
  }

  const Type& operator()() const { return value; }
  template <typename U>
  explicit operator U() const { return static_cast<U>(value); }
  constexpr static Type mod() { return T::value; }

  Modular& operator+=(const Modular& other) { if ((value += other.value) >= mod()) value -= mod(); return *this; }
  Modular& operator-=(const Modular& other) { if ((value -= other.value) < 0) value += mod(); return *this; }
  template <typename U> Modular& operator+=(const U& other) { return *this += Modular(other); }
  template <typename U> Modular& operator-=(const U& other) { return *this -= Modular(other); }
  Modular& operator++() { return *this += 1; }
  Modular& operator--() { return *this -= 1; }
  Modular operator++(int) { Modular result(*this); *this += 1; return result; }
  Modular operator--(int) { Modular result(*this); *this -= 1; return result; }
  Modular operator-() const { return Modular(-value); }

  template <typename U = T>
  typename enable_if<is_same<typename Modular<U>::Type, int>::value, Modular>::type& operator*=(const Modular& rhs) {
#ifdef _WIN32
    uint64_t x = static_cast<int64_t>(value) * static_cast<int64_t>(rhs.value);
    uint32_t xh = static_cast<uint32_t>(x >> 32), xl = static_cast<uint32_t>(x), d, m;
    asm(
      "divl %4; \n\t"
      : "=a" (d), "=d" (m)
      : "d" (xh), "a" (xl), "r" (mod())
    );
    value = m;
#else
    value = normalize(static_cast<int64_t>(value) * static_cast<int64_t>(rhs.value));
#endif
    return *this;
  }
  template <typename U = T>
  typename enable_if<is_same<typename Modular<U>::Type, int64_t>::value, Modular>::type& operator*=(const Modular& rhs) {
    int64_t q = static_cast<int64_t>(static_cast<long double>(value) * rhs.value / mod());
    value = normalize(value * rhs.value - q * mod());
    return *this;
  }
  template <typename U = T>
  typename enable_if<!is_integral<typename Modular<U>::Type>::value, Modular>::type& operator*=(const Modular& rhs) {
    value = normalize(value * rhs.value);
    return *this;
  }

  Modular& operator/=(const Modular& other) { return *this *= Modular(inverse(other.value, mod())); }

  template <typename U>
  friend bool operator==(const Modular<U>& lhs, const Modular<U>& rhs);

  template <typename U>
  friend bool operator<(const Modular<U>& lhs, const Modular<U>& rhs);

  template <typename U>
  friend std::istream& operator>>(std::istream& stream, Modular<U>& number);

 private:
  Type value;
};

template <typename T> bool operator==(const Modular<T>& lhs, const Modular<T>& rhs) { return lhs.value == rhs.value; }
template <typename T, typename U> bool operator==(const Modular<T>& lhs, U rhs) { return lhs == Modular<T>(rhs); }
template <typename T, typename U> bool operator==(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) == rhs; }

template <typename T> bool operator!=(const Modular<T>& lhs, const Modular<T>& rhs) { return !(lhs == rhs); }
template <typename T, typename U> bool operator!=(const Modular<T>& lhs, U rhs) { return !(lhs == rhs); }
template <typename T, typename U> bool operator!=(U lhs, const Modular<T>& rhs) { return !(lhs == rhs); }

template <typename T> bool operator<(const Modular<T>& lhs, const Modular<T>& rhs) { return lhs.value < rhs.value; }

template <typename T> Modular<T> operator+(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) += rhs; }
template <typename T, typename U> Modular<T> operator+(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) += rhs; }
template <typename T, typename U> Modular<T> operator+(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) += rhs; }

template <typename T> Modular<T> operator-(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) -= rhs; }
template <typename T, typename U> Modular<T> operator-(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) -= rhs; }
template <typename T, typename U> Modular<T> operator-(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) -= rhs; }

template <typename T> Modular<T> operator*(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) *= rhs; }
template <typename T, typename U> Modular<T> operator*(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) *= rhs; }
template <typename T, typename U> Modular<T> operator*(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) *= rhs; }

template <typename T> Modular<T> operator/(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) /= rhs; }
template <typename T, typename U> Modular<T> operator/(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) /= rhs; }
template <typename T, typename U> Modular<T> operator/(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) /= rhs; }

template<typename T, typename U>
Modular<T> power(const Modular<T>& a, const U& b) {
  assert(b >= 0);
  Modular<T> x = a, res = 1;
  U p = b;
  while (p > 0) {
    if (p & 1) res *= x;
    x *= x;
    p >>= 1;
  }
  return res;
}

template <typename T>
string to_string(const Modular<T>& number) {
  return to_string(number());
}

template <typename T>
std::ostream& operator<<(std::ostream& stream, const Modular<T>& number) {
  return stream << number();
}

template <typename T>
std::istream& operator>>(std::istream& stream, Modular<T>& number) {
  typename common_type<typename Modular<T>::Type, int64_t>::type x;
  stream >> x;
  number.value = Modular<T>::normalize(x);
  return stream;
}

/*
using ModType = int;

struct VarMod { static ModType value; };
ModType VarMod::value;
ModType& md = VarMod::value;
using Mint = Modular<VarMod>;
*/

constexpr int md = (int) 1e9 + 7;
using Mint = Modular<std::integral_constant<decay<decltype(md)>::type, md>>;

int n, w;

int main() {
  cin >> n >> w;
  vector<Mint> fact(n + 1);
  vector<Mint> inv_fact(n + 1);
  fact[0] = inv_fact[0] = 1;
  for(int i = 1; i <= n; i++) {
    fact[i] = fact[i - 1] * i;
    inv_fact[i] = 1 / fact[i];
  }
  auto choose_in = [&](int N, int M) {
    if(M > N) return Mint(0);
    return fact[N] * inv_fact[N - M];
  };
  Mint ret = 0;
  for(int s = w + 1; s <= w + n; s++) {
    int x = s - w;
    int sp = s - 2 * x;
    assert(sp > 0);
    if(sp >= 2) {
      Mint tot = choose_in(n, x) * n;
      Mint sub = choose_in(n, x) * (n - x);
      Mint mu = power(Mint(n), sp - 2);
      ret += (tot * tot - sub * sub) * mu;
    } else if(sp == 1) {
      assert(s == 2 * w - 1);
      Mint sub = choose_in(n - 1, x) * choose_in(n - 1, x);
      Mint tot = choose_in(n, x) * choose_in(n, x);
      ret += (tot - sub) * n;
    } else {
      int sz = -sp;
      Mint mu = choose_in(n, sz);
      Mint tot = choose_in(n - sz, w) * choose_in(n - sz, w);
      Mint sub = choose_in(n - sz, w) * choose_in(n - sz - 1, w);
      ret += (tot - sub) * mu;
    }
  }
  cout << ret;
  return 0;
}


#pragma comment(linker, "/STACK:65777216")

#include <algorithm>
#include <iostream>
#include <string>
#include<sstream>
#include<string.h>
#include <cstdio>
#include <vector>
#include <bitset>
#include <cmath>
#include <queue>
#include<stack>
#include <set>
#include <map>
#include<ctime>

using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> pii;
typedef pair<double,double> pdd;
typedef unsigned long long ull;

#define FOR(i,a,b) for (int i(a); i < (b); i++)
#define REP(i,n) FOR(i,0,n)
#define SORT(v) sort((v).begin(),(v).end())
#define UN(v) sort((v).begin(),(v).end()),v.erase(unique(v.begin(),v.end()),v.end())
#define CL(a,b) memset(a,b,sizeof(a))
#define pb push_back

const int mod = 1000000007;

int qp(ll c,int st){
	ll r = 1;
	while(st){
		if(st&1) r*=c,r%=mod;
		c*=c,c%=mod;
		st>>=1;
	}
	return r;
}

ll f[1111111];
ll inv[1111111];

int c(int n,int m){
	if(n<0 || m<0 || m>n) return 0;
	ll res = f[n];
	res *= inv[m];res%=mod;
	res *= inv[n-m];res%=mod;
	return res;
}

int main(){
#ifdef LocalHost
    freopen("input.txt","r",stdin);
//  freopen("output.txt","w",stdout);
#endif

	f[0]=1;
	FOR(i,1,1111111) f[i]=f[i-1]*i%mod;
	REP(i,1111111) inv[i]=qp(f[i],mod-2);

	int k,w;
	cin>>k>>w;

	int ans = 0;
	for(int len=w+1;;len++){
		//cout<<len<<endl;
		// case 1
		int lenw = 2*w - len;
		if(lenw>0){
			int lenx = w - lenw;
			//cout<<"case1 "<<lenw<<' '<<lenx<<endl;
			if(lenw==1){
				REP(same,lenx+1){
					ll t = c(k,same);
					t *= c(k-same,lenx-same); t%=mod;
					t *= c(k-lenx,lenx-same); t%=mod;
					t *= f[lenx]; t%=mod;
					t *= f[lenx]; t%=mod;
					t *= (lenx+lenx-same); t%=mod;
					ans += t; ans %= mod;
				}
			}else{
				ll t = 1;
				t *= c(k,lenx); t%=mod;
				t *= c(k,lenx); t%=mod;
				t *= f[lenx]; t%=mod;
				t *= f[lenx]; t%=mod;
				t *= qp(k,lenw-2); t%=mod;
				t *= ((k*ll(k)-ll(k-lenx)*(k-lenx))%mod); t%=mod;
				ans += t; ans %= mod;
			}
		}else{
			int lenw = len - w - w;
			if(lenw > k) break;
			ll t = c(k,lenw);
			t *= c(k-lenw,w); t%=mod;
			t *= c(k-lenw,w); t%=mod;
			t *= f[w]; t%=mod;
			t *= f[w]; t%=mod;
			t *= f[lenw]; t%=mod;
			ans += t; ans %= mod;

			t = c(k,lenw);
			t *= c(k-lenw,1); t%=mod;
			t *= c(k-lenw-1,1); t%=mod;
			t *= c(k-lenw-2,w-1); t%=mod;
			t *= c(k-lenw-2,w-1); t%=mod;
			t *= f[w-1]; t%=mod;
			t *= f[w-1]; t%=mod;
			t *= f[lenw]; t%=mod;
			ans -= t; if(ans<0) ans += mod;

		}

	}
	cout<<ans<<endl;

#ifdef LocalHost
	cout<<endl<<endl<<"TIME: "<<clock()<<endl;
#endif
    return 0;
}


#include <bits/stdc++.h>
#define MP make_pair
#define PB push_back
#define int long long
#define st first
#define nd second
#define rd third
#define FOR(i, a, b) for(int i =(a); i <=(b); ++i)
#define RE(i, n) FOR(i, 1, n)
#define FORD(i, a, b) for(int i = (a); i >= (b); --i)
#define REP(i, n) for(int i = 0;i <(n); ++i)
#define VAR(v, i) __typeof(i) v=(i)
#define FORE(i, c) for(VAR(i, (c).begin()); i != (c).end(); ++i)
#define ALL(x) (x).begin(), (x).end()
#define SZ(x) ((int)(x).size())
#define __builtin_ctz __builtin_ctzll
#define __builtin_clz __builtin_clzll
#define __builtin_popcount __builtin_popcountll
using namespace std;
template<typename TH> void _dbg(const char* sdbg, TH h) { cerr<<sdbg<<"="<<h<<"\n"; }
template<typename TH, typename... TA> void _dbg(const char* sdbg, TH h, TA... t) {
  while(*sdbg != ',') { cerr<<*sdbg++; } cerr<<"="<<h<<","; _dbg(sdbg+1, t...);
}
#define LOCAL
#ifdef LOCAL
#define debug(...) _dbg(#__VA_ARGS__, __VA_ARGS__)
#define debugv(x) {{cerr <<#x <<" = "; FORE(itt, (x)) cerr <<*itt <<", "; cerr <<"\n"; }}
#else
#define debug(...) (__VA_ARGS__)
#define debugv(x)
#define cerr if(0)cout
#endif
#define next ____next
#define prev ____prev
#define left ____left
#define hash ____hash
typedef long long ll;
typedef long double LD;
typedef pair<int, int> PII;
typedef pair<ll, ll> PLL;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<ll> VLL;
typedef vector<pair<int, int> > VPII;
typedef vector<pair<ll, ll> > VPLL;

template<class C> void mini(C&a4, C b4){a4=min(a4, b4); }
template<class C> void maxi(C&a4, C b4){a4=max(a4, b4); }
template<class T1, class T2>
ostream& operator<< (ostream &out, pair<T1, T2> pair) { return out << "(" << pair.first << ", " << pair.second << ")";}
template<class A, class B, class C> struct Triple { A first; B second; C third;
  bool operator<(const Triple& t) const { if (st != t.st) return st < t.st; if (nd != t.nd) return nd < t.nd; return rd < t.rd; } };
template<class T> void ResizeVec(T&, vector<int>) {}
template<class T> void ResizeVec(vector<T>& vec, vector<int> sz) {
  vec.resize(sz[0]); sz.erase(sz.begin()); if (sz.empty()) { return; }
  for (T& v : vec) { ResizeVec(v, sz); }
}
typedef Triple<int, int, int> TIII;
template<class A, class B, class C>
ostream& operator<< (ostream &out, Triple<A, B, C> t) { return out << "(" << t.st << ", " << t.nd << ", " << t.rd << ")"; }
template<class T> ostream& operator<<(ostream& out, vector<T> vec) { out<<"("; for (auto& v: vec) out<<v<<", "; return out<<")"; }
template<class T> ostream& operator<<(ostream& out, set<T> vec) { out<<"("; for (auto& v: vec) out<<v<<", "; return out<<")"; }
template<class L, class R> ostream& operator<<(ostream& out, map<L, R> vec) { out<<"("; for (auto& v: vec) out<<v<<", "; return out<<")"; }

const int P = 1e9 + 7;
const int N = 3e6;
int fac[N];
int inv_fac[N];
int k_pow[N];
int spow(int a, int b) {
	int r = 1;
	while (b) {
		if (b % 2) {
			r = a * r % P;
		}
		a = a * a % P;
		b /= 2;
	}
	return r;
}
int Inv(int a) {
	return spow(a, P - 2);
}
int DownFac(int a, int b) {
	if (a < b) { return 0; }
	return fac[a] * inv_fac[a - b] % P;
}
int Go(int k, int w, int min_len) { // ile jest stringow dla ktorych wynik jest <=w
	// nie ma zadnego dlugosci w+1
	int max_len = k + 1 + w;
	int res = 0;
	FOR (len, min_len, max_len) {
		if (len >= 2 * w) {
			int c = len - 2 * w;
			int here = DownFac(k, c);
			int side = DownFac(k - c, w);
			int lol = here * side % P * side % P;
			debug(k, w, len, lol);
			res = (res + lol) % P;
		} else {
			int c = 2 * w - len;
			int side = DownFac(k, w - c);
			int mid = Pow(k, c);
			int lol = side * side % P * mid;
			debug(k, w, len, lol);
			res = (res + lol) % P;
		}
	}
	debug(res);
	return res;
}
int32_t main() {

  ios_base::sync_with_stdio(0);
  cout << fixed << setprecision(10);
  cerr << fixed << setprecision(10);
  cin.tie(0);
  int w, k;
  cin>>k>>w;
  fac[0] = 1;
  k_pow[0] = 1;
  RE (i, N - 1) {
  	fac[i] = fac[i - 1] * i % P;
  	k_pow[i] = k_pow[i - 1] * k % P;
  }
  inv_fac[N - 1] = Inv(fac[N - 1]);
  FORD (i, N - 2, 0) {
  	inv_fac[i] = inv_fac[i + 1] * (i + 1) % P;
  }
  cout<<(Go(k, w, w) - Go(k, w - 1, w) + P) % P<<endl;

  return 0;
 }


#include <bits/stdc++.h>
#define MP make_pair
#define PB push_back
#define int long long
#define st first
#define nd second
#define rd third
#define FOR(i, a, b) for(int i =(a); i <=(b); ++i)
#define RE(i, n) FOR(i, 1, n)
#define FORD(i, a, b) for(int i = (a); i >= (b); --i)
#define REP(i, n) for(int i = 0;i <(n); ++i)
#define VAR(v, i) __typeof(i) v=(i)
#define FORE(i, c) for(VAR(i, (c).begin()); i != (c).end(); ++i)
#define ALL(x) (x).begin(), (x).end()
#define SZ(x) ((int)(x).size())
#define __builtin_ctz __builtin_ctzll
#define __builtin_clz __builtin_clzll
#define __builtin_popcount __builtin_popcountll
using namespace std;
template<typename TH> void _dbg(const char* sdbg, TH h) { cerr<<sdbg<<"="<<h<<"\n"; }
template<typename TH, typename... TA> void _dbg(const char* sdbg, TH h, TA... t) {
  while(*sdbg != ',') { cerr<<*sdbg++; } cerr<<"="<<h<<","; _dbg(sdbg+1, t...);
}
#define LOCAL
#ifdef LOCAL
#define debug(...) _dbg(#__VA_ARGS__, __VA_ARGS__)
#define debugv(x) {{cerr <<#x <<" = "; FORE(itt, (x)) cerr <<*itt <<", "; cerr <<"\n"; }}
#else
#define debug(...) (__VA_ARGS__)
#define debugv(x)
#define cerr if(0)cout
#endif
#define next ____next
#define prev ____prev
#define left ____left
#define hash ____hash
typedef long long ll;
typedef long double LD;
typedef pair<int, int> PII;
typedef pair<ll, ll> PLL;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<ll> VLL;
typedef vector<pair<int, int> > VPII;
typedef vector<pair<ll, ll> > VPLL;

template<class C> void mini(C&a4, C b4){a4=min(a4, b4); }
template<class C> void maxi(C&a4, C b4){a4=max(a4, b4); }
template<class T1, class T2>
ostream& operator<< (ostream &out, pair<T1, T2> pair) { return out << "(" << pair.first << ", " << pair.second << ")";}
template<class A, class B, class C> struct Triple { A first; B second; C third;
  bool operator<(const Triple& t) const { if (st != t.st) return st < t.st; if (nd != t.nd) return nd < t.nd; return rd < t.rd; } };
template<class T> void ResizeVec(T&, vector<int>) {}
template<class T> void ResizeVec(vector<T>& vec, vector<int> sz) {
  vec.resize(sz[0]); sz.erase(sz.begin()); if (sz.empty()) { return; }
  for (T& v : vec) { ResizeVec(v, sz); }
}
typedef Triple<int, int, int> TIII;
template<class A, class B, class C>
ostream& operator<< (ostream &out, Triple<A, B, C> t) { return out << "(" << t.st << ", " << t.nd << ", " << t.rd << ")"; }
template<class T> ostream& operator<<(ostream& out, vector<T> vec) { out<<"("; for (auto& v: vec) out<<v<<", "; return out<<")"; }
template<class T> ostream& operator<<(ostream& out, set<T> vec) { out<<"("; for (auto& v: vec) out<<v<<", "; return out<<")"; }
template<class L, class R> ostream& operator<<(ostream& out, map<L, R> vec) { out<<"("; for (auto& v: vec) out<<v<<", "; return out<<")"; }

const int P = 1e9 + 7;
const int N = 3e6;
int fac[N];
int inv_fac[N];
int k_pow[N];
int spow(int a, int b) {
	int r = 1;
	while (b) {
		if (b % 2) {
			r = a * r % P;
		}
		a = a * a % P;
		b /= 2;
	}
	return r;
}
int Inv(int a) {
	return spow(a, P - 2);
}
int DownFac(int a, int b) {
	if (a < b) { return 0; }
	return fac[a] * inv_fac[a - b] % P;
}
int Go(int k, int w, int min_len) { // ile jest stringow dla ktorych wynik jest <=w
	// nie ma zadnego dlugosci w+1
	int max_len = k + 1 + w;
	int res = 0;
	FOR (len, min_len, max_len) {
		if (len >= 2 * w) {
			int c = len - 2 * w;
			int here = DownFac(k, c);
			int side = DownFac(k - c, w);
			int lol = here * side % P * side % P;
			debug(k, w, len, lol);
			res = (res + lol) % P;
		} else {
			int c = 2 * w - len;
			int side = DownFac(k, w - c);
			int mid = spow(k, c);
			int lol = side * side % P * mid;
			debug(k, w, len, lol);
			res = (res + lol) % P;
		}
	}
	debug(res);
	return res;
}
int32_t main() {

  ios_base::sync_with_stdio(0);
  cout << fixed << setprecision(10);
  cerr << fixed << setprecision(10);
  cin.tie(0);
  int w, k;
  cin>>k>>w;
  fac[0] = 1;
  k_pow[0] = 1;
  RE (i, N - 1) {
  	fac[i] = fac[i - 1] * i % P;
  	k_pow[i] = k_pow[i - 1] * k % P;
  }
  inv_fac[N - 1] = Inv(fac[N - 1]);
  FORD (i, N - 2, 0) {
  	inv_fac[i] = inv_fac[i + 1] * (i + 1) % P;
  }
  cout<<(Go(k, w, w) - Go(k, w - 1, w) + P) % P<<endl;

  return 0;;;
 }


#include <iostream>
//#include <algorithm>
#include <math.h>
using namespace std;

long double pi = atan((long double)1)*4;

class Point
{
public:
	long double x;
	long double y;
	Point(long double xi, long double yi)
	{
		x=xi;
		y=yi;
	};
	Point()
	{
	};
};

class Segment
{
public:
	Point p1;
	Point p2;
	Segment(Point p1i, Point p2i)
	{
		p1.x=p1i.x;
		p1.y=p1i.y;
		p2.x=p2i.x;
		p2.y=p2i.y;
	};
	long double length()
	{
		return sqrt( (p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y) );
	}
};

void pos_circle(Point p, long double v, long double t, Point* final_p)
{
	long double R = sqrt((long double)(p.x*p.x+p.y*p.y));
	long double time_360 = 2*pi*R/v;
	long double ini_angle = atan2((long double)p.y,(long double)p.x);
	long double final_angle = t*2*pi/time_360 + ini_angle;

	final_p->x=cos(final_angle)*R;
	final_p->y=sin(final_angle)*R;
}

long double distance_to_segment (Point p, Segment seg)
{
	Segment a(seg.p1, p);
	Segment b(seg.p2, p);
	Segment* max;
	Segment* min;
	if(a.length() > b.length())
	{
		max = &a;
		min = &b;
	}
	else
	{
		max = &b;
		min = &a;
	}

	if(seg.length()==0 || min->length()==0)
		return min->length();

	if ((min->length() * min->length() + seg.length() * seg.length() - max->length() * max->length()) / (2*min->length()*seg.length()) < 0)
		return min->length();

	long double s = (a.length() + b.length() + seg.length())/2;
	return 2 * sqrt( s * ( s - a.length() ) * (s - b.length() ) * (s - seg.length() ) ) / seg.length();

}

void tangent_points_to_circle(Point center, long double R, Point p, Point* p1, Point* p2)
{
	Segment s(center, p);
	if( s.length() <= R)
	{
		p1->x = p.x;
		p1->y = p.y;
		p2->x = p.x;
		p2->y = p.y;
	}
	else
	{
		long double ini_angle = atan2(p.y - center.y , p.x - center.x);
		long double final_angle1 = ini_angle + acos(R/s.length()) ;
		long double final_angle2 = ini_angle - acos(R/s.length()) ;
		p1->x=cos(final_angle1)*R + center.x;
		p1->y=sin(final_angle1)*R + center.y;
		p2->x=cos(final_angle2)*R + center.x;
		p2->y=sin(final_angle2)*R + center.y;
	}
}

long double angle_between(Point p1, Point p2)
{
	long double result = atan2(p1.y, p1.x) - atan2(p2.y, p2.x);

	if (result > 2*pi)
		result -= 2*pi;
	if (result < -2*pi)
		result += 2*pi;
	if (result > pi )
	{
		result -= 2*pi;
	}
	if (result < -pi )
	{
		result += 2*pi;
	}
	return abs(result);
}

int main()
{
	cout.precision(20);
	int xp,yp,vp, xs,ys,V, R;

	cin >> xp;
	cin >> yp;
	cin >> vp;
	cin >> xs;
	cin >> ys;
	cin >> V;
	cin >> R;

	Point ini_perse(xp,yp);
	Point perse(0,0);
	Point center(0,0);
	Point ship(xs,ys);
	long double time = 0.0000000000000000;
	long double time_ship = 0;
	long double range_min,range_max;

	if(ini_perse.x == ship.x && ini_perse.y == ship.y)
	{
		cout << time << endl;
		return 0;
	}

	time = 100;

	while(true)
	{
		pos_circle(ini_perse,vp,time,&perse);
		Segment s(perse, ship);
		long double distance = distance_to_segment(center, s);
		if(distance >= R)
			time_ship =  s.length()/V;
		else
		{
			Point ship_tang1, ship_tang2, perse_tang1, perse_tang2;
			tangent_points_to_circle(center, R, ship, &ship_tang1, &ship_tang2);
			tangent_points_to_circle(center, R, perse, &perse_tang1, &perse_tang2);
			Segment route1_ship(ship, ship_tang1);
			Segment route2_ship(ship, ship_tang2);
			Segment route1_perse(perse_tang2, perse);
			Segment route2_perse(perse_tang1, perse);

			long double distance1 = route1_ship.length() + angle_between(ship_tang1, perse_tang2)*R + route1_perse.length();
			long double distance2 = route2_ship.length() + angle_between(ship_tang2, perse_tang1)*R + route2_perse.length();
			time_ship = min(distance1, distance2)/V;
		}
		if( time_ship < time )
			break;
		else
			time *= 2;
	}

	range_max = time;
	range_min = 0 ;

	while(true)
	{
		time = (range_max + range_min ) / 2;
		//time = 1.319045245;
		pos_circle(ini_perse,vp,time,&perse);
		Segment s(perse, ship);
		long double distance = distance_to_segment(center, s);
		if(distance >= R)
			time_ship =  s.length()/V;
		else
		{
			Point ship_tang1, ship_tang2, perse_tang1, perse_tang2;
			tangent_points_to_circle(center, R, ship, &ship_tang1, &ship_tang2);
			tangent_points_to_circle(center, R, perse, &perse_tang1, &perse_tang2);
			Segment route1_ship(ship, ship_tang1);
			Segment route2_ship(ship, ship_tang2);
			Segment route1_perse(perse_tang2, perse);
			Segment route2_perse(perse_tang1, perse);

			long double distance1 = route1_ship.length() + angle_between(ship_tang1, perse_tang2)*R + route1_perse.length();
			long double distance2 = route2_ship.length() + angle_between(ship_tang2, perse_tang1)*R + route2_perse.length();

			time_ship = min(distance1,distance2)/V;
		}

		if(abs(time-time_ship)<0.0000000001)
			break;

		if(time_ship < time)
			range_max = time;
		else
			range_min = time;
	}
	cout << time << endl;
	return 0;
}


#include<cstdio>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<algorithm>
using namespace std;
double xp,yp,vp,x,y,v,r,R;
const double pi=3.1415926535897926;
double dis(double x,double y,double xt,double yt)
{
	return pow(pow(x-xt,2)+pow(y-yt,2),0.5);
}
bool ok(double time)
{
	double xt,yt,a,cos1,sin1;
	a=vp*time/R;
	cos1=xp/R;sin1=yp/R;
	xt=R*(cos1*cos(a)-sin(a)*sin1);
	yt=R*(sin1*cos(a)+cos1*sin(a));
	double d=abs(x*yt-xt*y)/pow(pow(y-yt,2)+pow(xt-x,2),0.5);
	bool cd;
	if (x==xt) cd=x<=-r||x>=r;
	else
	{
		double k=(y-yt)/(x-xt),bb=(x*yt-y*xt)/(x-xt);
		cd=false;
		if (k*k*bb*bb-(bb*bb-r*r)*(1+k*k)<=0) cd=true;
		double aa=1+k*k,cc=bb*bb-r*r;
		bb=2*k*bb;
		double tt1=(aa*x*x+bb*x+cc),tt2=(aa*xt*xt+bb*xt+cc);
		if (tt1*tt2>=0&&(-bb/2/aa<=min(x,xt)||-bb/2/aa>=max(x,xt))) cd=true;
	}
	if (d>=r||cd) return (dis(x,y,xt,yt)/v)<=time;
	double d1=dis(0,0,x,y),d2=dis(0,0,xt,yt),d3,d4,sumd;
	d3=pow(d1*d1-r*r,0.5);d4=pow(d2*d2-r*r,0.5);
	sumd=d3+d4;
	double t1=atan(y/x);
	if (x<0) t1+=pi;
	double t2=atan(yt/xt);
	if (xt<0) t2+=pi;
	double b;
	b=t1-t2;
	b+=4*pi;
	while (b>2*pi) b-=2*pi;
	if (b>pi) b=2*pi-b;
	double cc,dd;
	cc=asin(d3/dis(0,0,x,y));
	dd=asin(d4/dis(0,0,xt,yt));
	b-=cc+dd;
	sumd+=b*r;
	return sumd/v<=time;
}
int main()
{
   // freopen("data.in","r",stdin);
	//freopen("data.out","w",stdout);
	scanf("%lf%lf%lf%lf%lf%lf%lf",&xp,&yp,&vp,&x,&y,&v,&r);
	R=pow(xp*xp+yp*yp,0.5);
	double l,r;
	l=0;r=1e99;
	while (abs(l-r)>1e-15)
	{
		double mid=(l+r)/2;
		if (ok(mid)) r=mid-1e-15;
		else l=mid+1e-15;
	}
	printf("%.9lf",l);
	return 0;
}


#include <iostream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <cstdio>
#include <ctime>
using namespace std;
#define START clock_t _clock = clock();
#define END cerr << endl << "time: " << (clock() - _clock) / LD(CLOCKS_PER_SEC) << endl;
typedef long double LD;
typedef long long LL;

const LD pi = acos(-1.0);
const LD eps = 1e-9;
LD xp, yp, vp, xs, ys, v, r;

LD sqr(LD x)
{
    return x * x;
}

LD mmax(LD x, LD y)
{
    return x > y ? x : y;
}

LD mmin(LD x, LD y)
{
    return x < y ? x : y;
}

LD distance(LD x1, LD y1, LD x2, LD y2)
{
    return sqrt( LD(sqr(x1 - x2) + sqr(y1 - y2)) );
}

LD cathetus(LD hyp, LD cath)
{
    return sqrt(sqr(hyp) - sqr(cath));
}

// в начале планета имеет угол atan(yp / xp)
// возвращает момент времени >= tm, когда планет будет иметь угол angle
LD ptime(LD angle, LD tm)
{
    // радиус обращения планеты
    LD R = distance(xp, yp, 0, 0);
    // начальный угол планеты
    LD pangle = atan2(yp, xp);
    if (pangle < 0)
        pangle += 2 * pi;
    // время достижения планетой угла angle
    LD res = ( angle + (angle < pangle ? 2 * pi : 0) - pangle) / vp * R;
    // время обращения планеты
    LD ptm = 2 * pi * R / vp;

    res += floor((res - ptm) / ptm) * ptm;
    while (res < tm)
        res += ptm;

    return res;
}

LD time(LD angle)
{
    // радиус обращения планеты
    LD R = distance(xp, yp, 0, 0);
    // место встречи планеты и корабля (D)
    LD xd = R * cos(angle);
    LD yd = R * sin(angle);

/*------------- придётся ли огибать звезду -----------------------------------*/
    bool intersect = false;

    // коэффициенты уравнения прямой
    LD A = ys - yd;
    LD B = xd - xs;
    LD C = xs * yd - xd * ys;
    // квадрат расстояния от центра окружности (0,0) до прямой SD
    LD sdist = sqr(C) / (sqr(A) + sqr(B));

    // если прямая и окружность пересекаются
    if (sdist <= sqr(r))
    {
        // коэффициенты квадратного уравнения персечения
        LD a = 1 + sqr(A / B);
        LD b = 2 * A * C / sqr(B);
        LD c = sqr(C / B) - sqr(r);
        LD discr = sqr(b) - 4 * a * c;
        // точки пересечения:
        LD x1 = (-b - sqrt(discr)) / (2 * a);
        LD x2 = (-b + sqrt(discr)) / (2 * a);
        // если отрезок и окружность пересекаются, то придётся огибать звезду
        if (min(xs, xd) <= x1 && x1 <= max(xs, xd) || min(xs, xd) <= x2 && x2 <= max(xs, xd))
            intersect = true;
    }
/*-----------------------------------------------------------------------------*/

    LD dist; // длина маршрута из точки S в точку D
    if (intersect)
    {
        LD a = distance(xs, ys, 0, 0);
        LD b = cathetus(a, r);  // расстояние до дуги

        LD c = distance(xd, yd, 0, 0);
        LD d = cathetus(c, r);  // расстояние после дуги

        LD e = distance(xs, ys, xd, yd);
        LD alpha = acos( (sqr(c) + sqr(a) - sqr(e)) / (2 * c * a) );
        LD alpha1 = atan2(d, r);
        LD alpha2 = atan2(b, r);

        LD phi = alpha - alpha1 - alpha2;
        LD arc = phi * r; // длина дуги

        // всё расстояние
        dist = b + arc + d;
    }
    else
        dist = distance(xs, ys, xd, yd);

    // время прибытия корабля в точку на орбите с углом angle:
    LD tm = dist / v;

    // время следующего прибытия планеты в эту же точку
    return ptime(angle, tm);
}

LD getminangle(LD left, LD right, LD step)
{
    LD  minangle = left,
        mintime = time(minangle);
    for (LD angle = left + step; angle < right; angle += step)
    {
        LD tm = time(angle);
        if (tm < mintime)
            mintime = tm,
            minangle = angle;
    }
    return minangle;
}

main()
{
    cin >> xp >> yp >> vp >> xs >> ys >> v >> r;

    const LD step = 0.00005;
    const LD u = 0.0008;
    const LD left = 0.0;
    const LD right = 2 * pi;

    // находим угол при котором значение функции time минимально на всём интервале углов
    LD a = getminangle(left, right, step);
    // находим минимальное время в окрестности угла a
    LD res = time(getminangle(mmax(left, a - u), mmin(right, a + u), eps));

    cout.setf(ios::fixed); cout.precision(8);

    cout << res << endl;
}
/*

Идея решения:

Возьмём произвольную точку на окружности (D), по которой обращается планета.
Определим расстояние от места старта корабля (S до этой точки.
Если на пути встетится окружность звезды, то придётся делать огибание,
в таком случае расстояние увеличится.

Теперь определим время (tm) прохождени корабля от S до D.

Результатом f(alpha) будет минимальное время, большее либо равное tm, при котором планета будет в точке D.

Ответом будет min(f(alpha)), которое можно найти тернарным поиском. alpha задаёт однозначное положение точки D.

*/


#include <iostream>
//#include <algorithm>
#include <math.h>
using namespace std;

long double pi = atan((long double)1)*4;

class Point
{
public:
	long double x;
	long double y;
	Point(long double xi, long double yi)
	{
		x=xi;
		y=yi;
	};
	Point()
	{
	};
};

class Segment
{
public:
	Point p1;
	Point p2;
	Segment(Point p1i, Point p2i)
	{
		p1.x=p1i.x;
		p1.y=p1i.y;
		p2.x=p2i.x;
		p2.y=p2i.y;
	};
	long double length()
	{
		return sqrt( (p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y) );
	}
};

void pos_circle(Point p, long double v, long double t, Point* final_p)
{
	long double R = sqrt((long double)(p.x*p.x+p.y*p.y));
	long double time_360 = 2*pi*R/v;
	long double ini_angle = atan2((long double)p.y,(long double)p.x);
	long double final_angle = t*2*pi/time_360 + ini_angle;

	final_p->x=cos(final_angle)*R;
	final_p->y=sin(final_angle)*R;
}

long double distance_to_segment (Point p, Segment seg)
{
	Segment a(seg.p1, p);
	Segment b(seg.p2, p);
	Segment* max;
	Segment* min;
	if(a.length() > b.length())
	{
		max = &a;
		min = &b;
	}
	else
	{
		max = &b;
		min = &a;
	}

	if(seg.length()==0 || min->length()==0)
		return min->length();

	if ((min->length() * min->length() + seg.length() * seg.length() - max->length() * max->length()) / (2*min->length()*seg.length()) < 0)
		return min->length();

	long double s = (a.length() + b.length() + seg.length())/2;
	return 2 * sqrt( s * ( s - a.length() ) * (s - b.length() ) * (s - seg.length() ) ) / seg.length();

}

void tangent_points_to_circle(Point center, long double R, Point p, Point* p1, Point* p2)
{
	Segment s(center, p);
	if( s.length() <= R)
		return;
	else
	{
		long double ini_angle = atan2(p.y - center.y , p.x - center.x);
		long double final_angle1 = ini_angle + acos(R/s.length()) ;
		long double final_angle2 = ini_angle - acos(R/s.length()) ;
		p1->x=cos(final_angle1)*R + center.x;
		p1->y=sin(final_angle1)*R + center.y;
		p2->x=cos(final_angle2)*R + center.x;
		p2->y=sin(final_angle2)*R + center.y;
	}
}

int main()
{
	cout.precision(20);
	int xp,yp,vp, xs,ys,V, R;

	cin >> xp;
	cin >> yp;
	cin >> vp;
	cin >> xs;
	cin >> ys;
	cin >> V;
	cin >> R;

	Point ini_perse(xp,yp);
	Point perse(0,0);
	Point center(0,0);
	Point ship(xs,ys);
	long double time = 0.0000000000000000;
	long double time_ship = 0;
	long double range_min,range_max;

	if(ini_perse.x == ship.x && ini_perse.y == ship.y)
	{
		cout << time << endl;
		return 0;
	}

	time = 100;

	while(true)
	{
		pos_circle(ini_perse,vp,time,&perse);
		Segment s(perse, ship);
		long double distance = distance_to_segment(center, s);
		if(distance >= R)
			time_ship =  s.length()/V;
		else
		{
			Point ship_tang1, ship_tang2, perse_tang1, perse_tang2;
			tangent_points_to_circle(center, R, ship, &ship_tang1, &ship_tang2);
			tangent_points_to_circle(center, R, perse, &perse_tang1, &perse_tang2);
			Segment route1_ship(ship, ship_tang1);
			Segment route2_ship(ship, ship_tang2);
			Segment route1_perse(perse_tang2, perse);
			Segment route2_perse(perse_tang1, perse);

			long double distance1 = route1_ship.length() + abs(atan2(ship_tang1.y, ship_tang1.x) - atan2(perse_tang2.y, perse_tang2.x))*2*R + route1_perse.length();
			long double distance2 = route2_ship.length() + abs(atan2(ship_tang2.y, ship_tang2.x) - atan2(perse_tang1.y, perse_tang1.x))*2*R + route2_perse.length();
			time_ship = min(distance1, distance2)/V;
		}
		if( time_ship < time )
			break;
		else
			time *= 2;
	}

	range_max = time;
	range_min = 0 ;

	while(true)
	{
		time = (range_max + range_min ) / 2;
		//time = 2.047618248;
		pos_circle(ini_perse,vp,time,&perse);
		Segment s(perse, ship);
		long double distance = distance_to_segment(center, s);
		if(distance >= R)
			time_ship =  s.length()/V;
		else
		{
			Point ship_tang1, ship_tang2, perse_tang1, perse_tang2;
			tangent_points_to_circle(center, R, ship, &ship_tang1, &ship_tang2);
			tangent_points_to_circle(center, R, perse, &perse_tang1, &perse_tang2);
			Segment route1_ship(ship, ship_tang1);
			Segment route2_ship(ship, ship_tang2);
			Segment route1_perse(perse_tang2, perse);
			Segment route2_perse(perse_tang1, perse);

			long double distance1 = route1_ship.length() + abs(atan2(ship_tang1.y, ship_tang1.x) - atan2(perse_tang2.y, perse_tang2.x))*R + route1_perse.length();
			long double distance2 = route2_ship.length() + abs(atan2(ship_tang2.y, ship_tang2.x) - atan2(perse_tang1.y, perse_tang1.x))*R + route2_perse.length();
			time_ship = min(distance1,distance2)/V;
		}

		if(abs(time-time_ship)<0.0000000001)
			break;

		if(time_ship < time)
			range_max = time;
		else
			range_min = time;
	}
	cout << time << endl;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
#define mp make_pair
#define PI pair<ll,ll>
#define poly vector<PI>
#define mem(a) memset((a),0,sizeof(a))
#define For(i,l,r) for(int i=(int)(l);i<=(int)(r);i++)
#define Rep(i,r,l) for(int i=(int)(r);i>=(int)(l);i--)
#define pb push_back
#define fi first
#define se second
inline char gc(){
    static char buf[100000],*p1=buf,*p2=buf;
    return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++;
}
#define gc getchar
inline ll read(){
	ll x = 0; char ch = gc(); bool positive = 1;
	for (; !isdigit(ch); ch = gc())	if (ch == '-')	positive = 0;
	for (; isdigit(ch); ch = gc())	x = x * 10 + ch - '0';
	return positive ? x : -x;
}
inline void write(ll a){
    if(a<0){
    	a=-a; putchar('-');
	}
    if(a>=10)write(a/10);
    putchar('0'+a%10);
}
inline void writeln(ll a){write(a); puts("");}
inline void wri(ll a){write(a); putchar(' ');}
inline ull rnd(){
	return ((ull)rand()<<30^rand())<<4|rand()%4;
}
void GG(){
	puts("-1"); exit(0);
}
ll a[4],b[4],ta,tb;
int aa[2],bb[2];
poly dq,ans;
ll g;
void pp(ll *a){
	For(i,0,3)wri(a[i]); puts("");
}
void bao(ll &a,ll &b){
	if(a==b)return;
	dq.pb(mp(a,b));
	a=2*b-a;
}
void pr(poly &a){
	for(auto i:a){
		ans.pb(i);
	}
}
poly bao(ll *a){
	while(a[3]-a[0]>g){
		ll t=(a[3]-a[0]+3)/4;
		if(a[1]>=a[0]+t&&a[1]<=a[3]-t){
			if(a[1]-a[0]<a[3]-a[1])bao(a[0],a[1]); else bao(a[3],a[1]);
		}else if(a[2]>=a[0]+t&&a[2]<=a[3]-t){
			if(a[2]-a[0]<a[3]-a[2])bao(a[0],a[2]); else bao(a[3],a[2]);
		}else{
			if(a[1]-a[0]<a[3]-a[2]){
				if(a[3]-a[2]<a[2]-a[0]){bao(a[1],a[2]); bao(a[1],a[3]);}
				else{bao(a[1],a[0]); bao(a[1],a[2]);}
			}else{
				if(a[3]-a[1]<a[1]-a[0]){bao(a[2],a[3]); bao(a[2],a[1]);}
				else{bao(a[2],a[1]); bao(a[2],a[0]);}
			}
		}
		sort(a,a+4);
	}
	poly jj=dq;
	dq.clear();
	return jj;
}
void chu(poly &x){
	reverse(x.begin(),x.end());
	for(auto &i:x){
		i.fi=2*i.se-i.fi;
	}
}
void solve(ll *a,ll d,int id){
	d/=2;  if(!d)return;
	while(a[3]-a[0]<d){
		bao(a[2],a[0]); bao(a[1],a[3]);
		sort(a,a+4);
	}
	while(1){
		while(a[3]-a[0]<=d){
			d-=a[3]-a[0];
			For(i,0,2)bao(a[i],a[3]);
			sort(a,a+4);
			For(i,0,2)bao(a[i],a[3]);
			sort(a,a+4);
		}
		if(a[3]-a[0]==g)break;
		bao(a[0],a[1]); bao(a[3],a[2]);//pp(a); exit(0);
		sort(a,a+4);
	}
	if(id)chu(dq);
	pr(dq);
	dq.clear();
}
int main(){
	For(i,0,3)aa[(a[i]=read())&1]++;
	sort(a,a+4);
	For(i,0,3)bb[(b[i]=read())&1]++;
	sort(b,b+4);
	For(i,1,3)ta=__gcd(ta,a[i]-a[0]);
	For(i,1,3)tb=__gcd(tb,b[i]-b[0]);
	if(ta!=tb)GG();
	if(aa[0]!=bb[0])GG();
	g=ta;
	poly A=bao(a);
	pr(A);
	poly B=bao(b);
	sort(a,a+4); sort(b,b+4);

	if((b[0]-a[0])/g%2)For(j,0,2)if((a[j]/g+a[3]/g)%2){
		bao(a[j],a[3]);
	}
	pr(dq); dq.clear();
	sort(a,a+4);
	if(b[0]>=a[0])solve(a,b[0]-a[0],0); else solve(b,a[0]-b[0],1);
	chu(B);
	pr(B);
	cout<<ans.size()<<endl;
	for(auto i:ans){
		wri(i.fi); writeln(i.se);
	}
}


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

using ll = long long;

pair<pair<ll, ll>, ll> sig(vector<ll> a){
	ll r1 = a[1] - a[0];
	ll r2 = a[2] - a[1];
	ll r3 = a[3] - a[2];
	ll g = __gcd(__gcd(r1, r2), r3);
	if(g == 0){
		return {{0, a[0]}, 0};
	}
	ll f = ((a[0] % g) + g) % g;

	ll res = 0;
	for(int j = 0; j < 4; j++) res += ((a[j] - f) / g) & 1;
	return {{g, f}, res};
}

bool between(ll x, ll a, ll b){
	return (a <= x && x <= b) || (b <= x && x <= a);
}

int main(){
	ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);

	function<void(vector<ll>&, vector<pair<ll, ll> >&)> solve;
	solve = [&](vector<ll>& v, vector<pair<ll, ll> >& moves) {
		auto make = [&](int i, int j) {
			moves.push_back({v[i], v[j]});
			v[i] = 2 * v[j] - v[i];
		};
		while(true){
			sort(v.begin(), v.end());
			if(v[0] == v[3]){
				// nothing
			} else if(v[0] + 1 < v[3]){
				ll th = (v[3] - v[0]) / 8;
				// get to a, a+1 only
				if(v[3] - v[2] > th && v[1] - v[0] > th){
					if(v[1] > 0){
						make(3, 1); continue;
					}
					if(v[2] < 0){
						make(0, 2); continue;
					}
				}
				for(int j = 1; j <= 2; j++){
					if(v[j] - v[0] > th && v[3] - v[j] > th){
						if(v[3] - v[j] > v[j] - v[0]){
							make(0, j); goto done;
						} else {
							make(3, j); goto done;
						}
					}
				}
				if(v[1] - v[0] > th){
					make(3, 1); continue;
				}
				if(v[3] - v[2] > th){
					make(0, 2); continue;
				}
				if(v[2] - v[1] > th){
					if(v[1] - v[0] > v[3] - v[2]){
						make(2, 1); make(2, 0); continue;
					} else {
						make(1, 2); make(1, 3); continue;
					}
				}
				assert(false);
			} else if(v[0] == 0){
				// nothing
			} else if(v[3] == 0 && v[0] < 0){
				for(int i = 0; i < 3; i++){
					make(i, 3);
				}
				continue;
			} else if(v[1] != v[2]) {
				if(v[0] > 0 && v[0] == v[2]){
					make(3, 0); sort(v.begin(), v.end());
				}
				if(v[3] < 0 && v[1] == v[3]){
					make(0, 3); sort(v.begin(), v.end());
				}
				while(v[3] < 0){
					make(1, 3); sort(v.begin(), v.end());
				}
				while(v[0] > 0){
					make(2, 0); sort(v.begin(), v.end());
				}
			} else {
				if(v[0] == v[2] && v[3] > 0) make(3, 0);
				if(v[1] == v[3] && v[0] < 0) make(0, 3);
				sort(v.begin(), v.end());
				bool flag = false;
				if(v[0] != v[2]) flag = true;

				if(flag) reverse(v.begin(), v.end());
				while(!between(0, v[0], v[3])){
					make(1, 3); sort(v.begin(), v.end()); if(flag) reverse(v.begin(), v.end());
				}
				while(abs(v[0] - v[3]) > 1){
					make(3, 2); sort(v.begin(), v.end()); if(flag) reverse(v.begin(), v.end());
					while(!between(0, v[0], v[3])){
						make(0, 3);
						make(1, 3);
						make(2, 3);
						flag = !flag;
						assert(moves.size() <= 1000)
					}
					assert(moves.size() <= 1000)
				}
				continue;
			}
			break;
			done:;
			continue;
		}
	};

	vector<vector<ll> > a(2, vector<ll>(4));
	for(int x = 0; x < 2; x++){
		for(int i = 0; i < 4; i++){
			cin >> a[x][i];
		}
		sort(a[x].begin(), a[x].end());
	}
	if(sig(a[0]) != sig(a[1])){
		cout << -1 << '\n';
		return 0;
	}
	ll g = sig(a[0]).first.first;
	ll f = sig(a[0]).first.second;
	if(g == 0){
		cout << 0 << '\n';
		return 0;
	}
	for(int j = 0; j < 2; j++){
		for(ll& x : a[j]){
			x = (x - f) / g;
		}
	}
	vector<vector<pair<ll, ll> > > moves(2);
	solve(a[0], moves[0]);
	solve(a[1], moves[1]);

	for(pair<ll, ll>& x : moves[1]){
		x.first = x.second * 2 - x.first;
	}
	reverse(moves[1].begin(), moves[1].end());
	moves[0].insert(moves[0].end(), moves[1].begin(), moves[1].end());

	vector<pair<ll, ll> > real_moves;
	for(pair<ll, ll> x : moves[0]){
		if(x.first == x.second) continue;
		real_moves.push_back(x);
	}
	cout << real_moves.size() << '\n';
	for(pair<ll, ll> x : real_moves){
		if(x.first == x.second) continue;
		cout << x.first * g + f << ' ' << x.second * g + f << '\n';
	}
}


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

using ll = long long;

pair<pair<ll, ll>, ll> sig(vector<ll> a){
	ll r1 = a[1] - a[0];
	ll r2 = a[2] - a[1];
	ll r3 = a[3] - a[2];
	ll g = __gcd(__gcd(r1, r2), r3);
	if(g == 0){
		return {{0, a[0]}, 0};
	}
	ll f = ((a[0] % g) + g) % g;

	ll res = 0;
	for(int j = 0; j < 4; j++) res += ((a[j] - f) / g) & 1;
	return {{g, f}, res};
}

bool between(ll x, ll a, ll b){
	return (a <= x && x <= b) || (b <= x && x <= a);
}

int main(){
	ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);

	function<void(vector<ll>&, vector<pair<ll, ll> >&)> solve;
	solve = [&](vector<ll>& v, vector<pair<ll, ll> >& moves) {
		auto make = [&](int i, int j) {
			moves.push_back({v[i], v[j]});
			v[i] = 2 * v[j] - v[i];
		};
		while(true){
			sort(v.begin(), v.end());
			if(v[0] == v[3]){
				// nothing
			} else if(v[0] + 1 < v[3]){
				ll th = (v[3] - v[0]) / 8;
				// get to a, a+1 only
				if(v[3] - v[2] > th && v[1] - v[0] > th){
					if(v[1] > 0){
						make(3, 1); continue;
					}
					if(v[2] < 0){
						make(0, 2); continue;
					}
				}
				for(int j = 1; j <= 2; j++){
					if(v[j] - v[0] > th && v[3] - v[j] > th){
						if(v[3] - v[j] > v[j] - v[0]){
							make(0, j); goto done;
						} else {
							make(3, j); goto done;
						}
					}
				}
				if(v[1] - v[0] > th){
					make(3, 1); continue;
				}
				if(v[3] - v[2] > th){
					make(0, 2); continue;
				}
				if(v[2] - v[1] > th){
					if(v[1] - v[0] > v[3] - v[2]){
						make(2, 1); make(2, 0); continue;
					} else {
						make(1, 2); make(1, 3); continue;
					}
				}
				assert(false);
			} else if(v[0] == 0){
				// nothing
			} else if(v[3] == 0 && v[0] < 0){
				for(int i = 0; i < 3; i++){
					make(i, 3);
				}
				continue;
			} else if(v[1] != v[2]) {
				if(v[0] > 0 && v[0] == v[2]){
					make(3, 0); sort(v.begin(), v.end());
				}
				if(v[3] < 0 && v[1] == v[3]){
					make(0, 3); sort(v.begin(), v.end());
				}
				while(v[3] < 0){
					make(1, 3); sort(v.begin(), v.end());
				}
				while(v[0] > 0){
					make(2, 0); sort(v.begin(), v.end());
				}
			} else {
				// no clue waht to do;
				if(moves.size() >= 1000) assert(false);
				continue;
			} else assert(false);
			break;
			done:;
			continue;
		}
	};

	vector<vector<ll> > a(2, vector<ll>(4));
	for(int x = 0; x < 2; x++){
		for(int i = 0; i < 4; i++){
			cin >> a[x][i];
		}
		sort(a[x].begin(), a[x].end());
	}
	if(sig(a[0]) != sig(a[1])){
		cout << -1 << '\n';
		return 0;
	}
	ll g = sig(a[0]).first.first;
	ll f = sig(a[0]).first.second;
	if(g == 0){
		cout << 0 << '\n';
		return 0;
	}
	for(int j = 0; j < 2; j++){
		for(ll& x : a[j]){
			x = (x - f) / g;
		}
	}
	vector<vector<pair<ll, ll> > > moves(2);
	solve(a[0], moves[0]);
	solve(a[1], moves[1]);

	for(pair<ll, ll>& x : moves[1]){
		x.first = x.second * 2 - x.first;
	}
	reverse(moves[1].begin(), moves[1].end());
	moves[0].insert(moves[0].end(), moves[1].begin(), moves[1].end());

	vector<pair<ll, ll> > real_moves;
	for(pair<ll, ll> x : moves[0]){
		if(x.first == x.second) continue;
		real_moves.push_back(x);
	}
	cout << real_moves.size() << '\n';
	for(pair<ll, ll> x : real_moves){
		if(x.first == x.second) continue;
		cout << x.first * g + f << ' ' << x.second * g + f << '\n';
	}
}


// Note: spoiler below (don't read until you've solved the problem)
//
// [I didn't read the editorial or see any failed test cases]
//
// I figured out the necessary and sufficient condition int the contest, but only until about 5 minutes
// remaining I get the key idea (reduce the gap, while ensure that it's not too far from the home -
// instead of reduce the maximum distance to the home - int the end they're the same, but
// the idea allows me to consider less cases)
//
// Before that I only roughly know which cases are "hard" and how to solve them (which cover all cases
// int the solution)
//
// I hope the number of steps int this solution is in o(log^2 (n)) (?)
//
// Not tested very carefully, but at least it passes the sample test cases.
//
#ifndef LOCAL
#define NDEBUG
#endif
#include<cassert>
#include<iostream>
#include<array>
#include<numeric>
#include<tuple>
#include<algorithm>
#include<cstdlib>

using i4=std::array<int64_t,4>;

struct step{
	int64_t pos,cen;
};

struct prop_t{
	int64_t gcd;
	int64_t home;
	int64_t cnthome; // number of values % (2*gcd) == home. the rest has value % (2*gcd) == (home+gcd).
	// between 1 and 3. !=0 when gcd !=0.

	auto tup()const{
		return std::make_tuple(gcd,home,cnthome);
	}
};

template<class Fn>
struct comparator_from_key_t{
	Fn f;
	bool operator()(auto a,auto b)const{
		return f(a)<f(b);
	};
};

template<class Fn>
auto comparator_from_key(Fn f){
	return comparator_from_key_t<Fn>{std::move(f)};
}

std::vector<step> movehome(i4& p,prop_t pp){
	// cnthome stones at home + (4-cnthome) stones at home+gcd
	auto const [gcd,home,cnthome]=pp;
	assert(gcd!=0);

	std::vector<step> out;

	auto flip=[&](int posi,int ceni){
		out.push_back({p[posi],p[ceni]});
		p[posi]=2*p[ceni]-p[posi];
		std::sort(begin(p),end(p));
	};
	std::sort(begin(p),end(p));

	while(p[3]<home){
		assert(p[1]<p[3]);
		flip(0,3);
	}

	while(p[0]>home){
		assert(p[2]>p[0]);
		flip(3,0);
	}

	while(p[3]>home+3*gcd or p[0]<home-3*gcd){
		assert(p[0]<=home and home<=p[3]);
		auto const oldgap=p[3]-p[0];

		for(;;){
			auto mid=(p[0]+p[3])/2;
			auto i=std::min_element(1+begin(p),end(p)-1,[mid](auto a,auto b){
					return std::abs(a-mid)<std::abs(b-mid);
					})-begin(p);

			if(std::abs(p[i]-mid)>(p[3]-p[0])/4){
				if(p[1]<mid){
					if(p[2]<mid){
						// * * * --- *
						flip(0,2);
					}else{
						// * * --- * *
						if(p[1]-p[0]>p[3]-p[2]){
							out.push_back({p[2],p[1]});
							out.push_back({2*p[1]-p[2],p[0]});
							p[2]-=(p[1]-p[0])*2;
							assert(std::is_sorted(begin(p),end(p)));
						}else{
							out.push_back({p[1],p[2]});
							out.push_back({2*p[2]-p[1],p[3]});
							p[1]+=(p[3]-p[2])*2;
							assert(std::is_sorted(begin(p),end(p)));
						}
					}
				}else{
					// * --- * * *
					flip(3,1);
				}
			}else{
				if(p[i]<mid) flip(0,i);
				else flip(3,i);
				break;
			}
		}

		auto const gap=p[3]-p[0];
		assert(gap<oldgap and gap>=oldgap/4 /* estimation. Any fraction int [0,1] is ok */);

		while(p[3]<home){
			for(int i=0;i<3;++i){
				out.push_back({p[i],p[3]});
				p[i]=2*p[3]-p[i];
			}
			std::sort(begin(p),end(p));
		}
		while(p[0]>home){
			for(int i=1;i<4;++i){
				out.push_back({p[i],p[0]});
				p[i]=2*p[0]-p[i];
			}
			std::sort(begin(p),end(p));
		}

		assert(p[3]-p[0]==gap);
	}

	for(;;){
		if(p[0]<home){
			auto i=std::min_element(begin(p)+1,end(p),comparator_from_key([&](auto x){
					return std::abs((home+gcd/2)-(x*2-p[0]));
					}))-begin(p);
			flip(0,i);
		}else if (p[3]>home+gcd){
			auto i=std::min_element(begin(p),end(p)-1,comparator_from_key([&](auto x){
					return std::abs((home+gcd/2)-(x*2-p[3]));
					}))-begin(p);
			flip(3,i);
		}else break;
	}

	assert(p[0]==home and p[3]==home+gcd);
	return out;
}

prop_t prop(i4 p){
	std::sort(begin(p),end(p));

	prop_t out{0,0,0};
	auto& gcd=out.gcd;

	for(int i=1;i<3;++i)
		gcd=std::gcd(gcd,p[i]-p[0]);
	if(gcd!=0){
		out.home=p[0]%gcd;
		if(out.home<0)out.home+=gcd;

		out.cnthome=(int)std::count_if(begin(p),end(p),[gcd,p0=p[0]](int x){return (x-p0)%(2*gcd)==0;});
		assert(out.cnthome>0 and out.cnthome<4);
	}else{
		out.home=p[0];
	}

	return out;
}

int main(){
	std::ios::sync_with_stdio(0);std::cin.tie(0);
	i4 a,b;
	for(auto& x:a)std::cin>>x;
	for(auto& x:b)std::cin>>x;

	std::sort(begin(a),end(a));
	std::sort(begin(b),end(b));
	if(a==b){
		std::cout<<"0\n";
		return 0;
	}

	prop_t pa=prop(a);
	prop_t pb=prop(b);
	if(pa.tup()!=pb.tup()){
		std::cout<<"-1\n";
		return 0;
	}

	assert(pa.gcd!=0);
	auto out1=movehome(a,pa);
	auto out2=movehome(b,pa);

	assert(a==b);

	std::reverse(begin(out2),end(out2)); // when will Range v3 be merged to C++ ...
	for(auto [pos,cen]:out1) std::cout<<pos<<' '<<cen<<'\n';
	for(auto [pos,cen]:out2) std::cout<<pos<<' '<<cen<<'\n';
}


// dolphinigle
// 15 JUL 2012

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <vector>
#include <deque>
#include <list>
#include <stack>
#include <queue>
#include <ctime>
#include <cmath>
#include <cassert>
#include <cstring>
#include <set>
#include <map>

#define FORN(X,Y) for (int X = 0; X < (Y); ++X)
#define REP(X,Y,Z) for (int X = (Y); X < (Z); ++X)
#define FORIT(X,Y) for (typeof((Y).begin()) X = (Y).begin(); X != (Y).end(); ++X)
#define SZ(X) ((int)(X).size())
#define A first
#define B second
#define MX(X,Y) X = max((X),(Y))
#define MN(X,Y) X = min((X),(Y))
#define MP make_pair
#define PB push_back

using namespace std;

typedef long long ll;
typedef double db;
typedef vector<int> vint;

typedef pair<db, db> Point;
typedef pair<Point, Point> Segment;
typedef vector<Point> Polygon;

ll Gcd(ll a, ll b) {
  if (a < 0LL || b < 0LL) return Gcd(abs(a), abs(b));
  if (b == 0) return a;
  return Gcd(b, a % b);
}

ll Power(ll num, ll ex, ll modu) {
  if (ex == 0LL) return 1LL % modu;
  if (ex % 2 == 0LL) {
    ll base = Power(num, ex/2, modu);
    return (base * base) % modu;
  }
  return (Power(num, ex-1, modu) * num) % modu;
}

ll Inverse(ll num, ll modu) {
  return Power(num, modu-2LL, modu);
}

void Answer(ll a) {
  cout << a << endl;
  exit(0);
}

int cnt[1 << 26];

int main() {
  return 0;
}


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

#define fore(i, a, b) for (int i = int(a); i < int(b); i++)
#define forn(i, n) fore(i, 0, n)
#define efor(i, a, b) for (int i = int(b) - 1; i >= int(a); i--)
#define nfor(i, n) efor(i, 0, n)

#define mp(x, y) make_pair(x, y)
#define pb(x) push_back(x)
#define all(v) (v).begin(), (v).end()
#define sz(v) int((v).size())
#define x first
#define y second

template <typename T> T abs(const T& x) { return x < 0 ? -x : x; }
template <typename T> T sqr(const T& x) { return x * x; }

template<typename X, typename Y> ostream& operator<< (ostream& out, const pair<X, Y>& p) {
	return out << "(" << p.x << ", " << p.y << ")";
}

template<typename X> ostream& operator<< (ostream& out, const vector<X>& a) {
	out << "[ ";
	forn(i, sz(a)) {
		if (i) out << ", ";
		out << a[i];
	}
	return out << " ]";
}

typedef unsigned long long li;
typedef long double ld;
typedef pair<int,int> pt;

ld gett() {
	return clock() / ld(CLOCKS_PER_SEC);
}

#ifdef TJS

#endif

const int N = int(1e6) + 5;
char s[N];
int q[N];
int n, m;

bool read() {
	if (scanf("%s", s) != 1)
		return false;
	assert(cin >> m);
	forn(i, m) {
		static char buf[30];
		assert(scanf("%s", buf) == 1);
		int l = strlen(buf);
		q[i] = 0;
		forn(j, l)
			q[i] |= (1 << int(buf[j] - 'a'));
	}
	return true;
}

int pos[26];
map <int, int> cnt;

void solve() {
	forn(i, 26)
		pos[i] = -1;
	cnt.clear();
	int n = strlen(s);
	s[n++] = '#';
	forn(i, n) {
		vector <pt> vv;
		forn(j, 26)
			if (pos[j] != -1)
				vv.pb(mp(pos[j], j));

		sort(all(vv));
		reverse(all(vv));
		int cmask = 0;
		for (auto p: vv) {
			if (p.y == int(s[i] - 'a'))
				break;
			cmask |= (1 << p.y);
			cnt[cmask]++;
		}

		if (i < n - 1)
			pos[int(s[i] - 'a')] = i;
	}

	forn(i, m)
		printf("%d\n", cnt[q[i]]);
}

int main() {
#ifdef TJS
	assert(freopen("input.txt", "r", stdin));
#else
#endif
	cerr << fixed << setprecision(5);
	cout << fixed << setprecision(10);
	while (read()) {
#ifdef TJS
		ld st = gett();
#endif
		solve();
#ifdef TJS
		cerr << " == TIME : " << gett() - st << " == " << endl;
#endif
	}
	return 0;
}


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

#define fore(i, a, b) for (int i = int(a); i < int(b); i++)
#define forn(i, n) fore(i, 0, n)
#define efor(i, a, b) for (int i = int(b) - 1; i >= int(a); i--)
#define nfor(i, n) efor(i, 0, n)

#define mp(x, y) make_pair(x, y)
#define pb(x) push_back(x)
#define all(v) (v).begin(), (v).end()
#define sz(v) int((v).size())
#define x first
#define y second

template <typename T> T abs(const T& x) { return x < 0 ? -x : x; }
template <typename T> T sqr(const T& x) { return x * x; }

template<typename X, typename Y> ostream& operator<< (ostream& out, const pair<X, Y>& p) {
	return out << "(" << p.x << ", " << p.y << ")";
}

template<typename X> ostream& operator<< (ostream& out, const vector<X>& a) {
	out << "[ ";
	forn(i, sz(a)) {
		if (i) out << ", ";
		out << a[i];
	}
	return out << " ]";
}

typedef unsigned long long li;
typedef long double ld;
typedef pair<int,int> pt;

ld gett() {
	return clock() / ld(CLOCKS_PER_SEC);
}

#ifdef TJS

#endif

const int N = int(1e6) + 5;
char s[N];
int q[N];
int n, m;

bool read() {
	if (scanf("%s", s) != 1)
		return false;
	assert(cin >> m);
	forn(i, m) {
		static char buf[30];
		assert(scanf("%s", buf) == 1);
		int l = strlen(buf);
		q[i] = 0;
		forn(j, l)
			q[i] |= (1 << int(buf[j] - 'a'));
	}
	return true;
}

int pos[26];
unordered_map <int, int> cnt;

void solve() {
	forn(i, 26)
		pos[i] = -1;
	cnt.clear();
	int n = strlen(s);
	s[n++] = '#';
	forn(i, n) {
		vector <pt> vv;
		forn(j, 26)
			if (pos[j] != -1)
				vv.pb(mp(pos[j], j));

		sort(all(vv));
		reverse(all(vv));
		int cmask = 0;
		for (auto p: vv) {
			if (p.y == int(s[i] - 'a'))
				break;
			cmask |= (1 << p.y);
			cnt[cmask]++;
		}

		if (i < n - 1)
			pos[int(s[i] - 'a')] = i;
	}

	forn(i, m)
		printf("%d\n", cnt[q[i]]);
}

int main() {
#ifdef TJS
	assert(freopen("input.txt", "r", stdin));
#else
#endif
	cerr << fixed << setprecision(5);
	cout << fixed << setprecision(10);
	while (read()) {
#ifdef TJS
		ld st = gett();
#endif
		solve();
#ifdef TJS
		cerr << " == TIME : " << gett() - st << " == " << endl;
#endif
	}
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 10;
char s[maxn];
int nxt[26][maxn];
int n;
vector<int> v;
int get_next(int id, int mask) {
	int res = n;
	for(int i = 0; i < 26; i++)
		if((mask & (1 << i)) == 0) res = min(res, nxt[i][id]);
	return res;
}
unordered_map<int, int> mp;
int main() {
	scanf("%s", s);
	n = strlen(s);
	for(int i = 0; i < 26; i++) nxt[i][n] = n;
	for(int i = n - 1; i >= 0; i--) {
		for(int j = 0; j < 26; j++) nxt[j][i] = nxt[j][i + 1];
		nxt[s[i] - 'a'][i] = i;
	}
	for(int i = 0; i < n; i++) {
		int prv = (i == 0) ? 30 : s[i - 1] - 'a';
		int cur_idx = i;
		int cur_mask = (1 << (s[i] - 'a'));
		while(cur_idx < n) {
			if((cur_mask & (1 << prv)) == 0) mp[cur_mask]++;
			else break;
			cur_idx = get_next(cur_idx, cur_mask);
			if(cur_idx < n) cur_mask |= (1 << (s[cur_idx] - 'a'));
		}
	}
	int q;
	scanf("%d", &q);
	while(q--) {
		char t[30];
		scanf("%s", t);
		int mask = 0;
		for(int i = 0; i < strlen(t); i++) mask |= (1 << (t[i] - 'a'));
		printf("%d\n", mp[mask]);
	}
	return 0;
}


#define _CRT_SECURE_NO_WARNINGS
#define pb push_back

#include <iostream>
#include <climits>
#include <algorithm>
#include <iomanip>
#include <cmath>
#include <vector>
#include <map>
#include <string>
#include <stack>
#include <set>
#include <cstdio>
#include <cctype>
#include <queue>
#include <bitset>
#include <functional>
#include <cassert>
#include <unordered_map>
#include <unordered_set>

using namespace std;

#define int long long

typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
typedef long double ld;
typedef double db;

const ll N = 1e6 + 20;
const ll INF = INT_MAX;

/*int p = 3571;
int mod = 2147483647;

namespace op {
	void add(int &a, int val) {
		a = ((a * p % mod + val) % mod + mod) % mod;
	}
	int calc(int a, int b) {
		return ((a % mod + b % mod) % mod + mod) % mod;
	}
	int mul(int a, int b) {
		return (((a % mod) * (b % mod)) % mod + mod) % mod;
	}
	int pow(int a, int n) {
		if (n == 0) return 1LL;
		if (n & 1) {
			int b = pow(a, n ^ 1) % mod;
			return mul(a, b);
		}
		else {
			int b = pow(a, n >> 1) % mod;
			return mul(b, b);
		}
	}
};
using namespace op;

struct hsh {
	string vec;
	vector<int> seg;
	int n;
	hsh(string a) {
		n = a.size();
		vec = a;
		seg.resize(a.size() + 1);
		for (int i = 0; i < a.size(); ++i) {
			seg[i + 1] = seg[i];
			add(seg[i + 1], a[i]);
		}
	}
	int seg_hash(int l, int r) {
		return calc(seg[r], (-1) * seg[l - 1] * pow(p, r - l + 1));
	}
};*/

vector<int> g[N];
int used[N], ct[N];

vector<int> comp[2];

int id;
void dfs(ll v) {
	comp[id].push_back(v);
	used[v] = 1;

	for (ll to : g[v]) {
		if (!used[to])
			dfs(to);
	}
}

void clear(int n) {
	for (ll i = 0; i < n; ++i) {
		g[i].clear();
		used[i] = ct[i] = 0;
	}
}

signed main() {
#ifndef ONLINE_JUDGE
	freopen("input.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);
#else
#endif
	ios_base::sync_with_stdio(0);
	cin.tie(0); cout.tie(0);

	int t;
	cin >> t;
	while (t--) {
		int n, m, a, b;
		cin >> n >> m >> a >> b;
		a--; b--;
		for (int i = 0; i < m; ++i) {
			int x, y;
			cin >> x >> y;
			--x; --y;
			g[x].push_back(y);
			g[y].push_back(x);
		}

		id = 0; used[b] = 1;
		dfs(a);
		for (auto &x : comp[0]) {
			used[x] = 0;
		}
		used[b] = 0;
		id = 1; used[a] = 1;
		dfs(b);
		for (auto &x : comp[0])
			ct[x]++;
		for (auto &x : comp[1])
			ct[x]++;

		int arr[2] = { -1,-1 };
		for (int i = 0; i < 2; ++i)
			for (auto &x : comp[i])
				if (ct[x] == 1)
					arr[i]++;

		cout << max(0ll, arr[0] * arr[1]) << endl;
		clear(n);
	}

	return 0;
}


#pragma GCC optimize("O3")
#pragma GCC target("mmx,sse,sse2,sse3,ssse3,sse4,avx,aes,pclmul,sse4.1,sse4.2")

#include<bits/stdc++.h>
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_DISABLE_PERFCRIT_LOCKS
#define cdbg cout << "Debug in " << __func__ << ", " << __LINE__ << ": "
#define q <<  '\n'
#define sp << ' '
#define mp make_pair
#define pb emplace_back
#define ft first
#define sd second
#define ld long double
#define ll long long
#define ull unsigned long long
#define lll __int128
#define pii pair<ll , ll>
#define vi vector<int>
#define y1 trymaxlox

using namespace std;

const int N = 5e5;
const ll INF = 1e18 + 7;
const int MOD = 1e9+7;

ll n, m, k, a, b, c, d, arr[N], res, kek, t ;
set<ll> st;
string str;
vi ans, v;
set<int> g[N];
bool used[N], used2[N];

void del(int v)
{
    used2[v] = 1;
    vi vv;
    for (int it : g[v])
    {
        if (!used2[it])
        {
            del(it);
            vv.pb(it);
        }
    }
     for (int i : vv)
    {
        g[v].erase(i);
        g[i].erase(v);
    }

}
bool dfsdel(int a, int v, int b, int p)
{
   // cdbg << v q;
    used[v] = 1;
    bool f = 0, ff = 0;
//    cout << "! ! ";
//    for (auto it : g[v]) cout << it sp;
//    cout q;
    vi vv;
    for (auto it : g[v])
    {
       // cdbg << "  " << it q;
        if (!used[it])
        {
            if (it == b)
            {
                vv.pb(it);
                f = 1;
                ff = 1;
            }
            else
            {
                bool kex = dfsdel(a, it, b, v);
                if (kex)
                {
                    vv.pb(it);
                    f = 1;
                }
            }
        }
    }
    for (int i : vv)
    {
        g[v].erase(i);
        g[i].erase(v);
    }
    if (ff)
    {
        for (auto it : g[v])
        {
            if (it != p) del(v);
        }
    }
  //  cdbg << v sp << f q;
    return f;
}

ll dfs(int v)
{
   // cdbg << v q;
    used[v] = 1;
    ll ans = 0;
    for (auto it : g[v])
    {
        if (!used[it])
        {
            ans += dfs(it);
        }
    }
    return ans + 1;
}
main()
{
        ios::sync_with_stdio(0);
        cin.tie(0);
        cout.tie(0);

        cin >> t;
        while (t--)
        {
            cin >> n >> m >> a >> b;
            for (int i = 0;i <= n; i++)
            {
                g[i].clear();
            }
           // cdbg << "a" q;
            memset(used, 0, sizeof(used));
            ll x , y;
            for (int i = 0; i < m; i++)
            {
                cin >> x >> y;
                g[x].insert(y);
                g[y].insert(x);
            }
            //cdbg << "aaa" q;
            dfsdel(a, a, b, a);
            memset(used, 0, sizeof(used));
            ll cnta = dfs(a);
            cnta--;
            memset(used, 0, sizeof(used));
            ll cntb = dfs(b);
            cntb--;
            cout << cnta * cntb q;
        }

/*
3
a???cb
a??bbc
a?b?c
*/

}


#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#include <iostream>
#include <vector>
#include <cstdio>
#include <string>
#include <set>
#include <algorithm>
#include <unordered_map>
#include <map>
#include <unordered_set>
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <bitset>
#include <climits>
#include <queue>
using namespace std;
typedef  long long  li;
typedef long double ld;
const li MAX = 100042;
li n, l[MAX], used[MAX], a, b, cnt;
vector<li> gr[MAX];
set<li> who;
vector<li> tmp;
void dfs(li vert) {
	cnt++;
	used[vert] = 1;
	tmp.push_back(vert);
	for (auto i : gr[vert]) {
		if (i == a) who.insert(a);
		else if (i == b) who.insert(b);
		else{
			if (used[i] != 1)
			dfs(i);
		}
	}
}
int main() {
	//	freopen("input.txt", "r", stdin);
	//	freopen("output.txt", "w", stdout);
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	li q;
	cin >> q;
	while (q--) {
		li m;
		cin >> n >> m >> a >> b;
		for (int i = 1; i <= n; i++) {
			used[i] = 0;
		}
		li an1 = 0, an2 = 0;
		for (int i = 1; i <= n; i++) gr[i].clear();
		for (int i = 0; i < m; i++) {
			li c, d;
			cin >> c >> d;
			gr[c].push_back(d);
			gr[d].push_back(c);
		}
		for (int i = 1; i <= n; i++) {
			if (!used[i] && i != a && i != b) {
				cnt = 0;
				dfs(i);
				if (who.size() == 1) {
					if (*(who.begin()) == a) {
						an1 += cnt;
					}
					else an2 += cnt;
				}
				who.clear();
			}
		}
		li ans = (an1 * an2);
		cout << ans << "\n";
	}
//	system("pause");
	return 0;
}


#include <bits/stdc++.h>

//#pragma comment(linker, "/STACK:16777216")

using namespace std;

//mt19937 rnd(228+1337);

#define ll long long
#define ull unsigned long long
#define inf INT_MAX
#define F first
#define S second
#define int ll
const int SZ = 4e4 + 4;
const double EPS = 1e-7;

int n, m, a, b;
vector<int> g[SZ];

bool used[2][SZ];

void read() {
    cin >> n >> m >> a >> b;
    --a, --b;
    for (int i = 0; i < n; ++i) {
        g[i].clear();
        used[0][i] = used[1][i] = 0;
    }
    for (int i = 0; i < m; ++i) {
        int u, v;
        cin >> u >> v;
        --u, --v;
        g[u].push_back(v);
        g[v].push_back(u);
    }
}

int dfs(int u, int perm, int p) {
    used[p][u] = true;
    for (auto v : g[u]) {
        if (v == perm) continue;
        if (!used[p][v]) {
            dfs(v, perm, p);
        }
    }
}

void solve() {
    dfs(a, b, 0);
    dfs(b, a, 1);
    int x = -1, y = -1;
    for (int i = 0; i < n; ++i) {
        if (used[0][i] && !used[1][i]) {
            ++x;
        } else if (!used[0][i] && used[1][i]) {
            ++y;
        }
    }
    cout << x * y << "\n";
}

signed main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    int t;
    cin >> t;
    for (int i = 0; i < t; ++i) {
        read();
        solve();
    }

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int n,m,id[300010],last[300010];
vector<int> route[300010];
vector<pair<int,int> > edg[300010];
void solve()
{
    scanf("%d%d",&n,&m);
    int sk=0;
    for(int i=1,K;i<=m;i++)
    {
        sk+=K;
        scanf("%d",&K);
        route[i].resize(K);
        for(int j=0;j<K;j++)scanf("%d",&route[i][j]);
    }
    int blk=sqrt(sk);
    vector<int> bel[2];
    for(int i=1;i<=m;i++)
    {
        if(route[i].size()>=blk)bel[1].push_back(i);
        else bel[0].push_back(i);
    }
    fill(last+1,last+n+1,-1);
    for(int &p:bel[1])
    {
        for(int j=0;j<route[p].size();j++)last[route[p][j]]=j;
        for(int j=1;j<=m;j++)
        {
            if(route[j].size()>=blk&&j>=p)continue;
            int v=last[route[j].back()];
            for(int k=(int)route[j].size()-2;k>=0;k--)
            {
                if(last[route[j][k]]==-1)continue;
                if(v>last[route[j][k]])
                {
                    if(route[p][last[route[j][k]]+1]!=route[j][k+1])
                    {
                        puts("Human");
                        return;
                    }
                }
                else
                {
                    v=last[route[j][k]];
                }
            }
        }
        for(int &x:route[p])last[x]=-1;
    }
    for(int i=1;i<=n;i++)edg[i].clear();
    for(int &p:bel[0])
    {
        for(int j=0;j<route[p].size();j++)
        {
            for(int k=j+1;k<route[p].size();k++)
            {
                edg[route[p][j]].push_back(make_pair(route[p][k],route[p][j+1]));
            }
        }
    }
    fill(id+1,id+n+1,0);
    for(int i=1;i<=n;i++)
    {
        for(auto &x:edg[i])
        {
            if(id[x.first]&&id[x.first]!=x.second)
            {
                puts("Human");
                return;
            }
            id[x.first]=x.second;
        }
        for(auto &x:edg[i])id[x.first]=0;
    }
    puts("Robot");
    return;
}
int T;
int main()
{
    scanf("%d",&T);
    while(T--)solve();
    return 0;
}


#include<bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define SZ(x) ((int)x.size())
#define L(i,u) for (register int i=head[u]; i; i=nxt[i])
#define rep(i,a,b) for (register int i=(a); i<=(b); i++)
#define per(i,a,b) for (register int i=(a); i>=(b); i--)
using namespace std;
typedef long long ll;
typedef unsigned int ui;
typedef pair<int,int> Pii;
typedef vector<int> Vi;
inline void read(int &x) {
	x=0; char c=getchar(); int f=1;
	while (!isdigit(c)) {if (c=='-') f=-1; c=getchar();}
	while (isdigit(c)) {x=x*10+c-'0'; c=getchar();} x*=f;
}
const int N = 303000, S = 350, inf = 0x3f3f3f3f;
int n,q,bg[N],ed[N],a[N],bel[N],len;bool gg;
vector<Pii>mrk[N];int qaq[N],pos[N];
inline void init(){
	rep(i,0,len+1)bel[i]=0;
	gg=0;rep(i,0,n+1)mrk[i].clear();len=0;
}
//inline void upd(Pii &u, int x){u=Pii((1LL*u.fi*b1+x)%mo1,(1LL*u.se*b2+x)%mo2);}
inline bool solve(int p){
	int mx=0,now=inf;bool gg=0;
	per(i,ed[p],bg[p]){
		now=!pos[a[i]]?inf:(pos[a[i]]+1==pos[a[i+1]]?now:pos[a[i]]);
		mx=max(mx,pos[a[i]]);gg|=mx>now;
	}
	return gg;
}
int main() {
	int T;read(T);
	while(T--){
		read(n);read(q);init();
		rep(i,1,q){
			int l,x;read(l);bg[i]=len+1;
			rep(j,1,l)read(x),a[++len]=x,bel[len]=i;ed[i]=len;
		}
		rep(i,1,len)if(ed[i]-bg[i]<=S){
			Pii u(0,0);
			for(register int j=i+1;j-i<=S&&bel[i]==bel[j]&&j<=len;j++)
				mrk[a[i]].pb(Pii(a[j],a[j-1]));
		}
		rep(i,1,n){
			rep(j,0,SZ(mrk[i])-1){
				int u=mrk[i][j].fi,v=mrk[i][j].se;
				gg|=qaq[u]&&qaq[u]!=v;qaq[u]=v;
			}
			rep(j,0,SZ(mrk[i])-1)qaq[mrk[i][j].fi]=0;
		}
	//	Vi a;a.clear();rep(i,1,q)if(ed[i]-bg[i]>=S)a.pb(i);
	//	rep(i,0,SZ(a)-1)rep(j,i+1,SZ(a)-1)gg|=solve(i,j);
		rep(i,1,q)if(ed[i]-bg[i]>=S){
			rep(j,bg[i],ed[i])pos[a[j]]=j;
			rep(j,1,q)if(i!=j)gg|=solve(j);
			rep(j,bg[i],ed[i])pos[a[j]]=0;
		}
		if(gg)puts("Human");else puts("Robot");
	}
	return 0;
}


#pragma GCC optimize("Ofast")
#include<bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define SZ(x) ((int)x.size())
#define L(i,u) for (register int i=head[u]; i; i=nxt[i])
#define rep(i,a,b) for (register int i=(a); i<=(b); i++)
#define per(i,a,b) for (register int i=(a); i>=(b); i--)
using namespace std;
typedef long long ll;
typedef unsigned int ui;
typedef pair<int,int> Pii;
typedef vector<int> Vi;
inline void read(int &x) {
	x=0; char c=getchar(); int f=1;
	while (!isdigit(c)) {if (c=='-') f=-1; c=getchar();}
	while (isdigit(c)) {x=x*10+c-'0'; c=getchar();} x*=f;
}
const int N = 303000, S = 350, inf = 0x3f3f3f3f;
int n,q,bg[N],ed[N],a[N],bel[N],len;bool gg;
vector<Pii>mrk[N];int qaq[N],pos[N];
inline void init(){
	rep(i,0,len+1)bel[i]=0;
	gg=0;rep(i,0,n+1)mrk[i].clear();len=0;
}
//inline void upd(Pii &u, int x){u=Pii((1LL*u.fi*b1+x)%mo1,(1LL*u.se*b2+x)%mo2);}
inline bool solve(int p){
	int mx=0,now=inf;bool gg=0;
	per(i,ed[p],bg[p]){
		now=!pos[a[i]]?inf:(pos[a[i]]+1==pos[a[i+1]]?now:pos[a[i]]);
		mx=max(mx,pos[a[i]]);gg|=mx>now;
	}
	return gg;
}
int main() {
	int T;read(T);
	while(T--){
		read(n);read(q);init();
		rep(i,1,q){
			int l,x;read(l);bg[i]=len+1;
			rep(j,1,l)read(x),a[++len]=x,bel[len]=i;ed[i]=len;
		}
		rep(i,1,len)if(ed[i]-bg[i]<=S){
			Pii u(0,0);
			for(register int j=i+1;j-i<=S&&bel[i]==bel[j]&&j<=len;j++)
				mrk[a[i]].pb(Pii(a[j],a[j-1]));
		}
		rep(i,1,n){
			rep(j,0,SZ(mrk[i])-1){
				int u=mrk[i][j].fi,v=mrk[i][j].se;
				gg|=qaq[u]&&qaq[u]!=v;qaq[u]=v;
			}
			rep(j,0,SZ(mrk[i])-1)qaq[mrk[i][j].fi]=0;
		}
	//	Vi a;a.clear();rep(i,1,q)if(ed[i]-bg[i]>=S)a.pb(i);
	//	rep(i,0,SZ(a)-1)rep(j,i+1,SZ(a)-1)gg|=solve(i,j);
		rep(i,1,q)if(ed[i]-bg[i]>=S){
			rep(j,bg[i],ed[i])pos[a[j]]=j;
			rep(j,1,q)if(i!=j)gg|=solve(j);
			rep(j,bg[i],ed[i])pos[a[j]]=0;
		}
		if(gg)puts("Human");else puts("Robot");
		rep(i,0,n)mrk[i].clear();
	}
	return 0;
}


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

const int N = 300000;
const int SN = sqrt(N);

int n, q;
vector<int> rides[N];

int solve() {
  scanf("%d", &n);
  scanf("%d", &q);
  for (int i=0; i<q; i++) {
    int k;
    scanf("%d", &k);

    rides[i].clear();
    while (k--) {
      int c;
      scanf("%d", &c);
      --c;

      rides[i].push_back(c);
    }
  }

  vector<pair<int, int>> v[n];

  for (int i=0; i<q; i++) {
    if (rides[i].size() < SN) {
      for (int j=0; j<rides[i].size(); j++) for (int k=j+1; k<rides[i].size(); k++) {
        v[rides[i][j]].push_back({rides[i][k], rides[i][j+1]});
      }
    } else {
      vector<int> pos(n, -1);
      for (int j=0; j<rides[i].size(); j++) pos[rides[i][j]] = j;

      for (int j=0; j<q; j++) {
        if (i == j) continue;

        int lst = -1;
        for (int k=0; k<rides[j].size(); ++k) {
          int p = pos[rides[j][k]];
          if (p == -1) continue;

          if (lst != -1 && p > lst+1 && pos[rides[j][k-1]] != lst)) return 0 * printf("Human\n");
          lst = p;
        }
      }
    }
  }

  for (int i=0; i<n; i++) {
    sort(v[i].begin(), v[i].end());
    for (int j=1; j<v[i].size(); j++) {
      if (v[i][j].first == v[i][j-1].first && v[i][j].second != v[i][j-1].second) {
        // cerr << i << " " << v[i][j].first << " " << v[i][j-1].second << " " << v[i][j].second << endl;
        return 0 * printf("Human\n");
      }
    }
  }

  printf("Robot\n");
  return 0;
}

int main() {
  int t;
  scanf("%d", &t);
  while (t--) solve();
  return 0;
}


#error "Incomplete"

// http://codeforces.com/contest/913/problem/H

#ifndef _GLIBCXX_DEBUG
#define NDEBUG
#endif
#include <cassert>

#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <limits>

int constexpr MOD = 998244353;

int inverse(int x, int y) {
	int a = x, b = y, ax = 1, ay = 0, bx = 0, by = 1;
	while (b) {
		int q = a / b, tmp;
		tmp = a  - q * b ; a  = b ; b  = tmp;
		tmp = ax - q * bx; ax = bx; bx = tmp;
		tmp = ay - q * by; ay = by; by = tmp;
	}
	while (ax < 0) ax += y;
	return ax;
}

template <int MOD>
class num_mod {
	int v;
public:
	num_mod() : v(0) {}
	num_mod(int v) : v(v) {
		assert(0 <= v && v < MOD);
	}
	explicit operator int () const {
		return v;
	}
	num_mod& operator += (num_mod a) { v += a.v; if (v >= MOD) v -= MOD; return *this; }
	num_mod& operator -= (num_mod a) { v -= a.v; if (v < 0   ) v += MOD; return *this; }
	num_mod& operator *= (num_mod a) { v = v * (int64_t)        a.v     %MOD; return *this; }
	num_mod& operator /= (num_mod a) { v = v * (int64_t)inverse(a.v,MOD)%MOD; return *this; }
 	#define d(OP) num_mod operator OP (num_mod x) const { return x OP##= *this; }
	d(+) d(-) d(*) d(/)
	#undef d
	num_mod operator - () const {
		return { MOD - v - MOD *!v }; // *!: obfuscation (subtract MOD iff v == 0 (falsy))
	}

	bool operator == (num_mod x) const { return v == x.v; }
}; // NOT ordered

template <int DENOM>
class fix_frac {
	int v;
public:
	fix_frac() : v() {}
	fix_frac(int v) : v(v) {}

	fix_frac operator - () const {
		assert(v != INT_MIN);
		return fix_frac(-v);
	}
	fix_frac& operator += (fix_frac x) {
		if (v == INT_MIN) {

			/* not necessary */ assert(false);

			// -inf already, nothing to do
		} else if (x.v == INT_MIN) {

			/* not necessary */ assert(false);

			v = INT_MIN;
		} else
			v += x.v;
		return *this;
	}
	fix_frac& operator -= (fix_frac x) {
		if (v == INT_MIN) {

			/* not necessary */ assert(false);

			assert (x.v != INT_MIN);
			return *this; // -inf already, nothing to do
		}
		assert(x.v != INT_MIN); // cannot subtract (-INF) (will get +INF, not supported)
		v -= x.v; return *this;
	}

 	#define d(OP) \
	fix_frac operator OP (fix_frac x) const { return x OP##= *this; }
	d(+) d(-)
	#undef d

	template <int MOD>
	explicit operator num_mod<MOD> () const {
		int64_t const INV_DENOM = inverse(DENOM, MOD);
		int ans = v * INV_DENOM % MOD;
		return { ans + MOD * (ans < 0) };
	}

	// bool operator <=> // someday...
	#define d(OP) \
	bool operator OP (fix_frac x) const { return v OP x.v; }
	d(<) d(>) d(<=) d(>=) d(==) d(!=)
	#undef d

	static fix_frac const MIN;
};
template <int DENOM>
fix_frac<DENOM> const fix_frac<DENOM>::MIN { INT_MIN };
namespace std {
	template <int DENOM>
	struct numeric_limits<fix_frac<DENOM>> {
		static fix_frac<DENOM> const min () {
			return fix_frac<DENOM>::MIN;
		}
	};
}

template <class num>
class poly {
public:
	std::vector<num> x; // coefficients

	poly() : x (1) {} // zero polynomial (coeff size == 1)
	poly(std::vector<num> x) : x(std::move(x)) {}

	poly& operator += (poly const & b) {
		if (x.size() < b.x.size())
			x.resize(b.x.size(), 0);
		for (size_t i = b.x.size(); i --> 0;)
			x[i] += b.x[i];
		return *this;
	}

	poly operator + (poly x) const { return x += *this; }

	poly integrate() const {
		poly ans; ans.x.resize(x.size()+1);
		for (size_t i = ans.x.size(); i --> 1;)
			ans.x[i] = x[i-1] / i;
		return ans;
	}

	// Polynomial multiplication.
	poly operator * (poly const & b) const {
		std::vector<num> ans; ans.resize(x.size() + b.x.size() - 1);

		for (size_t i = x.size(); i --> 0;)
			for (size_t j = b.x.size(); j --> 0;)
				ans[i+j] += x[i] * b.x[j];

		return poly(std::move(ans));
	}

	poly& operator *= (poly b) {
		return *this = *this * b;
	}

	poly& operator *= (num b) {
		for (num& a : x) a *= b;
		return *this;
	}

	poly operator * (num b) const { poly ans = *this; return ans *= b; }

	/// Function composition.
	poly operator ^ (poly const & b) const {
		poly ans; // zero
		poly base; base.x[0] = 1; // base(x) == 1
		for (num v : x) {
			ans += base * v;
			base *= b;
		}
		return ans;
	}

	poly& operator ^= (poly x) { return *this = x ^ *this; }

	poly operator - () const {
		poly ans; ans.x.resize(x.size());
		for (size_t i = x.size(); i --> 0;)
			ans.x[i] = -x[i];
		return ans;
	}

	/// polynomial evaluation
	num operator () (num a) {
		num base = 1, ans = 0;
		for (num v : x) {
			ans += base * v;
			base *= a;
		}
		return ans;
	}
};

/// Piecewise polynomial.
template <class xnum, class ynum>
class func {
	using polyN = poly<ynum>;
	using funcN = func<xnum, ynum>;

	struct piece {
		polyN p; xnum s; // start
		piece(polyN p, xnum s) : p(p), s(s) {}
	};

public:
	std::vector<piece> t;

	/// Initialize to the step function f(x) = 0 if x <= 0 else 1
	func() : t { piece{polyN(), std::numeric_limits<xnum>::min()}, piece{polyN({1}), 0} } {
		// self.t = t or [poly(), 0, poly([0, 1])] # <-- max(0, x), integrate of step function.
	}
	func(std::vector<piece> t) : t(std::move(t)) {}

	funcN operator - () const {
		funcN ans (t);
		for (piece& p : ans.t)
			p.p = -p.p;
		return ans;
	}

	funcN operator + (funcN const & x) const {
		std::vector<piece> ans;

		std::vector<piece> a = t, b = x.t; // copy

		while (!a.empty() && !b.empty()) {
			if (a.back().s < b.back().s) {
				ans.emplace_back(a.back().p + b.back().p, b.back().s);
				b.pop_back();
			} else if (b.back().s < a.back().s) {
				ans.emplace_back(a.back().p + b.back().p, a.back().s);
				a.pop_back();
			} else {
				ans.emplace_back(a.back().p + b.back().p, a.back().s);
				a.pop_back();
				b.pop_back();
			}
		}

		assert(a.empty() && b.empty());
		assert(ans.back().s == std::numeric_limits<xnum>::min());

		std::reverse(ans.begin(), ans.end());
		return funcN(std::move(ans));
	}

	funcN& operator += (funcN x) { return *this = x + *this; }

	funcN integrate() const {
		std::vector<piece> ans = t;
		for (piece& p : ans)
			p.p = p.p.integrate();

		for (size_t i = 1; i < ans.size(); ++i) {

			// fit poly ans.t[i] with ans.t[i-2]
			ynum last_val = ans[i-1].p((ynum) ans[i].s);
			ynum this_val = ans[i  ].p((ynum) ans[i].s);
			ans[i].p.x[0] += last_val - this_val;

			assert( ans[i-1].p((ynum) ans[i].s) == ans[i  ].p((ynum) ans[i].s) );
		}

		return ans;
	}

	/// Shift this function left (++) by (a) units.
	funcN& operator >>= (xnum a) {
		polyN p ({(ynum) -a, (ynum) 1});
		for (piece& pi : t) {
			pi.p ^= p;
			pi.s += a;
		}
		return *this;
	}

	funcN operator >> (xnum a) const {
		funcN ans = *this;
		return ans >>= a;
	}

	/// Set all values of self at value >= a to self(a).
	funcN& flatten_larger(xnum a) {
		if (!(t.size() == 1 || t.back().s < a)) {
			// len(t) must be at least 3 and t[1] >= a
			while (t.size() >= 2 and (----t.end())->s  >= a)
				t.pop_back();
			t.pop_back(); // remove the last function
		}
		t.emplace_back( polyN( { t.back().p((ynum) a) } ), a );
		return *this;
	}

};

int main() {
	int constexpr DENOM = 1000000;
	int const INV_DENOM = inverse(DENOM, MOD);

	int n; std::cin >> n;

	func<fix_frac<DENOM>, num_mod<MOD>> fn;
	for (int i = n; i --> 0;) {
		double xi_f; std::cin >> xi_f;
		fix_frac<DENOM> xi { (int) std::round(xi_f * DENOM) };
		fn = fn.integrate();
		fn += -(fn >> 1);
		fn.flatten_larger(xi);
	}

	int ans = (int) (num_mod<MOD>) fn.t.back().p.x[0]; // this must be a constant function
	// print(ans.numerator * inverse(ans.denominator, mod) % mod)
	std::cout << ans << '\n';

}