multiset+暴力枚举
#include <cstdio>
#include <cstring>
#include <string>
#include <iostream>
#include <map>
#include <set>
#include <vector>
#include <cmath>
#include <stack>
#include <queue>
#include <cstdlib>
#include <algorithm>
using namespace std;
typedef __int64 int64;
typedef long long ll;
#define M 500005
#define N 1000005
#define max_inf 0x7f7f7f7f
#define min_inf 0x80808080
#define mod 1000000007
#define lc rt<<1
#define rc rt<<1|1
struct Point
{
ll x , y;
bool operator < (const Point &a) const
{
return x < a.x;
}
};
ll x[M] , y[M];
int main()
{
int n , t , i;
scanf("%d",&t);
while (t--)
{
scanf("%d",&n);
ll a , b , c;
scanf("%I64d %I64d %I64d",&a,&b,&c);
for (x[0] = 0 , i = 1 ; i <= n ; i++)x[i] = (x[i-1]*a+b)%c;
scanf("%I64d %I64d %I64d",&a,&b,&c);
for (y[0] = 0 , i = 1 ; i <= n ; i++)y[i] = (y[i-1]*a+b)%c;
Point p;
multiset<Point> sq;
ll Min = (ll)1<<60 , ans = 0;
p.x = x[1] , p.y = y[1];
sq.insert(p);
for (i = 2 ; i <= n ; i++)
{
p.x = x[i] , p.y = y[i];
multiset<Point>::iterator it , It;
It= sq.lower_bound(p);
for (it = It ; it != sq.end() ; it++)
{
ll xx = it->x-x[i];
xx *= xx;
if (xx >= Min)break;
ll yy = it->y-y[i];
yy *= yy;
Min = min(Min,yy+xx);
}
for (it = It ; it != sq.begin() ;)
{
it--;
ll xx = it->x-x[i];
xx *= xx;
if (xx >= Min)break;
ll yy = it->y-y[i];
yy *= yy;
Min = min(Min,yy+xx);
}
sq.insert(p);
ans += Min;
}
cout << ans << endl;
}
return 0;
}