#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp> 
#include <ext/pb_ds/tree_policy.hpp> 
#include <functional> // for less 
using namespace __gnu_pbds; 
using namespace std;
#define int long long
#define endl "\n"
#define deb(x) cout<<#x<<" "<<x<<endl;
#define sc(ar,n) for(int pen=0;pen<n;pen++){ cin>>ar[pen];}
#define pr(ar,n) for(int pen=0;pen<n;pen++){ cout<<ar[pen]<<" ";} cout<<endl;
#define fr(i,x,n) for(int i=x;i<n;i++)
#define frt(it,vb) for(auto it=vb.begin();it!=vb.end();it++)
#define mem(ar,x) memset(ar,x,sizeof(ar));
#define pb push_back
#define fastio ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define mod 1000000007
#define rt return 0;
#define ct continue;
#define MAX 1000000000000000000
#define MAX1 1000000000
#define CLK clock_t clk = clock();//Start of main
#define OCLK cerr << "Time (in ms): " << (double)(clock() - clk) * 1000.0 / CLOCKS_PER_SEC << '\n';//End of main
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update> 

inline int solve()
{
    int n,m;
    cin>>n>>m;
    map <int , vector <int> > mp;
    fr(i,0,m){
        int x,y;
        cin>>x>>y;
        mp[x].push_back(y);
    }
    set <int> st;
    st.insert(n);
    for(auto it : mp){

        set <int> a,b;
        for(auto ut : it.second){
            int x = ut;
            if(st.find(x) != st.end() && st.find(x-1) == st.end() && st.find(x+1) == st.end()){
                b.insert(x);
            }
            if(st.find(x) == st.end() && (st.find(x-1) != st.end() || st.find(x+1) != st.end()) ){
                a.insert(x);
            }
        }
        for(auto ut : a){
            st.insert(ut);
        }
        for(auto ut : b){
            st.erase(ut);
        }
    }
    cout << st.size() << endl;
    rt;
}
signed main()
{
    // fastio;
    int t;
    int test_cases=1;
    if(test_cases==0)
    cin>>t;
    else
    t=1;
    while(t--){
        solve();
    }
}
#include <iostream>
#include <vector>
#include <algorithm>

const int INF = 0x3fffffff;

using namespace std;

int main() {
    int n, m;
    cin >> n >> m;

    vector<int> H(n);
    vector<int> W(m);

    for (int i = 0; i < n; i++)
        cin >> H[i];
    for (int i = 0; i < m; i++)
        cin >> W[i];

    sort(H.begin(), H.end());
    sort(W.begin(), W.end());

    vector<int> sum1((n + 1) / 2);
    vector<int> sum2((n + 1) / 2);

    for (int i = 0; i + 1 < n; i += 2) {
        int j = i + 1;
        sum1[i / 2 + 1] = sum1[i / 2] + H[i+1] - H[i];
        sum2[j / 2 + 1] = sum2[j / 2] + H[j+1] - H[j];
    }

    long long ans = 100000000000;
    for (auto w : W) {
        int idx = lower_bound(H.begin(), H.end(), w) - H.begin();
        long long sum = 0;
        if (idx % 2 != 0) {
            idx--;
        }
        sum += abs(H[idx] - w);
        sum += sum1[idx / 2] + sum2[n / 2] - sum2[idx / 2];
        ans = min(ans, sum);
    }
    printf("%lld\n", ans);    
    return 0;
}
