#include <bits/stdc++.h>
using namespace std;
long long M = 1000000007 ;
map < long long , bool > have;
vector < long long > goRight, goLeft;
long long countLeq( vector < long long > & array, long long x)
{
long long L = - 1 , R = array.size ( ) , M;
while ( R - L > 1 )
{
M = ( L + R) / 2 ;
if ( array[ M] <= x)
L = M;
else
R = M;
}
return L + 1 ;
}
long long query( long long rank, long long delta)
{
long long L = - 1000000000 , R = 2000000000 , M;
while ( R- L > 1 )
{
M = ( L + R) / 2 ;
if ( countLeq( goRight, M - delta) + countLeq( goLeft, M + delta) < rank + 1 )
L = M;
else
R = M;
}
return abs ( R) ;
}
int indexToRank[ 1000001 ] ;
class FindingKids
{
public : long long getSum( int n, int q, int A, int B, int C)
{
vector < long long > pos;
for ( int i = 0 ; i < n; i++ )
{
A = ( ( long long ) A * B + C) % M;
long long p = A % ( M - n + i + 1 ) ;
if ( have.count ( p) )
p = M - n + i;
have[ p] = true ;
pos.push_back ( p * 1000000LL + i) ;
if ( p % 2 == 0 )
goRight.push_back ( p) ;
else
goLeft.push_back ( p) ;
}
sort( pos.begin ( ) , pos.end ( ) ) ;
for ( int i = 0 ; i < n; i++ )
indexToRank[ pos[ i] % 1000000 ] = i;
sort( goLeft.begin ( ) , goLeft.end ( ) ) ;
sort( goRight.begin ( ) , goRight.end ( ) ) ;
long long ans = 0 ;
for ( int i = 0 ; i < q; i++ )
{
A = ( ( long long ) A * B + C) % M;
long long query_kid = A % n;
A = ( ( long long ) A * B + C) % M;
long long query_time = A;
ans + = query( indexToRank[ query_kid] , query_time) ;
}
return ans;
}
} ;
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7Cgpsb25nIGxvbmcgTSA9IDEwMDAwMDAwMDc7Cm1hcCA8bG9uZyBsb25nLCBib29sPiBoYXZlOwp2ZWN0b3IgPGxvbmcgbG9uZz4gZ29SaWdodCwgZ29MZWZ0OwoKbG9uZyBsb25nIGNvdW50TGVxKHZlY3RvciA8bG9uZyBs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