# include <bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef long double ld;
typedef pair <int, int> pii;

# define F first
# define S second
# define endl '\n'
# define sep ' '
# define pb push_back
# define fast_io ios::sync_with_stdio(0);cin.tie(0); cout.tie(0);

const ll md = 998244353;
const int xn = 1e5+10;
const int xm = 1e2+10;
const int SQ = 50;
const int sq = 1e3+10;
const ll inf = 1e18+10;

ll power(ll a, ll b) {
    return (!b ? 1 : (b & 1 ? a * power(a * a % md, b / 2) % md : power(a * a % md, b / 2) % md));
}

int n;
ll x[xn], v[xn], p[xn][2], inv, timeb[xn][4], dp[xn][2], ans, P[2];
ld tmb[xn][4];
vector <pair <ld, ll> > b[sq][4];

void Build(){
	for (int i = 0; i < n; i += SQ){
		int ind = i/SQ;
		for (int j = 0; j < 4; j += 2){
			sort(b[ind][j].begin(), b[ind][j].end());
			for (int k = 0; k < b[ind][j].size(); k++){
				ld t = b[ind][j][k].F;
				dp[i][0] = dp[i][1] = 0;
				if (j < 2) dp[i][0] = p[i][0];
				else dp[i][1] = p[i][1];
				for (int pnt = i + 1; pnt < i+SQ; pnt++){
					if (i >= n) break;
					dp[pnt][0] = dp[pnt][1] = 0;
					if (tmb[pnt][0] >= t) dp[pnt][0] += dp[pnt - 1][0], dp[pnt][0] %= md;
					if (tmb[pnt][2] >= t) dp[pnt][0] += dp[pnt - 1][1], dp[pnt][0] %= md;
					dp[pnt][0] = (dp[pnt][0] * p[pnt][0] + 100 * md) % md;

					if (tmb[pnt][1] >= t) dp[pnt][1] += dp[pnt - 1][0], dp[pnt][1] %= md;
					if (tmb[pnt][3] >= t) dp[pnt][1] += dp[pnt - 1][1], dp[pnt][1] %= md;
					dp[pnt][1] = (dp[pnt][1] * p[pnt][1] + 100 * md) % md;
				}
				int dx = min(i+SQ-1, n-1);
				b[ind][j][k].S = dp[dx][0];
				b[ind][j + 1][k].S = dp[dx][1];
			}
		}
	}
}
void get(int dx, int f){
	P[0] = P[1] = 1;
	ld t = tmb[dx][f];
	for (int i = 0; i < dx; i += SQ){
		if (i/SQ == dx/SQ) break;
		int l = -1, r = b[i/SQ][0].size(), mid;
		while (r - l > 1){
			mid = (l + r) / 2;
			if (b[i/SQ][0][mid].F <= t) l = mid;
			else r = mid;
		}
		int ind = r;
		//cout << ind << endl;
		if (ind == b[i/SQ][0].size()){
			P[0] = P[1] = 0;
			return;
		}
		if (P[0] == P[1] && P[0] == 1 && i == 0){
			P[0] = P[1] = 0;
			P[0] += b[0][0][ind].S, P[0] %= md;
			P[0] += b[0][2][ind].S, P[0] %= md;
			P[1] += b[0][1][ind].S, P[1] %= md;
			P[1] += b[0][3][ind].S, P[1] %= md;
			continue;
		}
		ll h1 = 0, h2 = 0;
		if (tmb[i][0] > t) h1 += (b[i/SQ][0][ind].S * P[0] + 100 * md) % md, h1 %= md;
		if (tmb[i][2] > t) h1 += (b[i/SQ][0][ind].S * P[1] + 100 * md) % md, h1 %= md;
		if (tmb[i][1] > t) h1 += (b[i/SQ][2][ind].S * P[0] + 100 * md) % md, h1 %= md;
		if (tmb[i][3] > t) h1 += (b[i/SQ][2][ind].S * P[1] + 100 * md) % md, h1 %= md;

		if (tmb[i][0] > t) h2 += (b[i/SQ][1][ind].S * P[0] + 100 * md) % md, h2 %= md;
		if (tmb[i][2] > t) h2 += (b[i/SQ][1][ind].S * P[1] + 100 * md) % md, h2 %= md;
		if (tmb[i][1] > t) h2 += (b[i/SQ][3][ind].S * P[0] + 100 * md) % md, h2 %= md;
		if (tmb[i][3] > t) h2 += (b[i/SQ][3][ind].S * P[1] + 100 * md) % md, h2 %= md;

		P[0] = h1, P[1] = h2;
	}
	//cout << P[0] << sep << P[1] << endl;

	for (int i = dx-dx%SQ; i < dx; i++){
		if (i == 0){
			P[0] = p[i][0], P[1] = p[i][1];
			continue;
		}
		dp[i][0] = dp[i][1] = 0;
		if (tmb[i][0] > t) dp[i][0] += P[0], dp[i][0] %= md;
		if (tmb[i][2] > t) dp[i][0] += P[1], dp[i][0] %= md;
		dp[i][0] = (dp[i][0] * p[i][0] + 100 * md) % md;

		if (tmb[i][1] > t) dp[i][1] += P[0], dp[i][1] %= md;
		if (tmb[i][3] > t) dp[i][1] += P[1], dp[i][1] %= md;
		dp[i][1] = (dp[i][1] * p[i][1] + 100 * md) % md;

		P[0] = dp[i][0];
		P[1] = dp[i][1];
	}
	if (f < 2) P[1] = 0;
	else P[0] = 0;

	//cout << P[0] << sep << P[1] << endl;

	if (f == 0) P[0] = (P[0] * p[dx][0] + 100 * md) % md;
	else if (f == 1) P[1] = (P[0] * p[dx][1] + 100 * md) % md, P[0] = 0;
	else if (f == 2) P[0] = (P[1] * p[dx][0] + 100 * md) % md, P[1] = 0;
	else P[1] = (P[1] * p[dx][1] + 100 * md) % md;

	for (int i = dx+1; i < dx-dx%SQ+SQ; i++){
		if (i >= n) break;
		dp[i][0] = dp[i][1] = 0;
		if (tmb[i][0] >= t) dp[i][0] += P[0], dp[i][0] %= md;
		if (tmb[i][2] >= t) dp[i][0] += P[1], dp[i][0] %= md;
		dp[i][0] = (dp[i][0] * p[i][0] + 100 * md) % md;

		if (tmb[i][1] >= t) dp[i][1] += P[0], dp[i][1] %= md;
		if (tmb[i][3] >= t) dp[i][1] += P[1], dp[i][1] %= md;
		dp[i][1] = (dp[i][1] * p[i][1] + 100 * md) % md;

		P[0] = dp[i][0];
		P[1] = dp[i][1];
	}

	for (int i = dx-dx%SQ+SQ; i < n; i += SQ){

		int l = -1, r = b[i/SQ][0].size(), mid;
		while (r - l > 1){
			mid = (l + r) / 2;
			if (b[i/SQ][0][mid].F < t) l = mid;
			else r = mid;
		}
		int ind = r;
		if (ind == b[i/SQ][0].size()){
			P[0] = P[1] = 0;
			break;
		}
		ll h1 = 0, h2 = 0;
		if (tmb[i][0] >= t) h1 += (b[i/SQ][0][ind].S * P[0] + 100 * md) % md, h1 %= md;
		if (tmb[i][2] >= t) h1 += (b[i/SQ][0][ind].S * P[1] + 100 * md) % md, h1 %= md;
		if (tmb[i][1] >= t) h1 += (b[i/SQ][2][ind].S * P[0] + 100 * md) % md, h1 %= md;
		if (tmb[i][3] >= t) h1 += (b[i/SQ][2][ind].S * P[1] + 100 * md) % md, h1 %= md;

		if (tmb[i][0] >= t) h2 += (b[i/SQ][1][ind].S * P[0] + 100 * md) % md, h2 %= md;
		if (tmb[i][2] >= t) h2 += (b[i/SQ][1][ind].S * P[1] + 100 * md) % md, h2 %= md;
		if (tmb[i][1] >= t) h2 += (b[i/SQ][3][ind].S * P[0] + 100 * md) % md, h2 %= md;
		if (tmb[i][3] >= t) h2 += (b[i/SQ][3][ind].S * P[1] + 100 * md) % md, h2 %= md;

		P[0] = h1, P[1] = h2;
		//cout << h1 << sep << h2 << endl;
	}
	P[0] += P[1];

	//cout << dx << sep << f << sep << P[0] << endl;

	ans = (ans + (P[0] * timeb[dx][f] + 100 * md) % md + 100 * md) % md;
}

