#include <bits/stdc++.h>

using namespace std;

int m, n, t;
long long a[102][102], ans;

inline int64_t f(int64_t med, int64_t a, int64_t b, int64_t c, int64_t d) {
    return abs(med - a) + abs(med - b) + abs(med - c) + abs(med - d);
}

int64_t findmin(int64_t a, int64_t b, int64_t c, int64_t d) {
    int64_t l = 0, r = 1000000000000LL;
    while (r - l > 2) {
        int64_t v1 = l + (r - l) / 3;
        int64_t v2 = r - (r - l) / 3;
        // cout << l << ' ' << r << ' ' << v1 << ' ' << v2 << endl;
        int64_t sum1 = f(v1, a, b, c, d);
        int64_t sum2 = f(v2, a, b, c, d);
        if (sum1 > sum2) {
            l = v1;
        } else {
            r = v2;
        }
    }
    int64_t ret = l;
    int64_t sum1 = f(l, a, b, c, d);
    int64_t sum2 = f(r, a, b, c, d);
    int64_t sum3 = f((r + l) / 2, a, b, c, d);
    if (sum1 > sum2) {
        ret = r;
    }
    if (sum2 > sum3) {
        ret = (r + l) / 2;
    }
    return ret;
}

int main ()
{
    cin >> t;
    while (t--){
        cin >> m >> n;
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                cin >> a[i][j];
            }
        }

        ans = 0;

        int halfm = m >> 1;
        int halfn = n >> 1;

        for (int i = 0; i < halfm; ++i) {
            for (int j = 0; j < halfn; ++j) {
                long long avg = findmin(a[i][j], a[m - i - 1][j], a[i][n - j - 1], a[m - i - 1][n - j - 1]);
                ans += abs(avg - a[i][j]) + abs(avg - a[m - i - 1][j]) + abs(avg - a[i][n - j - 1]) + abs(avg - a[m - i - 1][n - j - 1]);
            }
        }

        if (n % 2) {
            for (int i = 0; i < m/2; ++i) {
                ans += abs(a[i][halfn] - a[m - i - 1][halfn]);
            }
        }

        if (m % 2) {
            for (int j = 0; j < n/2; ++j) {
                ans += abs(a[halfm][j] - a[halfm][n - j - 1]);
            }
        }

        cout << ans << endl;
    }

}


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

// MISC.
#define read(x)           x; cin>>x;
#define reads(x,y)        x,y; cin>>x>>y;
#define save(C,x)         x; cin>>x; C[x]
#define saveo(C,x,o)      x; cin>>x; C[x+(o)]
#define emplf(C,x)        x; cin>>x; C.emplace(C.begin(),x)
#define emplb(C,x)        x; cin>>x; C.emplace_back(x)
#define rser(n,C)         C; C.reserve(n)

// SORTING.
#define rsort(C)          sort(C.rbegin(),C.rend())

// ITERNATION.
#define forn(i,n)         for(int i=0;i<n;i+=1)
#define iter(it,C)        for(auto it=C.begin();it!=C.end();it++)
#define range(i,b,e)      for(int i=b;i<=e;i+=1)
#define rrange(i,b,e)     for(int i=b;i>=e;i-=1)

// REVERSE ITERATION.
#define rforn(i,n)        for(int i=(n-1);i>=0;i-=1)
#define riter(it,C)       for(auto it=C.rbegin();it!=C.rend();it++)

// ENUMERATION.
#define forea(c,C)        for(auto c:C)

// REVERSE INITIALIZATION.
#define init_xvec(V,xV)   auto tV=V[0];for(int i=0;i<V[0].size();i+=1){tV.clear();for(auto v: V){tV.push_back(v[i]);}xV.emplace_back(tV);}
#define init_rmap(M,rM)   for(auto kv: M){rM[kv.second]=kv.first;}

// VECTORS.
#define vi                vector<int>
#define vvi               vector<vector<int>>

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    // The range of long and int are the same, 1 - 2bil.
    int read(t);

    forn(i,t){
    	long long ans=0;
    	long long reads(n,m);

    	// Read inputs.
    	vector<vector<long long>> rser(n,VV);
    	forn(j,n){
    		vector<long long> rser(m,V);

    		forn(k,m){
    			long long emplb(V,num);
			}
			VV.emplace_back(V);
		}

		// Process info.
		forn(j,n/2){
			forn(k,m/2){
				long long q,w,e,r;

				q=VV[j][k];
				w=VV[j][m-1-k];
				e=VV[n-1-j][k];
				r=VV[n-1-j][m-1-k];

				long long mid;

				long long maximum,minimum;
				maximum=max(max(q,w),max(e,r));
				minimum=min(min(q,w),min(e,r));

				if(q!=maximum&&q!=minimum){
					mid=q;
				}else if(w!=maximum&&w!=minimum){
					mid=w;
				}else if(e!=maximum&&e!=minimum){
					mid=e;
				}else{
					mid=r;
				}
//
//				if(mid%4==0){
//					mid/=4;
//				}else{
//					(mid/=4)+=1;
//				}
				//cout<<"........................................ mid = "<<mid<<endl;

				ans+=abs(q-mid);
				ans+=abs(w-mid);
				ans+=abs(e-mid);
				ans+=abs(r-mid);

//				map<int,int> M;
//
//				M[VV[j][k]]+=1;
//				M[VV[j][m-1-k]]+=1;
//				M[VV[n-1-j][k]]+=1;
//				M[VV[n-1-j][m-1-k]]+=1;
//
//				int curr=0,val=0;
//				forea(kv,M){
//					if(kv.second>curr){
//						curr=kv.second;
//						val=kv.first;
//					}
//				}
//
//				forea(kv,M){
//					ans+=abs(kv.first-val);
//				}
			}
		}

		// Check if m is even...
		if(m%2==1){
			forn(j,n/2){
				if(VV[j][m/2]!=VV[n-1-j][m/2]){
					ans+=abs(VV[j][m/2]-VV[n-1-j][m/2]);
					//cout<<"........................................ diff m = "<<abs(VV[j][m/2+1]-VV[n-1-j][m/2+1])<<endl;
				}
			}
		}

		// Might have to manually assess the middle row.
		if(n%2==1){
			forn(j,m/2){
				if(VV[n/2][j]!=VV[n/2][m-1-j]){
					ans+=abs(VV[n/2][j]-VV[n/2][m-1-j]);
					//cout<<"........................................ diff n = "<<VV[n/2+1][j]<<" - "<<VV[n/2+1][m-1-j]<<endl;
				}
			}
		}

		// Print ans.
		cout<<ans<<endl;
	}

    return 0;
}


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

// MISC.
#define ll                long long
#define read(x)           x; cin>>x;
#define reads(x,y)        x,y; cin>>x>>y;
#define save(C,x)         x; cin>>x; C[x]
#define saveo(C,x,o)      x; cin>>x; C[x+(o)]
#define emplf(C,x)        x; cin>>x; C.emplace(C.begin(),x)
#define emplb(C,x)        x; cin>>x; C.emplace_back(x)
#define rser(n,C)         C; C.reserve(n)

// SORTING.
#define rsort(C)          sort(C.rbegin(),C.rend())

// ITERNATION.
#define forn(i,n)         for(int i=0;i<n;i+=1)
#define iter(it,C)        for(auto it=C.begin();it!=C.end();it++)
#define range(i,b,e)      for(int i=b;i<=e;i+=1)
#define rrange(i,b,e)     for(int i=b;i>=e;i-=1)

// REVERSE ITERATION.
#define rforn(i,n)        for(int i=(n-1);i>=0;i-=1)
#define riter(it,C)       for(auto it=C.rbegin();it!=C.rend();it++)

// ENUMERATION.
#define forea(c,C)        for(auto c:C)

// REVERSE INITIALIZATION.
#define init_xvec(V,xV)   auto tV=V[0];for(int i=0;i<V[0].size();i+=1){tV.clear();for(auto v: V){tV.push_back(v[i]);}xV.emplace_back(tV);}
#define init_rmap(M,rM)   for(auto kv: M){rM[kv.second]=kv.first;}

// VECTORS.
#define vi                vector<int>
#define vvi               vector<vector<int>>

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    // The range of long and int are the same, 1 - 2bil.
    int read(t);

    forn(i,t){
    	long long ans=0;
    	long long reads(n,m);

    	// Read inputs.
    	vector<vector<long long>> rser(n,VV);
    	forn(j,n){
    		vector<long long> rser(m,V);

    		forn(k,m){
    			long long emplb(V,num);
			}
			VV.emplace_back(V);
		}

		// Process info.
		forn(j,n/2){
			forn(k,m/2){
				long long q,w,e,r;

				q=VV[j][k];
				w=VV[j][m-1-k];
				e=VV[n-1-j][k];
				r=VV[n-1-j][m-1-k];

				vector<ll> upsolveV;
				upsolveV.emplace_back(q);
				upsolveV.emplace_back(w);
				upsolveV.emplace_back(e);
				upsolveV.emplace_back(r);
				sort(upsolveV.begin(),upsolveV.end());
				long long mid=upsolveV[2];
//				long long maximum,minimum;
//				maximum=max(max(q,w),max(e,r));
//				minimum=min(min(q,w),min(e,r));
//
//				if(q!=maximum&&q!=minimum){
//					mid=q;
//				}else if(w!=maximum&&w!=minimum){
//					mid=w;
//				}else if(e!=maximum&&e!=minimum){
//					mid=e;
//				}else{
//					mid=r;
//				}

				ans+=abs(q-mid);
				ans+=abs(w-mid);
				ans+=abs(e-mid);
				ans+=abs(r-mid);
			}
		}

		// Check if m is even...
		if(m%2==1){
			forn(j,n/2){
				if(VV[j][m/2]!=VV[n-1-j][m/2]){
					ans+=abs(VV[j][m/2]-VV[n-1-j][m/2]);
					//cout<<"........................................ diff m = "<<abs(VV[j][m/2+1]-VV[n-1-j][m/2+1])<<endl;
				}
			}
		}

		// Might have to manually assess the middle row.
		if(n%2==1){
			forn(j,m/2){
				if(VV[n/2][j]!=VV[n/2][m-1-j]){
					ans+=abs(VV[n/2][j]-VV[n/2][m-1-j]);
					//cout<<"........................................ diff n = "<<VV[n/2+1][j]<<" - "<<VV[n/2+1][m-1-j]<<endl;
				}
			}
		}

		// Print ans.
		cout<<ans<<endl;
	}

    return 0;
}

// Learning point: Given 4 integers, how to find the minimum step for convergence?
//     - Find the integer of rank 2 or 3 (e.g. 2 or 4 in 1-2-4-7).
//     - Let all others rise or fall to one of the 2 integers.


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

// MISC.
#define read(x)           x; cin>>x;
#define reads(x,y)        x,y; cin>>x>>y;
#define save(C,x)         x; cin>>x; C[x]
#define saveo(C,x,o)      x; cin>>x; C[x+(o)]
#define emplf(C,x)        x; cin>>x; C.emplace(C.begin(),x)
#define emplb(C,x)        x; cin>>x; C.emplace_back(x)
#define rser(n,C)         C; C.reserve(n)

// SORTING.
#define rsort(C)          sort(C.rbegin(),C.rend())

// ITERNATION.
#define forn(i,n)         for(int i=0;i<n;i+=1)
#define iter(it,C)        for(auto it=C.begin();it!=C.end();it++)
#define range(i,b,e)      for(int i=b;i<=e;i+=1)
#define rrange(i,b,e)     for(int i=b;i>=e;i-=1)

// REVERSE ITERATION.
#define rforn(i,n)        for(int i=(n-1);i>=0;i-=1)
#define riter(it,C)       for(auto it=C.rbegin();it!=C.rend();it++)

// ENUMERATION.
#define forea(c,C)        for(auto c:C)

// REVERSE INITIALIZATION.
#define init_xvec(V,xV)   auto tV=V[0];for(int i=0;i<V[0].size();i+=1){tV.clear();for(auto v: V){tV.push_back(v[i]);}xV.emplace_back(tV);}
#define init_rmap(M,rM)   for(auto kv: M){rM[kv.second]=kv.first;}

// VECTORS.
#define vi                vector<int>
#define vvi               vector<vector<int>>

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int read(t);

    forn(i,t){
    	long ans=0;
    	long reads(n,m);

    	// Read inputs.
    	vector<vector<long>> rser(n,VV);
    	forn(j,n){
    		vector<long> rser(m,V);

    		forn(k,m){
    			long emplb(V,num);
			}
			VV.emplace_back(V);
		}

		// Process info.
		forn(j,n/2){
			forn(k,m/2){
				long q,w,e,r;

				q=VV[j][k];
				w=VV[j][m-1-k];
				e=VV[n-1-j][k];
				r=VV[n-1-j][m-1-k];

				long mid=(q+w+e+r)/4;
				//cout<<"........................................ mid = "<<mid<<endl;

				ans+=abs(q-mid);
				ans+=abs(w-mid);
				ans+=abs(e-mid);
				ans+=abs(r-mid);

//				map<int,int> M;
//
//				M[VV[j][k]]+=1;
//				M[VV[j][m-1-k]]+=1;
//				M[VV[n-1-j][k]]+=1;
//				M[VV[n-1-j][m-1-k]]+=1;
//
//				int curr=0,val=0;
//				forea(kv,M){
//					if(kv.second>curr){
//						curr=kv.second;
//						val=kv.first;
//					}
//				}
//
//				forea(kv,M){
//					ans+=abs(kv.first-val);
//				}
			}
		}

		// Check if m is even...
		if(m%2==1){
			forn(j,n/2){
				if(VV[j][m/2]!=VV[n-1-j][m/2]){
					ans+=abs(VV[j][m/2]-VV[n-1-j][m/2]);
					//cout<<"........................................ diff m = "<<abs(VV[j][m/2+1]-VV[n-1-j][m/2+1])<<endl;
				}
			}
		}

		// Might have to manually assess the middle row.
		if(n%2==1){
			forn(j,m/2){
				if(VV[n/2][j]!=VV[n/2][m-1-j]){
					ans+=abs(VV[n/2][j]-VV[n/2][m-1-j]);
					//cout<<"........................................ diff n = "<<VV[n/2+1][j]<<" - "<<VV[n/2+1][m-1-j]<<endl;
				}
			}
		}

		// Print ans.
		cout<<ans<<endl;
	}

    return 0;
}


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

// MISC.
#define read(x)           x; cin>>x;
#define reads(x,y)        x,y; cin>>x>>y;
#define save(C,x)         x; cin>>x; C[x]
#define saveo(C,x,o)      x; cin>>x; C[x+(o)]
#define emplf(C,x)        x; cin>>x; C.emplace(C.begin(),x)
#define emplb(C,x)        x; cin>>x; C.emplace_back(x)
#define rser(n,C)         C; C.reserve(n)