int main(){
	fast_io;

	cin >> n;
	for (int i = 0; i < n; i++) cin >> x[i] >> v[i] >> p[i][0], p[i][1] = 100 - p[i][0];

	cout << fixed << setprecision(10);

	inv = power(ll(100), md - 2);

	for (int i = 0; i < n; i++) for (int j = 0; j < 2; j++) p[i][j] = (p[i][j] * inv + 100 * md) % md;

	for (int i = 0; i < 4; i++) tmb[0][i] = inf;
	for (int i = 1; i < n; i++){
		tmb[i][2] = inf;
		timeb[i][1] = ((x[i] - x[i - 1]) * power(v[i] + v[i - 1], md - 2) + 100 * md) % md;
		tmb[i][1] = ld(x[i] - x[i - 1]) / ld(v[i] + v[i - 1]);
		if (v[i - 1] > v[i]){
			timeb[i][0] = ((x[i] - x[i - 1]) * power(v[i - 1] - v[i], md - 2) + 100 * md) % md;
			tmb[i][0] = ld(x[i] - x[i - 1]) / ld(v[i - 1] - v[i]);
			tmb[i][3] = inf;
		}
		else if (v[i] > v[i - 1]){
			timeb[i][3] = ((x[i] - x[i - 1]) * power(v[i] - v[i - 1], md - 2) + 100 * md) % md;
			tmb[i][3] = ld(x[i] - x[i - 1]) / (v[i] - v[i - 1]);
			tmb[i][0] = inf;
		}
		else{
			tmb[i][0] = tmb[i][3] = inf;
		}
	}
	for (int i = 1; i < n; i++){
		if (i%SQ == 0) continue;
		for (int j = 0; j < 4; j++){
			if (tmb[i][j] == inf) continue;
			for (int k = 0; k < 4; k++) b[i/SQ][k].pb({tmb[i][j], 0});
		}
	}

	for (int i = SQ; i < n; i += SQ){
		for (int j = 0; j < 4; j++){
			if (tmb[i][j] == inf) continue;
			ll ehtemal = 1;
			dp[0][0] = p[0][0];
			dp[0][1] = p[0][1];
			for (int k = 1; k <= i - 1; k++){
				dp[k][0] = 0;
				if (tmb[k][0] > tmb[i][j]) dp[k][0] += dp[k - 1][0], dp[k][0] %= md;
				if (tmb[k][2] > tmb[i][j]) dp[k][0] += dp[k - 1][1], dp[k][0] %= md;
				dp[k][0] = (dp[k][0] * p[k][0] + 100 * md) % md;

				dp[k][1] = 0;
				if (tmb[k][1] > tmb[i][j]) dp[k][1] += dp[k - 1][0], dp[k][1] %= md;
				if (tmb[k][3] > tmb[i][j]) dp[k][1] += dp[k - 1][1], dp[k][1] %= md;
				dp[k][1] = (dp[k][1] * p[k][1] + 100 * md) % md;
			}
			if (j < 2) dp[i - 1][1] = 0;
			else dp[i - 1][0] = 0;

			dp[i][0] = dp[i][1] = 0;
			if (j == 0) dp[i][0] = dp[i - 1][0];
			else if (j == 2) dp[i][0] = dp[i - 1][1];
			else if (j == 1) dp[i][1] = dp[i - 1][0];
			else dp[i][1] = dp[i - 1][1];

			if (j%2 == 0) dp[i][0] = (dp[i][0] * p[i][0] + 100 * md) + md;
			else dp[i][1] = (dp[i][1] * p[i][1] + 100 * md) % md;

			for (int k = i + 1; k < n; k++){
				dp[k][0] = 0;
				if (tmb[k][0] >= tmb[i][j]) dp[k][0] += dp[k - 1][0], dp[k][0] %= md;
				if (tmb[k][2] >= tmb[i][j]) dp[k][0] += dp[k - 1][1], dp[k][0] %= md;
				dp[k][0] = (dp[k][0] * p[k][0] + 100 * md) % md;

				dp[k][1] = 0;
				if (tmb[k][1] >= tmb[i][j]) dp[k][1] += dp[k - 1][0], dp[k][1] %= md;
				if (tmb[k][3] >= tmb[i][j]) dp[k][1] += dp[k - 1][1], dp[k][1] %= md;
				dp[k][1] = (dp[k][1] * p[k][1] + 100 * md) % md;
			}
			ehtemal = (dp[n - 1][0] + dp[n - 1][1] + 100 * md) % md;
			ans = (ans + (ehtemal * timeb[i][j] + 100 * md) % md + 100 * md) % md;
		}
	}

	Build();

	for (int i = 1; i < n; i++){
		if (i%SQ == 0) continue;
		for (int j = 0; j < 4; j++){
			if (tmb[i][j] == inf) continue;
			get(i, j);
		}
	}
	cout << ans << endl;

	return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main () {
long n,k,sum[10000],ii=0,pp=0,h,one=0,two=0;
cin>>n>>k;
long *a=new long(n);
//int *l=new int(k);

for(int i=0;i<n;i++)
cin>>a[i];
int b=n/k;

for(int p=0;p<n;p=p+k){
  ii=p;
 // cout<<"here  ";
  //cout<<p<<endl;
for(int i=0;i<n;i++)
{
  // cout<<a[6]<<endl;

//cout<<a[ii]<<" "<<a[i]<<" "<<ii<<" "<<i<<endl;
if(a[ii]==a[i])
sum[pp]++;
if(ii==k-1+p){
ii=p;
}
else
ii++;
}
pp++;}
int s=sum[0];
for(int i=0;i<k;i++)
{
s=max(s,sum[i]);
}
for(int i=0;i<k;i++)
{
if(sum[i]==s){
h=i;
break;}
}
int kk,avg1=0,avg2=0,avg3=0;
h=h*k;
kk=k+h;
int l=h;
for(int i=0;i<n;i++){
if(a[h]!=a[i]){
avg1++;}
if(h==kk-1)
h=l;
else
h++;
if(a[i]==1)
one++;
if(a[i]==2)
two++;
}
if(one>=two)
avg2=n-one;
else
avg2=n-two;
cout<<min(avg1,avg2);
}


#include <iostream>
#include <iterator>
#include <vector>
#include <set>
#include <algorithm>
#include <numeric>

using namespace std;
typedef vector<int> IntV;

template<typename InputIt, typename Size, typename OutputIt>
OutputIt copy_n(InputIt &first /*dirty hack reference - we're adjusting input iterator*/, Size count, OutputIt result)
{
   while (count-- > 0)
   {
      *result++ = *first++;
   }
   return result;
}

template<typename AllLsType>
struct Printer
{
   size_t current;
   const AllLsType &allLs;

   explicit Printer(const AllLsType &i_allLs)
      : current(0U),
        allLs(i_allLs)
   {

   }

   void operator()(const int& i)
   {
      cout << (current ? "\n" : "") << allLs[i - 1];
      ++current;
   }
};

template<typename AllLsType>
Printer<AllLsType> make_printer(const AllLsType& l)
{
   return Printer<AllLsType>(l);
}

int main(int, char*[])
{
   istream_iterator<int> it(cin);
   const int N = *it++;
   const int K = *it++;

   IntV A;
   A.reserve(N);

   copy_n(it, N, back_inserter(A));

   int numOfArrays = N / K;

   int totalChanges = 0;

   for (int i = 0; i < K; ++i)
   {
      int numOf1 = 0;
      int numOf2 = 0;

      for (int j = 0; j < numOfArrays; ++j)
      {
         if (1 == A[i + j*K])
            ++numOf1;
         else
            ++numOf2;
      }

      if ((numOf1 > 0) && (numOf2 > 0))
      {
         totalChanges += min(numOf1, numOf2);
      }
   }

   cout << totalChanges;

   return 0;
}


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

int N, K;
int ar[128];

int main() {
	cin >> N >> K;
	for (int i = 0; i < N; i++) {
		cin >> ar[i];
	}

	int ans = 0;

	for (int i = 0; i < K; i++) {
		map<int, int> appearances;
		// i < N/K
		for (int j = i; j < N; j += K) {
			if (ar[i] != ar[j]) ans++;
			if (ar[i] != ar[j]) ans--;
			appearances[ar[j]] += 1;
		}
		for (int j = i+k; j < K; j += K){
			ans += min(appearances[1], appearances[2]); break;
		}
	}

	cout << ans << endl;
}


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

const int maxn = 200000+10;
int n, k, m;
multiset<int> s; // count 现在可用的车子都停在哪些地方
typedef ll int;
typedef pair<ll, int> pt;
set<pt> v[maxn]; // 记录每个地方等待的出租车
struct node {
    int num; int x;
    ll T;

    bool operator < (const node& x) const {
        return T > x.T;
    }
} ;
priority_queue<node> p;

void POP(ll T) {
    while(!p.empty()) {
        node tmp = p.top();
        if(tmp.T > T) break;

        p.pop();
        s.insert(tmp.x);
        v[tmp.x].insert({tmp.T, tmp.num});
    }
}

int main() {
    scanf("%d%d%d", &n, &k, &m);
    for(int i = 1; i <= k; i++) {
        int loc; scanf("%d", &loc);
        p.push({i, loc, 0});
    }
    int a, b;
    ll T;
    for(int i = 1; i <= m; i++) {

        scanf("%I64d%d%d", &T, &a, &b);
        // puts("!");
        POP(T);
        if(s.empty()) POP((p.top()).T);
        // puts("!");
        auto it = s.lower_bound(a); int dis = INT_MAX;
        int x;
        pt contain;
        if(it != s.end()) {
            x = *it;
            dis = abs(*it - a);
            contain = *v[x].begin();
        }
        if(it != s.begin()) {
            it--; int x2 = *it;
            if(abs(x2 - a) < dis) dis = abs(x2 - a), contain = *v[x2].begin(), x = x2;
            else if(abs(x2 - a) == dis and *v[x2].begin() < contain)  contain = *v[x2].begin(), x = x2;
        }
        // puts("!");
        // printf("%d %I64d\n", dis, contain.first);
        // puts("!");
        printf("%d %I64d\n", contain.second, dis + max(T, contain.first) - T);
        s.erase(s.find(x)); v[x].erase(v[x].begin());
        p.push({contain.second, b, dis + max(T, contain.first) + abs(b - a)});
        // printf("!%d %I64d\n", contain.second, dis + max(T, contain.first) + abs(b - a));
    }
    return 0;
}

/*
10 2 4
1 10
2 1 3
3 10 9
6 5 6
7 6 5
*/
/*
1 0
2 0
1 2
2 3
*/


#include <cstdio>
#include <algorithm>
#include <queue>
#include <set>
using namespace std;

//common reference
int n,K,m;

//define size
#define pli pair<long long,int>
#define N_ 201000
multiset<int> AV;
set<pli> V[N_];

priority_queue<point> PQ;

struct point{
    int num, x;
    long long T;

    bool operator<(const point &p) const{
        return T>p.T;
    }
};

//priority queue (PQ)
void POP(long long T){
    while(!PQ.empty()){
        point tp = PQ.top();
        if(tp.T > T)break;
        PQ.pop();
        AV.insert(tp.x);
        V[tp.x].insert({tp.T, tp.num});
    }
}

int main(){

    int i, x;
    scanf("%d%d%d",&n,&K,&m);

    for(i=1;i<=K;i++){
        scanf("%d",&x);
        PQ.push({i,x,0});
    }

    long long T;
    int a, b;
    for(i=0;i<m;i++){
        scanf("%lld%d%d",&T,&a,&b);
        POP(T);
        if(AV.empty()){
            POP(PQ.top().T);
        }
        auto it = AV.lower_bound(a);
        int M = 1e9, x;
        pli tp;
        if(it != AV.end()){
            x = *it;
            M = abs(x - a);
            tp = *V[x].begin();
        }
        if(it != AV.begin()){
            it--;
            int x2 = *it;
            if(M > abs(x2-a) || (M==abs(x2-a) && *V[x2].begin() < tp))M = abs(x2-a), x = x2, tp = *V[x2].begin();
        }
        printf("%d %lld\n",tp.second, M + max(T, tp.first) - T);
        PQ.push({tp.second, b, M + max(T, tp.first) + abs(b-a)});
        V[x].erase(V[x].begin());
        AV.erase(AV.find(x));
    }

}


#include <cstdio>
#include <algorithm>
#include <queue>
#include <set>
using namespace std;

//common reference
int n,K,m,i,x;
long long T;
int a, b;

//define size
#define pli pair<long long,int>
#define N_ 201000
multiset<int> AV;
set<pli> V[N_];

priority_queue<point> PQ;

struct point{
    int num, x;
    long long T;

    bool operator<(const point &p) const{
        return T>p.T;
    }
};

//priority queue (PQ)
void POP(long long T){
    while(!PQ.empty()){
        point tp = PQ.top();
        if(tp.T > T)break;
        PQ.pop();
        AV.insert(tp.x);
        V[tp.x].insert({tp.T, tp.num});
    }
}

int main(){

    //int i, x;
    scanf("%d%d%d",&n,&K,&m);

    for(i=1;i<=K;i++){
        scanf("%d",&x);
        PQ.push({i,x,0});
    }

    //long long T;
    //int a, b;
    for(i=0;i<m;i++){
        scanf("%lld%d%d",&T,&a,&b);
        POP(T);
        if(AV.empty()){
            POP(PQ.top().T);
        }
        auto it = AV.lower_bound(a);
        int M = 1e9, x;
        pli tp;
        if(it != AV.end()){
            x = *it;
            M = abs(x - a);
            tp = *V[x].begin();
        }
        if(it != AV.begin()){
            it--;
            int x2 = *it;
            if(M > abs(x2-a) || (M==abs(x2-a) && *V[x2].begin() < tp))M = abs(x2-a), x = x2, tp = *V[x2].begin();
        }
        printf("%d %lld\n",tp.second, M + max(T, tp.first) - T);
        PQ.push({tp.second, b, M + max(T, tp.first) + abs(b-a)});
        V[x].erase(V[x].begin());
        AV.erase(AV.find(x));
    }

}


#define _CRT_SECURE_NO_WARNINGS
void Solve(); int main() { Solve(); }
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <iomanip>
#include <queue>
#include <stack>
#include <assert.h>
using namespace std;
#define int long long
#define endl '\n'
#define fib(i, n) for (int i = n; i >= 0; i--)
#define fi(i,a,b) for(int i = (a); i < (b); i++)
#define MAX 1 << 10
#define pii pair<int,int>
#define F first
#define S second
#define pb push_back
#define F first
#define S second
#define pb push_back
#define MOD 1000000007
#define MAXN 100500

typedef long long ll;
int n, k, m;
set<pair<int, int> > q[200002];
set<int> av;
vector<pair<int, int> > ans;
deque<pair<int, pair<int, int> > > waiting;
map<int, pair<vector<pair<int, int>>, vector<pair<int, int>>>> events;

void assign(int i, int t, int a, int b) {
	assert(!av.empty());
	auto it = av.upper_bound(a);
	auto jt = it == av.begin() ? it : prev(it);
	if (it == av.end()) --it;
	int l = *it, r = *jt;
	if (abs(l - a) > abs(r - a)) swap(l, r);
	if (abs(l - a) == abs(r - a) && l != r) {
		if (*q[l].begin() > *q[r].begin()) l = r;
	}
	int driver = q[l].begin()->second;
	int wf = q[l].begin()->first;
	q[l].erase(q[l].begin());
	if (q[l].empty()) av.erase(l);
	int s = max(wf, t);
	ans[i] = { driver, s - t + abs(l - a) };
	events[s + abs(l - a) + abs(b - a)].second.emplace_back(driver, b);
}

void Solve()
{
#ifdef _DEBUG
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif
	for (; cin >> n >> k >> m; ) {
		fi(i, n) q[i].clear();
		av.clear();
		ans.resize(m);
		waiting.clear();
		events.clear();

		fi(i, k) {
			int x;
			cin >> x;
			q[x].emplace(0, i + 1);
			av.insert(x);
		}
		fi(i, m) {
			int t, a, b;
			cin >> t >> a >> b;
			events[t].first.emplace_back(a, b);
		}
		int e = 0;
		for (auto it : events) {
			int t = it.first;
			for (auto jt : it.second.second) {
				int driver = abs(jt.first);
				q[jt.second].emplace(t, driver);
				av.insert(jt.second);
			}
			while (waiting.size() > 0 && av.size() > 0) {
				auto cur = waiting.front();
				waiting.pop_front();
				assign(e++, cur.first, cur.second.first, cur.second.second);
			}
			for (auto jt : it.second.first) {
				if (av.empty()) {
					waiting.emplace_back(t, jt);
				}
				else {
					int a = jt.first, b = jt.second;
					assert(waiting.size() == 0);
					assign(e++, t, a, b);
				}
			}
		}
		assert(waiting.size() == 0);
		for (auto it : ans) cout << it.first << ' ' << it.second << '\n';

}


#include<cstring>
#include<cstdio>

using namespace std;

#define rep(i,a,b) for (int i=(a);i<=(b);i++)
#define per(i,b,a) for (int i=(b);i>=(a);i--)
#define ms(x,y) memset(x,y,sizeof(x))

const int N=605,X=90005,M=200005;

int n,m,p,S,T,nA,nB,ans,du[N],le[X],ri[X],ans[X];
int tot,lnk[N],son[M],w[M],v[M],nxt[M];
int q[N],dst[N],pre[N];
bool bo[N],vis[N];

int read()
{
	int x=0;char ch=getchar();
	while (ch<'0'||ch>'9') ch=getchar();
	while (ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
	return x;
}
void Ifmin(int &x,int y) {if (y<x) x=y;}
void add(int x,int y,int z1,int z2)
{
	tot++;son[tot]=y;w[tot]=z1;v[tot]=z2;nxt[tot]=lnk[x];lnk[x]=tot;
	tot++;son[tot]=x;w[tot]=0;v[tot]=-z2;nxt[tot]=lnk[y];lnk[y]=tot;
}
bool spfa()
{
	rep(i,1,n) bo[i]=vis[i]=0,dst[i]=1e9;
	int hed=0,tal=1;dst[q[1]=S]=0;bo[S]=vis[S]=1;
	while (hed!=tal)
	{
		int x=q[hed=(hed+1)%N];vis[x]=0;
		for (int j=lnk[x];j;j=nxt[j])
		  if (w[j]>0&&dst[x]+v[j]<dst[son[j]])
		  {
		  	dst[son[j]]=dst[x]+v[j];bo[son[j]]=1;pre[son[j]]=j;
		  	if (!vis[son[j]]) vis[q[tal=(tal+1)%N]=son[j]]=1;
		  }
	}
	return bo[T];
}
void getflow()
{
	while (spfa())
	{
		int mn=1e9;for (int x=T;x!=S;x=son[pre[x]^1]) Ifmin(mn,w[pre[x]]);
		for (int x=T;x!=S;x=son[pre[x]^1]) w[pre[x]]-=mn,w[pre[x]^1]+=mn;
	}
}
int main()
{
	nA=read(),nB=read(),m=read(),p=read();
	rep(i,1,m) le[i]=read(),ri[i]=read();
	rep(i,1,m) du[le[i]]++,du[nA+ri[i]]++;
	rep(i,1,nA+nB) if (du[i]%p) ans++;printf("%d\n",ans);
	for (n=nA+nB,S=++n,T=++n;p;p--)
	{
		tot=1;ms(lnk,0);
		rep(i,1,m) if (!ans[i]) add(le[i],nA+ri[i],1,0);
		rep(i,1,nA) {add(S,i,du[i]/p,0);if (du[i]%p) add(S,i,1,1);}
		rep(i,nA+1,nA+nB) {add(i,T,du[i]/p,0);if (du[i]%p) add(i,T,1,1);}
		getflow();int _=0;
		rep(i,1,m) if (!ans[i]) {_+=2;if (!w[_]) ans[i]=p,du[le[i]]--,du[nA+ri[i]]--;}
	}
	rep(i,1,m) printf("%d ",ans[i]);puts("");
	return 0;
}


#include<bits/stdc++.h>
#define ll long long
#define ull unsigned ll
#define uint ungigned
#define db long double
#define pii pair<int,int>
#define IT iterator

#define PB push_back
#define MK make_pair
#define LB lower_bound
#define UB upper_bound
#define fi first
#define se second

#define For(i,j,k) for (int i=(int)(j);i<=(int)(k);i++)
#define Rep(i,j,k) for (int i=(int)(j);i>=(int)(k);i--)
#define UPD(x,y) (((x)+=(y))>=mo?x-=mo:233)
#define CLR(a,v) memset(a,v,sizeof(a));
#define CPY(a,b) memcpy(a,b,sizeof(a));

#define LS3 k*2,l,mid
#define RS3 k*2+1,mid+1,r
#define LS5 k*2,l,mid,x,y
#define RS5 k*2+1,mid+1,r,x,y
#define GET pushdown(k);int mid=(l+r)/2

#define INF ((1<<30)-233)
#define sqr(x) ((x)*(x))
#define debug puts("wzpkking")
using namespace std;

const int M=5555;
const int N=205;

struct edge{
	int to,next,f;
}e[M*10];
int head[M],tot=1;
int q[M],dis[M];
int nd,S,T;
void add(int x,int y,int f){
	e[++tot]=(edge){y,head[x],f};
	head[x]=tot;
	e[++tot]=(edge){x,head[y],0};
	head[y]=tot;
}
bool bfs(){
	For(i,1,nd) dis[i]=-1;
	int h=0,t=1; dis[q[1]=S]=0;
	while (h!=t){
		int x=q[++h];
		for (int i=head[x];i;i=e[i].next)
			if (dis[e[i].to]==-1&&e[i].f){
				dis[e[i].to]=dis[x]+1;
				if (e[i].to==T) return 1;
				q[++t]=e[i].to;
			}
	}
	return 0;
}
int dfs(int x,int flow){
	if (x==T) return flow;
	int k,rest=flow;
	for (int i=head[x];i&&rest;i=e[i].next)
		if (dis[e[i].to]==dis[x]+1&&e[i].f){
			k=dfs(e[i].to,min(rest,e[i].f));
			e[i].f-=k; e[i^1].f+=k; rest-=k;
		}
	if (rest) dis[x]=-1;
	return flow-rest;
}

int n,m,k,s,ans[M];
int sz[2][N],id[2][N];
map<int,int> Id[M];
int main(){
	scanf("%d%d%d%d",&n,&m,&k,&s);
	if (s==1){
	    puts("0");
		For(i,1,k) printf("1 ");
		return 0;
	}
	nd=2; S=1; T=2;
	For(i,1,n) sz[0][i]=s;
	For(i,1,m) sz[1][i]=s;
	For(i,1,k){
		int x,y;
		scanf("%d%d",&x,&y);
		if (sz[0][x]==s){
			sz[0][x]=0;
			id[0][x]=++nd;
			add(S,nd,1);
		}
		sz[0][x]++; x=id[0][x];
		if (sz[1][y]==s){
			sz[1][y]=0;
			id[1][y]=++nd;
			add(nd,T,1);
		}
		sz[1][y]++; y=id[1][y];
		add(x,y,1);
		Id[x][y]=i;
	}

	int ans=0;
	For(i,1,n) ans+=(sz[0][i]!=s);
	For(i,1,m) ans+=(sz[1][i]!=s);
	printf("%d\n",ans);

	For(i,1,s){
		int ans2=0;
		for (;bfs();ans2+=dfs(S,INF));
		For(j,1,nd)
			for (int k=head[j];k;k=e[k].next)
				if (!(k&1)){
					if (j==S||e[k].to==T)
						e[k].f=1,e[k^1].f=0;
					else if (!e[k].f&&e[k^1].f){
						ans[Id[j][e[k].to]]=i;
						e[k^1].f=0;
					}
				}
	}

	For(i,1,k)
		printf("%d ",ans[i]);
}


#include<iostream>
#include<cstdlib>
#include<cstring>
#include<stdio.h>
#include<algorithm>
#include<cmath>
#include<map>
#include<vector>
#include<set>
using namespace std;
const int inf=1e9;
struct fur
{
    int id,day;
    bool operator <(const fur &temp)const
    {
         return day<temp.day;
    }
};
fur ff[222];
int n,m,t,k;
struct pp
{
    int id,c,ie;
};
pp adj[522][522];
int cur[522],gap[522],top;
int e[2][5555];
int ipn[522][522],ans[5555];
int num[522],to[522][522],queue[11111],temp1,temp2,temp,path[11111],flow[11111],pa[11111],re;
bool vis[1222];
int col[522][522],stk[2][11111],dist[11111],deg[522],cq[522][522];
void addedge(int id1,int id2,int c,int ie)
{
    adj[id1][num[id1]].id=id2;
    adj[id1][num[id1]].ie=ie;
    adj[id1][num[id1]].c=c;
    to[id1][num[id1]++]=num[id2];
    adj[id2][num[id2]].id=id1;
    adj[id2][num[id2]].ie=ie;
    adj[id2][num[id2]].c=0;
    to[id2][num[id2]++]=num[id1]-1;
}
bool bfs(int st,int en,int n)
{
    int i,j,s,p,q,id,ip;
    queue[0]=en;
    memset(dist,0,sizeof(dist));
    memset(gap,0,sizeof(gap));
    gap[0]++;
    temp1=temp2=0;
    temp=1;
    while(temp1<=temp2)
    {
        for(i=temp1;i<=temp2;i++)
        {
            id=queue[i];
            for(j=0;j<num[id];j++)
            {
                ip=adj[id][j].id;
                if(dist[ip]==0&&ip!=en)
                {
                    dist[ip]=dist[id]+1;
                    gap[dist[ip]]++;
                    queue[temp++]=ip;
                }
            }
        }
        temp1=temp2+1;
        temp2=temp-1;
    }
}
int max_flow(int st,int en,int n)
{
    int i,j,s,p,q,res=0,id,ip;
    bfs(st,en,n);
    memset(cur,0,sizeof(cur));
    stk[0][0]=st;
    flow[st]=inf;
    top=1;
    while(true)
    {
        id=stk[0][top-1];
        for(i=cur[id];i<num[id];i++)
        {
            ip=adj[id][i].id;
            if(adj[id][i].c>0&&dist[id]==dist[ip]+1)
            {
                cur[id]=i;
                stk[1][top-1]=i;
                stk[0][top]=ip;
                flow[ip]=min(flow[id],adj[id][i].c);
                break;
            }
        }
        if(i<num[id])
        {
            if(ip!=en)
               top++;
            else
            {
                res+=flow[ip];
                for(i=top-1;i>=0;i--)
                {
                    int ie=stk[1][i];
                    id=stk[0][i];
                    adj[id][ie].c-=flow[ip];
                    adj[adj[id][ie].id][to[id][ie]].c+=flow[ip];
                }
                top=1;
            }
        }
        else
        {
            gap[dist[id]]--;
            if(gap[dist[id]]==0)
               return res;
            dist[id]=n;
            cur[id]=0;
            for(i=0;i<num[id];i++)
            {
                ip=adj[id][i].id;
                if(adj[id][i].c>0&&dist[id]>dist[ip]+1)
                {
                    dist[id]=dist[ip]+1;
                    cur[id]=i;
                }
            }
            if(dist[id]<n)
               gap[dist[id]]++;
            if(top>1)
               top--;
        }
        if(dist[st]>=n)
           return res;
    }
}
int main()
{
    int i,j,s,p,q,id1,id2,id,ip,ie;
    bool fir;
    scanf("%d%d%d%d",&n,&m,&k,&t);
    memset(deg,0,sizeof(deg));
    for(i=0;i<k;i++)
    {
        scanf("%d%d",&e[0][i],&e[1][i]);
        e[0][i]--;
        e[1][i]--;
        deg[e[0][i]]++;
        deg[e[1][i]+n]++;
    }
    re=0;
    memset(ans,-1,sizeof(ans));
    for(i=0;i<n+m;i++)
    {
        if(deg[i]%t)
           re++;
    }
    memset(ans,-1,sizeof(ans));
    for(i=0;i<t;i++)
    {
        memset(num,0,sizeof(num));
        int sum=0;
        for(j=0;j<n;j++)
        {
           if(deg[j]/(t-i))
           {
              addedge(0,j+1,(deg[j]/(t-i)),-1);
              addedge(n+m+2,n+m+1,deg[j]/(t-i),-1);
              sum+=deg[j]/(t-i);
           }
        }
        for(j=0;j<m;j++)
        {
            if(deg[j+n]/(t-i))
            {
                addedge(j+n+1,m+n+1,(deg[j+n]/(t-i)),-1);
                addedge(0,n+m+3,deg[j+n]/(t-i),-1);
                sum+=deg[j+n]/(t-i);
            }
        }
        for(j=0;j<k;j++)
        {
            if(ans[j]<0)
                addedge(e[0][j]+1,e[1][j]+n+1,1,j);
        }
        for(j=0;j<n;j++)
        {
            if(deg[j]%(t-i)!=0)
            {
               addedge(n+m+2,j+1,1,-1);
            }
        }
        for(j=0;j<m;j++)
        {
            if(deg[j+n]%(t-i)!=0)
               addedge(j+n+1,n+m+3,1,-1);
        }
        addedge(n+m+3,n+m+2,inf,-1);
        int rs=max_flow(0,n+m+1,n+m+4);
        for(j=0;j<n;j++)
        {
            for(s=0;s<num[j+1];s++)
            {
                if(adj[j+1][s].ie>=0&&adj[j+1][s].c==0)
                {
                    ie=adj[j+1][s].ie;
                 //   printf("ie=%d,i=%d\n",ie,i);
                    deg[e[0][ie]]--;
                    deg[e[1][ie]+n]--;
                    ans[ie]=i+1;
                }
            }
        }
    }
    printf("%d\n",re);
    for(i=0;i<k;i++)
       printf("%d ",ans[i]);
    printf("\n");
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
using lint = long long;
using pi = pair<int, int>;
#define sz(v) ((int)(v).size())
#define all(v) (v).begin(), (v).end()
const int MAXN = 5005;
const int MAXM = 5005;

struct edge_color{ // must use 1-based
	int deg[2][MAXN];
	pi has[2][MAXN][MAXN];
	int color[MAXM];
	int c[2];

	void clear(int n){
		for(int t=0; t<2; t++){
			for(int i=0; i<=n; i++){
				deg[t][i] = 0;
				for(int j=0; j<=n; j++){
					has[t][i][j] = pi(0, 0);
				}
			}
		}
	}

	void dfs(int x, int p) {
		auto i = has[p][x][c[!p]];
		if (has[!p][i.first][c[p]].second) dfs(i.first,!p);
		else has[!p][i.first][c[!p]] = pi(0,0);
		has[p][x][c[p]] = i;
		has[!p][i.first][c[p]] = pi(x,i.second);
		color[i.second] = c[p];
	}

	int solve(vector<pi> v, vector<int> &cv){
		int m = sz(v);
		int ans = 0;
		for (int i=1;i<=m;i++) {
			int x[2];
			x[0] = v[i-1].first;
			x[1] = v[i-1].second;
			for (int d=0;d<2;d++) {
				deg[d][x[d]]+=1;
				ans = max(ans,deg[d][x[d]]);
				for (c[d]=1;has[d][x[d]][c[d]].second;c[d]++);
			}
			if (c[0]!=c[1]) dfs(x[1],1);
			for (int d=0;d<2;d++) has[d][x[d]][c[0]] = pi(x[!d],i);
			color[i] = c[0];
		}
		cv.resize(m);
		for(int i=1; i<=m; i++){
			cv[i-1] = color[i];
			color[i] = 0;
		}
		return ans;
	}
}EC;

int cnt[2][MAXN];
int idx[2][MAXN], L, R;

int main(){
	int m, t;
	scanf("%*d %*d %d %d",&m,&t);
	vector<pi> ans;
	for(int i=0; i<m; i++){
		int l, r; scanf("%d %d",&l,&r);
		if(cnt[0][l] == 0) idx[0][l] = ++L;
		if(cnt[1][r] == 0) idx[1][r] = ++R;
		cnt[0][l]++;
		cnt[1][r]++;
		if(cnt[0][l] == t) cnt[0][l] = 0;
		if(cnt[1][r] == t) cnt[1][r] = 0;
		ans.emplace_back(idx[0][l], idx[1][r]);
	}
	int ret = 0;
	for(int i=0; i<MAXN; i++){
		ret += (cnt[0][i] > 0);
		ret += (cnt[1][i] > 0);
	}
	cout << ret << endl;
	vector<int> color;
	EC.solve(ans, color);
	for(auto &i : color) printf("%d ", i);
}


#include <bits/stdc++.h>
#include <ktl/util/extio.cpp>

using namespace std;

const size_t MAX = 1 << 17;

vector<size_t> graph[MAX];
size_t n, parent[MAX], sz[MAX], depth[MAX];

size_t subtree_size(size_t u, size_t v)
{
    auto re = parent[v] == u ? sz[v] : n - sz[u];
    //cout << u << "-(" << v << " -> " << re << endl;
    return re;
}

void dfs(size_t u)
{
    sz[u] = 1;
    for(auto v : graph[u])
        if(v != parent[u])
            parent[v] = u, depth[v] = depth[u] + 1, dfs(v), sz[u] += sz[v];
}

size_t find_centroid(size_t u)
{
    while(true)
    {
        bool any = false;
        for(auto v : graph[u])
          if(subtree_size(u, v) > subtree_size(v, u))
        {
            u = v;
            any = true;
            break;
        }
        if(not any)
            break;
    }
    return u;
}

void dfs2(size_t u, vector<size_t>& ord)
{
    ord.push_back(u);
    for(auto v : graph[u])
        if(v != parent[u])
            dfs2(v, ord);
}

int main()
{
    cin >> n;

    for(size_t i = 0; i < n - 1; i++)
    {
        size_t u, v;
        cin >> u >> v;
        graph[u].push_back(v);
        graph[v].push_back(u);
    }

    dfs(1);
    auto cen = find_centroid(1);

    fill(parent, parent + MAX, 0);
    fill(sz, sz + MAX, 0);
    fill(depth, depth + MAX, 0);
    dfs(cen);

    vector<vector<size_t>> groups;
    for(auto u : graph[cen])
    {
        vector<size_t> curr;
        dfs2(u, curr);
        groups.push_back(curr);
    }

    vector<size_t> to(n+1);
    size_t last = cen, m = n;

    while(m > 1)
    {
        for(auto& g : groups)
          if(not g.empty())
        {
            to[last] = g.back();
            m--;
            last = g.back();
            g.pop_back();
        }
    }
    to[last] = cen;

    uint64_t result = 0;
    for(size_t u = 1; u <= n; u++)
        result += depth[u] + depth[to[u]];

    cout << result << endl;
    for(size_t u = 1; u <= n; u++)
        cout << to[u] << ' ';
    cout << endl;
}


/*

Code for problem  by cookiedoth
Generated 23 Jul 2020 at 05.35 PM

СТРОИМ КОММУНИЗМ РАБОТЯГИ!

                                    ╦═╩═╦═╩═█
                          ████▄▄▄═╦═╩═╦═╩═╦═█
                  ████████████████▄▄╦═╩═╦═╩═█
█═╦═╩═╦▄████████████████▀▀▀▀█████████▄╦═╩═╦═█
█═╩═╦═████████████████████▄═╦▀█████████═╦═╩═█
█═╦═▄██████████▀╩═╦═╩▄██████▄═╦▀████████▄═╦═█
█═╩═█████████▀╩═╦═╩═█████████▄╩═╦████████═╩═█
█═╦█████████▄═╦═╩═╦═▀█████████╦═╩═████████╦═█
█═╩███████████▄▄██▄═╦═▀████████═╦═████████╩═█
█═██████████████████▄═╦═▀█████▀═╩═█████████═█
█═████████████████████▄═╦═▀███╩═╦═█████████═█
█═╦████████████▀╩▀██████▄═╦═▀═╦═╩█████████╦═█
█═╩█████████▀═╩═╦═╩▀▀███▀▀╩═╦═╩═██████████╩═█
█═╦═██████▀═╦═▄▄█▄▄═╩═╦═╩═╦═╩═╦═╩▀███████═╦═█
█═╩═▀████═╩═▄█████████▄▄▄▄████▄═╦═╩█████▀═╩═█
█═╦═╩═██████████████████████████▄═▄████═╩═╦═█
█═╩═╦═╩▀█████████████████████████████▀╩═╦═╩═█
█═╦═╩═╦═╩▀▀███████████████████████▀▀╩═╦═╩═╦═█
█═╩═╦═╩═╦═╩═▀▀▀███████████████▀▀▀═╩═╦═╩═╦═╩═█
█═╦═╩═╦═╩═╦═╩═╦═╩═▀▀▀▀▀▀▀▀▀═╩═╦═╩═╦═╩═╦═╩═╦═█
█═╩═╦═╩═╦═╩═╦═╩═╦═╩═╦═╩═╦═╩═╦═╩═╦═╩═╦═╩═╦═╩═█
█▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄█

¯\_(ツ)_/¯
^_^
-_-

*/

#include <iostream>
#include <fstream>
#include <vector>
#include <set>
#include <map>
#include <bitset>
#include <algorithm>
#include <iomanip>
#include <cmath>
#include <ctime>
#include <functional>
#include <unordered_set>
#include <unordered_map>
#include <string>
#include <queue>
#include <deque>
#include <stack>
#include <complex>
#include <cassert>
#include <random>
#include <cstring>
#include <numeric>
#define ll long long
#define ld long double
#define null NULL
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
#define debug(a) cerr << #a << " = " << a << endl
#define forn(i, n) for (int i = 0; i < n; ++i)
#define sz(a) (int)a.size()

using namespace std;

template<class T> int chkmax(T &a, T b) {
	if (b > a) {
		a = b;
		return 1;
	}
	return 0;
}

template<class T> int chkmin(T &a, T b) {
	if (b < a) {
		a = b;
		return 1;
	}
	return 0;
}

template<class iterator> void output(iterator begin, iterator end, ostream& out = cerr) {
	while (begin != end) {
		out << (*begin) << " ";
		begin++;
	}
	out << endl;
}

template<class T> void output(T x, ostream& out = cerr) {
	output(x.begin(), x.end(), out);
}

void fast_io() {
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
}

const int INF = 1e9;
const int mx = 1e5 + 228;
int n, sz[mx], d[mx][mx];
vector<vector<int> > g;

void build_d() {
	for (int i = 0; i < n; ++i) {
		for (int j = 0; j < n; ++j) {
			if (i != j) {
				d[i][j] = INF;
			}
		}
	}
	for (int i = 0; i < n; ++i) {
		for (auto v : g[i]) {
			d[i][v] = 1;
		}
	}
	for (int k = 0; k < n; ++k) {
		for (int i = 0; i < n; ++i) {
			for (int j = 0; j < n; ++j) {
				chkmin(d[i][j], d[i][k] + d[k][j]);
			}
		}
	}
}

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

void calc_sz(int v, int pv) {
	sz[v] = 1;
	for (auto v1 : g[v]) {
		if (v1 != pv) {
			calc_sz(v1, v);
			sz[v] += sz[v1];
		}
	}
}

int find_centroid(int v, int pv) {
	for (auto v1 : g[v]) {
		if (v1 != pv && 2 * sz[v1] > n) {
			return find_centroid(v1, v);
		}
	}
	return v;
}

vector<vector<int> > subtrees;

void add_to_last_subtree(int v, int pv) {
	subtrees.back().push_back(v);
	for (auto v1 : g[v]) {
		if (v1 != pv) {
			add_to_last_subtree(v1, v);
		}
	}
}

int c;

void add_subtrees() {
	for (auto v1 : g[c]) {
		subtrees.push_back(vector<int> ());
		add_to_last_subtree(v1, c);
	}
}

set<pair<pair<int, int>, int> > S;

void construct_S() {
	for (int i = 0; i < subtrees.size(); ++i) {
		// int t = (2 * subtrees[i].size() >= n ? INF : subtrees[i].size());
		int t = subtrees[i].size();
		S.insert({{t, t}, i});
	}
	S.insert({{1, 1}, subtrees.size()});
	subtrees.push_back({c});
	// cerr << "subtrees" << endl;
	// for (auto v : subtrees) {
	// 	output(all(v));
	// }
}

vector<int> order;

void process() {
	int lst = -1;
	for (int i = 0; i < n; ++i) {
		auto it = prev(S.end());
		while (it->second == lst) {
			it--;
		}
		auto pp = (*it);
		S.erase(it);
		lst = pp.second;
		order.push_back(subtrees[pp.second].back());
		subtrees[pp.second].pop_back();
		pp.first.first--;
		S.insert(pp);
	}
	// output(all(order));
}

vector<int> p;
ll ans;

void print_ans() {
	p.resize(n);
	calc_sz(c, c);
	for (int i = 0; i < n; ++i) {
		if (i != c) {
			ans += 2 * (ll)sz[i];
		}
	}
	for (int i = 0; i < n; ++i) {
		p[order[i]] = order[(i + 1) % n];
	}
	cout << ans << '\n';
	for (int i = 0; i < n; ++i) {
		cout << p[i] + 1 << ' ';
	}
	cout << '\n';
}

void check_ans() {
	build_d();
	ll real_ans = 0;
	for (int i = 0; i < n; ++i) {
		assert(p[i] != i);
		real_ans += d[i][p[i]];
	}
	assert(ans == real_ans);
}

signed main() {
	fast_io();
	read();
	calc_sz(0, 0);
	c = find_centroid(0, 0);
	// cerr << "c = " << c << endl;
	add_subtrees();
	construct_S();
	process();
	print_ans();
	// check_ans();
}


// Null
#include <bits/stdc++.h>

#define pb push_back
#define F first
#define S second
#define all(x) x.begin(), x.end()
#define debug(x) cerr << #x << " : " << x << '\n'

using namespace std;

typedef long long ll;
typedef long double ld;
typedef string str;
typedef pair<ll, ll> pll;

const ll Mod = 1000000007LL;
const int N = 1e5 + 10;
const ll Inf = 2242545357980376863LL;
const ll Log = 30;

vector<int> G[N];
int n;
ll ans;
int sub[N];

int DFS(ll u, ll p){
	sub[u] = 1;
	for(auto adj : G[u]){
		if(adj == p) continue;
		sub[u] += DFS(adj, u);
	}
	ans += min(sub[u], n - sub[u]);
	return sub[u];
}
vector<int> V;
void dfs(ll u, ll p){
	V.pb(u);
	for(auto adj : G[u]) if(adj != p) dfs(adj, u);
}
int des[N];
int main(){
	ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	cin >> n;
	ll u, v;
	for(int i = 1; i < n; i++){
		cin >> u >> v;
		G[u].pb(v);
		G[v].pb(u);
	}
	DFS(1, -1);
	cout << ans + ans << '\n';

	ll cen = 1;
	bool fnd = false;
	while(!fnd){
		fnd = true;
		for(auto adj : G[cen]){
			if(sub[adj] >= sub[cen]) continue;
			if(sub[adj] + sub[adj] > n){
				fnd = false;
				cen = adj;
				break;
			}
		}
	}
	dfs(cen, -1);
	ll jmp = n/2;
	assert((V.size() == n))
	for(int i = 0; i < n; i++){
		ll idx = (i + jmp) % n;
		des[V[i]] = V[idx];
	}
	for(int i = 1; i <= n; i++) cout << des[i] << ' ';
	cout << '\n';
	return 0;
}


#include <bits/stdc++.h>
#define ll long long
#define F first
#define FF first.first
#define FS first.second
#define S second
#define pb push_back
using namespace std;
const int N=1000006, INF=1e9+1;

ll n, q=1, m, a[N], f[N], o, k, t, x, y, d, Y, z, w, l, r, u, h, mx, mn, ans, Ans[N];
vector<int> v[N], e[N];

void dfs(int x, int pa){
	e.pb(x);
	for (int i=0; i<v[x].size(); i++){
		int y=v[x][i];
		if(y==pa)continue;
		dfs(y, x);
		sz[x]+=sz[y];
	}

}

void DFS(int x, int pa){
	if((sz[x]-1)*2<=n){k=x;return;}
	for (int i=0; i<v[x].size(); i++){
		int y=v[x][i];
		if(y==pa)continue;
		if((sz[y]-1)*2>n)DFS(y, x);
	}
}

main(){ios_base::sync_with_stdio(false), cin.tie(0);
	cin>>n;
	for (int i=1; i<n; i++){
		cin>>x>>y;
		v[x].pb(y);
		v[y].pb(x);
		sz[i]=1;
	}
	dfs(1, 1);
	DFS(1, 1);
	e.clear();Dfs(k, k);

	for (int i=0; i<e.size(); i++)Ans[e[i]]=e[(i+e.size()/2)%e.size()];
	for (int i=1; i<=n; i++)cout<<Ans[i]<<" ";

}


#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int N, R;
double a[51][6000];
int f[50], s[50];
double p[50];
int main(int argc, char *argv[]) {
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	cin >> N >> R;
	for(int i = 0; i < N; i++) {
		cin >> f[i] >> s[i] >> p[i];
		p[i] /= 100;
	}
	double l = 0, pl = -1e9;;
	while(fabs(l - pl) > 1e-10) {
		//cerr << l << '\n';
		pl = l;
		for(int t = 0; t <= 5000; t++)
			a[N][t] = (t <= R ? t : 1e100);
		for(int i = N - 1; i >= 0; i--)
			for(int t = 0; t <= 5000; t++)
				a[i][t] = p[i] * min(t + f[i] + T, a[i + 1][t + f[i]]) + (1 - p[i]) * min(t + s[i] + T, a[i + 1][t + s[i]]);
		l = a[0][0];
	}
	cout << fixed << setprecision(10) << l << endl;
	return 0;
}


#include <iostream>
#include <cmath>
#include <algorithm>
#include <iomanip>
using namespace std;
int N, R;
double a[51][6000];
int f[50], s[50];
double p[50];
int main(int argc, char *argv[]) {
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	cin >> N >> R;
	for(int i = 0; i < N; i++) {
		cin >> f[i] >> s[i] >> p[i];
		p[i] /= 100;
	}
	double T = 0, pT = -1e9;;
	while(fabs(T - pT) / max(1, T) > 1e-10) {
		//cerr << l << '\n';
		pT = T;
		for(int t = 0; t <= 5000; t++)
			a[N][t] = (t <= R ? t : 1e100);
		for(int i = N - 1; i >= 0; i--)
			for(int t = 0; t <= 5000; t++)
				a[i][t] = p[i] * min(t + f[i] + T, a[i + 1][t + f[i]]) + (1 - p[i]) * min(t + s[i] + T, a[i + 1][t + s[i]]);
		T = a[0][0];
	}
	cout << fixed << setprecision(10) << T << endl;
	return 0;
}


using namespace std;
#include<deque>
#include<stdint.h>
#include<set>
#include<stack>
#include <iostream>
#include <algorithm>
#include<cmath>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<vector>
#include<iomanip>
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cstring>
#include<map>
#define sqr(x) (x)*(x)
#define sort stable_sort
#define ll long long
#define mp make_pair
#define pb push_back
#define in insert
#define mtr(x,y,z) mp(mp(x,y),z)
#define fi first
#define se second
#define lch(x) ((x)<<1)
#define rch(x) (((x)<<1)|1)
#define all(x) (x).begin(),(x).end()
#define fpi(x) freopen(x,"r",stdin);
#define fpo(x) freopen(x,"w",stdout);
#define fprio fpi("in.txt");fpo("out.txt"):
#define fast ios::sync_with_stdio(false);
void readi(int &x)
{
	int v=0,f=1;
	char c=getchar();
	while (!isdigit(c)&&c!='-') c=getchar();
	if (c=='-') f=-1; else v=v*10+c-'0';
	while (isdigit(c=getchar())) v=v*10+c-'0';
	x=v*f;
}
void readll(ll &x)
{
	ll v=0ll,f=1ll;
	char c=getchar();
	while (!isdigit(c)&&c!='-') c=getchar();
	if (c=='-') f=-1; else v=v*10+c-'0';
	while (isdigit(c=getchar())) v=v*10+c-'0';
	x=v*f;
}
void readc(char &x)
{
	char c;
	while ((c=getchar())==' ');
	x=c;
}
void writes(string s){puts(s.c_str());}
void writeln(){writes("");}
void writei(int x)
{
	if (!x) putchar('0');
	char a[25];
	int top=0;
	while (x)
	{
		a[++top]=(x%10)+'0';
		x/=10;
	}
	while (top)
	{
		putchar(a[top]);
		top--;
	}
}
void writell(ll x)
{
	if (!x) putchar('0');
	char a[25];
	int top=0;
	while (x)
	{
		a[++top]=(x%10)+'0';
		x/=10;
	}
	while (top)
	{
		putchar(a[top]);
		top--;
	}
}
/*************************************************/
int n,m,i,j,mid,s[55],t[55];
double p[55],l,r,dp[55][5555];
int main()
{
	cin>>n>>m;
	for (i=1;i<=n;i++)
	{
		cin>>s[i]>>t[i]>>p[i];
		p[i]/=100.0;
	}
	l=0;r=1e16;
	while (l<r)
	{
		mid=(l+r)/2;
		for (i=m+1;i<=5000;i++)
		{
			dp[n+1][j]=1e200;
		}
		for (i=n;i;i--)
		{
			for (j=0;j<=(i-1)*100;j++)
			{
				 dp[i][j]=(s[i]+dp[i+1][j+s[i]])*p[i]+(t[i]+min(dp[i+1][j+t[i]],mid))*(1-p[i]);
			}
		}
		if (dp[1][0]<mid) l=mid;
			else r=mid;
	}
	cout<<(l+r)/2;
	return 0;
}


#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int N, R;
double a[51][6000];
int f[50], s[50];
double p[50];
int main(int argc, char *argv[]) {
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	cin >> N >> R;
	for(int i = 0; i < N; i++) {
		cin >> f[i] >> s[i] >> p[i];
		p[i] /= 100;
	}
	double T = 0, pT = -1e9;;
	while(fabs(l - pl) > 1e-10) {
		//cerr << l << '\n';
		pT = T;
		for(int t = 0; t <= 5000; t++)
			a[N][t] = (t <= R ? t : 1e100);
		for(int i = N - 1; i >= 0; i--)
			for(int t = 0; t <= 5000; t++)
				a[i][t] = p[i] * min(t + f[i] + T, a[i + 1][t + f[i]]) + (1 - p[i]) * min(t + s[i] + T, a[i + 1][t + s[i]]);
		T = a[0][0];
	}
	cout << fixed << setprecision(10) << T << endl;
	return 0;
}


#include <bits/stdc++.h>

using namespace std;

typedef long long coord;

struct vec{
	coord x, y; int id;
	vec(coord a = 0, coord b = 0) : x(a), y(b) {}
	vec operator+(const vec &o) const{
		return {x + o.x, y + o.y};
	}
    vec operator-(const vec &o) const{
        return {x - o.x, y - o.y};
    }
    coord operator*(const vec &o) const{
        return x * o.x + y * o.y;
    }
	coord operator^(const vec &o) const{ // sin
		return x * o.y - y * o.x;
	}
	bool operator<(const vec &o) const{
		if(x != o.x) return x < o.x;
		return y < o.y;
	}
	coord cross(const vec &a, const vec &b) const{
		return (a-(*this)) ^ (b-(*this));
	}
    coord dot(const vec &a, const vec &b) const{
        return (a-(*this)) * (b - (*this));
    }
    int ccw(const vec &a, const vec &b) const{
        coord tmp = cross(a, b);
        return (tmp > 0) - (tmp < 0);
    }
};

const int N = 1000006;

vector<vec> mk(const vector<vec>&a,const vector<vec>&b){
    int i = 0, j = 0;
    for(int k = 0; k < (int)a.size(); k++)if(a[k] <a[i])
        i = k;
    for(int i = 0; i < (int)b.size(); i++)if(b[k] <b[j])
        j = k;

    vector<vec> c;
    c.reserve(a.size() + b.size());
    vec pt;
    for(int k = 0; k < int(a.size()+b.size()); k++){
        pt = a[i] + b[j];
        if((int)c.size() >= 2
            && c[c.size()-2].ccw(c.back(), pt) == 0)
            c.pop_back();
        c.push_back(pt);
        int q = i+1, w = j+1;
        if(q == int(a.size())) q = 0;
        if(w == int(b.size())) w = 0;
        if(c.back().ccw(a[i]+b[w], a[q]+b[j]) == -1) i = q;
        else j = w;
    }
    c.shrink_to_fit();

    return c;
}

vec lo[N], hi[N];
int nl, nh;

bool below(vec p){
    auto it = lower_bound(hi, hi+nh, p);
    if(it == hi) return p.x == hi[0].x && p.y == hi[0].y;
    if(it == hi+nh) return false;
    return prev(it)->cross(*it, p) <= 0;
}

bool above(vec p){
    auto it = lower_bound(lo, lo+nl, p);
    if(it == lo) return p.x == lo[0].x && p.y == lo[0].y;
    if(it == lo+nl) return false;
    return prev(it)->cross(*it, p) >= 0;
}

bool inside(vec p){
    return below(p) && above(p);
}

bool inside(const vector<vec> &v, vec p){
    if(v[0].ccw(v[1], p) < 0) return false;
    if(v[0].ccw(v.back(), p) > 0) return 0;
    if(v[0].ccw(v.back(), p) == 0){
        // return v[0].dot(p, v.back()) >= 0 && v.back().dot(p, v[0]) >= 0;
    }

    int L = 1, R = (int)v.size() - 1, ans = 1;

    while(L <= R){
        int mid = (L+R)/2;
        if(v[0].ccw(v[mid], p) >= 0) ans = mid, L = mid+1;
        else R = mid-1;
    }

    return v[ans].ccw(v[(ans+1)%v.size()], p) >= 0;
}

int main(){

    vector<vec> a, b;
    int n, m;
    scanf("%d", &n);
    a.resize(n);

    for(int i = 0; i < n; i++)
        scanf("%lld %lld", &a[i].x, &a[i].y);

    /*for(int i = 0; i < sz; i++)
        printf("%lld %lld\n", a[i].x, a[i].y);
    printf("\n");
    printf("\n");*/
    scanf("%d", &m);
    b.resize(m);
    for(int i = 0; i < m; i++)
        scanf("%lld %lld", &b[i].x, &b[i].y);
    a = mink(a, b);

    scanf("%d", &m);
    b.resize(m);
    for(int i = 0; i < m; i++)
        scanf("%lld %lld", &b[i].x, &b[i].y);
    a = mink(a, b);
    n = (int)a.size();

    /*for(int i = 0; i < sz; i++)
        printf("%lld %lld\n", a[i].x, a[i].y);

    printf("\n");
    printf("\n");*/

    {
        int w = 0, e = 0;
        for(int i = 0; i < n; i++){
            if(a[i] < a[w]) w = i;
            if(a[e] < a[i]) e = i;
        }

        for(int i = w; ; i++){
            if(i == n) i = 0;
            lo[nl++] = a[i];
            if(i == e) break;
        }
        for(int i = e; ; i++){
            if(i == n) i = 0;
            hi[nh++] = a[i];
            if(i == w) break;
        }
        reverse(hi, hi+nh);
    }

    // for(auto x : a) printf("%lld %lld\n", x.x, x.y);

    /*for(int i = 0; i < nl; i++)
        printf("%lld %lld\n", lo[i].x, lo[i].y);

    printf("\n");
    printf("\n");

    for(int i = 0; i < nh; i++)
        printf("%lld %lld\n", hi[i].x, hi[i].y);

    printf("\n");
    printf("\n");*/

    int q;

    scanf("%d", &q);
    vec v;

    while(q--){
        scanf("%lld %lld", &v.x, &v.y);
        v.x *= 3;
        v.y *= 3;
        printf("%s\n", inside(v) ? "YES" : "NO");
    }

}


#include <map>
#include <set>
#include <cmath>
#include <stack>
#include <queue>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
#define li		long long
#define rep(i,to)	for(li i=0;i<((li)to);i++)
#define pb		push_back
#define sz(v)		((li)v.size())

#define P pair<li,li>
vector< P > con[3];
vector< P > sum;
int main(){
	rep(i,3){
		li n;
		cin>>n;
		rep(j,n){
			li x,y;
			cin>>x>>y;
			con[i].pb(make_pair(x,y));
		}
	}
	li pos[3]={1,1,1};
	li start[3]={1,1,1};
	rep(i,3)rep(j,sz(con[i]))if(con[i][start[i]]<con[i][j]) pos[i]=start[i]=j;
#define x(a,b) (con[a][b].first)
#define y(a,b) (con[a][b].second)
	li sum_x=0;
	li sum_y=0;
	bool f[3]={true,true,true};
	while(pos[0]!=start[0]||pos[1]!=start[1]||pos[2]!=start[2]||f[0]||f[1]||f[2]){
		double ang[3]={0,0,0};
		li next[3]={(pos[0]+1)%sz(con[0]),(pos[1]+1)%sz(con[1]),(pos[2]+1)%sz(con[2])};
		rep(i,3){
			double xx=x(i,next[i])-x(i,pos[i]);
			double yy=y(i,next[i])-y(i,pos[i]);
			ang[i]=(yy==0)?(acos(-1)/2.0):acos(yy/hypot(xx,yy));
			if(0<xx) ang[i]=acos(-1)*2.0-ang[i];
			if(ang[i]==0) ang[i]=acos(-1)*2.0;
			if(pos[i]==start[i] && !f[i]) ang[i]=365;
		}
		li mini=0;
		rep(i,3)if(ang[i]<ang[mini]) mini=i;
		pos[mini]=next[mini];
		f[mini]=false;
		sum_x=sum_y=0;
		rep(i,3) sum_x+=x(i,pos[i]);
		rep(i,3) sum_y+=y(i,pos[i]);
		sum.pb(make_pair(sum_x,sum_y));
	}

	vector< P > low,high;
	li mini=0,maxi=0;
	li mini_y[2],maxi_y[2];
	rep(i,sz(sum))if(sum[i]<sum[mini]) mini=i;
	rep(i,sz(sum))if(sum[maxi]<sum[i]) maxi=i;
	for(int i=mini;i!=maxi;i=(i+1)%sz(sum))	low.pb(sum[i]);
	for(int i=mini;i!=maxi;i=(i+sz(sum)-1)%sz(sum)) high.pb(sum[i]);
	low.pb(sum[maxi]);
	high.pb(sum[maxi]);
	rep(i,2) mini_y[i]=sum[mini].second;
	rep(i,2) maxi_y[i]=sum[maxi].second;
	rep(i,sz(sum))if(sum[i].first==sum[mini].first){
		mini_y[0]=min(mini_y[0],sum[i].second);
		mini_y[1]=max(mini_y[1],sum[i].second);
	}
	rep(i,sz(sum))if(sum[i].first==sum[maxi].first){
		maxi_y[0]=min(maxi_y[0],sum[i].second);
		maxi_y[1]=max(maxi_y[1],sum[i].second);
	}
	li n;
	cin>>n;
	rep(i,n){
		li xx,yy;
		cin>>xx>>yy;
		xx*=3;
		yy*=3;
		if(xx==sum[maxi].first){
			if(maxi_y[0]<=yy && yy<=maxi_y[1]) cout<<"YES"<<endl;
			else cout<<"NO"<<endl;
		}else if(xx==sum[mini].first){
			if(mini_y[0]<=yy && yy<=mini_y[1]) cout<<"YES"<<endl;
			else cout<<"NO"<<endl;
		}else if(sum[mini]<xx && xx<sum[maxi]){
			vector< P >::iterator lp0=upper_bound(low.begin(),low.end(),make_pair(xx,yy));
			vector< P >::iterator hp0=upper_bound(high.begin(),high.end(),make_pair(xx,yy));
			vector< P >::iterator lp1=lp0--;
			vector< P >::iterator hp1=hp0--;
			if(xx*(lp1->second-lp0->second)<=yy*(lp1->first-lp0->first)
			&& yy*(hp1->first-hp0->first)<=xx*(hp1->second-hp0->second)){
				cout<<"YES"<<endl;
			}else{
				cout<<"NO"<<endl;
			}
		}else{
			cout<<"NO"<<endl;
		}
	}
}


#include <cstdio>
#include <algorithm>
using namespace std;

#define N 100005
#define LL long long

struct Point {
    LL x, y;
    Point(LL x = 0, LL y = 0):x(x), y(y) {}
    bool operator < (const Point & b) const {
        if (y != b.y) return y < b.y;
        return x < b.x;
    }
    Point operator + (const Point & b) {
        return Point(x + b.x, y + b.y);
    }
    Point operator - (const Point & b) {
        return Point(x - b.x, y - b.y);
    }
};

int n;
int sz[N], st[3];
Point p[3][N], v[3][N], a[N*3], b[N*3], o, ta[N*3];

inline int sta(const Point & a) {
	return a.y > 0 || (a.y == 0 && a.x >= 0);
}

bool cmp(const Point & a, const Point & b) {
	int s1 = sta(a), s2 = sta(b);
	if (s1 != s2) return s1 > s2;
    return a.x * b.y - a.y * b.x > 0;
}

inline LL cross(const Point & a, const Point & b) {
    return a.x * b.y - a.y * b.x;
}

inline LL len(const Point & a) {
    return a.x * a.x + a.y * a.y;
}

bool gao(Point v) {
    if (v < o) return 0;
    v = v - o;
    int l = 0, r = n-1;
    while (l <= r) {
        int mid = (l + r) >> 1;
        if (cross(a[mid], v) >= 0) l = mid + 1;
        else r = mid - 1;
    }
    --l;
    if (l == n-1)
        return  cross(v, a[l]) == 0 && len(v) <= len(a[l]);
    return cross(a[l+1] - a[l], v - a[l]) >= 0;
}

int main() {
//	freopen("data.in", "r", stdin);
//	freopen("E.out", "w", stdout);
//	freopen("newdata", "r", stdin);
    n = 0;
    o = Point(0, 0);
    for (int i = 0; i < 3; ++i) {
        scanf("%d", &sz[i]);
        for (int j = 0; j < sz[i]; ++j)
            scanf("%I64d %I64d", &p[i][j].x, &p[i][j].y);
        p[i][ sz[i] ] = p[i][0];
        for (int j = 0; j < sz[i]; ++j)
            b[n++] = v[i][j] = p[i][j+1] - p[i][j];
        st[i] = 0;
        for (int j = 1; j < sz[i]; ++j)
            if (p[i][j] < p[i][ st[i] ])
                st[i] = j;
        o = o + p[i][ st[i] ];
    }
/*
    sort(b, b + n, cmp);
    int k = 0;
    for (int i = 0; i < n; ++i) {
    	int j;
    	for (j = i + 1; j < n && cross(b[i], b[j]) == 0; ++j);
    	b[k] = b[i];
    	for (int e = i + 1; e < j; ++e)
    		b[k] = b[k] + b[e];
    	++k;
    	i = j - 1;
    }
    n = k;
    for (int i = 1; i <= n; ++i)
    	a[i] = a[i-1] + b[i-1];*/
    /*
    a[0] = Point(0, 0);
    for (int cc = 0; cc < n; ++cc) {
        int k = -1;
        for (int i = 0; i < 3; ++i)
        	if (0 == cc) {
        		if (-1 == k || cross(v[i][ st[i] ], v[k][ st[k] ]) > 0)
        			k = i;
        	} else if (cross(a[cc] - a[cc-1], v[i][ st[i] ]) >= 0) {
        		if (-1 == k || cross(v[i][ st[i] ], v[k][ st[k] ]) > 0)
        			k = i;
        	}
        a[cc+1] = a[cc] + v[k][ st[k] ];
        ++st[k];
        if (st[k] == sz[k]) st[k] = 0;
    }*/
    /*
    printf("o %lld, %lld\n", o.x, o.y);
    for (int i = 0; i <= n; ++i)
    	printf(" %lld, %lld\n", a[i].x, a[i].y);
    */
    for (int cc = 0; cc < n; ++cc) {
        int k = 0;
        for (int i = 1; i < 3; ++i)
        	if (cross(v[i][ st[i] ], v[k][ st[k] ]) > 0)
        		k = i;
        b[cc] = v[k][ st[k] ];
        ++st[k];
        if (st[k] == sz[k]) st[k] = 0;
    }
    for (int i = 0; i < n; ++i) {
    	int j;
    	for (j = i + 1; j < n && cross(b[i], b[j]) == 0; ++j);
    	b[k] = b[i];
    	for (int e = i + 1; e < j; ++e)
    		b[k] = b[k] + b[e];
    	++k;
    	i = j - 1;
    }
    n = k;
    for (int i = 1; i <= n; ++i)
    	a[i] = a[i-1] + b[i-1];
    /*
    for (int i = 0; i < n; ++i) printf(" %3lld,%3lld", a[i].x, a[i].y); puts("");
    for (int i = 0; i < n; ++i) printf(" %3lld,%3lld", ta[i].x, ta[i].y); puts("");
    */

    int m;
    scanf("%d", &m);
    while (m--) {
        Point v;
        scanf("%I64d %I64d", &v.x, &v.y);
        v.x *= 3; v.y *= 3;
        puts( gao(v) ? "YES" : "NO" );
    }
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

typedef long long coord;

struct vec{
	coord x, y; int id;
	vec(coord a = 0, coord b = 0) : x(a), y(b) {}
	vec operator+(const vec &o) const{
		return {x + o.x, y + o.y};
	}
    vec operator-(const vec &o) const{
        return {x - o.x, y - o.y};
    }
	coord operator^(const vec &o) const{ // sin
		return x * o.y - y * o.x;
	}
	bool operator<(const vec &o) const{
		if(x != o.x) return x < o.x;
		return y < o.y;
	}
	coord cross(const vec &a, const vec &b) const{
		return (a-(*this)) ^ (b-(*this));
	}
    int ccw(const vec &a, const vec &b) const{
        coord tmp = cross(a, b);
        return (tmp > 0) - (tmp < 0);
    }
};

const int N = 1000006;

vec a[N], b[N], c[N];
int sz, szb;

void mink(){
    int q = 0, w = 0;
    for(int i = 0; i < sz; i++) if(a[i] < a[q]) q = i;
    for(int i = 0; i <szb; i++) if(b[i] < b[w]) w = i;

    for(int i = 0; i < sz + szb; i++){
        c[i] = a[q] + b[w];
        int qq = q+1, ww = w+1;
        if(qq == sz) qq = 0;
        if(ww ==szb) ww = 0;
        if(c[i].ccw(a[q]+b[ww], a[qq]+b[w]) == -1)
            q = qq;
        else w = ww;
    }

    for(int i = 0; i < sz + szb; i++) a[i] = c[i];
    sz += szb;
}

vec lo[N], hi[N];
int nl, nh;

bool below(vec p){
    auto it = lower_bound(hi, hi+nh, p);
    if(it == hi) return p.x == hi[0].x && py <= hi[0].y;
    return prev(it)->cross(*it, p) <= 0;
}

bool above(vec p){
    auto it = lower_bound(lo, lo+nl, p);
    if(it == lo) return p.x == lo[0].x && p.y >= lo[0].y;
    return prev(it)->cross(*it, p) >= 0;
}

bool inside(vec p){
    return below(p) && above(p);
}

int main(){

    scanf("%d", &sz);

    for(int i = 0; i < sz; i++)
        scanf("%lld %lld", &a[i].x, &a[i].y);

    /*for(int i = 0; i < sz; i++)
        printf("%lld %lld\n", a[i].x, a[i].y);
    printf("\n");
    printf("\n");*/
    scanf("%d", &szb);
    for(int i = 0; i < szb; i++)
        scanf("%lld %lld", &b[i].x, &b[i].y);
    mink();

    scanf("%d", &szb);
    for(int i = 0; i < szb; i++)
        scanf("%lld %lld", &b[i].x, &b[i].y);

    mink();

    /*for(int i = 0; i < sz; i++)
        printf("%lld %lld\n", a[i].x, a[i].y);

    printf("\n");
    printf("\n");*/

    {
        int w = 0, e = 0;
        for(int i = 0; i < sz; i++){
            if(a[i] < a[w]) w = i;
            if(a[e] < a[i]) e = i;
        }

        // printf("@ %d %d\n", w, e);

        for(int i = w; ; i++){
            if(i == sz) i = 0;
            lo[nl++] = a[i];
            if(i == e) break;
        }
        for(int i = e; ; i++){
            if(i == sz) i = 0;
            hi[nh++] = a[i];
            if(i == w) break;
        }
        reverse(hi, hi+nh);
    }

    /*for(int i = 0; i < nl; i++)
        printf("%lld %lld\n", lo[i].x, lo[i].y);

    printf("\n");
    printf("\n");

    for(int i = 0; i < nh; i++)
        printf("%lld %lld\n", hi[i].x, hi[i].y);

    printf("\n");
    printf("\n");*/

    int m;

    scanf("%d", &m);
    vec v;

    while(m--){
        scanf("%lld %lld", &v.x, &v.y);
        v.x *= 3;
        v.y *= 3;
        printf("%s\n", inside(v) ? "YES" : "NO");
    }

}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <map>
#include <set>
#include <vector>
#include <queue>

#pragma warning(disable: 4996)

#define INF 1LL<<60

using namespace std;

int n, m, k;
vector<__int64> customK;
__int64 h;
__int64 a[100009];
int c[100009];
bool aVisited[100009];
//map<__int64, int> posToIndex;
map<int, set<__int64>> costToPos;
__int64 D[1009];

void pe()
{
  printf("wtf\n");
  exit(0);
}

void ReadData()
{
  //posToIndex.clear();
  customK.clear();
  costToPos.clear();
  memset(aVisited, 0, sizeof(aVisited));
  scanf("%I64d %d %d %d", &h, &n, &m, &k);
  customK.push_back(k);
  for(int i = 0; i < n; i++)
  {
    scanf("%I64d %d", &a[i], &c[i]);
    //posToIndex[a[i]] = i;
    if(((a[i] - 1) % k) == 0)
    {
      aVisited[i] = true;
      costToPos[c[i]].insert(a[i]);
    }
  }
  for(int i = 0; i < k; i++)
  {
    D[i] = INF;
  }
  D[1 % k] = 1LL;
}

void Operation_1()
{
  __int64 val;
  scanf("%I64d", &val);
  customK.push_back(val);
  set<pair<__int64, int>> pq;
  pq.insert(make_pair(D[1 % k], 1 % k));
  while(!pq.empty())
  {
    pair<__int64, int> current = *pq.begin();
    pq.erase(pq.begin());
    for(vector<__int64>::iterator it = customK.begin(); it != customK.end(); it++)
    {
      __int64 nxt = (current.first + *it) % k;
      if(D[nxt] > current.first + *it)
      {
        pq.erase(make_pair(D[nxt], (int)nxt));
        D[nxt] = current.first + *it;
        pq.insert(make_pair(D[nxt], (int)nxt));
      }
    }
  }
  for(int i = 0; i < n; i++)
  {
    if(aVisited[i])
    {
      continue;
    }
    if(D[a[i] % k] <= a[i])
    {
      aVisited[i] = true;
      costToPos[c[i]].insert(a[i]);
    }
  }
}

void Operation_2()
{
  int ind, cost;
  scanf("%d %d", &ind, &cost);
  if(cost == 0)
  {
    return;
  }
  ind--;
  if(aVisited[ind])
  {
    int newVal = c[ind] - cost;
    if(costToPos[c[ind]].size() == 1)
    {
      costToPos.erase(c[ind]);
    }
    else
    {
      costToPos[c[ind]].erase(a[ind]);
    }
    c[ind] = newVal;
    costToPos[c[ind]].insert(a[ind]);
  }
  else
  {
    c[ind] -= cost;
  }
}

void Operation_3()
{
  if(costToPos.empty())
  {
    printf("0\n");
    return;
  }
  map<int, set<__int64>>::iterator it = costToPos.end();
  it--;
  printf("%d\n", it->first);
  if(it->second.size() == 1)
  {
    costToPos.erase(it);
  }
  else
  {
    it->second.erase(it->second.begin());
  }
}

void Solve()
{
  for(int i = 0; i < m; i++)
  {
    int operationType;
    scanf("%d", &operationType);
    switch(operationType)
    {
      case 1:
        Operation_1();
        break;
      case 2:
        Operation_2();
        break;
      case 3:
        Operation_3();
        break;
      default:
        pe();
    }
  }
}

void WriteData()
{
  printf("\n");
}

int main()
{
  int QWE = 1;
#ifndef ONLINE_JUDGE
  freopen("input.txt", "r", stdin);
  scanf("%d", &QWE);
#endif
  for(int T = 0; T < QWE; T++)
  {
    ReadData();
    Solve();
    WriteData();
  }
  return 0;
}


#include <vector>
#include <iterator>
#include <map>
#include <unordered_map>
#include <set>
#include <deque>
#include <queue>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <string>
using namespace std;
int bitct(long long r) {return r == 0 ? 0 : (bitct(r>>1) + (r&1));}
long long gcd(long long x, long long y) {return x ? gcd(y%x,x) : y;}
template<typename T> ostream& operator << (ostream &o,vector<T> v) {o<<"{";
	int i=0,s=v.size();for(;i+1<s;i++)o<<v[i]<<", ";if(s)o<<v[i];o<<"}";return o;}
  /*jj
template<typename K, typename V> ostream& operator << (ostream &o,
  unordered_map<K, V> m) {o<<"{";for(auto i=m.begin();i!=m.end();++i)
  o<<i->first<<" -> "<< i->second << ", "; o<<"}";return o;}
  */
long long choose(long long n, long long q)
{ if(n==0 || q==0) return 1;
	if (q==1) return n; else return ( choose(n, q-1) * (n-q+1 ) /q); }
int dx[4] = {1,0,-1,0};
int dy[4] = {0,1,0,-1};

main() {
  long long h;
  cin >> h;
  :wq

	int N;
	cin >> N;
  int ct=0;
  for(int i=1;i<=N;i++)
    for(int j=i;j<=N;j++)
      {
      int c2 = i*i+j*j;
      double c2d = sqrt(c2);
      int test=(int) (c2d + 0.0001);
      if(test*test==c2 && test <= N)
        {
        ct++;
        }
      }
			cout << ct << endl;

}


#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <cstddef>
#include <complex>
#include <ctime>
#include <climits>

#include <algorithm>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <vector>
#include <deque>
#include <list>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <bitset>
#include <string>
#include <numeric>
#include <functional>
#include <iterator>
#include <typeinfo>
#include <utility>
#include <memory>

#include <cassert>

#if __cplusplus >= 201103L
#include <tuple>
#include <ratio>
#include <array>
#include <forward_list>
#include <unordered_map>
#include <unordered_set>
#endif
using namespace std;

typedef long long int64;
const int inf = 2000000000;
static inline int Rint()
{
	struct X{ int dig[256]; X(){
	for(int i = '0'; i <= '9'; ++i) dig[i] = 1; dig['-'] = 1;
	}};
	static 	X fuck;int s = 1, v = 0, c;
	for (;!fuck.dig[c = getchar()];);
	if (c == '-') s = 0; else if (fuck.dig[c]) v = c ^ 48;
	for (;fuck.dig[c = getchar()]; v = v * 10 + (c ^ 48));
	return s ? v : -v;
}
typedef vector<int> vi;
typedef map<int, int> mii;
typedef set<int> si;

#define all(x) (x).begin(), (x).end()
#define pb push_back
#define mp make_pair
#define sz(x) ((int)(x).size())
#define rep(i, s, e) for (int i = (s); i < (e); ++i)

#if __cplusplus >= 201103L
#define foreach(iter, c) for(auto& iter : c)
#else
#define foreach(itr, c) for(__typeof((c).begin()) itr = (c).begin(); itr != (c).end(); ++itr)
#endif

template<typename T> static inline void cmax(T& a, const T& b){if(b>a)a=b;}
template<typename T> static inline void cmin(T& a, const T& b){if(b<a)a=b;}
#define SL static inline

#define dbg(x) cerr << (#x) << " = " << (x) << endl

const int maxn = 100005;
int64 h;
int n, m, k;

int64 pos[maxn];
int treasure[maxn];
int flag[maxn];

int64 D[10005];

int64 allk[32];
int top;

struct Pt
{
	int64 t, p, id;
	int operator < (const Pt& o) const
	{
		if (t != o.t) return t < o.t;
		if (p != o.p) return p > o.p;
		return id < o.id;
	}
};

void fix(priority_queue<Pt>& pq)
{
	set<pair<int64, int> > st;

	for (int i = 0; i < k; ++i)
	if (D[i] != -1)
	st.insert({D[i], i});

	while (!st.empty())
	{
		auto where = st.begin();
		auto curr = *where;
		st.erase(where);
		if (D[curr.second] != curr.first) continue;
		for (int i = 0; i < top; ++i)
		{
			int64 val = curr.first
			for (int coe = 0; coe < 3; ++coe)
			{
				val += allk[i];
				if (val > h) continue;

				int next = val % k;

				if (next == curr.second)
				{
					continue;
				}

				if (D[next] == -1)
				{
					D[next] = val;
					st.insert({D[next], next});
				}
				else if (D[next] > val)
				{
					D[next] = val;
					st.insert({D[next], next});
				}
			}
		}
	}

	for (int i = 1; i <= n; ++i) if (flag[i] == 0)
	{
		const int bucket = pos[i] % k;
		if (D[bucket] != -1)
		{
			if (pos[i] >= D[bucket])
			{
				pq.push({treasure[i], pos[i], i});
				flag[i] = 1;
			}
		}
	}
}

int main()
{
	scanf("%I64d", &h);
	n = Rint(), m = Rint(), k = Rint();

	for (int i = 1; i <= n; ++i)
	scanf("%I64d %d", pos+i, treasure+i);

	memset(D, -1, sizeof D);
	D[1%k] = 1;

	priority_queue<Pt> pq;

	for (int i = 1; i <= n; ++i)
	{
		const int bucket = pos[i] % k;
		if (D[bucket] != -1)
		{
			if (pos[i] >= D[bucket])
			{
				pq.push({treasure[i], pos[i], i});
				flag[i] = 1;
			}
		}
	}

	for (int id = 0; id < m; ++id)
	{
		const int cmd = Rint();
		if (cmd == 3)
		{
			while (!pq.empty())
			{
				auto curr = pq.top();
				if (treasure[curr.id] != curr.t)
				{
					pq.pop();
				}
				else
				{
					break;
				}
			}
			int64 ans = 0;
			if (!pq.empty())
			{
				ans = pq.top().t;
				treasure[pq.top().id] = -1;
				flag[pq.top().id] = 2;
				//dbg(pq.top().id);
				//dbg(pq.top().p);
				pq.pop();
			}
			printf("%I64d\n", ans);
		}
		else if (cmd == 2)
		{
			const int x = Rint();
			const int c = Rint();
			treasure[x] -= c;
			if (c != 0 && flag[x])
			{
				//assert(flag[x] == 1);
				if (flag[x] == 1)
				{
					pq.push({treasure[x], pos[x], x});
				}
			}
		}
		else
		{
			int64 x; scanf("%I64d", &x);
			int ok = 1;
			//for (int i = 0; i < top; ++i)
			//if (x % allk[i] == 0) ok = 0;
			//if (x % k == 0) ok = 0;
			if (ok)
			{
				allk[top++] = x;
				fix(pq);
				#if 0
				for (int i = 1; i <= n; ++i)
				if (flag[i])
				cerr << pos[i] << " " << treasure[i] << endl;
				cerr << endl;

				for (int i = 0; i < k; ++i)
				cerr << i << " " << D[i] << endl;
				cerr << endl;
				#endif
			}
		}
	}

	return 0;
}


#include <vector>
#include <iterator>
#include <map>
#include <unordered_map>
#include <set>
#include <deque>
#include <queue>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <string>
using namespace std;
int bitct(long long r) {return r == 0 ? 0 : (bitct(r>>1) + (r&1));}
long long gcd(long long x, long long y) {return x ? gcd(y%x,x) : y;}
template<typename T> ostream& operator << (ostream &o,vector<T> v) {o<<"{";
	int i=0,s=v.size();for(;i+1<s;i++)o<<v[i]<<", ";if(s)o<<v[i];o<<"}";return o;}
  /*jj
template<typename K, typename V> ostream& operator << (ostream &o,
  unordered_map<K, V> m) {o<<"{";for(auto i=m.begin();i!=m.end();++i)
  o<<i->first<<" -> "<< i->second << ", "; o<<"}";return o;}
  */
long long choose(long long n, long long q)
{ if(n==0 || q==0) return 1;
	if (q==1) return n; else return ( choose(n, q-1) * (n-q+1 ) /q); }
int dx[4] = {1,0,-1,0};
int dy[4] = {0,1,0,-1};

vector<int> ta, tc;

set<pair<int,int> > reachable;

vector<int> moves;
int h,k;

void make_reach()
{
  reachable.clear();
  vector<int> r(k, -1);
  r[0]=0;
  queue<int> Q;
  Q.push(0);
  while(Q.size())
    {
    int me = Q.front();
    Q.pop();
    for(int i:moves)
      {
      int nm = i+me;
      int nv = i+r[me];
      if(nv>h)
        continue;
      if(-1 == r[nm%k] || nv < r[nm%k])
        {
        r[nm%k] = nv;
        Q.push(nm%k);
        }
      }
    }
  for(int i=0;i<ta.size();i++)
    if(r[ta[i]%k] != -1 && r[ta[i]%k]<= ta[i])
      if(tc[i])
        {
        reachable.insert(make_pair(tc[i], i));
        }
}

main() {
	int n,m;
	cin >> h>>n>>m>>k;
  for(int i=0;i<n;i++)
    {
    int a,c;
    cin >> a >> c;
    ta.push_back(a-1);
    tc.push_back(c);
    }

  make_reach();
  for(int xx=0;xx<m;xx++)
    {
    int typ=0;
    cin >> typ;
    if(typ==1)
      {
      int x;
      cin >> x;
      moves.push_back(x);
      make_reach();
      }
    else if (typ==2)
      {
      int x,y;
      cin >> x>>y;
      x--;

      int has=(reachable.end() != reachable.find(make_pair(tc[x], x)));
      if(has)
        reachable.erase(make_pair(tc[x], x));
      tc[x]-=y;
      if(has)
        reachable.insert(make_pair(tc[x], x));

      }
    else
      {
      if(reachable.size())
        {
        cout << reachable.rbegin()->first << endl;
        int z=reachable.rbegin()->second;
        tc[z]=0;
        reachable.erase(*reachable.rbegin());
        }
      else
        cout << 0 << endl;
      }
    }
}


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

typedef long long LL;

LL inf = 1e18;

LL solve() {
    LL n;
    int m, K;
    cin >> n;
    cin >> m >> K;
    vector<LL> a;
    LL lst = 0;
    for(int i = 0; i < m; i++) {
        LL x;
        cin >> x;
        a.push_back(x - lst);
        lst = x;
    }
    a.push_back(n - lst);
    K += a.size();
    LL lo = 1, hi = inf;
    for(LL x : a) hi = min(hi, x);
    while(hi > lo) {
        LL mid = (hi+lo+1)/2;
        LL tot = 0;
        for(LL x : a) {
            tot += x / mid;
        }
        if(tot >= K) lo = mid;
        else hi = mid-1;
    }
    LL MIN = lo;
    lo = 1, hi = inf;
    while(hi > lo) {
        LL mid = (hi+lo)/2;
        LL tot = 0;
        for(LL x : a) {
            tot += (x+mid-1)/mid;
        }
        if(tot <= K) hi = mid;
        else lo = mid+1;
    }
    LL MAX = lo;
    if(all.size() > 1e3) {
        cout << "MIN MAX" << endl;
        cout << MIN << " " << MAX;
        exit(0);
    }
    vector<pair<LL,LL>> bad;
    for(LL w : a) {
        LL x = w/MIN, y = (w+MAX-1)/MAX;
        if(x >= y) continue;
        bad.push_back({w/y, (w+x-1)/x});
    }
    if(bad.empty()) return MAX-MIN;
    sort(bad.begin(), bad.end());
    bad.push_back({MIN, MAX});
    LL ans = inf;
    for(int i = 0; i < bad.size(); i++) {
        ans = min(ans, MAX - bad[i].first);
        MAX = max(MAX, bad[i].second);
    }
    return ans;
}

int main() {
    // freopen("in.txt", "r", stdin);
    ios::sync_with_stdio(0);
    cin.tie(0);
    int tc;
    cin >> tc;
    while(tc--) cout << solve() << "\n";

    return 0;
}


#ifndef LOCAL
#define NDEBUG 1
#endif
#include<bits/stdc++.h>

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wall"
#pragma GCC diagnostic ignored "-Wconversion"
#pragma GCC diagnostic ignored "-Wsign-compare"
#pragma GCC diagnostic ignored "-Wmisleading-indentation"
namespace io{using namespace std;template<class T>struct is_iterator{template<class U,typename enable_if<!is_convertible<U,const char*>::value,int>::type=0>constexpr static auto has_indirection(int)->decltype(*declval<U>(),bool()){return true;}template<class>constexpr static bool has_indirection(long){return false;}constexpr static bool value=has_indirection<T>(0);};using uint=unsigned int;const uint BUFFER_SIZE=1<<12;const uint MAX_LENGTH=1<<7;namespace Detail{struct Width{uint value;};struct Fill{char value;};struct Base{uint value;};struct Precision{uint value;};struct Delimiter{const char*value;};}Detail::Width setWidth(uint value=0){return{value};}Detail::Fill setFill(char value=' '){return{value};}Detail::Base setBase(uint value=10){assert(2<=value&&value<=36);return{value};}Detail::Precision setPrecision(uint value=9){assert(value<MAX_LENGTH);return{value};}Detail::Delimiter setDelimiter(const char*value=" "){return{value};}class InputDevice{protected:const char*head;const char*tail;InputDevice(const char*head,const char*tail): head(head),tail(tail),base(setBase().value){}virtual void fillInput()=0;inline char nextChar(){if(__builtin_expect(head>=tail,false))fillInput();return*head++;}template<class I>int readUnsignedIntGeneral(I&arg,char c){I value=0;int length=0;for(;;++length,c=nextChar()){if(isDigit(c))c-='0';else if(isUpper(c))c-='A'-10;else if(isLower(c))c-='a'-10;else c=base;if(c>=base)break;value=base*value+c;}arg=value;return--head,length;}template<class I>inline int readUnsignedInt(I&arg,char c){if(__builtin_expect(base>10,false))return readUnsignedIntGeneral(arg,c);I value=0;int length=0;for(;static_cast<unsigned char>(c-'0')<base;++length,c=nextChar())value=base*value+c-'0';arg=value;return--head,length;}template<class I>inline bool readSignedInt(I&arg,char c){bool negative=c=='-';if(negative)c=nextChar();typename make_unsigned<I>::type unsignedArg;if(readUnsignedInt(unsignedArg,c)==0)return false;arg=negative ? ~static_cast<I>(unsignedArg-1): static_cast<I>(unsignedArg);return true;}template<class F>bool readFloatingPoint(F&arg,char c){bool negative=c=='-';if(negative)c=nextChar();unsigned long long integerPart;if(readUnsignedInt(integerPart,c)==0)return false;arg=static_cast<F>(integerPart);if(nextChar()=='.'){unsigned long long fractionalPart=0;int fractionalLength=readUnsignedInt(fractionalPart,nextChar());if(fractionalLength>0){unsigned long long basePower=1;for(;fractionalLength;--fractionalLength)basePower*=base;arg+=static_cast<F>(fractionalPart)/basePower;}}else --head;if(negative)arg=-arg;return true;}public:uint base;InputDevice(InputDevice const&)=delete;InputDevice&operator=(InputDevice const&)=delete;static inline bool isSpace(char c){return static_cast<unsigned char>(c-'\t')<5||c==' ';}static inline bool isDigit(char c){return static_cast<unsigned char>(c-'0')<10;}static inline bool isUpper(char c){return static_cast<unsigned char>(c-'A')<26;}static inline bool isLower(char c){return static_cast<unsigned char>(c-'a')<26;}static inline bool isOneOf(char c,const char*str){return strchr(str,c)!=nullptr;}void putBack(){--head;}inline bool readChar(char&arg){if(__builtin_expect(head>=tail,false)){fillInput();if(__builtin_expect(head>=tail,false))return arg='\0',false;}return arg=*head++,true;}template<class UnaryPredicate>inline char skipCharacters(UnaryPredicate isSkipped){char c;do{c=nextChar();}while(isSkipped(c));return c;}inline char skipCharacters(){return skipCharacters(isSpace);}template<class UnaryPredicate>inline int readString(char*arg,int limit,UnaryPredicate isTerminator){skipCharacters(isTerminator);int charsRead=0;for(--head,--limit;head<tail;fillInput()){ptrdiff_t chunkSize=find_if(head,min(tail,head+limit-charsRead),isTerminator)-head;arg=copy_n(head,chunkSize,arg);head+=chunkSize;charsRead+=chunkSize;if(chunkSize==0||head<tail)break;}return*arg='\0',charsRead;}inline int readString(char*arg,int limit,const char*terminators){if(!*terminators)return readString(arg,limit,InputDevice::isSpace);return readString(arg,limit,[terminators](char c){return InputDevice::isOneOf(c,terminators);});}inline bool read(Detail::Base newBase){base=newBase.value;return true;}inline bool read(){return true;}inline bool read(char&arg){return readChar(arg);}template<class I>inline typename enable_if<is_integral<I>::value&&is_unsigned<I>::value,bool>::type read(I&arg){return readUnsignedInt(arg,skipCharacters())>0;}template<class I>inline typename enable_if<is_integral<I>::value&&is_signed<I>::value,bool>::type read(I&arg){return readSignedInt(arg,skipCharacters());}template<class F>inline typename enable_if<is_floating_point<F>::value,bool>::type read(F&arg){return readFloatingPoint(arg,skipCharacters());}inline bool read(const char&arg){skipCharacters([arg](char c){return arg!=c;});return true;}inline bool read(const char*arg){if(*arg)skipCharacters([arg](char c){return InputDevice::isOneOf(c,arg);});else skipCharacters();return putBack(),true;}inline bool read(bool(*isSkipped)(char)){skipCharacters(isSkipped);putBack();return true;}template<class I,class Terminator,class... Ts>inline typename enable_if<is_integral<I>::value,bool>::type read(char*arg,I limit,Terminator terminator,Ts&&... args){readString(arg,static_cast<int>(limit),terminator);return read(forward<Ts>(args)...);}template<class I>inline typename enable_if<is_integral<I>::value,bool>::type read(char*arg,I limit){return read(arg,limit,"");}template<class... Ts>inline bool read(char*first,char*last,Ts&&... args){return read(first,static_cast<int>(last-first),forward<Ts>(args)...);}template<int N,class... Ts>inline bool read(char(&arg)[N],Ts&&... args){return read(static_cast<char*>(arg),N,forward<Ts>(args)...);}template<class Terminator,class... Ts>inline bool read(string&arg,Terminator terminator,Ts&&... args){for(int length=16,last=0;;last+=length,length<<=1){arg.resize(last+length);int charsRead=readString(&arg[last],length+1,terminator);if(charsRead<length){arg.resize(last+charsRead);return read(forward<Ts>(args)...);}}}inline bool read(string&arg){return read(arg,"");}template<class T1,class T2>inline bool read(pair<T1,T2>&arg){return read(arg.first,arg.second);}template<class T>inline bool read(complex<T>&arg){T real,imag;if(!read(real,imag))return false;arg.real(real),arg.imag(imag);return true;}template<class T>inline bool read(vector<T>&arg){uint n;if(!read(n))return false;arg.resize(n);return read(arg.begin(),arg.end());}template<class Iterator,class... Ts>inline typename enable_if<is_iterator<Iterator>::value,bool>::type read(Iterator first,Iterator last,Ts&&... args){for(;first!=last;++first)if(!read(*first))return false;return read(forward<Ts>(args)...);}template<class Iterator,class I,class... Ts>inline typename enable_if<is_iterator<Iterator>::value&&is_integral<I>::value,bool>::type read(Iterator first,I count,Ts&&... args){return read(first,first+count,forward<Ts>(args)...);}template<class T>inline auto read(T&arg)->decltype(arg.read(*this)){return arg.read(*this);}template<class T0,class T1,class... Ts>inline typename enable_if<!is_iterator<T0>::value&&!is_convertible<T0,char*>::value,bool>::type read(T0&&arg0,T1&&arg1,Ts&&... args){return read(forward<T0>(arg0))&&read(forward<T1>(arg1),forward<Ts>(args)...);}};class InputFile : public InputDevice{FILE*file;bool lineBuffered;bool owner;char buffer[BUFFER_SIZE];void fillInput()override{head=buffer;*buffer='\0';if(__builtin_expect(!lineBuffered,true)){tail=head+fread(buffer,1,BUFFER_SIZE,file);}else{tail=head;if(fgets(buffer,BUFFER_SIZE,file))while(*tail)++tail;}}public:InputFile(FILE*file=stdin,bool lineBuffered=true,bool takeOwnership=false): InputDevice(buffer,buffer),file(file),lineBuffered(lineBuffered),owner(takeOwnership){}InputFile(const char*fileName): InputFile(fopen(fileName,"r"),false,true){}~InputFile(){if(owner)fclose(file);}};class InputString : public InputDevice{void fillInput()override{while(*tail)++tail;}public:InputString(const string&s): InputDevice(s.data(),s.data()+s.size()){}InputString(const char*s): InputDevice(s,s+strlen(s)){}};class OutputDevice{protected:char buffer[BUFFER_SIZE+MAX_LENGTH];char*output;char*end;bool separate;OutputDevice(): output(buffer),end(buffer+BUFFER_SIZE+MAX_LENGTH),separate(false),width(setWidth().value),fill(setFill().value),base(setBase().value),precision(setPrecision().value),delimiter(setDelimiter().value){computeBasePower();}virtual void writeToDevice(uint count)=0;inline void flushMaybe(){if(__builtin_expect(output>=buffer+BUFFER_SIZE,false)){writeToDevice(BUFFER_SIZE);output=copy(buffer+BUFFER_SIZE,output,buffer);}}void computeBasePower(){basePower=1;for(uint i=0;i<precision;++i)basePower*=base;}template<class I>inline char*writeUnsignedInt(I arg,char*last){if(__builtin_expect(arg==0,false))*--last='0';if(__builtin_expect(base==10,true)){for(;arg;arg/=10)*--last='0'+arg%10;}else for(;arg;arg/=base){I digit=arg%base;*--last=digit<10 ? '0'+digit : 'A'-10+digit;}return last;}template<class I>inline char*writeSignedInt(I arg,char*last){auto unsignedArg=static_cast<typename make_unsigned<I>::type>(arg);if(arg<0){last=writeUnsignedInt(~unsignedArg+1,last);*--last='-';return last;}return writeUnsignedInt(unsignedArg,last);}template<class F>char*writeFloatingPoint(F arg,char*last){bool negative=signbit(arg);if(negative)arg=-arg;if(isnan(arg))for(int i=0;i<3;++i)*--last=i["NaN"];else if(isinf(arg))for(int i=0;i<3;++i)*--last=i["fnI"];else{auto integerPart=static_cast<unsigned long long>(arg);auto fractionalPart=static_cast<unsigned long long>((arg-integerPart)*basePower+F(0.5));if(fractionalPart>=basePower)++integerPart,fractionalPart=0;char*point=last-precision;if(precision>0){io::fill(point,writeUnsignedInt(fractionalPart,last),'0');*--point='.';}last=writeUnsignedInt(integerPart,point);}if(negative)*--last='-';return last;}inline int writeT(char*first){int delimiterLenght=separate ? writeDelimiter(): 0;separate=true;uint charsWritten=static_cast<uint>(end-first);if(__builtin_expect(charsWritten<width,false))charsWritten+=writeFill(width-charsWritten);output=copy(first,end,output);flushMaybe();return delimiterLenght+static_cast<int>(charsWritten);}inline int writeFill(uint count){int charsWritten=static_cast<int>(count);if(__builtin_expect(output+count+MAX_LENGTH<end,true)){if(count==1)*output++=fill;else output=fill_n(output,count,fill);}else for(uint chunkSize=static_cast<uint>(buffer+BUFFER_SIZE-output);;chunkSize=BUFFER_SIZE){if(chunkSize>count)chunkSize=count;output=fill_n(output,chunkSize,fill);flushMaybe();if((count-=chunkSize)==0)break;}return charsWritten;}public:uint width;char fill;uint base;uint precision;unsigned long long basePower;string delimiter;OutputDevice(OutputDevice const&)=delete;OutputDevice&operator=(OutputDevice const&)=delete;virtual ~OutputDevice(){};inline int writeChar(char arg){separate=false;*output++=arg;flushMaybe();return 1;}inline int writeString(const char*arg,size_t length,bool checkWidth=true){separate=false;uint count=static_cast<uint>(length);int charsWritten=static_cast<int>(count)+(checkWidth&&count<width ? writeFill(width-count): 0);if(__builtin_expect(output+count+MAX_LENGTH<end,true)){if(count==1)*output++=*arg;else output=copy_n(arg,count,output);}else for(uint chunkSize=static_cast<uint>(buffer+BUFFER_SIZE-output);;chunkSize=BUFFER_SIZE){if(chunkSize>count)chunkSize=count;output=copy_n(arg,chunkSize,output);flushMaybe();if((count-=chunkSize)==0)break;arg+=chunkSize;}return charsWritten;}inline int writeDelimiter(){return writeString(delimiter.c_str(),delimiter.size(),false);}inline void flush(){writeToDevice(static_cast<uint>(output-buffer));output=buffer;}inline int write(Detail::Width newWidth){width=newWidth.value;return 0;}inline int write(Detail::Fill newFill){fill=newFill.value;return 0;}inline int write(Detail::Base newBase){base=newBase.value;computeBasePower();return 0;}inline int write(Detail::Precision newPrecision){precision=newPrecision.value;computeBasePower();return 0;}inline int write(Detail::Delimiter newDelimiter){delimiter=newDelimiter.value;return 0;}inline int write(){return 0;}inline int write(char arg){return writeChar(arg);}template<class I>inline typename enable_if<is_integral<I>::value&&is_unsigned<I>::value,int>::type write(I arg){return writeT(writeUnsignedInt(arg,end));}template<class I>inline typename enable_if<is_integral<I>::value&&is_signed<I>::value,int>::type write(I arg){return writeT(writeSignedInt(arg,end));}template<class F>inline typename enable_if<is_floating_point<F>::value,int>::type write(F arg){return writeT(writeFloatingPoint(arg,end));}inline int write(const char*arg){return writeString(arg,strlen(arg));}template<int N>inline int write(char(&arg)[N]){return writeString(arg,strlen(arg));}inline int write(const string&arg){return writeString(arg.c_str(),arg.size());}template<class T1,class T2>inline int write(const pair<T1,T2>&arg){int charsWritten=write(arg.first);charsWritten+=writeDelimiter();return charsWritten+write(arg.second);}template<class T>inline int write(const complex<T>&arg){return write(real(arg),imag(arg));}template<class Iterator,class... Ts>inline typename enable_if<is_iterator<Iterator>::value,int>::type write(Iterator first,Iterator last,Ts&&... args){int charsWritten=0;for(;first!=last;charsWritten+=++first==last ? 0 : writeDelimiter())charsWritten+=write(*first);return charsWritten+write(forward<Ts>(args)...);}template<class Iterator,class I,class... Ts>inline typename enable_if<is_iterator<Iterator>::value&&is_integral<I>::value,int>::type write(Iterator first,I count,Ts&&... args){return write(first,first+count,forward<Ts>(args)...);}template<class T>inline auto write(const T&arg)->decltype(arg.write(*this)){return arg.write(*this);}template<class T0,class T1,class... Ts>inline typename enable_if<!is_iterator<T0>::value,int>::type write(T0&&arg0,T1&&arg1,Ts&&... args){int charsWritten=write(forward<T0>(arg0));return charsWritten+write(forward<T1>(arg1),forward<Ts>(args)...);}};class OutputFile : public OutputDevice{FILE*file;bool owner;void writeToDevice(uint count)override{fwrite(buffer,1,count,file);fflush(file);}public:OutputFile(FILE*file=stdout,bool takeOwnership=false): file(file),owner(takeOwnership){}OutputFile(const char*fileName): OutputFile(fopen(fileName,"w"),true){}~OutputFile()override{flush();if(owner)fclose(file);}};class OutputString : public OutputDevice{string&str;void writeToDevice(uint count)override{str.append(buffer,count);}public:OutputString(string&str): OutputDevice(),str(str){}~OutputString()override{flush();}};unique_ptr<InputDevice>input;unique_ptr<OutputDevice>output;template<class... Ts>inline bool read(Ts&&... args){return input->read(forward<Ts>(args)...);}template<class... Ts>inline int write(Ts&&... args){return output->write(forward<Ts>(args)...);}template<class... Ts>inline int writeln(Ts&&... args){return write(forward<Ts>(args)...,'\n');}void flush(){output->flush();}}
#pragma GCC diagnostic pop

struct Input{
	Input(){ io::input.reset(new io::InputFile(stdin, false)); }
	template<class T> auto& operator>>(T& t){ io::read(t); return *this; }
} cin;
struct Output{
	Output(){ io::output.reset(new io::OutputFile()); }
	template<class T> auto& operator<<(T const& t){ io::write(t); return *this; }
} cout;

void up();
int main(){
	int numTest; cin>>numTest;
	while(numTest--) up();
}

void up(){
	int64_t len, numAdd; int numBlock;
	cin>>len>>numBlock>>numAdd;
	assert(numAdd<len-numBlock);
	std::vector<int64_t> segments;
	segments.reserve(numBlock+1);
	{
		int64_t last=0;
		for(int _=0;_<numBlock;++_) {
			int64_t pos; cin>>pos;
			if(segments.size()>=segments.capacity()) __builtin_unreachable();
			segments.push_back(pos-last);
			last=pos;
		}
		if(segments.size()>=segments.capacity()) __builtin_unreachable();
		segments.push_back(len-last);
	}
	assert((int)segments.size()==numBlock+1);

	if(numAdd==0){
		cout<<
			*std::max_element(begin(segments),end(segments))-*std::min_element(begin(segments),end(segments))
			<<'\n';
		return;
	}

	int64_t l, r;
	assert(std::accumulate(begin(segments),end(segments),(int64_t)0)==len);
	l=len/(numAdd+numBlock+1); r=l+(len%(numAdd+numBlock+1)!=0);
	--l; --r;
	auto const fr=[&](auto n, auto r) __attribute__((const)) { return (n+r)/(r+1); };
	auto const fl=[&](auto n, auto l) __attribute__((const)) { return n/(l+1); };
	auto const have_previous_fl=[&](auto n, auto l) __attribute__((const)) {
		return l>0;
	};
	auto const previous_fl=[&](auto n, auto l) __attribute__((const)) {
		auto const l1=n/(fl(n, l)+1)-1;
		assert(l1<l);
		assert(fl(n, l1)>fl(n, l));
		assert(fl(n, l1+1)==fl(n, l));
		return l1;
	};
	auto const have_next_fr=[&](auto n, auto r) __attribute__((const)) {
		return n-1>=r+1;
	};
	auto const next_fr=[&](auto n, auto r) __attribute__((const)) {
		assert(have_next_fr(n, r));
		auto const r1=(n-1)/(fr(n, r)-1);
		assert(r1>r);
		assert(fr(n, r1)<fr(n, r));
		assert(fr(n, r1-1)==fr(n, r));
		return r1;
	};

	l=std::min(l, *std::min_element(begin(segments),end(segments))-1);
	auto const vl=[&](auto l){ return std::accumulate(begin(segments),end(segments), (int64_t)0,
				[&](auto result, auto n)->int64_t{ return result+n/(l+1)-1; }); };
	auto const vr=[&](auto r){ return std::accumulate(begin(segments),end(segments), (int64_t)0,
				[&](auto result, auto n)->int64_t{ return result+(n+r)/(r+1)-1; }); };

	{
		auto result=vl(l);
		if(result<numAdd){
			assert(numAdd-result<=(int64_t)segments.size());

			struct T{
				int64_t value, segment;
				bool operator<(T sec) const{ return value<sec.value; }
			};
			std::vector<T> queue;
			for(auto n: segments)
				queue.push_back({previous_fl(n, l), n});
			std::make_heap(begin(queue),end(queue));

			while(result<numAdd){
				assert(queue[0].value<l);
				auto const l1=queue[0].value;
				do{
					auto n=queue[0].segment; std::pop_heap(begin(queue),end(queue)); queue.pop_back();
					result+=fl(n, l1)-fl(n, l);
					if(have_previous_fl(n, l1)) {
						if(queue.size()>=queue.capacity()) __builtin_unreachable();
						queue.push_back({previous_fl(n, l1), n});
						std::push_heap(begin(queue),end(queue));
					}
				}while(not queue.empty() and queue[0].value==l1);
				l=l1;

				assert(result==vl(l));
			}

			assert(vl(l)>=numAdd);
			assert(vl(l+1)<numAdd);
		}
	}
	{
		auto result=vr(r);
		if(result>numAdd){
			assert(result-numAdd<=(int64_t)segments.size());

			struct T{
				int64_t value, segment;
				bool operator<(T sec) const{ return value>sec.value; }
			};
			std::vector<T> queue;
			for(auto n: segments) if(have_next_fr(n, r))
				queue.push_back({next_fr(n, r), n});
			std::make_heap(begin(queue),end(queue));

			while(result>numAdd){
				assert(queue[0].value>r);
				auto const r1=queue[0].value;
				do{
					auto n=queue[0].segment; std::pop_heap(begin(queue),end(queue)); queue.pop_back();
					result+=fr(n, r1)-fr(n, r);
					if(have_next_fr(n, r1)) {
						if(queue.size()>=queue.capacity()) __builtin_unreachable();
						queue.push_back({next_fr(n, r1), n});
						std::push_heap(begin(queue),end(queue));
					}
				}while(not queue.empty() and queue[0].value==r1);
				r=r1;

				assert(result==vr(r));
			}
		}
	}
	assert(vr(r)<=numAdd);
	assert(r==0 or vr(r-1)>numAdd);
	assert(l<=r); assert(l>=0);
	std::vector<std::pair<int64_t, int64_t>> pairs; pairs.reserve(segments.size()+2);
	for(auto n: segments){
		auto q=fr(n, r);
		if(q>fl(n, l)){
			assert(q-1==fl(n, l));
			if(pairs.size()>=pairs.capacity()) __builtin_unreachable();
			pairs.push_back({previous_fl(n, l), next_fr(n, r)});
		}
	}
	if(pairs.size()>=pairs.capacity()) __builtin_unreachable();
	pairs.push_back({-1, r});
	if(pairs.size()>=pairs.capacity()) __builtin_unreachable();
	pairs.push_back({l, INT64_MAX});
	assert(pairs.size()<=segments.size()+2);
	std::sort(begin(pairs),end(pairs),[&](auto x, auto y){
		return x.first<y.first; });
	auto out=++begin(pairs);
	std::for_each(++begin(pairs),end(pairs),[&](auto it){
		if(it.second>out[-1].second){
			if(out[-1].first==it.first) --out;
			*out++=it;
		}
	});
	pairs.erase(out, end(pairs));

	int64_t result=INT64_MAX;
	for(int index=1;index<(int)pairs.size();++index)
		result=std::min(result, pairs[index-1].second-pairs[index].first);
	cout<<result<<'\n';
	return 0;
}


#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
int T;
long long n,m,k,dis[400040],cnt[400040],l[400040],r[400040];
struct data
{
	int id;
	friend bool operator < (data a,data b)
	{
		if(r[a.id]!=r[b.id])return r[a.id]<r[b.id];
		else return dis[a.id]/(cnt[a.id]+2)<dis[b.id]/(cnt[b.id]+2);
	}
};
priority_queue<data>q;
int main()
{
	scanf("%d",&T);
	while(T--)
	{
		scanf("%lld %lld %lld",&n,&m,&k);
		long long last=0,cur;
		for(int i=1;i<=m;++i)
		{
			scanf("%lld",&cur);
			dis[i]=cur-last;last=cur;
		}
		dis[m+1]=n-last;
		for(int i=1;i<=m+1;++i)
		{
			cnt[i]=((__int128)dis[i])*(k+m+1)/n-1;if(cnt[i]<0)++cnt[i];
			l[i]=dis[i]/(cnt[i]+1);
			r[i]=(dis[i]-1)/(cnt[i]+1)+1;
		//	printf("%lld %lld %lld\n",cnt[i],l[i],r[i]);
			q.push(data{i});
		}//printf("\n");
		for(int i=1;i<=m+1;++i)k-=cnt[i];
		while(k--)
		{
			int x=q.top().id;q.pop();//printf("ins%d\n",x);
			++cnt[x];l[x]=dis[x]/(cnt[x]+1),r[x]=(dis[x]-1)/(cnt[x]+1)+1;
			q.push(data{x});
		}
		long long mi=0x3f3f3f3f3f3f3f3f,mx=0;
		for(int i=1;i<=m+1;++i)mx=max(mx,r[i]),mi=min(mi,l[i]);
		printf("%lld\n",mx-mi);
		while(!q.empty())q.pop();
	}
	return 0;
}


#include<bits/stdc++.h>
#define rep(i,a,b) for(int i=(a);i<(b);++i)
#define per(i,a,b) for(int i=(b)-1;i>=(a);--i)
#define ll long long
#define lb(x) ((x)&(-x))
#define pii pair<int,int>
#define vi vector<int>
#define pb push_back
#define fi first
#define se second
#define de(x) cout<<#x<<" x"<<endl
#define LCAFA rep(i,1,20)rep(j,1,n+1)fa[j][i]=fa[fa[j][i-1]][i-1]
#define all(x) x.begin(),x.end()
#define ls(x) x<<1
#define rs(x) x<<1|1
#define pr(x) {for(auto v:x)cout<<x<<' ';cout<<#x<<endl;}
using namespace std;
const int N=4e5+9;
const ll mod=998244353;
const ll Inf=1e18;
ll s[N],p[N];
vector<pii> g;
pii stk[N];
ll down(ll a,ll b){
	return a/b;
}
ll up(ll a,ll b){
	return (a+b-1)/b;
}
void solve(){
	int n,m,k;
	scanf("%d%d%d",&n,&m,&k);
	rep(i,1,m+1)scanf("%lld",&p[i]);
	p[++m]=n;
	rep(i,1,m+1)s[i]=p[i]-p[i-1];
	ll MIN=Inf,MAX=0,l=1,r=Inf,K=k+m;
	while(l<r){
		ll sum=0,mid=l+r>>1;
		rep(i,1,m+1)sum+=down(s[i],mid);
		if(sum>=K)l=mid+1;
		else r=mid;
	}
	MIN=l-1;
	l=1,r=Inf;
	while(l<r){
		ll sum=0,mid=l+r>>1;
		rep(i,1,m+1)sum+=up(s[i],mid);
		if(sum<=K)r=mid;
		else l=mid+1;
	}
	MAX=l;
	ll ans=MAX-MIN;
	//cout<<MIN<<' '<<MAX<<"?\n";
	g.clear();
	rep(i,1,m+1){
		int L=up(s[i],MAX),R=down(s[i],MIN);
		if(L<=R)continue;
	//	cout<<s[i]<<' '<<L<<' '<<R<<"???\n";
		g.pb({MIN-down(s[i],L),(R?up(s[i],R):Inf)-MAX});
	}
//	cout<<"MAX\n";
	if(g.size()==0){
		printf("%lld\n",ans);
		return;
	}
	sort(all(g));
	int c=0;
	rep(i,0,g.size()){
		while(c&&stk[c].se<g[i].se)--c;
		stk[++c]=g[i];
	//	cout<<stk[c].fi<<' '<<stk[c].se<<"check\n";
	}
	ll add=min(stk[1].se,stk[c].fi);
	rep(i,1,c){
		add=min(add,stk[i].se+stk[i+1].fi);
	}
	ans+=add;
	printf("%lld\n",ans);
}
int main(){
	int t;
	scanf("%d",&t);
	while(t--)solve();
}


#include<iostream>
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<vector>
#include<queue>
#include<map>
#include<stdlib.h>
#include<algorithm>
#include<limits.h>
#include<stack>
#include<deque>
#include<set>

using namespace std;

#define i_n(a) scanf("%d",&a)
#define l_n(a) scanf("%lld",&a)
#define LL long long int
#define pb(a) push_back(a)
#define pp pair<int,int>
#define vv vector<int>
#define vvp vector<pp>
#define i_p(a) printf("%d\n",a)
#define l_p(a) printf("%lld\n",a)
#define pnt(expr) printf(#expr"\n")
#define reset(a,val) memset(a,val,sizeof(a))
#define m1 1000000000
#define mod 1000000007
#define pr(cn,x) ((cn).find(x)!=(cn).end())
#define tr(cn,it) for(typeof((cn).begin()) it=(cn).begin();it!=(cn).end();it++)
#define read() freopen("fraud.in","r",stdin)
#define write() freopen("fraud.out","w",stdout)
bool cmp(const pair<int, int>& p1, const pair<int, int>& p2)
{
    return p1.first < p2.first;
}
int k,m;
int curr;
int flag=0;
set<int>out;
void sol(int a,int b)
{
  //  cout<<a<<" "<<b<<endl;
    if(!b)
    {
        int x;
            t=abs(a);
        x=abs(t-k);
        if(x>=10000)
            return ;
        if(out.size()<m)
            out.insert((10000*x)+curr);
        if(out.size()<m)
            out.insert((10000*curr)+x);
        if(out.size()==m)
            {
                flag=1;

            }
            return ;
    }
    sol(a-b%10,b/10);
    sol(a+b/10,b/10);
    sol(a*(b%10),b/10);
}
int main()
{
    i_n(k);i_n(m);
    int i=0;
    while(1)
    {
        curr=i;
        sol(i%10,i/10);
        if(flag)
            break;
        else
            i++;
    }
    tr(out,it)
    {
        printf("%08d\n",*it);
    }

    return 0;
}


										/* in the name of Allah */
#include <algorithm>
#include <iostream>
#include <memory.h>
#include <iomanip>
#include <sstream>
#include <fstream>
#include <cstdio>
#include <string>
#include <vector>
#include <queue>
#include <cmath>
#include <list>
#include <map>
#include <set>

using namespace std;

#define uint unsigned int
#define int64 long long
#define P pair<int, int>
#define Pss pair<string, string>
#define PLL pair<int64, int64>
#define Inf 1000000
#define Mod 1000000007LL

int n, k;
set <int> st;
char str[9];

void solve(int idx, int val, int rem){
	if(idx == 8){
		if(val == rem && st.size() < k)
			st.insert(atoi(str));
		return;
	}
	str[idx] = '0';
	solve(idx + 1, val, rem);
	if(val != 0 && rem % val == 0)
		solve(idx + 1, 0, rem / val);
	for(int i = 1; i < 10 && st.size() < k; i++){
		str[idx] = (char)('0' + i);
		if(val != 0 && rem % val == 0)
			solve(idx + 1, i, rem / val);
		solve(idx + 1, val + i, rem);
		if(val != 0 && rem % val == 0)
			solve(idx + 1, -i, rem / val);
		solve(idx + 1, val - i, rem);
	}
}

int main(){
	cin >> n >> k;
	if(n == 0){
		for(int i = 0; i < k; i++)
			printf("%08d\n", i);
	}
	else{
		solve(0, 0, n);
		for(set <int>::iterator it = st.begin(); it != st.end(); it++)
			printf("%08d\n", *it);
	}
	return 0;
}