// SORTING.
#define rsort(C)          sort(C.rbegin(),C.rend())

// ITERNATION.
#define forn(i,n)         for(int i=0;i<n;i+=1)
#define iter(it,C)        for(auto it=C.begin();it!=C.end();it++)
#define range(i,b,e)      for(int i=b;i<=e;i+=1)
#define rrange(i,b,e)     for(int i=b;i>=e;i-=1)

// REVERSE ITERATION.
#define rforn(i,n)        for(int i=(n-1);i>=0;i-=1)
#define riter(it,C)       for(auto it=C.rbegin();it!=C.rend();it++)

// ENUMERATION.
#define forea(c,C)        for(auto c:C)

// REVERSE INITIALIZATION.
#define init_xvec(V,xV)   auto tV=V[0];for(int i=0;i<V[0].size();i+=1){tV.clear();for(auto v: V){tV.push_back(v[i]);}xV.emplace_back(tV);}
#define init_rmap(M,rM)   for(auto kv: M){rM[kv.second]=kv.first;}

// VECTORS.
#define vi                vector<int>
#define vvi               vector<vector<int>>

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int read(t);

    forn(i,t){
    	long long ans=0;
    	long long reads(n,m);

    	// Read inputs.
    	vector<vector<long long>> rser(n,VV);
    	forn(j,n){
    		vector<long long> rser(m,V);

    		forn(k,m){
    			long long emplb(V,num);
			}
			VV.emplace_back(V);
		}

		// Process info.
		forn(j,n/2){
			forn(k,m/2){
				long long q,w,e,r;

				q=VV[j][k];
				w=VV[j][m-1-k];
				e=VV[n-1-j][k];
				r=VV[n-1-j][m-1-k];

				long long mid=(q+w+e+r)/4;
				//cout<<"........................................ mid = "<<mid<<endl;

				ans+=abs(q-mid);
				ans+=abs(w-mid);
				ans+=abs(e-mid);
				ans+=abs(r-mid);

//				map<int,int> M;
//
//				M[VV[j][k]]+=1;
//				M[VV[j][m-1-k]]+=1;
//				M[VV[n-1-j][k]]+=1;
//				M[VV[n-1-j][m-1-k]]+=1;
//
//				int curr=0,val=0;
//				forea(kv,M){
//					if(kv.second>curr){
//						curr=kv.second;
//						val=kv.first;
//					}
//				}
//
//				forea(kv,M){
//					ans+=abs(kv.first-val);
//				}
			}
		}

		// Check if m is even...
		if(m%2==1){
			forn(j,n/2){
				if(VV[j][m/2]!=VV[n-1-j][m/2]){
					ans+=abs(VV[j][m/2]-VV[n-1-j][m/2]);
					//cout<<"........................................ diff m = "<<abs(VV[j][m/2+1]-VV[n-1-j][m/2+1])<<endl;
				}
			}
		}

		// Might have to manually assess the middle row.
		if(n%2==1){
			forn(j,m/2){
				if(VV[n/2][j]!=VV[n/2][m-1-j]){
					ans+=abs(VV[n/2][j]-VV[n/2][m-1-j]);
					//cout<<"........................................ diff n = "<<VV[n/2+1][j]<<" - "<<VV[n/2+1][m-1-j]<<endl;
				}
			}
		}

		// Print ans.
		cout<<ans<<endl;
	}

    return 0;
}


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

// MISC.
#define read(x)           x; cin>>x;
#define reads(x,y)        x,y; cin>>x>>y;
#define save(C,x)         x; cin>>x; C[x]
#define saveo(C,x,o)      x; cin>>x; C[x+(o)]
#define emplf(C,x)        x; cin>>x; C.emplace(C.begin(),x)
#define emplb(C,x)        x; cin>>x; C.emplace_back(x)
#define rser(n,C)         C; C.reserve(n)

// SORTING.
#define rsort(C)          sort(C.rbegin(),C.rend())

// ITERNATION.
#define forn(i,n)         for(int i=0;i<n;i+=1)
#define iter(it,C)        for(auto it=C.begin();it!=C.end();it++)
#define range(i,b,e)      for(int i=b;i<=e;i+=1)
#define rrange(i,b,e)     for(int i=b;i>=e;i-=1)

// REVERSE ITERATION.
#define rforn(i,n)        for(int i=(n-1);i>=0;i-=1)
#define riter(it,C)       for(auto it=C.rbegin();it!=C.rend();it++)

// ENUMERATION.
#define forea(c,C)        for(auto c:C)

// REVERSE INITIALIZATION.
#define init_xvec(V,xV)   auto tV=V[0];for(int i=0;i<V[0].size();i+=1){tV.clear();for(auto v: V){tV.push_back(v[i]);}xV.emplace_back(tV);}
#define init_rmap(M,rM)   for(auto kv: M){rM[kv.second]=kv.first;}

// VECTORS.
#define vi                vector<int>
#define vvi               vector<vector<int>>

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int read(t);

    forn(i,t){
    	int ans=0;
    	int reads(n,m);

    	// Read inputs.
    	vector<vi> rser(n,VV);
    	forn(j,n){
    		vi rser(m,V);

    		forn(k,m){
    			int emplb(V,num);
			}
			VV.emplace_back(V);
		}

		// Process info.
		forn(j,n/2){
			forn(k,m/2){
				int q,w,e,r;

				q=VV[j][k];
				w=VV[j][m-1-k];
				e=VV[n-1-j][k];
				r=VV[n-1-j][m-1-k];

				int mid=(q+w+e+r)/4;
				//cout<<"........................................ mid = "<<mid<<endl;

				ans+=abs(q-mid);
				ans+=abs(w-mid);
				ans+=abs(e-mid);
				ans+=abs(r-mid);

//				map<int,int> M;
//
//				M[VV[j][k]]+=1;
//				M[VV[j][m-1-k]]+=1;
//				M[VV[n-1-j][k]]+=1;
//				M[VV[n-1-j][m-1-k]]+=1;
//
//				int curr=0,val=0;
//				forea(kv,M){
//					if(kv.second>curr){
//						curr=kv.second;
//						val=kv.first;
//					}
//				}
//
//				forea(kv,M){
//					ans+=abs(kv.first-val);
//				}
			}
		}

		// Check if m is even...
		if(m%2==1){
			forn(j,n/2){
				if(VV[j][m/2]!=VV[n-1-j][m/2]){
					ans+=abs(VV[j][m/2]-VV[n-1-j][m/2]);
					//cout<<"........................................ diff m = "<<abs(VV[j][m/2+1]-VV[n-1-j][m/2+1])<<endl;
				}
			}
		}

		// Might have to manually assess the middle row.
		if(n%2==1){
			forn(j,m/2){
				if(VV[n/2][j]!=VV[n/2][m-1-j]){
					ans+=abs(VV[n/2][j]-VV[n/2][m-1-j]);
					//cout<<"........................................ diff n = "<<VV[n/2+1][j]<<" - "<<VV[n/2+1][m-1-j]<<endl;
				}
			}
		}

		// Print ans.
		cout<<ans<<endl;
	}

    return 0;
}


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

// MISC.
#define read(x)           x; cin>>x;
#define reads(x,y)        x,y; cin>>x>>y;
#define save(C,x)         x; cin>>x; C[x]
#define saveo(C,x,o)      x; cin>>x; C[x+(o)]
#define emplf(C,x)        x; cin>>x; C.emplace(C.begin(),x)
#define emplb(C,x)        x; cin>>x; C.emplace_back(x)
#define rser(n,C)         C; C.reserve(n)

// SORTING.
#define rsort(C)          sort(C.rbegin(),C.rend())

// ITERNATION.
#define forn(i,n)         for(int i=0;i<n;i+=1)
#define iter(it,C)        for(auto it=C.begin();it!=C.end();it++)
#define range(i,b,e)      for(int i=b;i<=e;i+=1)
#define rrange(i,b,e)     for(int i=b;i>=e;i-=1)

// REVERSE ITERATION.
#define rforn(i,n)        for(int i=(n-1);i>=0;i-=1)
#define riter(it,C)       for(auto it=C.rbegin();it!=C.rend();it++)

// ENUMERATION.
#define forea(c,C)        for(auto c:C)

// REVERSE INITIALIZATION.
#define init_xvec(V,xV)   auto tV=V[0];for(int i=0;i<V[0].size();i+=1){tV.clear();for(auto v: V){tV.push_back(v[i]);}xV.emplace_back(tV);}
#define init_rmap(M,rM)   for(auto kv: M){rM[kv.second]=kv.first;}

// VECTORS.
#define vi                vector<int>
#define vvi               vector<vector<int>>

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    // The range of long and int are the same, 1 - 2bil.
    int read(t);

    forn(i,t){
    	long long ans=0;
    	long long reads(n,m);

    	// Read inputs.
    	vector<vector<long long>> rser(n,VV);
    	forn(j,n){
    		vector<long long> rser(m,V);

    		forn(k,m){
    			long long emplb(V,num);
			}
			VV.emplace_back(V);
		}

		// Process info.
		forn(j,n/2){
			forn(k,m/2){
				long long q,w,e,r;

				q=VV[j][k];
				w=VV[j][m-1-k];
				e=VV[n-1-j][k];
				r=VV[n-1-j][m-1-k];

				long long mid=(q+w+e+r);

				if(mid%4==0){
					mid/=4;
				}else{
					(mid/=4)+=1;
				}
				//cout<<"........................................ mid = "<<mid<<endl;

				ans+=abs(q-mid);
				ans+=abs(w-mid);
				ans+=abs(e-mid);
				ans+=abs(r-mid);

//				map<int,int> M;
//
//				M[VV[j][k]]+=1;
//				M[VV[j][m-1-k]]+=1;
//				M[VV[n-1-j][k]]+=1;
//				M[VV[n-1-j][m-1-k]]+=1;
//
//				int curr=0,val=0;
//				forea(kv,M){
//					if(kv.second>curr){
//						curr=kv.second;
//						val=kv.first;
//					}
//				}
//
//				forea(kv,M){
//					ans+=abs(kv.first-val);
//				}
			}
		}

		// Check if m is even...
		if(m%2==1){
			forn(j,n/2){
				if(VV[j][m/2]!=VV[n-1-j][m/2]){
					ans+=abs(VV[j][m/2]-VV[n-1-j][m/2]);
					//cout<<"........................................ diff m = "<<abs(VV[j][m/2+1]-VV[n-1-j][m/2+1])<<endl;
				}
			}
		}

		// Might have to manually assess the middle row.
		if(n%2==1){
			forn(j,m/2){
				if(VV[n/2][j]!=VV[n/2][m-1-j]){
					ans+=abs(VV[n/2][j]-VV[n/2][m-1-j]);
					//cout<<"........................................ diff n = "<<VV[n/2+1][j]<<" - "<<VV[n/2+1][m-1-j]<<endl;
				}
			}
		}

		// Print ans.
		cout<<ans<<endl;
	}

    return 0;
}


#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <cctype>
#include <queue>
#include <stdlib.h>
#include <cstdlib>
#include <math.h>
#include"map"
#include <set>
#include"queue"
#include <vector>
#define inf 1e9
#define M 10010001
#define ll long long
#define PII pair<int,int>
using namespace std;
inline int read(){
    ll xx = 0, w = 1; char ch = getchar();
    while(ch < '0' || ch > '9')   { if(ch == '-') w = -1; ch = getchar(); }
    while(ch >= '0' && ch <= '9') { xx = (xx << 3) + (xx << 1) + (ch ^ 48); ch = getchar(); }
    return xx * w;
}
const int N = 100100;
const double eps=1e-9;
int head[N],ver[N << 1],Next[N << 1],Edge[N << 1],tot;

int G[110][110];
ll abs(ll a,ll b){
    if(a > b)
    return a - b;
    else return b - a;
}
ll ans = 0;
ll check(int a,int b,int c,int d){
    ll s1 = abs(b - a) + abs(c - a) + abs(d - a);
    ll s2 = abs(a - b) + abs(c - b) + abs(d - b);
    ll s3 = abs(a - c) + abs(b - c) + abs(d - c);
    return min(min(s1,s2),s3);
}
int main() {
	int T = read();
	while(T --){
        ans = 0;
        int n = read(),m = read();
        for(int i = 1; i <= n;i ++){
            for(int j = 1; j <= m;j ++){
               G[i][j] = read();
            }
        }

        for(int i = 1,j = n; i < j; i ++,j --){
            for(int k = 1,z = m; k < z; k ++,z --){
                ans += check(G[i][k],G[i][z],G[j][k],G[j][z]);
            }
        }
     //   printf("ans = %lld\n",ans);
        if(n % 2){
            int mid = n / 2 + 1;
            for(int i = 1,j = m; i < j; i ++,j --){
               ans += abs(G[mid][i]-G[mid][j]);
            }
        }
        if(m % 2){
            int mid = m / 2 + 1;
            for(int i = 1,j = n; i < j;i ++,j --){
                ans += abs(G[i][mid]-G[j][mid]);
            }
        }
        printf("%lld\n",ans);
	}
}


#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <cctype>
#include <queue>
#include <stdlib.h>
#include <cstdlib>
#include <math.h>
#include"map"
#include <set>
#include"queue"
#include <vector>
#define inf 1e9
#define M 10010001
#define ll long long
#define PII pair<int,int>
using namespace std;
inline int read(){
    ll xx = 0, w = 1; char ch = getchar();
    while(ch < '0' || ch > '9')   { if(ch == '-') w = -1; ch = getchar(); }
    while(ch >= '0' && ch <= '9') { xx = (xx << 3) + (xx << 1) + (ch ^ 48); ch = getchar(); }
    return xx * w;
}
const int N = 100100;
const double eps=1e-9;
int head[N],ver[N << 1],Next[N << 1],Edge[N << 1],tot;

int G[110][110];
ll abs(ll a){
    if(a > 0)
    return a ;
    else return -a;
}
ll ans = 0;
ll check(int a,int b,int c,int d){
    ll s1 = abs(b - a) + abs(c - a) + abs(d - a);
    ll s2 = abs(a - b) + abs(c - b) + abs(d - b);
    ll s3 = abs(a - c) + abs(b - c) + abs(d - c);
    return min(min(s1,s2),s3);
}
int main() {
	int T = read();
	while(T --){
        ans = 0;
        int n = read(),m = read();
        for(int i = 1; i <= n;i ++){
            for(int j = 1; j <= m;j ++){
               G[i][j] = read();
            }
        }

        for(int i = 1,j = n; i < j; i ++,j --){
            for(int k = 1,z = m; k < z; k ++,z --){
                ans += check(G[i][k],G[i][z],G[j][k],G[j][z]);
            }
        }
     //   printf("ans = %lld\n",ans);
        if(n % 2){
            int mid = n / 2 + 1;
            for(int i = 1,j = m; i < j; i ++,j --){
               ans += abs(G[mid][i]-G[mid][j]);
            }
        }
        if(m % 2){
            int mid = m / 2 + 1;
            for(int i = 1,j = n; i < j;i ++,j --){
                ans += abs(G[i][mid]-G[j][mid]);
            }
        }
        printf("%lld\n",ans);
	}
}


#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <cctype>
#include <queue>
#include <stdlib.h>
#include <cstdlib>
#include <math.h>
#include"map"
#include <set>
#include"queue"
#include <vector>
#define inf 1e9
#define M 10010001
#define ll long long
#define PII pair<int,int>
using namespace std;
inline int read(){
    ll xx = 0, w = 1; char ch = getchar();
    while(ch < '0' || ch > '9')   { if(ch == '-') w = -1; ch = getchar(); }
    while(ch >= '0' && ch <= '9') { xx = (xx << 3) + (xx << 1) + (ch ^ 48); ch = getchar(); }
    return xx * w;
}
const int N = 100100;
const double eps=1e-9;

int G[110][110];
ll abs(ll a){
    if(a > 0)
    return a ;
    else return -a;
}
ll ans = 0;
ll check(ll a,ll b,ll c,ll d){
    ll s1 = abs(b - a) + abs(c - a) + abs(d - a);
    ll s2 = abs(a - b) + abs(c - b) + abs(d - b);
    ll s3 = abs(a - c) + abs(b - c) + abs(d - c);
    return min(min(s1,s2),s3);
}
int main() {
	int T = read();
	while(T --){
        ans = 0;
        int n = read(),m = read();
        for(int i = 1; i <= n;i ++){
            for(int j = 1; j <= m;j ++){
               G[i][j] = read();
            }
        }

        for(int i = 1,j = n; i < j; i ++,j --){
            for(int k = 1,z = m; k < z; k ++,z --){
                ans += check(G[i][k],G[i][z],G[j][k],G[j][z]);
            }
        }
     //   printf("ans = %lld\n",ans);
        if(n % 2){
            int mid = n / 2 + 1;
            for(int i = 1,j = m; i < j; i ++,j --){
               ans += abs(G[mid][i]-G[mid][j]);
            }
        }
        if(m % 2){
            int mid = m / 2 + 1;
            for(int i = 1,j = n; i < j;i ++,j --){
                ans += abs(G[i][mid]-G[j][mid]);
            }
        }
        printf("%lld\n",ans);
	}
}


#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <cctype>
#include <queue>
#include <stdlib.h>
#include <cstdlib>
#include <math.h>
#include"map"
#include <set>
#include"queue"
#include <vector>
#define inf 1e9
#define M 10010001
#define ll long long
#define PII pair<int,int>
using namespace std;
inline int read(){
    ll xx = 0, w = 1; char ch = getchar();
    while(ch < '0' || ch > '9')   { if(ch == '-') w = -1; ch = getchar(); }
    while(ch >= '0' && ch <= '9') { xx = (xx << 3) + (xx << 1) + (ch ^ 48); ch = getchar(); }
    return xx * w;
}
const int N = 100100;
const double eps=1e-9;
int head[N],ver[N << 1],Next[N << 1],Edge[N << 1],tot;

int G[110][110];
ll abs(ll a){
    if(a > 0)
    return a ;
    else return 0 - a;
}
ll ans = 0;
ll check(int a,int b,int c,int d){
    ll s1 = abs(b - a) + abs(c - a) + abs(d - a);
    ll s2 = abs(a - b) + abs(c - b) + abs(d - b);
    ll s3 = abs(a - c) + abs(b - c) + abs(d - c);
    return min(min(s1,s2),s3);
}
int main() {
	int T = read();
	while(T --){
        ans = 0;
        int n = read(),m = read();
        for(int i = 1; i <= n;i ++){
            for(int j = 1; j <= m;j ++){
               G[i][j] = read();
            }
        }

        for(int i = 1,j = n; i < j; i ++,j --){
            for(int k = 1,z = m; k < z; k ++,z --){
                ans += check(G[i][k],G[i][z],G[j][k],G[j][z]);
            }
        }
     //   printf("ans = %lld\n",ans);
        if(n % 2){
            int mid = n / 2 + 1;
            for(int i = 1,j = m; i < j; i ++,j --){
               ans += abs(G[mid][i]-G[mid][j]);
            }
        }
        if(m % 2){
            int mid = m / 2 + 1;
            for(int i = 1,j = n; i < j;i ++,j --){
                ans += abs(G[i][mid]-G[j][mid]);
            }
        }
        printf("%lld\n",ans);
	}
}


#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <cctype>
#include <queue>
#include <stdlib.h>
#include <cstdlib>
#include <math.h>
#include"map"
#include <set>
#include"queue"
#include <vector>
#define inf 1e9
#define M 10010001
#define ll long long
#define PII pair<int,int>
using namespace std;
inline int read(){
    ll xx = 0, w = 1; char ch = getchar();
    while(ch < '0' || ch > '9')   { if(ch == '-') w = -1; ch = getchar(); }
    while(ch >= '0' && ch <= '9') { xx = (xx << 3) + (xx << 1) + (ch ^ 48); ch = getchar(); }
    return xx * w;
}
const int N = 100100;
const double eps=1e-9;

int G[110][110];
ll absf(ll a){
    if(a > 0)
    return a ;
    else return -a;
}
ll ans = 0;
ll check(ll a,ll b,ll c,ll d){
    ll s1 = absf(b - a) + absf(c - a) + absf(d - a);
    ll s2 = absf(a - b) + absf(c - b) + absf(d - b);
    ll s3 = absf(a - c) + absf(b - c) + absf(d - c);
    return min(min(s1,s2),s3);
}
int main() {
	int T = read();
	while(T --){
        ans = 0;
        int n = read(),m = read();
        for(int i = 1; i <= n;i ++){
            for(int j = 1; j <= m;j ++){
               G[i][j] = read();
            }
        }

        for(int i = 1,j = n; i < j; i ++,j --){
            for(int k = 1,z = m; k < z; k ++,z --){
                ans += check(G[i][k],G[i][z],G[j][k],G[j][z]);
            }
        }
     //   printf("ans = %lld\n",ans);
        if(n % 2){
            int mid = n / 2 + 1;
            for(int i = 1,j = m; i < j; i ++,j --){
               ans += absf(G[mid][i]-G[mid][j]);
            }
        }
        if(m % 2){
            int mid = m / 2 + 1;
            for(int i = 1,j = n; i < j;i ++,j --){
                ans += absf(G[i][mid]-G[j][mid]);
            }
        }
        printf("%lld\n",ans);
	}
}


#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <cctype>
#include <queue>
#include <stdlib.h>
#include <cstdlib>
#include <math.h>
#include"map"
#include <set>
#include"queue"
#include <vector>
#define inf 1e9
#define M 10010001
#define ll long long
#define PII pair<int,int>
using namespace std;
inline int read(){
    ll xx = 0, w = 1; char ch = getchar();
    while(ch < '0' || ch > '9')   { if(ch == '-') w = -1; ch = getchar(); }
    while(ch >= '0' && ch <= '9') { xx = (xx << 3) + (xx << 1) + (ch ^ 48); ch = getchar(); }
    return xx * w;
}
const int N = 100100;
const double eps=1e-9;
int head[N],ver[N << 1],Next[N << 1],Edge[N << 1],tot;

int G[110][110];

ll ans = 0;
ll check(int a,int b,int c,int d){
    ll s1 = abs(b - a) + abs(c - a) + abs(d - a);
    ll s2 = abs(a - b) + abs(c - b) + abs(d - b);
    ll s3 = abs(a - c) + abs(b - c) + abs(d - c);
    return min(min(s1,s2),s3);
}
int main() {
	int T = read();
	while(T --){
        ans = 0;
        int n = read(),m = read();
        for(int i = 1; i <= n;i ++){
            for(int j = 1; j <= m;j ++){
               G[i][j] = read();
            }
        }

        for(int i = 1,j = n; i < j; i ++,j --){
            for(int k = 1,z = m; k < z; k ++,z --){
                ans += check(G[i][k],G[i][z],G[j][k],G[j][z]);
            }
        }
     //   printf("ans = %lld\n",ans);
        if(n % 2){
            int mid = n / 2 + 1;
            for(int i = 1,j = m; i < j; i ++,j --){
               ans += abs(G[mid][i]-G[mid][j]);
            }
        }
        if(m % 2){
            int mid = m / 2 + 1;
            for(int i = 1,j = n; i < j;i ++,j --){
                ans += abs(G[i][mid]-G[j][mid]);
            }
        }
        printf("%lld\n",ans);
	}
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define ll long long
#define FASTIO ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define inf 1e18
#define ff first
#define ss second
#define MOD 1000000007
#define lb lower_bound
#define ub upper_bound
#define bs binary_search
#define mod 1000000007
#define pb push_back
#define all(s) s.begin(),s.end()
#define pie 3.14159265358979323846
#define fr(i,a,b)  for(ll i=a;i<b;i++)
#define frr(i,a,b) for(ll i=b-1;i>=a;i--)
#define gcd __gcd
#define con continue
#define pii pair<ll,ll>
const ll N=18;
char arr[N][N];

signed main(){
    FASTIO;
    ll tt=1;
    cin>>tt;
    while(tt--){
       ll n,m;cin>>n>>m;
       ll a[n][m],ans=0,fans=0;
       for(ll i=0;i<n;i++)for(ll j=0;j<m;j++)cin>>a[i][j];
       set<pii>sst;
       for(ll i=0;i<(n+1)/2;i++){
          set<pii>st;
          for(ll j=0;j<(m+1)/2;j++){
             st.insert({i,j});
             st.insert({i,m-j-1});
             st.insert({n-i-1,j});
             st.insert({n-i-1,m-j-1});
          }
          ll s=0,e=1e17,ans;
          while(s<=e){
             ll sum=0,mid;
             mid=(s+e)/2;
             for(auto x:st){
                sum+=mid-a[x.ff][x.ss];
             }
             //sum/=st.size();
             if(sum>=0){
               e=mid-1;
               ans=mid;
               //cout<<ans<<"d\n";
             }
             else s=mid+1;
          }
          //cout<<pre<<"\n";
          //cout<<ans<<"same\n";
          ll mid=ans;
          //cout<<mid<<"\n";
          for(auto x:st){
             fans+=abs(mid-a[x.ff][x.ss]);
          }
          //cout<<"dd";
       }
       cout<<fans<<"\n";
    }
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define ll long long
#define FASTIO ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define inf 1e18
#define ff first
#define ss second
#define MOD 1000000007
#define lb lower_bound
#define ub upper_bound
#define bs binary_search
#define mod 1000000007
#define pb push_back
#define all(s) s.begin(),s.end()
#define pie 3.14159265358979323846
#define fr(i,a,b)  for(ll i=a;i<b;i++)
#define frr(i,a,b) for(ll i=b-1;i>=a;i--)
#define gcd __gcd
#define con continue
#define pii pair<ll,ll>
const ll N=18;
char arr[N][N];

signed main(){
    FASTIO;
    ll tt=1;
    cin>>tt;
    while(tt--){
       ll n,m;cin>>n>>m;
       ll a[n][m],ans=0,fans=0;
       for(ll i=0;i<n;i++)for(ll j=0;j<m;j++)cin>>a[i][j];
       set<pii>sst;
       for(ll i=0;i<(n+1)/2;i++){
          set<pii>st;
          for(ll j=0;j<(m+1)/2;j++){
             st.insert({i,j});
             st.insert({i,m-j-1});
             st.insert({n-i-1,j});
             st.insert({n-i-1,m-j-1});
          }
          ll sum=0;
          for(auto x:st){
             sum+=a[x.ff][x.ss];
          }

          sum/=st.size();
          for(auto x:st){
             fans+=abs(sum-a[x.ff][x.ss]);
          }
       }
       cout<<fans<<"\n";
    }
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define ll long long
#define FASTIO ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define inf 1e11
#define ff first
#define ss second
#define MOD 1000000007
#define lb lower_bound
#define ub upper_bound
#define bs binary_search
#define mod 1000000007
#define pb push_back
#define all(s) s.begin(),s.end()
#define pie 3.14159265358979323846
#define fr(i,a,b)  for(ll i=a;i<b;i++)
#define frr(i,a,b) for(ll i=b-1;i>=a;i--)
#define gcd __gcd
#define con continue
#define pii pair<ll,ll>
const ll N=18;
char arr[N][N];

signed main(){
    FASTIO;
    ll tt=1;
    cin>>tt;
    while(tt--){
       ll n,m;cin>>n>>m;
       ll a[n][m],ans=0,fans=0;
       for(ll i=0;i<n;i++)for(ll j=0;j<m;j++)cin>>a[i][j];
       set<pii>sst;
       for(ll i=0;i<(n+1)/2;i++){
          set<pii>st;
          for(ll j=0;j<(m+1)/2;j++){
             st.insert({i,j});
             st.insert({i,m-j-1});
             st.insert({n-i-1,j});
             st.insert({n-i-1,m-j-1});
          }
          ll s=0,e=1e17,pre=inf;
          while(s<=e){
             ll s1=0,mid,s2=0;
             mid=(s+e)/2;
             for(auto x:st){
                s1+=abs(mid-a[x.ff][x.ss]);
             }
             mid--;
             for(auto x:st){
                s2+=abs(mid-a[x.ff][x.ss]);
             }
             mid++;
             if(s1>s2){
               e=mid-1;
               //cout<<e<<"\n";
               pre=e;
             }
             else s=mid+1;
          }
          for(auto x:st){
             fans+=abs(pre-a[x.ff][x.ss]);
          }
       }
       cout<<fans<<"\n";
    }
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define ll long long
#define FASTIO ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define inf 1e11
#define ff first
#define ss second
#define MOD 1000000007
#define lb lower_bound
#define ub upper_bound
#define bs binary_search
#define mod 1000000007
#define pb push_back
#define all(s) s.begin(),s.end()
#define pie 3.14159265358979323846
#define fr(i,a,b)  for(ll i=a;i<b;i++)
#define frr(i,a,b) for(ll i=b-1;i>=a;i--)
#define gcd __gcd
#define con continue
#define pii pair<ll,ll>
const ll N=1e6+5;
ll prime[N];

signed main(){
    FASTIO;
    ll tt=1;
    cin>>tt;
    while(tt--){
       ll n,m;cin>>n>>m;
       ll a[n][m],fans=0;
       for(ll i=0;i<n;i++)for(ll j=0;j<m;j++)cin>>a[i][j];
       for(ll i=0;i<n;i++){
          for(ll j=0;j<m;j++){
             vector<ll>v;
             v.pb(a[i][j]);
             v.pb(a[i][m-j-1]);
             v.pb(a[n-i-1][j]);
             v.pb(a[n-i-1][m-j-1]);
             sort(all(v));
             ll ans=0;
             ans+=abs(a[i][j]-v[1]);
             a[i][j]=v[1];
             ans+=abs(a[n-i-1][j]-v[1]);
             a[n-i-1][j]=v[1];
             ans+=abs(a[i][m-j-1]-v[1]);
             a[i][m-j-1]=v[1];
             ans+=abs(a[n-i-1][m-j-1]-v[1]);
             a[n-i-1][m-j-1]=v[1];
             fans+=ans;
          }
       }
       cout<<fans<<"\n";
    }
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define ll long long
#define FASTIO ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define inf 1e11
#define ff first
#define ss second
#define MOD 1000000007
#define lb lower_bound
#define ub upper_bound
#define bs binary_search
#define mod 1000000007
#define pb push_back
#define all(s) s.begin(),s.end()
#define pie 3.14159265358979323846
#define fr(i,a,b)  for(ll i=a;i<b;i++)
#define frr(i,a,b) for(ll i=b-1;i>=a;i--)
#define gcd __gcd
#define con continue
#define pii pair<ll,ll>
const ll N=1e6+5;
ll prime[N];

signed main(){
    FASTIO;
    ll tt=1;
    cin>>tt;
    while(tt--){
       ll n,m;cin>>n>>m;
       ll a[n][m],fans=0;
       for(ll i=0;i<n;i++)for(ll j=0;j<m;j++)cin>>a[i][j];
       for(ll i=0;i<n;i++){
          for(ll j=0;j<m;j++){
             vector<pii>vv;
             vv.pb({i,j});vv.pb({n-i-1,j});
             vv.pb({i,m-j-1});vv.pb({n-i-1,m-j-1});
             sort(all(vv));
             ll ans=0,ele=a[vv[1].ff][vv[1].ss];
             for(auto x:vv){
                ans+=abs(a[x.ff][x.ss]-ele);
                a[x.ff][x.ss]=ele;
             }
             fans+=ans;
          }
       }
       cout<<fans<<"\n";
    }
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define ll long long
#define FASTIO ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define inf 1e11
#define ff first
#define ss second
#define MOD 1000000007
#define lb lower_bound
#define ub upper_bound
#define bs binary_search
#define mod 1000000007
#define pb push_back
#define all(s) s.begin(),s.end()
#define pie 3.14159265358979323846
#define fr(i,a,b)  for(ll i=a;i<b;i++)
#define frr(i,a,b) for(ll i=b-1;i>=a;i--)
#define gcd __gcd
#define con continue
#define pii pair<ll,ll>
const ll N=18;
char arr[N][N];

signed main(){
    FASTIO;
    ll tt=1;
    cin>>tt;
    while(tt--){
       ll n,m;cin>>n>>m;
       ll a[n][m],ans=0,fans=0;
       for(ll i=0;i<n;i++)for(ll j=0;j<m;j++)cin>>a[i][j];
       set<pii>sst;
       for(ll i=0;i<(n+1)/2;i++){
          set<pii>st;
          for(ll j=0;j<(m+1)/2;j++){
             st.insert({i,j});
             st.insert({i,m-j-1});
             st.insert({n-i-1,j});
             st.insert({n-i-1,m-j-1});
          }
          ll s=0,e=1e9+6,pre=inf;
          while(s<=e){
             ll sum=0,mid;
             mid=(s+e)/2;
             for(auto x:st){
                sum+=abs(mid-a[x.ff][x.ss]);
             }
             if(sum<pre){
               e=mid-1;
               pre=sum;
             }
             else s=mid+1;
          }
          //cout<<pre<<"\n";
          fans+=pre;
       }
       cout<<fans<<"\n";
    }
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define ll long long
#define FASTIO ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define inf 1e18
#define ff first
#define ss second
#define MOD 1000000007
#define lb lower_bound
#define ub upper_bound
#define bs binary_search
#define mod 1000000007
#define pb push_back
#define all(s) s.begin(),s.end()
#define pie 3.14159265358979323846
#define fr(i,a,b)  for(ll i=a;i<b;i++)
#define frr(i,a,b) for(ll i=b-1;i>=a;i--)
#define gcd __gcd
#define con continue
#define pii pair<ll,ll>
const ll N=18;
char arr[N][N];

signed main(){
    FASTIO;
    ll tt=1;
    cin>>tt;
    while(tt--){
       ll n,m;cin>>n>>m;
       ll a[n][m],ans=0,fans=0;
       for(ll i=0;i<n;i++)for(ll j=0;j<m;j++)cin>>a[i][j];
       for(ll i=0;i<n;i++){
          set<pii>st;
          for(ll j=0;j<m;j++){
             st.insert({i,j});
             st.insert({i,m-j-1});
             st.insert({n-i-1,j});
             st.insert({n-i-1,m-j-1});
          }
          ans+=st.size();
          ll sum=0;
          for(auto x:st){
             sum+=a[x.ff][x.ss];
          }
          //cout<<st.size()<<"\n";
          sum/=st.size();
          for(auto x:st){
             fans+=abs(sum-a[x.ff][x.ss]);
          }
          if(ans==n*m)break;
       }
       cout<<fans<<"\n";
    }
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define ll long long
#define FASTIO ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define inf 1e11
#define ff first
#define ss second
#define MOD 1000000007
#define lb lower_bound
#define ub upper_bound
#define bs binary_search
#define mod 1000000007
#define pb push_back
#define all(s) s.begin(),s.end()
#define pie 3.14159265358979323846
#define fr(i,a,b)  for(ll i=a;i<b;i++)
#define frr(i,a,b) for(ll i=b-1;i>=a;i--)
#define gcd __gcd
#define con continue
#define pii pair<ll,ll>
const ll N=18;
char arr[N][N];

signed main(){
    FASTIO;
    ll tt=1;
    cin>>tt;
    while(tt--){
       ll n,m;cin>>n>>m;
       ll a[n][m],ans=0,fans=0;
       for(ll i=0;i<n;i++)for(ll j=0;j<m;j++)cin>>a[i][j];
       set<pii>sst;
       for(ll i=0;i<(n+1)/2;i++){
          set<pii>st;
          for(ll j=0;j<(m+1)/2;j++){
             st.insert({i,j});
             st.insert({i,m-j-1});
             st.insert({n-i-1,j});
             st.insert({n-i-1,m-j-1});
          }
          ll s=0,e=1e17,pre=inf;
          while(s<=e){
             ll s1=0,mid,s2=0;
             mid=(s+e)/2;
             for(auto x:st){
                s1+=abs(mid-a[x.ff][x.ss]);
             }
             mid--;
             for(auto x:st){
                s2+=abs(mid-a[x.ff][x.ss]);
             }
             mid++;
             if(s1>=s2){
               e=mid-1;
               //cout<<e<<"\n";
               pre=e;
             }
             else s=mid+1;
          }
          for(auto x:st){
             fans+=abs(pre-a[x.ff][x.ss]);
          }
       }
       cout<<fans<<"\n";
    }
}


#include<bits/stdc++.h>
#define MAXN 300
long long M[MAXN][MAXN];
using namespace std;
int main()
{
    int T;cin>>T;
    while(T--)
    {
        long long ans=0;
        int n,m;cin>>n>>m;
        for(int i=1;i<=n;i++)
            for(int j=1;j<=m;j++)
                cin>>M[i][j];
        for(int i=1;i<=(n+1)/2;i++)
            for(int j=1;j<=(m+1)/2;j++)
        {
            long long sum=M[i][j]+M[n-i+1][j]+M[i][m-j+1]+M[n-i+1][m-j+1];
            long long t=sum/4*4;
            if(sum-t>=2)t=sum/4+1;
            else t=sum/4;
            long long a=(n-i+1!=i),b=(m-j+1!=j),c=a&&b;
            ans+=abs(M[i][j]-t)+a*abs(M[n-i+1][j]-t)+b*abs(M[i][m-j+1]-t)+c*abs(M[n-i+1][m-j+1]-t);
       }
        cout<<ans<<endl;
    }
}


#include<bits/stdc++.h>
#define MAXN 30
long long M[MAXN][MAXN];
using namespace std;
int main()
{
    int T;cin>>T;
    while(T--)
    {
        long long ans=0;
        int n,m;cin>>n>>m;
        for(int i=1;i<=n;i++)
            for(int j=1;j<=m;j++)
                cin>>M[i][j];
        for(int i=1;i<=(n+1)/2;i++)
            for(int j=1;j<=(m+1)/2;j++)
        {
            long long aa[4];aa[0]=M[i][j],aa[1]=M[n-i+1][j],aa[2]=M[i][m-j+1],aa[3]=M[n-i+1][m-j+1];
            sort(aa,aa+4);
            long long t=aa[1],t1=aa[2];
            long long a=(n-i+1!=i),b=(m-j+1!=j),c=a&&b;
            long long a1=abs(M[i][j]-t)+a*abs(M[n-i+1][j]-t)+b*abs(M[i][m-j+1]-t)+c*abs(M[n-i+1][m-j+1]-t);
            long long a2=abs(M[i][j]-t1)+a*abs(M[n-i+1][j]-t1)+b*abs(M[i][m-j+1]-t1)+c*abs(M[n-i+1][m-j+1]-t1);
            //ans+=min(a1,a2);
            cout<<ans<<endl;
       }
        cout<<ans<<endl;
    }
}


#include<bits/stdc++.h>
#define MAXN 30
long long M[MAXN][MAXN];
using namespace std;
int main()
{
    int T;cin>>T;
    while(T--)
    {
        long long ans=0;
        int n,m;cin>>n>>m;
        for(int i=1;i<=n;i++)
            for(int j=1;j<=m;j++)
                cin>>M[i][j];
        for(int i=1;i<=(n+1)/2;i++)
            for(int j=1;j<=(m+1)/2;j++)
        {
            long long sum=M[i][j]+M[n-i+1][j]+M[i][m-j+1]+M[n-i+1][m-j+1];
            long long t=sum/4*4;
            if(sum-t>=2)t=sum/4+1;
            else t=sum/4;
            int a=!(n-i+1==i),b=!(m-j+1==j),c=a&&b;
            ans+=abs(M[i][j]-t)+a*abs(M[n-i+1][j]-t)+b*abs(M[i][m-j+1]-t)+c*abs(M[n-i+1][m-j+1]-t);
       }
        cout<<ans<<endl;
    }
}


#include<bits/stdc++.h>
#define MAXN 105
long long M[MAXN][MAXN];
using namespace std;
int main()
{
    int T;cin>>T;
    while(T--)
    {
        long long ans=0;
        int n,m;cin>>n>>m;
        for(int i=1;i<=n;i++)
            for(int j=1;j<=m;j++)
                cin>>M[i][j];
        for(int i=1;i<=(n+1)/2;i++)
            for(int j=1;j<=(m+1)/2;j++)
        {
            long long sum=M[i][j]+M[n-i+1][j]+M[i][m-j+1]+M[n-i+1][m-j+1];
            long long t=sum/4*4;
            if(sum-t>=2)t=sum/4+1;
            else t=sum/4;
            int a=!(n-i+1==i),b=!(m-j+1==j),c=a&&b;
            ans+=abs(M[i][j]-t)+a*abs(M[n-i+1][j]-t)+b*abs(M[i][m-j+1]-t)+c*abs(M[n-i+1][m-j+1]-t);
       }
        cout<<ans<<endl;
    }
}


#include<bits/stdc++.h>
#define MAXN 300
long long M[MAXN][MAXN];
using namespace std;
int main()
{
    int T;cin>>T;
    while(T--)
    {
        long long ans=0;
        int n,m;cin>>n>>m;
        for(int i=1;i<=n;i++)
            for(int j=1;j<=m;j++)
                cin>>M[i][j];
        for(int i=1;i<=(n+1)/2;i++)
            for(int j=1;j<=(m+1)/2;j++)
        {
            long long aa[4];aa[0]=M[i][j],aa[1]=M[n-i+1][j],aa[2]=M[i][m-j+1],aa[3]=M[n-i+1][m-j+1];
            sort(aa,aa+4);
            long long t=aa[1],t1=aa[2];
            long long a=(n-i+1!=i),b=(m-j+1!=j),c=a&&b;
            long long a1=abs(M[i][j]-t)+a*abs(M[n-i+1][j]-t)+b*abs(M[i][m-j+1]-t)+c*abs(M[n-i+1][m-j+1]-t);
            long long a2=abs(M[i][j]-t1)+a*abs(M[n-i+1][j]-t1)+b*abs(M[i][m-j+1]-t1)+c*abs(M[n-i+1][m-j+1]-t1);
            ans+=min(a1,a2);
            //cout<<ans<<endl;
       }
        cout<<ans<<endl;
    }
}


#include<bits/stdc++.h>
using namespace std;
#define FIO ios_base::sync_with_stdio (false) ;cin.tie(NULL);
#define tc  int t;cin>>t;for(int i=0;i<t;i++)
#define ll long long int
#define forn(i,n) for(int i=0;i<n;i++)
#define forn1(i,a,b) for(int i=a;i<=b;i++)
#define pb push_back
#define um(a,b) unordered_map<a,b>
#define vv(a) vector<a>
#define pp(a,b) pair<a,b>
ll power(ll a,ll b,ll mod){  ll ans=1;  while(b>0){
  if(b&1){ ans=(ans*a)%mod;} a=(a*a)%mod;  b=b/2; } return ans;}
ll computeCost(vector<ll>&a,ll val){
    ll ans=0;
    for(auto k:a){
        ans+= abs(k-val);
    }
    return ans;
}

ll ternary_search(vector<ll>&arr,ll l,ll r)
{

            ll temp1 = INT_MAX;
            while(l <= r){
                ll mid1 = l + (r-l)/3;
                ll mid2 = r - (r-l)/3;
                ll val1 = computeCost(arr, mid1);
                ll val2 = computeCost(arr, mid2);
                temp1 = min(temp,min(val1, val2));
                if(val1 <= val2){
                    r = mid2-1;
                }else{
                    l = mid1+1;
                }
            }
            return temp1;
}
int main(){
FIO
tc{
     ll n,m;
     cin>>n>>m;
     ll arr[n][m];
     for(ll i=0;i<n;i++){
         for(ll j=0;j<m;j++){
             cin>>arr[i][j];
         }
     }
     ll ans=0;
     ll b=0;
     ll c=pow(10,9);
     for(int i=0;i<n/2;i++){
         for(int j=0;j<m/2;j++){
             vector<ll> a;
             a.push_back(arr[i][j]);
             a.push_back(arr[n-1-i][j]);
             a.push_back(arr[i][m-1-j]);
             a.push_back(arr[n-1-i][m-1-j]);
             ans+=ternary_search(a,b,c);
         }
     }
     if(n%2==1){
         for(int j=0;j<m/2;j++){
             vector<ll> a;
             a.push_back(arr[n/2][j]);
             a.push_back(arr[n/2][m-1-j]);
             ans+=ternary_search(a,b,c);
         }
     }
     if(m%2==1){
         for(int i=0;i<n/2;i++){
             vector<ll> a;
             a.push_back(arr[i][m/2]);
             a.push_back(arr[n-1-i][m/2]);
             ans+=ternary_search(a,b,c);
         }
     }
     cout<<ans<<endl;
     }
}


#include<bits/stdc++.h>
using namespace std;
#define FIO ios_base::sync_with_stdio (false) ;cin.tie(NULL);
#define tc  int t;cin>>t;for(int i=0;i<t;i++)
#define ll long long int
#define forn(i,n) for(int i=0;i<n;i++)
#define forn1(i,a,b) for(int i=a;i<=b;i++)
#define pb push_back
#define um(a,b) unordered_map<a,b>
#define vv(a) vector<a>
#define pp(a,b) pair<a,b>
ll power(ll a,ll b,ll mod){  ll ans=1;  while(b>0){
  if(b&1){ ans=(ans*a)%mod;} a=(a*a)%mod;  b=b/2; } return ans;}
ll computeCost(vector<ll>&a,ll val){
    ll ans=0;
    for(auto k:a){
        ans+=abs(k-val);
    }
    return ans;
}

ll ternary_search(vector<ll>&arr,ll low,ll high)
{

    while ((high - low) > 0) {

        ll mid1 = low + (high - low) / 3;
        ll mid2 = high - (high - low) / 3;

        ll cost1 = computeCost(arr, mid1);
        ll cost2 = computeCost(arr, mid2);
        if (cost1 < cost2)
            high = mid2;
        else
            low = mid1;
    }
    return computeCost(arr, (low + high) / 2);
}
int main(){
FIO
tc{
     ll n,m;
     cin>>n>>m;
     ll arr[n][m];
     for(ll i=0;i<n;i++){
         for(ll j=0;j<m;j++){
             cin>>arr[i][j];
         }
     }
     ll ans=0;
     ll b=0;
     ll c=pow(10,9);
     for(int i=0;i<n/2;i++){
         for(int j=0;j<m/2;j++){
             vector<ll> a;
             a.push_back(arr[i][j]);
             a.push_back(arr[n-1-i][j]);
             a.push_back(arr[i][m-1-j]);
             a.push_back(arr[n-1-i][m-1-j]);
             ans+=ternary_search(a,b,c);
         }
     }
     if(n%2==1){
         for(int j=0;j<m/2;j++){
             vector<ll> a;
             a.push_back(arr[n/2][j]);
             a.push_back(arr[n/2][m-1-j]);
             ans+=ternary_search(a,b,c);
         }
     }
     if(m%2==1){
         for(int i=0;i<n/2;i++){
             vector<ll> a;
             a.push_back(arr[i][m/2]);
             a.push_back(arr[n-1-i][m/2]);
             ans+=ternary_search(a,b,c);
         }
     }
     cout<<ans<<endl;
     }
}


#include<bits/stdc++.h>
using namespace std;
#define FIO ios_base::sync_with_stdio (false) ;cin.tie(NULL);
#define tc  int t;cin>>t;for(int i=0;i<t;i++)
#define ll long long int
#define forn(i,n) for(int i=0;i<n;i++)
#define forn1(i,a,b) for(int i=a;i<=b;i++)
#define pb push_back
#define um(a,b) unordered_map<a,b>
#define vv(a) vector<a>
#define pp(a,b) pair<a,b>
ll power(ll a,ll b,ll mod){  ll ans=1;  while(b>0){
  if(b&1){ ans=(ans*a)%mod;} a=(a*a)%mod;  b=b/2; } return ans;}
ll computeCost(vector<ll>&a,ll val){
    ll ans=0;
    for(auto k:a){
        ans+=abs(k-val);
    }
    return ans;
}

ll ternary_search(vector<ll>&arr,ll l,ll r)
{

            ll temp1 = INT_MAX;
            while(l <= r){
                ll mid1 = l + (r-l)/3;
                ll mid2 = r - (r-l)/3;
                ll val1 = computeCost(arr, mid1);
                ll val2 = computeCost(arr, mid2);
                temp1 = min(val1, val2);
                if(val1 <= val2){
                    r = mid2-1;
                }else{
                    l = mid1+1;
                }
            }
            return temp1;
}
int main(){
FIO
tc{
     ll n,m;
     cin>>n>>m;
     ll arr[n][m];
     for(ll i=0;i<n;i++){
         for(ll j=0;j<m;j++){
             cin>>arr[i][j];
         }
     }
     ll ans=0;
     ll b=0;
     ll c=pow(10,9);
     for(int i=0;i<n/2;i++){
         for(int j=0;j<m/2;j++){
             vector<ll> a;
             a.push_back(arr[i][j]);
             a.push_back(arr[n-1-i][j]);
             a.push_back(arr[i][m-1-j]);
             a.push_back(arr[n-1-i][m-1-j]);
             ans+=ternary_search(a,b,c);
         }
     }
     if(n%2==1){
         for(int j=0;j<m/2;j++){
             vector<ll> a;
             a.push_back(arr[n/2][j]);
             a.push_back(arr[n/2][m-1-j]);
             ans+=ternary_search(a,b,c);
         }
     }
     if(m%2==1){
         for(int i=0;i<n/2;i++){
             vector<ll> a;
             a.push_back(arr[i][m/2]);
             a.push_back(arr[n-1-i][m/2]);
             ans+=ternary_search(a,b,c);
         }
     }
     cout<<ans<<endl;
     }
}


#include<bits/stdc++.h>
using namespace std;
#define FIO ios_base::sync_with_stdio (false) ;cin.tie(NULL);
#define tc  int t;cin>>t;for(int i=0;i<t;i++)
#define ll long long int
#define forn(i,n) for(int i=0;i<n;i++)
#define forn1(i,a,b) for(int i=a;i<=b;i++)
#define pb push_back
#define um(a,b) unordered_map<a,b>
#define vv(a) vector<a>
#define pp(a,b) pair<a,b>
ll power(ll a,ll b,ll mod){  ll ans=1;  while(b>0){
  if(b&1){ ans=(ans*a)%mod;} a=(a*a)%mod;  b=b/2; } return ans;}
ll computeCost(vector<ll>&a,ll val){
    ll ans=0;
    for(auto k:a){
        ans+=abs(k-val);
    }
    return ans;
}

ll ternary_search(vector<ll>&arr,ll l,ll r)
{
    sort(arr.begin(),arr.end());
    ll t = arr[arr.size()/2];
    ll ans = 0;
    for(auto i:arr) ans += abs(i-t);
    //dbgt(a) dbg(ans)
    return ans;

}
int main(){
FIO
tc{
     ll n,m;
     cin>>n>>m;
     ll arr[n][m];
     for(ll i=0;i<n;i++){
         for(ll j=0;j<m;j++){
             cin>>arr[i][j];
         }
     }
     ll ans=0;
     ll b=1;
     ll c=pow(10,9)+5;
     for(int i=0;i<n/2;i++){
         for(int j=0;j<m/2;j++){
             vector<ll> a;
             a.push_back(arr[i][j]);
             a.push_back(arr[n-1-i][j]);
             a.push_back(arr[i][m-1-j]);
             a.push_back(arr[n-1-i][m-1-j]);
             ans+=ternary_search(a,b,c);
         }
     }
     if(n%2==1){
         for(int j=0;j<m/2;j++){
             vector<ll> a;
             a.push_back(arr[n/2][j]);
             a.push_back(arr[n/2][m-1-j]);
             ans+=ternary_search(a,b,c);
         }
     }
     if(m%2==1){
         for(int i=0;i<n/2;i++){
             vector<ll> a;
             a.push_back(arr[i][m/2]);
             a.push_back(arr[n-1-i][m/2]);
             ans+=ternary_search(a,b,c);
         }
     }
     cout<<ans<<endl;
     }
}


#include <bits/stdc++.h>
using namespace std;
struct _ { ios_base::Init i; _() { cin.sync_with_stdio(0); cin.tie(0); } } _;

void definitions()
{
	#define pb push_back
	#define it(name, type) vector <type>::iterator name
	#define b() begin()
	#define e() end()
	#define vec(name, type) vector <type> name
}

struct order
{
	char direction;
	int price;
	int volume;
	void input()
	{
		cin >> direction;
		cin >> price;
		cin >> volume;
	}
	void output()
	{
		cout << direction << " " << price << " " << volume << '\n';
		//
	}
};

bool comparebyprice(const order &a, const order &b)
{
    return a.price > b.price;
    //
}

int main()
{
    int n, s;
    cin >> n >> s;
    vec(buy, order);
    vec(sell, order);

    while (n--)
    {
	    order temp;
    	temp.input();
    	if (temp.direction=='B') buy.pb(temp);
    	else sell.pb(temp);

    } cout << endl;

    vec(newb, order);
    int flag;
    for (it(i, order)=buy.b(); i!=buy.e(); i++)
    {
    	flag=0;
    	for (it(j, order)=newb.b(); j!=newb.e(); j++)
    	{
    		if (i->direction==j->direction && i->price==j->price)
    		{
    			flag=1;
    			j->volume+=i->volume;
    		}
    	}
		if (flag==0)
		{
			newb.pb(*i);
		}
    }

    vec(news, order);
    for (it(i, order)=sell.b(); i!=sell.e(); i++)
    {
    	flag=0;
    	for (it(j, order)=news.b(); j!=news.e(); j++)
    	{
    		if (i->direction==j->direction && i->price==j->price)
    		{
    			flag=1;
    			j->volume+=i->volume;
    		}
    	}
		if (flag==0)
		{
			news.pb(*i);
		}
    }

    sort(newb.begin(), newb.end(), comparebyprice);
	sort(news.begin(), news.end(), comparebyprice);

    int count=0;
    for (it(i, order)=news.b(); (i!=news.e() && count<s); i++, count++)
    {
    	i->output();
    }

    count=0;
    for (it(i, order)=newb.b(); (i!=newb.e() && count<s); i++, count++)
    {
    	i->output();
    }

}


 #include <bits/stdc++.h>
#define maxn 1001
using namespace std;
int n, s;
int b = 0, sell = 0;
struct data
{
    int d, p, q;
};
data a[maxn], mua[maxn], ban[maxn];

bool comp(data x, data y)
{
    if (x.d != y.d) return (x.d == 0);
    return (x.p < y.p);
}
void nhap()
{
    cin >> n >> s;
    char c;
    for (int i = 1; i <= n; i++)
    {
        cin >> c >> a[i].p >> a[i].q;
        a[i].d = (c == 'S');
    }
    sort (a+1, a+n+1, comp);
}
void xuly()
{
    for (int i = 1; i <= n; i++)
        if (a[i].d == 0)
        {
            if (a[i].p == a[i-1].p) mua[b].q += a[i].q;
                else mua[++b] = a[i];
        }
        else
        {
            if (a[i-1].d && a[i].p == a[i-1].p) ban[sell].q += a[i].q;
                else ban[++sell] = a[i];
        }
    for (int i = min (s, sell); i >= 1; i--)
        cout << "S" << " " << ban[i].p << " " << ban[i].q << endl;
    if (sell == 0) cout << "S " << 0 << " " << ban[1].q << endl;
    for (int i = b; i >= b - min (s, b) + 1; i--)
        cout << "B " << mua[i].p << " " << mua[i].q << endl;
    if (b == 0) cout << "B " << 0 << " " << ban[1].q << endl;
}
int main()
{
    ios_base::sync_with_stdio(0);
    nhap();
    xuly();
    return 0;
}


#include <bits/stdc++.h>
#define maxn 100001
using namespace std;
int n, s;
int a[maxn], b[maxn], c[maxn];

int main()
{
    ios_base::sync_with_stdio(0);
    cin >> n >> s;
    char ch;
    int x, y, k = 0, j = 0;
    for (int i = 1; i <= n; i++)
    {
        cin >> ch >> x >> y;
        if (ch == 'S') a[x] += y;
            else b[x] += y;
    }
    for (int i = 0; i <= 10000; i++)
    {
        if (a[i] > 0)
        {
            k++;
            c[++j] = i;
        }
        if (k == s) break;
    }
    for (int i = j; i >= 1; i--)
        cout << "S " << c[i] << " " << a[c[i]] << endl;
    k = 0;
    for (int i = 100000; i >= 0; i--)
    {
        if (b[i] > 0)
        {
            k++;
            cout << "B " << i << " " << b[i] << endl;
        }
        if (k == s) break;
    }
    return 0;
}


#include <bits/stdc++.h>
#define maxn 100010
using namespace std;
int n, s;
int a[maxn], b[maxn], c[maxn];

int main()
{
    ios_base::sync_with_stdio(0);
    cin >> n >> s;
    char ch;
    int x, y, k = 0, j = 0;
    for (int i = 1; i <= n; i++)
    {
        cin >> ch >> x >> y;
        if (ch == 'S') a[x] += y;
            else b[x] += y;
    }
    for (int i = 0; i <= 100000; i++)
    {
        if (a[i] > 0)
        {
            k++;
            c[++j] = i;
        }
        if (k == s) break;
    }
    for (int i = j; i >= 1; i--)
        cout << "S " << c[i] << " " << a[c[i]] << endl;
    k = 0;
    for (int i = 100000; i >= 0; i--)
    {
        if (b[i] > 0)
        {
            k++;
            cout << "B " << i << " " << b[i] << endl;
        }
        if (k == s) break;
    }
    return 0;
}


 #include <bits/stdc++.h>
#define maxn 1001
using namespace std;
int n, s;
int b = 0, sell = 0;
struct data
{
    int d, p, q;
};
data a[maxn], mua[maxn], ban[maxn];

bool comp(data x, data y)
{
    if (x.d != y.d) return (x.d == 0);
    return (x.p < y.p);
}
void nhap()
{
    cin >> n >> s;
    char c;
    for (int i = 1; i <= n; i++)
    {
        cin >> c >> a[i].p >> a[i].q;
        a[i].d = (c == 'S');
    }
    sort (a+1, a+n+1, comp);
}
void xuly()
{
    for (int i = 1; i <= n; i++)
        if (a[i].d == 0)
        {
            if (a[i].p == a[i-1].p) mua[b].q += a[i].q;
                else mua[++b] = a[i];
        }
        else
        {
            if (a[i-1].d && a[i].p == a[i-1].p) ban[sell].q += a[i].q;
                else ban[++sell] = a[i];
        }
    for (int i = min (s, sell); i >= 1; i--)
        cout << "S" << " " << ban[i].p << " " << ban[i].q << endl;
    if (sell == 0) cout << "B " << 0 << " " << sell[1].q << endl;
    for (int i = b; i >= b - min (s, b) + 1; i--)
        cout << "B " << mua[i].p << " " << mua[i].q << endl;
    if (b == 0) cout << "B " << 0 << " " << ban[1].q << endl;
}
int main()
{
    ios_base::sync_with_stdio(0);
    nhap();
    xuly();
    return 0;
}


#include <bits/stdc++.h>
#define maxn 100001
using namespace std;
int n, s;
int a[maxn], b[maxn], c[maxn];

int main()
{
    ios_base::sync_with_stdio(0);
    cin >> n >> s;
    char ch;
    int x, y, k = 0, j = 0;
    for (int i = 1; i <= n; i++)
    {
        cin >> ch >> x >> y;
        if (ch == 'S') a[x] += y;
            else b[x] += y;
    }
    for (int i = 0; i <= maxn; i++)
    {
        if (a[i] > 0)
        {
            k++;
            c[++j] = i;
        }
        if (k == s) break;
    }
    for (int i = j; i >= 1; i--)
        cout << "S " << c[i] << " " << a[c[i]] << endl;
    k = 0;
    for (int i = 100000; i >= 0; i--)
    {
        if (b[i] > 0)
        {
            k++;
            cout << "B " << i << " " << b[i] << endl;
        }
        if (k == s) break;
    }
    return 0;
}


 #include <bits/stdc++.h>
#define maxn 1001
using namespace std;
int n, s;
int b = 0, sell = 0;
struct data
{
    int d, p, q;
};
data a[maxn], mua[maxn], ban[maxn];

bool comp(data x, data y)
{
    if (x.d != y.d) return (x.d == 0);
    return (x.p < y.p);
}
void nhap()
{
    cin >> n >> s;
    char c;
    for (int i = 1; i <= n; i++)
    {
        cin >> c >> a[i].p >> a[i].q;
        a[i].d = (c == 'S');
    }
    sort (a+1, a+n+1, comp);
}
void xuly()
{
    for (int i = 1; i <= n; i++)
        if (a[i].d == 0)
        {
            if (a[i].p == a[i-1].p) mua[b].q += a[i].q;
                else mua[++b] = a[i];
        }
        else
        {
            if (a[i-1].d && a[i].p == a[i-1].p) ban[sell].q += a[i].q;
                else ban[++sell] = a[i];
        }
    for (int i = min (s, sell); i >= 1; i--)
        cout << "S" << " " << ban[i].p << " " << ban[i].q << endl;
    for (int i = b; i >= b - min (s, b) + 1; i--)
        cout << "B " << mua[i].p << " " << mua[i].q << endl;
    if (b == 0) cout << "B " << 0 << " " << ban[1].q << endl;
}
int main()
{
    ios_base::sync_with_stdio(0);
    nhap();
    xuly();
    return 0;
}


 #include <bits/stdc++.h>
#define maxn 1001
using namespace std;
int n, s;
int b = 0, sell = 0;
struct data
{
    int d, p, q;
};
data a[maxn], mua[maxn], ban[maxn];

bool comp(data x, data y)
{
    if (x.d != y.d) return (x.d == 0);
    return (x.p < y.p);
}
void nhap()
{
    cin >> n >> s;
    char c;
    for (int i = 1; i <= n; i++)
    {
        cin >> c >> a[i].p >> a[i].q;
        a[i].d = (c == 'S');
    }
    sort (a+1, a+n+1, comp);
}
void xuly()
{
    for (int i = 1; i <= n; i++)
        if (a[i].d == 0)
        {
            if (a[i].p == a[i-1].p) mua[b].q += a[i].q;
                else mua[++b] = a[i];
        }
        else
        {
            if (a[i-1].d && a[i].p == a[i-1].p) ban[sell].q += a[i].q;
                else ban[++sell] = a[i];
        }
    for (int i = min (s, sell); i >= 1; i--)
        cout << "S" << " " << ban[i].p << " " << ban[i].q << endl;
    for (int i = b; i >= b - min (s, b) + 1; i--)
        cout << "B " << mua[i].p << " " << mua[i].q << endl;
}
int main()
{
    ios_base::sync_with_stdio(0);
    nhap();
    xuly();
    return 0;
}


#include <bits/stdc++.h>
#define maxn 1001
using namespace std;
int n, s;
int b = 0, sell = 0;
struct data
{
    int d, p, q;
};
data a[maxn], mua[maxn], ban[maxn];

bool comp(data x, data y)
{
    if (x.d != y.d) return (x.d == 0);
    return (x.p < y.p);
}
void nhap()
{
    cin >> n >> s;
    char c;
    for (int i = 1; i <= n; i++)
    {
        cin >> c >> a[i].p >> a[i].q;
        a[i].d = (c == 'S');
    }
    sort (a+1, a+n+1, comp);
}
void xuly()
{
    for (int i = 1; i <= n; i++)
        if (a[i].d == 0)
        {
            if (a[i].p == a[i-1].p) mua[b].q += a[i].q;
                else mua[++b] = a[i];
        }
        else
        {
            if (a[i-1].d && a[i].p == a[i-1].p) ban[sell].q += a[i].q;
                else ban[++sell] = a[i];
        }
    for (int i = min (s, sell); i >= 1; i--)
        cout << "S" << " " << ban[i].p << " " << ban[i].q << endl;
    for (int i = b; i >= b - min (s, b) +1; i--)
        cout << "B " << mua[i].p << " " << mua[i].q << endl;
}
int main()
{
    ios_base::sync_with_stdio(0);
    nhap();
    xuly();
    return 0;
}


#include <bits/stdc++.h>
#define maxn 100000
using namespace std;
int n, s;
int a[maxn], b[maxn], c[maxn];

int main()
{
    ios_base::sync_with_stdio(0);
    cin >> n >> s;
    char ch;
    int x, y, k = 0, j = 0;
    for (int i = 1; i <= n; i++)
    {
        cin >> ch >> x >> y;
        if (ch == 'S') a[x] += y;
            else b[x] += y;
    }
    for (int i = 0; i <= 100000; i++)
    {
        if (a[i] > 0)
        {
            k++;
            c[++j] = i;
        }
        if (k == s) break;
    }
    for (int i = j; i >= 1; i--)
        cout << "S " << c[i] << " " << a[c[i]] << endl;
    k = 0;
    for (int i = 100000; i >= 0; i--)
    {
        if (b[i] > 0)
        {
            k++;
            cout << "B " << i << " " << b[i] << endl;
        }
        if (k == s) break;
    }
    return 0;
}


//============================================================================
// Name        : ramadan2515
// Author      : Mohamed Ahmed Ramadan
// Version     :
// Copyright   : Your copyright notice
// Description :  C++,
//============================================================================

#include <bits/stdc++.h>
#define fore(i,n) for(long long i = 0; i< n ; i++ )
#define lop(i,n) for(long long i = 1 ; i<=n ; i++ )
#define ops(i,n) for(long long  i = n-1 ; i>=0 ; i-- )
#define MAX 100001
#define MAXI 10000000
#define r(input) freopen("input.in","r",stdin)
#define w(output) freopen("output.out","w",stdout)

using namespace std;
typedef long long ll;
typedef pair<int,int>pii;
typedef pair<long long,long long>pll;
typedef vector<int> vi;
typedef vector<ll> vll;
struct node{
    char a;
    ll b,c;
    ll idx;
};
map<pair<char,int>,int >ma;
vector<node> v;
vector<node> vv;
vector<node> vvv;
bool compare1(node a,node b){
    if(a.b>b.b)return true;
    else return false;
}
bool compare2(node a,node b){
    if(a.b<b.b)return true;
    return false;
}

int main(){
    int n,s;
    cin >> n >> s;
    fore(i,n){
        char a;
        ll b,c;
        cin >> a >> b >> c;
        if(ma.find(make_pair(a,b))!=ma.end()){
            ll z=ma[make_pair(a,b)];
            if(a=='S'||a=='B'){
                ll idx=0;
                fore(i,vv.size()){
                    if(vv[i].a==a&&vv[i].b==b&&vv[i].c==z){
                        idx=i;
                    }
                }
                vv.erase(vv.begin()+idx);
            }
            c+=z;
        }
        ma[make_pair(a,b)]=c;
        if(a=='B')v.push_back({a,b,c,i});
        if(a=='S')vv.push_back({a,b,c,i});
    }
    sort(v.begin(),v.end(),compare1);
    sort(vv.begin(),vv.end(),compare2);
    int o=vv.size();
    fore(i,min(s,o))vvv.push_back(vv[i]);
    sort(vvv.begin(),vvv.end(),compare1);
    fore(i,vvv.size()){
        cout << vvv[i].a << " "<< vvv[i].b << " " << vvv[i].c << "\n";
    }
    vvv.clear();
    o=v.size();
    fore(i,min(s,o))vvv.push_back(v[i]);
    sort(vvv.begin(),vvv.end(),compare1);
    fore(i,vvv.size()){
        cout << vvv[i].a << " "<< vvv[i].b << " " << vvv[i].c << "\n";
    }
    return 0;
}


//============================================================================
// Name        : ramadan2515
// Author      : Mohamed Ahmed Ramadan
// Version     :
// Copyright   : Your copyright notice
// Description :  C++,
//============================================================================

#include <bits/stdc++.h>
#define fore(i,n) for(long long i = 0; i< n ; i++ )
#define lop(i,n) for(long long i = 1 ; i<=n ; i++ )
#define ops(i,n) for(long long  i = n-1 ; i>=0 ; i-- )
#define MAX 100001
#define MAXI 10000000
#define r(input) freopen("input.in","r",stdin)
#define w(output) freopen("output.out","w",stdout)

using namespace std;
typedef long long ll;
typedef pair<int,int>pii;
typedef pair<long long,long long>pll;
typedef vector<int> vi;
typedef vector<ll> vll;
struct node{
    char a;
    ll b,c;
    ll idx;
};
map<pair<char,int>,int >ma;
vector<node> v;
vector<node> vv;
vector<node> vvv;
bool compare1(node a,node b){
    if(a.c>b.c)return true;
    else return false;
}
bool compare2(node a,node b){
    if(a.c<b.c)return true;
    return false;
}

int main(){
    int n,s;
    cin >> n >> s;
    fore(i,n){
        char a;
        ll b,c;
        cin >> a >> b >> c;
        if(ma.find(make_pair(a,b))!=ma.end()){
            ll z=ma[make_pair(a,b)];
            if(a=='S'){
                ll idx=0;
                fore(i,vv.size()){
                    if(vv[i].a==a&&vv[i].b==b&&vv[i].c==z){
                        idx=i;
                    }
                }
                vv.erase(vv.begin()+idx);
            }
            c+=z;
        }
        ma[make_pair(a,b)]+=c;
        if(a=='B')v.push_back({a,b,c,i});
        if(a=='S')vv.push_back({a,b,c,i});
    }
    sort(v.begin(),v.end(),compare1);
    sort(vv.begin(),vv.end(),compare2);
    fore(i,s)vvv.push_back(vv[i]);
    sort(vvv.begin(),vvv.end(),compare1);
    fore(i,vvv.size()){
        cout << vvv[i].a << " "<< vvv[i].b << " " << vvv[i].c << "\n";
    }
    vvv.clear();
    fore(i,s)vvv.push_back(v[i]);
    sort(vvv.begin(),vvv.end(),compare1);
    fore(i,vvv.size()){
        cout << vvv[i].a << " "<< vvv[i].b << " " << vvv[i].c << "\n";
    }
    return 0;
}


//============================================================================
// Name        : ramadan2515
// Author      : Mohamed Ahmed Ramadan
// Version     :
// Copyright   : Your copyright notice
// Description :  C++,
//============================================================================

#include <bits/stdc++.h>
#define fore(i,n) for(long long i = 0; i< n ; i++ )
#define lop(i,n) for(long long i = 1 ; i<=n ; i++ )
#define ops(i,n) for(long long  i = n-1 ; i>=0 ; i-- )
#define MAX 100001
#define MAXI 10000000
#define r(input) freopen("input.in","r",stdin)
#define w(output) freopen("output.out","w",stdout)

using namespace std;
typedef long long ll;
typedef pair<int,int>pii;
typedef pair<long long,long long>pll;
typedef vector<int> vi;
typedef vector<ll> vll;
struct node{
    char a;
    ll b,c;
    ll idx;
};
map<pair<char,int>,int >ma;
vector<node> v;
vector<node> vv;
vector<node> vvv;
bool compare1(node a,node b){
    if(a.b>b.b)return true;
    else return false;
}
bool compare2(node a,node b){
    if(a.b<b.b)return true;
    return false;
}

int main(){
    int n,s;
    cin >> n >> s;
    fore(i,n){
        char a;
        ll b,c;
        cin >> a >> b >> c;
        if(ma.find(make_pair(a,b))!=ma.end()){
            ll z=ma[make_pair(a,b)];
            if(a=='S'){
                ll idx=0;
                fore(i,vv.size()){
                    if(vv[i].a==a&&vv[i].b==b&&vv[i].c==z){
                        idx=i;
                    }
                }
                vv.erase(vv.begin()+idx);
            }
            if(a=='B'){
                ll idx=0;
                fore(i,v.size()){
                    if(v[i].a==a&&v[i].b==b&&v[i].c==z){
                        idx=i;
                    }
                }
                v.erase(v.begin()+idx);
            }
            c+=z;
        }
        ma[make_pair(a,b)]=c;
        if(a=='B')v.push_back({a,b,c,i});
        if(a=='S')vv.push_back({a,b,c,i});
    }
    sort(v.begin(),v.end(),compare1);
    sort(vv.begin(),vv.end(),compare2);
    int o=vv.size();
    fore(i,min(s,o))vvv.push_back(vv[i]);
    sort(vvv.begin(),vvv.end(),compare1);
    fore(i,vvv.size()){
        cout << vvv[i].a << " "<< vvv[i].b << " " << vvv[i].c << "\n";
    }
    vvv.clear();
    o=v.size();
    fore(i,min(s,o))vvv.push_back(v[i]);
    sort(vvv.begin(),vvv.end(),compare1);
    fore(i,vvv.size()){
        cout << vvv[i].a << " "<< vvv[i].b << " " << vvv[i].c << "\n";
    }
    return 0;
}


//============================================================================
// Name        : ramadan2515
// Author      : Mohamed Ahmed Ramadan
// Version     :
// Copyright   : Your copyright notice
// Description :  C++,
//============================================================================

#include <bits/stdc++.h>
#define fore(i,n) for(long long i = 0; i< n ; i++ )
#define lop(i,n) for(long long i = 1 ; i<=n ; i++ )
#define ops(i,n) for(long long  i = n-1 ; i>=0 ; i-- )
#define MAX 100001
#define MAXI 10000000
#define r(input) freopen("input.in","r",stdin)
#define w(output) freopen("output.out","w",stdout)

using namespace std;
typedef long long ll;
typedef pair<int,int>pii;
typedef pair<long long,long long>pll;
typedef vector<int> vi;
typedef vector<ll> vll;
struct node{
    char a;
    ll b,c;
    ll idx;
};
map<pair<char,int>,int >ma;
vector<node> v;
vector<node> vv;
vector<node> vvv;
bool compare1(node a,node b){
    if(a.c>b.c)return true;
    else return false;
}
bool compare2(node a,node b){
    if(a.c<b.c)return true;
    return false;
}

int main(){
    int n,s;
    cin >> n >> s;
    fore(i,n){
        char a;
        ll b,c;
        cin >> a >> b >> c;
        if(ma.find(make_pair(a,b))!=ma.end()){
            ll z=ma[make_pair(a,b)];
            if(a=='S'){
                ll idx=0;
                fore(i,vv.size()){
                    if(vv[i].a==a&&vv[i].b==b&&vv[i].c==z){
                        idx=i;
                    }
                }
                vv.erase(vv.begin()+idx);
            }
            c+=z;
        }
        ma[make_pair(a,b)]+=c;
        if(a=='B')v.push_back({a,b,c,i});
        if(a=='S')vv.push_back({a,b,c,i});
    }
    sort(v.begin(),v.end(),compare1);
    sort(vv.begin(),vv.end(),compare2);
    int o=vv.size();
    fore(i,min(s,o))vvv.push_back(vv[i]);
    sort(vvv.begin(),vvv.end(),compare1);
    fore(i,vvv.size()){
        cout << vvv[i].a << " "<< vvv[i].b << " " << vvv[i].c << "\n";
    }
    vvv.clear();
    o=v.size();
    fore(i,min(s,o))vvv.push_back(v[i]);
    sort(vvv.begin(),vvv.end(),compare1);
    fore(i,vvv.size()){
        cout << vvv[i].a << " "<< vvv[i].b << " " << vvv[i].c << "\n";
    }
    return 0;
}


//============================================================================
// Name        : ramadan2515
// Author      : Mohamed Ahmed Ramadan
// Version     :
// Copyright   : Your copyright notice
// Description :  C++,
//============================================================================

#include <bits/stdc++.h>
#define fore(i,n) for(long long i = 0; i< n ; i++ )
#define lop(i,n) for(long long i = 1 ; i<=n ; i++ )
#define ops(i,n) for(long long  i = n-1 ; i>=0 ; i-- )
#define MAX 100001
#define MAXI 10000000
#define r(input) freopen("input.in","r",stdin)
#define w(output) freopen("output.out","w",stdout)

using namespace std;
typedef long long ll;
typedef pair<int,int>pii;
typedef pair<long long,long long>pll;
typedef vector<int> vi;
typedef vector<ll> vll;
struct node{
    char a;
    ll b,c;
    ll idx;
};
map<pair<char,int>,int >ma;
vector<node> v;
vector<node> vv;
vector<node> vvv;
bool compare1(node a,node b){
    if(a.c>b.c)return true;
    else return false;
}
bool compare2(node a,node b){
    if(a.c<b.c)return true;
    return false;
}

int main(){
    int n,s;
    cin >> n >> s;
    fore(i,n){
        char a;
        ll b,c;
        cin >> a >> b >> c;
        if(ma.find(make_pair(a,b))!=ma.end()){
            ll z=ma[make_pair(a,b)];
            if(a=='S'){
                ll idx=0;
                fore(i,vv.size()){
                    if(vv[i].a==a&&vv[i].b==b&&vv[i].c==z){
                        idx=i;
                    }
                }
                vv.erase(vv.begin()+idx);
            }
            c+=z;
        }
        ma[make_pair(a,b)]+=c;
        if(a=='B')v.push_back({a,b,c,i});
        if(a=='S')vv.push_back({a,b,c,i});
    }
    sort(v.begin(),v.end(),compare1);
    sort(vv.begin(),vv.end(),compare2);
    int bests=s,bestb=s;
    if(v.size()<s){
        bests+=s-v.size();
        bestb-=s-v.size();

    }
    else if(vv.size()<s){
        bestb+=s-vv.size();
        bests-=s-vv.size();
    }
    fore(i,bests)vvv.push_back(vv[i]);
    sort(vvv.begin(),vvv.end(),compare1);
    fore(i,vvv.size()){
        cout << vvv[i].a << " "<< vvv[i].b << " " << vvv[i].c << "\n";
    }
    vvv.clear();
    fore(i,bestb)vvv.push_back(v[i]);
    sort(vvv.begin(),vvv.end(),compare1);
    fore(i,vvv.size()){
        cout << vvv[i].a << " "<< vvv[i].b << " " << vvv[i].c << "\n";
    }
    return 0;
}


//============================================================================
// Name        : ramadan2515
// Author      : Mohamed Ahmed Ramadan
// Version     :
// Copyright   : Your copyright notice
// Description :  C++,
//============================================================================

#include <bits/stdc++.h>
#define fore(i,n) for(long long i = 0; i< n ; i++ )
#define lop(i,n) for(long long i = 1 ; i<=n ; i++ )
#define ops(i,n) for(long long  i = n-1 ; i>=0 ; i-- )
#define MAX 100001
#define MAXI 10000000
#define r(input) freopen("input.in","r",stdin)
#define w(output) freopen("output.out","w",stdout)

using namespace std;
typedef long long ll;
typedef pair<int,int>pii;
typedef pair<long long,long long>pll;
typedef vector<int> vi;
typedef vector<ll> vll;
struct node{
    char a;
    ll b,c;
    ll idx;
};
map<pair<char,int>,int >ma;
vector<node> v;
vector<node> vv;
vector<node> vvv;
bool compare1(node a,node b){
    if(a.b>b.b)return true;
    else return false;
}
bool compare2(node a,node b){
    if(a.b<b.b)return true;
    return false;
}

int main(){
    int n,s;
    cin >> n >> s;
    fore(i,n){
        char a;
        ll b,c;
        cin >> a >> b >> c;
        if(ma.find(make_pair(a,b))!=ma.end()){
            ll z=ma[make_pair(a,b)];
            if(a=='S'){
                ll idx=0;
                fore(i,vv.size()){
                    if(vv[i].a==a&&vv[i].b==b&&vv[i].c==z){
                        idx=i;
                    }
                }
                vv.erase(vv.begin()+idx);
            }
            c+=z;
        }
        ma[make_pair(a,b)]=c;
        if(a=='B')v.push_back({a,b,c,i});
        if(a=='S')vv.push_back({a,b,c,i});
    }
    sort(v.begin(),v.end(),compare1);
    sort(vv.begin(),vv.end(),compare2);
    int o=vv.size();
    fore(i,min(s,o))vvv.push_back(vv[i]);
    sort(vvv.begin(),vvv.end(),compare1);
    fore(i,vvv.size()){
        cout << vvv[i].a << " "<< vvv[i].b << " " << vvv[i].c << "\n";
    }
    vvv.clear();
    o=v.size();
    fore(i,min(s,o))vvv.push_back(v[i]);
    sort(vvv.begin(),vvv.end(),compare1);
    fore(i,vvv.size()){
        cout << vvv[i].a << " "<< vvv[i].b << " " << vvv[i].c << "\n";
    }
    return 0;
}


//============================================================================
// Name        : ramadan2515
// Author      : Mohamed Ahmed Ramadan
// Version     :
// Copyright   : Your copyright notice
// Description :  C++,
//============================================================================

#include <bits/stdc++.h>
#define fore(i,n) for(long long i = 0; i< n ; i++ )
#define lop(i,n) for(long long i = 1 ; i<=n ; i++ )
#define ops(i,n) for(long long  i = n-1 ; i>=0 ; i-- )
#define MAX 100001
#define MAXI 10000000
#define r(input) freopen("input.in","r",stdin)
#define w(output) freopen("output.out","w",stdout)

using namespace std;
typedef long long ll;
typedef pair<int,int>pii;
typedef pair<long long,long long>pll;
typedef vector<int> vi;
typedef vector<ll> vll;
struct node{
    char a;
    ll b,c;
    ll idx;
};
map<pair<char,int>,int >ma;
vector<node> v;
vector<node> vv;
vector<node> vvv;
bool compare1(node a,node b){
    if(a.c>b.c)return true;
    else return false;
}
bool compare2(node a,node b){
    if(a.c<b.c)return true;
    return false;
}

int main(){
    int n,s;
    cin >> n >> s;
    fore(i,n){
        char a;
        ll b,c;
        cin >> a >> b >> c;
        if(ma.find(make_pair(a,b))!=ma.end()){
            ll z=ma[make_pair(a,b)];
            if(a=='S'){
                ll idx=0;
                fore(i,vv.size()){
                    if(vv[i].a==a&&vv[i].b==b&&vv[i].c==z){
                        idx=i;
                    }
                }
                vv.erase(vv.begin()+idx);
            }
            c+=z;
        }
        ma[make_pair(a,b)]=c;
        if(a=='B')v.push_back({a,b,c,i});
        if(a=='S')vv.push_back({a,b,c,i});
    }
    sort(v.begin(),v.end(),compare1);
    sort(vv.begin(),vv.end(),compare2);
    int o=vv.size();
    fore(i,min(s,o))vvv.push_back(vv[i]);
    sort(vvv.begin(),vvv.end(),compare1);
    fore(i,vvv.size()){
        cout << vvv[i].a << " "<< vvv[i].b << " " << vvv[i].c << "\n";
    }
    vvv.clear();
    o=v.size();
    fore(i,min(s,o))vvv.push_back(v[i]);
    sort(vvv.begin(),vvv.end(),compare1);
    fore(i,vvv.size()){
        cout << vvv[i].a << " "<< vvv[i].b << " " << vvv[i].c << "\n";
    }
    return 0;
}


//============================================================================
// Name        : ramadan2515
// Author      : Mohamed Ahmed Ramadan
// Version     :
// Copyright   : Your copyright notice
// Description :  C++,
//============================================================================

#include <bits/stdc++.h>
#define fore(i,n) for(long long i = 0; i< n ; i++ )
#define lop(i,n) for(long long i = 1 ; i<=n ; i++ )
#define ops(i,n) for(long long  i = n-1 ; i>=0 ; i-- )
#define MAX 100001
#define MAXI 10000000
#define r(input) freopen("input.in","r",stdin)
#define w(output) freopen("output.out","w",stdout)

using namespace std;
typedef long long ll;
typedef pair<int,int>pii;
typedef pair<long long,long long>pll;
typedef vector<int> vi;
typedef vector<ll> vll;
struct node{
    char a;
    ll b,c;
    ll idx;
};
map<pair<char,int>,int >ma;
vector<node> v;
vector<node> vv;
vector<node> vvv;
bool compare1(node a,node b){
    if(a.c>b.c)return true;
    else return false;
}
bool compare2(node a,node b){
    if(a.c<b.c)return true;
    return false;
}

int main(){
    int n,s;
    cin >> n >> s;
    fore(i,n){
        char a;
        ll b,c;
        cin >> a >> b >> c;
        if(ma.find(make_pair(a,b))!=ma.end()){
            ll z=ma[make_pair(a,b)];
            if(a=='S'){
                ll idx=0;
                fore(i,vv.size()){
                    if(vv[i].a==a&&vv[i].b==b&&vv[i].c==z){
                        idx=i;
                    }
                }
                vv.erase(vv.begin()+idx);
            }
            c+=z;
        }
        ma[make_pair(a,b)]+=c;
        if(a=='B')v.push_back({a,b,c,i});
        if(a=='S')vv.push_back({a,b,c,i});
    }
    sort(v.begin(),v.end(),compare1);
    sort(vv.begin(),vv.end(),compare2);
    fore(i,min(s,vv.size()))vvv.push_back(vv[i]);
    sort(vvv.begin(),vvv.end(),compare1);
    fore(i,vvv.size()){
        cout << vvv[i].a << " "<< vvv[i].b << " " << vvv[i].c << "\n";
    }
    vvv.clear();
    fore(i,min(s,v.size()))vvv.push_back(v[i]);
    sort(vvv.begin(),vvv.end(),compare1);
    fore(i,vvv.size()){
        cout << vvv[i].a << " "<< vvv[i].b << " " << vvv[i].c << "\n";
    }
    return 0;
}


//============================================================================
// Name        : ramadan2515
// Author      : Mohamed Ahmed Ramadan
// Version     :
// Copyright   : Your copyright notice
// Description :  C++,
//============================================================================

#include <bits/stdc++.h>
#define fore(i,n) for(long long i = 0; i< n ; i++ )
#define lop(i,n) for(long long i = 1 ; i<=n ; i++ )
#define ops(i,n) for(long long  i = n-1 ; i>=0 ; i-- )
#define MAX 100001
#define MAXI 10000000
#define r(input) freopen("input.in","r",stdin)
#define w(output) freopen("output.out","w",stdout)

using namespace std;
typedef long long ll;
typedef pair<int,int>pii;
typedef pair<long long,long long>pll;
typedef vector<int> vi;
typedef vector<ll> vll;
struct node{
    char a;
    ll b,c;
    ll idx;
};
map<pair<char,int>,int >ma;
vector<node> v;
vector<node> vv;
vector<node> vvv;
bool compare1(node a,node b){
    if(a.c>b.c)return true;
    else return false;
}
bool compare2(node a,node b){
    if(a.c<b.c)return true;
    return false;
}
bool compare3(node a,node b){
    if(a.idx<b.idx)return true;
    return false;
}
int main(){
    int n,s;
    cin >> n >> s;
    fore(i,n){
        char a;
        ll b,c;
        cin >> a >> b >> c;
        if(ma.find(make_pair(a,b))!=ma.end()){
            ll z=ma[make_pair(a,b)];
            if(a=='S'){
                ll idx=0;
                fore(i,vv.size()){
                    if(vv[i].a==a&&vv[i].b==b&&vv[i].c==z){
                        idx=i;
                    }
                }
                vv.erase(vv.begin()+idx);
            }
            c+=z;
        }
        ma[make_pair(a,b)]+=c;
        if(a=='B')v.push_back({a,b,c,i});
        if(a=='S')vv.push_back({a,b,c,i});
    }
    sort(v.begin(),v.end(),compare1);
    sort(vv.begin(),vv.end(),compare2);
    fore(i,s)vvv.push_back(v[i]),vvv.push_back(vv[i]);
    sort(vvv.begin(),vvv.end(),compare3);
    fore(i,vvv.size()){
        cout << vvv[i].a << " "<< vvv[i].b << " " << vvv[i].c << "\n";
    }
    return 0;
}


//============================================================================
// Name        : ramadan2515
// Author      : Mohamed Ahmed Ramadan
// Version     :
// Copyright   : Your copyright notice
// Description :  C++,
//============================================================================

#include <bits/stdc++.h>
#define fore(i,n) for(long long i = 0; i< n ; i++ )
#define lop(i,n) for(long long i = 1 ; i<=n ; i++ )
#define ops(i,n) for(long long  i = n-1 ; i>=0 ; i-- )
#define MAX 100001
#define MAXI 10000000
#define r(input) freopen("input.in","r",stdin)
#define w(output) freopen("output.out","w",stdout)

using namespace std;
typedef long long ll;
typedef pair<int,int>pii;
typedef pair<long long,long long>pll;
typedef vector<int> vi;
typedef vector<ll> vll;
struct node{
    char a;
    ll b,c;
    ll idx;
};
map<pair<char,int>,int >ma;
vector<node> v;
vector<node> vv;
vector<node> vvv;
bool compare1(node a,node b){
    if(a.c>b.c)return true;
    else return false;
}
bool compare2(node a,node b){
    if(a.c<b.c)return true;
    return false;
}
bool compare3(node a,node b){
    if(a.a==b.a&&a.a=='S'){
        if(a.c>b.c)return true;
    }
    else if(a.a==b.a&&a.a=='B'){
        if(a.c>b.c)return true;
    }
    else if(a.idx<b.idx)return true;
    return false;
}
int main(){
    int n,s;
    cin >> n >> s;
    fore(i,n){
        char a;
        ll b,c;
        cin >> a >> b >> c;
        if(ma.find(make_pair(a,b))!=ma.end()){
            ll z=ma[make_pair(a,b)];
            if(a=='S'){
                ll idx=0;
                fore(i,vv.size()){
                    if(vv[i].a==a&&vv[i].b==b&&vv[i].c==z){
                        idx=i;
                    }
                }
                vv.erase(vv.begin()+idx);
            }
            c+=z;
        }
        ma[make_pair(a,b)]+=c;
        if(a=='B')v.push_back({a,b,c,i});
        if(a=='S')vv.push_back({a,b,c,i});
    }
    sort(v.begin(),v.end(),compare1);
    sort(vv.begin(),vv.end(),compare2);
    fore(i,s)vvv.push_back(v[i]),vvv.push_back(vv[i]);
    sort(vvv.begin(),vvv.end(),compare3);
    fore(i,vvv.size()){
        cout << vvv[i].a << " "<< vvv[i].b << " " << vvv[i].c << "\n";
    }
    return 0;
}


#include <iostream>
using namespace std;

int main() {
	int n,s;
	cin>>n>>s;
	char d;
	bool checkb[100001]={false},checks[100001]={false};
	long long int stb[100001]={0},sts[100001]={0};
	long long int p,q;
	long long int count=0,countb=0;
	if(n<s)
	s=n;
	for(int i=0;i<n;i++)
	{
		cin>>d;
		if(d=='B')
		{	countb++;
			cin>>p>>q;
			if(checkb[p])
				stb[p]+=q;
			else
			{
				checkb[p]=true;
				stb[p]=q;
			}

		}
		else
		{	cin>>p>>q;
			count++;
			if(checks[p])
				sts[p]+=q;
			else
			{	checks[p]=true;
				sts[p]=q;
			}
		}
	}
	long long int i=100000;
	if(count<s)
	s=count;
	int r=count-s;
	if(count<s)
	s=count;

	while(r>-(s-1)||r==0)
	{
		if(checks[i])
		{
				r--;
			if(r<1)
				cout<<"S "<<i<<" "<<sts[i]<<endl;

		}
		i--;

	}

	r=0;
	i=100000;
	if(countb!=0)
	while(r<s)
	{
		if(checkb[i])
		{
			r++;
			cout<<"B "<<i<<" "<<stb[i]<<endl;
		}
		i--;
	}

	return 0;
}


#include <iostream>
using namespace std;

int main() {
	int n,s;
	cin>>n>>s;
	char d;
	bool checkb[100001]={false},checks[100001]={false};
	long long int stb[100001]={0},sts[100001]={0};
	long long int p,q;
	long long int count=0,countb=0;
	if(n<s)
	s=n;
	for(int i=0;i<n;i++)
	{
		cin>>d;
		if(d=='B')
		{	countb++;
			cin>>p>>q;
			if(checkb[p])
				stb[p]+=q;
			else
			{
				checkb[p]=true;
				stb[p]=q;
			}

		}
		else
		{	cin>>p>>q;
			count++;
			if(checks[p])
				sts[p]+=q;
			else
			{	checks[p]=true;
				sts[p]=q;
			}
		}
	}
	long long int i=100000;
	int s1=s;
	if(count<s)
	s=count;
	int r=count-s;
	if(count<s)
	s=count;

	if(count!=0)

	while(r>-(s-1)||r==0)
	{
		if(checks[i])
		{
				r--;
			if(r<1)
				cout<<"S "<<i<<" "<<sts[i]<<endl;

		}
		i--;

	}

	r=0;
	i=100000;
	if(countb!=0)
	while(r<s1)
	{
		if(checkb[i])
		{
			r++;
			cout<<"B "<<i<<" "<<stb[i]<<endl;
		}
		i--;
	}

	return 0;
}


#include <iostream>
using namespace std;

int main() {
	int n,s;
	cin>>n>>s;
	char d;
	bool checkb[100001]={false},checks[100001]={false};
	long long int stb[100001]={0},sts[100001]={0};
	long long int p,q;
	long long int count=0,countb=0;
	if(n<s)
	s=n;
	for(int i=0;i<n;i++)
	{
		cin>>d;
		if(d=='B')
		{	countb++;
			cin>>p>>q;
			if(checkb[p])
				stb[p]+=q;
			else
			{
				checkb[p]=true;
				stb[p]=q;
			}

		}
		else
		{	cin>>p>>q;
			count++;
			if(checks[p])
				sts[p]+=q;
			else
			{	checks[p]=true;
				sts[p]=q;
			}
		}
	}
	long long int i=100000;
	int s1=s;
	if(count<s)
	s=count;
	int r=count-s;
	if(count<s)
	s=count;

	if(count!=0)

	while(r>-(s-1)||r==0)
	{
		if(checks[i])
		{
				r--;
			if(r<1)
				cout<<"S "<<i<<" "<<sts[i]<<endl;

		}
		i--;

	}

	r=0;
	i=100000;
	if(countb<s1)
	s1=countb;
	if(countb!=0)
	while(r<s1)
	{
		if(checkb[i])
		{
			r++;
			cout<<"B "<<i<<" "<<stb[i]<<endl;
		}
		i--;
	}

	return 0;
}


#include <iostream>
using namespace std;

int main() {
	int n,s;
	cin>>n>>s;
	char d;
	bool checkb[100001]={false},checks[100001]={false};
	long long int stb[100001]={0},sts[100001]={0};
	long long int p,q;
	long long int count=0;
	for(int i=0;i<n;i++)
	{
		cin>>d;
		if(d=='B')
		{
			cin>>p>>q;
			if(checkb[p])
				stb[p]+=q;
			else
			{
				checkb[p]=true;
				stb[p]=q;
			}

		}
		else
		{	cin>>p>>q;
			count++;
			if(checks[p])
				sts[p]+=q;
			else
			{	checks[p]=true;
				sts[p]=q;
			}
		}
	}
	long long int i=100000;
	int r=count-s;

	while(r>-(s-1)||r==0)
	{
		if(checks[i])
		{
				r--;
			if(r<1)
				cout<<"S "<<i<<" "<<sts[i]<<endl;

		}
		i--;

	}

	r=0;
	i=100000;
	while(r<s)
	{
		if(checkb[i])
		{
			r++;
			cout<<"B "<<i<<" "<<stb[i]<<endl;
		}
		i--;
	}

	return 0;
}


#include <iostream>
using namespace std;

int main() {
	int n,s;
	cin>>n>>s;
	char d;
	bool checkb[100001]={false},checks[100001]={false};
	long long int stb[100001]={0},sts[100001]={0};
	long long int p,q;
	long long int count=0,countb=0;
	if(n<s)
	s=n;
	for(int i=0;i<n;i++)
	{
		cin>>d;
		if(d=='B')
		{	countb++;
			cin>>p>>q;
			if(checkb[p])
				stb[p]+=q;
			else
			{
				checkb[p]=true;
				stb[p]=q;
			}

		}
		else
		{	cin>>p>>q;
			count++;
			if(checks[p])
				sts[p]+=q;
			else
			{	checks[p]=true;
				sts[p]=q;
			}
		}
	}
	long long int i=100000;
	int r=count-s;

	while(r>-(s-1)||r==0)
	{
		if(checks[i])
		{
				r--;
			if(r<1)
				cout<<"S "<<i<<" "<<sts[i]<<endl;

		}
		i--;

	}

	r=0;
	i=100000;
	if(countb!=0)
	while(r<s)
	{
		if(checkb[i])
		{
			r++;
			cout<<"B "<<i<<" "<<stb[i]<<endl;
		}
		i--;
	}

	return 0;
}


#include<iostream>
#include<vector>
#include<map>
using namespace std;
int main()
{
    map<int,int> S;
    map<int,int> B;
    int n, s;
    cin >> n >> s;
    int dummy = s;
    char d;
    int p,q;
    for(int i=0;i<n;i++)
    {
        cin >> d >> p >> q;
        if(d=='B')
        {
            B[p] += q;
        }
        if(d =='S')
        {
            S[p]+=q;
        }
    }

    while(S.size()> s)
    {
        S.erase(--S.end());
    }
    while(B.size()>s)
    {
        B.erase(B.begin());
    }

    for(map<int,int>::reverse_iterator it=S.rbegin();it!=S.rend();it++)
    {
        cout << "S " << it->first << " " << it->second << endl;
    }
    for(map<int,int>::reverse_iterator it=B.rbegin();it!=B.rend();it++)
    {
        cout << "B " << it->first << " " << it->second << endl;
    }

}


#include <iostream>
using namespace std;

int main() {
	int n,s;
	cin>>n>>s;
	char d;
	bool checkb[100001]={false},checks[100001]={false};
	long long int stb[100001]={0},sts[100001]={0};
	long long int p,q;
	long long int count=0;
	if(n<s)
	s=n;
	for(int i=0;i<n;i++)
	{
		cin>>d;
		if(d=='B')
		{
			cin>>p>>q;
			if(checkb[p])
				stb[p]+=q;
			else
			{
				checkb[p]=true;
				stb[p]=q;
			}

		}
		else
		{	cin>>p>>q;
			count++;
			if(checks[p])
				sts[p]+=q;
			else
			{	checks[p]=true;
				sts[p]=q;
			}
		}
	}
	long long int i=100000;
	int r=count-s;

	while(r>-(s-1)||r==0)
	{
		if(checks[i])
		{
				r--;
			if(r<1)
				cout<<"S "<<i<<" "<<sts[i]<<endl;

		}
		i--;

	}

	r=0;
	i=100000;
	while(r<s)
	{
		if(checkb[i])
		{
			r++;
			cout<<"B "<<i<<" "<<stb[i]<<endl;
		}
		i--;
	}

	return 0;
}


#include <iostream>
using namespace std;

int main() {
	int n,s;
	cin>>n>>s;
	char d;
	bool checkb[100001]={false},checks[100001]={false};
	long long int stb[100001]={0},sts[100001]={0};
	long long int p,q;
	long long int count=0;
	for(int i=0;i<n;i++)
	{
		cin>>d;
		if(d=='B')
		{
			cin>>p>>q;
			if(checkb[p])
				stb[p]+=q;
			else
			{
				checkb[p]=true;
				stb[p]=q;
			}

		}
		else
		{	cin>>p>>q;
			count++;
			if(checks[p])
				sts[p]+=q;
			else
			{	checks[p]=true;
				sts[p]=q;
			}
		}
	}
	long long int i=100000;
	int r=count-s;

		while(r!=-(s-1))
	{
		if(checks[i])
		{
			r--;
			if(r<=0)
				cout<<"S "<<i<<" "<<sts[i]<<endl;
		}
		i--;

	}
	r=0;
	i=100000;
	while(r<s)
	{
		if(checkb[i])
		{
			r++;
			cout<<"B "<<i<<" "<<stb[i]<<endl;
		}
		i--;
	}

	return 0;
}


#include <bits/stdc++.h>

using namespace std;

#define ms(a,x) memset(a, x, sizeof(a))
#define trace(x) cout << #x ": " << x << endl;
#define Rep(i,n) for(int i = 0; i < (n); ++i)
#define Repd(i,n) for(int i = (n)-1; i >= 0; --i)
#define For(i,a,b) for(int i = (a); i <= (b); ++i)
#define Ford(i,a,b) for(int i = (a); i >= (b); --i)
#define ll long long
#define pb push_back
#define mp make_pair
ll gcd(ll a, ll b) {ll r; while (b != 0) {r = a % b; a = b; b = r;} return a;}
ll lcm(ll a, ll b) {return a / gcd(a, b) * b;}
#define mod  1000000007
#define oo   1000000000
#define nmax 100001
#define mmax 1000001
vector <ll> V,VV;
vector < pair<ll,ll> > M;
ll B[nmax], S[nmax], C[3][nmax];
char c;
ll n,ss,price,sl, tmp, gt;
int main()
{   ios_base::sync_with_stdio(false);
    cin.tie(NULL);
   // freopen("data.txt", "r", stdin);
    cin>>n>>ss;
    For(i,1,n)
    {
        cin>>c>>price>>sl;
        if (c == 'B')
        {
            if (B[price] == 0) { B[price] += sl; V.pb(price); }
            else B[price] += sl;
        };
        if ( c == 'S')
        {
            if (S[price] == 0) { S[price]+=sl; VV.pb(price); }
            else S[price]+=sl;
        }
    }
    if (!VV.empty())
    {
        Rep(i,VV.size())
        {
            tmp = VV[i];
            gt = tmp * S[tmp];
            M.pb(mp(gt,i));
        }
        sort(M.begin(), M.end());
        tmp = M.size();
        if (tmp > ss)
        {
            Ford(i,ss-1,0) cout<<"S "<<VV[ M[i].second ]<<" "<<S[ VV[ M[i].second ] ]<<endl;
        }
        else
            Repd(i,M.size()) cout<<"S "<<VV[ M[i].second ]<<" "<<S[ VV[ M[i].second ] ]<<endl;
    M.clear();
    }

    //------------------------------------------
    if (!V.empty())
    {
        Rep(i,V.size())
        {
            tmp = V[i];
            gt = tmp * B[tmp];
            M.pb(mp(gt,i));
        }
        sort(M.begin(), M.end());
        tmp = M.size();
        if (tmp>ss)
        {
        Ford(i,M.size()-1,tmp-ss) cout<<"B "<<V[ M[i].second ]<<" "<<B[ V[ M[i].second ] ]<<endl;
        }
        else
        {
            Repd(i,M.size()) cout<<"B "<<V[ M[i].second ]<<" "<<B[ V[ M[i].second ] ]<<endl;
        }
    }
}