#include <cstring>
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
typedef long long ll;
int const N = 1e5 + 10, M = 5e3 + 10, mod = 1e9 + 7;
int n, q, cnt, a[N], h[M], mx[M], st[N][20], lg[N];
double dp[M][M], P[M][M], Q[M][M];
struct Node {
    int l, r;
    double p;
    bool operator<(Node const &other) const {
        if (l == other.l) return r > other.r;
        else return l < other.l;
    }
} rec[M];
struct Edge {
    int t, n;
} tree[M];
void insert(int f, int t) {
    tree[cnt].t = t;
    tree[cnt].n = h[f];
    h[f] = cnt++;
}
void solve(int rt) {
    for (int i = 0; i <= q; i++) {
        P[rt][i] = 1;
        Q[rt][i] = 1;
    }
    for (int i = h[rt], t; ~i; i = tree[i].n) {
        solve(t = tree[i].t);
        for (int j = 0, k; j <= q; j++) {
            k = mx[rt] - mx[t] + j;
            if (j) P[rt][j] *= dp[t][min(k - 1, q)];
            Q[rt][j] *= dp[t][min(k, q)];
        }
    }
    for (int i = 0; i <= q; i++) dp[rt][i] = (i ? P[rt][i] : 0) * rec[rt].p + Q[rt][i] * (1 - rec[rt].p);
}
inline int rmq(int l, int r) {
    int len = r - l + 1;
    return max(st[l][lg[len]], st[r - (1 << lg[len]) + 1][lg[len]]);
}
int main() {
    //freopen("in.txt", "r", stdin);
    //freopen("out.txt", "w", stdout);
    cin >> n >> q;
    for (int i = 1; i <= n; i++) cin >> a[i];
    rec[0].l = 1; rec[0].r = n; rec[0].p = 0;
    for (int i = 1; i <= q; i++) cin >> rec[i].l >> rec[i].r >> rec[i].p;
    sort(rec, rec + q + 1);
    memset(h, -1, sizeof(h));
    for (int i = 1, j; i <= q; i++) {
        for (j = i - 1; rec[j].r < rec[i].r; j--);
        insert(j, i);
    }
    lg[1] = 0;
    for (int i = 2; i <= n; i++) lg[i] = lg[i - 1] + !((i - 1) & i);
    for (int i = 1; i <= n; i++) st[i][0] = a[i];
    for (int i = 1; i < 20; i++)
        for (int j = 1; j <= n; j++)
            st[j][i] = max(st[j][i - 1], (j + (1 << i - 1)) <= n ? st[j + (1 << i - 1)][i - 1] : 0);
    for (int i = 0, j; i <= q; i++) mx[i] = rmq(rec[i].l, rec[i].r);
    q++;
    solve(0);
    double ans = dp[0][0] * mx[0];
    for (int i = 1; i <= q; i++)
        ans += (dp[0][i] - dp[0][i - 1]) * (mx[0] + i);
    printf("%.6f\n", ans);
    return 0;
}


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

#define ms(s, n) memset(s, n, sizeof(s))
#define FOR(i, a, b) for(int i = (a); i < (b); i++)
#define FORd(i, a, b) for(int i = (a) - 1; i >= (b); i--)
#define sz(a) int((a).size())
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef pair<int, int> pi;
typedef vector<int> vi;
typedef vector<pi> vii;
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;}

struct recommendation {
	int l, r;
	int max;
	ld pro;
};

const int maxn = 100010;
const int maxq = 5010;
int n, q;
int a[maxn];
int amax;
recommendation re[maxq];
vi head;
vi nex[maxq];
ld pro[maxq];
ld f[maxq][2 * maxq];

ld cal(int cur, int val) {
	if (f[cur][val + maxq] != -1.0) return f[cur][val + maxq];
	if (re[cur].max > amax + val) return 0.0;
	if (!sz(nex[cur])) {
		if (re[cur].max == amax + val) return 1.0 - re[cur].pro; else return 1.0;
	}
	ld res = 1.0;
	FOR(i, 0, sz(nex[cur])) {
		ld tmp = (1.0 - re[cur].pro) * cal(nex[cur][i], val);
		if (re[cur].max < amax + val) tmp += re[cur].pro * cal(nex[cur][i], val - 1);
		res *= tmp;
	}
	return f[cur][val + maxq] = res;
}

void cal() {
	FOR(i, 0, maxq) FOR(j, 0, 2 * maxq) f[i][j] = -1.0;
	FOR(val, 0, q + 1) {
		pro[val] = 1.0;
		FOR(i, 0, sz(head)) {
			int cur = head[i];
			pro[val] *= cal(cur, val);
		}
	}
}

int go(int cur, int r) {
	int i;
	for (i = cur + 1; i < q && re[i].r <= r; i++) {
		if (cur == -1) head.push_back(i); else nex[cur].push_back(i);
		i = go(i, re[i].r);
	}
	return i - 1;
}

void solve() {
	scanf("%d%d", &n, &q);
	amax = 0;
	FOR(i, 0, n) {
		scanf("%d", a + i);
		amax = max(amax, a[i]);
	}
	FOR(i, 0, q) {
		cin>>re[i].l>>re[i].r>>re[i].pro; re[i].l--; re[i].r--;
		re[i].max = 0; FOR(j, re[i].l, re[i].r + 1) re[i].max = max(re[i].max, a[j]);
	}
	FOR(i, 0, q) FOR(j, i + 1, q) if (make_pair(re[i].l, -re[i].r) > make_pair(re[j].l, -re[j].r)) swap(re[i], re[j]);
	go(-1, INT_MAX); cal();
	ld ans = pro[q] * (amax + q);
	FOR(i, 0, q) ans -= pro[i];
	cout<<fixed<<setprecision(9)<<ans;
}

int main() {
#ifdef _LOCAL_
	freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout);
#endif
	solve();
#ifdef _LOCAL_
	printf("\nTime elapsed: %dms", 1000 * clock() / CLOCKS_PER_SEC);
#endif
	return 0;
}


#pragma gcc optimize("O3, unroll-loops")
#include<bits/stdc++.h>
using namespace std;
#define ff first
#define ss second
#define pb push_back
#define all(x) (x).begin(), (x).end()
typedef int64_t lld;
typedef pair<int, int> pii;
//#define endl '\n'

template<typename It>
ostream& outIt(ostream& out, It b, It e){
    for(It i = b; i != e; i++)
        out << (i==b?"":" ") << *i;
    return out;
}
template<typename T>
ostream& operator<<(ostream& out, vector<T>& v){
    return outIt(out << '[', all(v))<< ']';
}
template<typename T1, typename T2>
ostream& operator<<(ostream& out, pair<T1, T2> p){
    return out << '(' << p.ff << ", " << p.ss << ')';
}
template<typename T1, typename T2>
istream& operator>>(istream& in, pair<T1, T2>& p){
    return in >> p.ff >> p.ss;
}
vector<lld>ans;
int fpow(int a, int b, int mod){
    int ans = 1;
    do if(b&1)ans = (lld)ans * a % mod;
    while(a = (lld)a*a%mod, b>>=1);
    return ans;
}
//const int mod = 1000000007;
signed main(){cin.tie(0); ios_base::sync_with_stdio(0);
    int n;
    cin >> n;
    ans.resize(n+1); ans[0] = LLONG_MAX;
    int x = fpow(7, n-2, n);
    for(int i = 1; i <= n; i++){
        int x;
        cin >> x;
        if(n%7 == 0){
            if(i%7 == 0)ans[i] = LLONG_MAX;
            else ans[i] = i + (lld)(x-1)*n;
        }else{
            int next = ((lld)a*i*7-i+7*n)%(7*n)+i; // next = 7k = i mod n
            cout << i << " " << next << endl;
            if((next-i)/n+1 > x) ans[i] = i + (lld)(x-1)*n;
            else ans[i] = ((lld)(x-(next-i)/n-1)/6*7+(x-(next-i)/n-1)+1)*n+next;
        }
    }
    //cout << ans << endl;
    cout << min_element(all(ans))-ans.begin() << endl;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
#include <string>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <random>
#include <list>
#include <stack>
#include <queue>

#include <cmath>
#include <cstdio>
#include <ctime>
#include <cassert>

using namespace std;

const int inf = int (1e9) + 7;

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

    int n;

    cin >> n;

    vector<int> arr (n);

    for (auto &it : arr)
        cin >> it;

    if (n % 7 == 0)
    {
        for (int i = 6; i < arr.size (); i += 7)
            arr[i] = inf;

        cout << (min_element (arr.begin (), arr.end ()) - arr.begin () + 1) << endl;

        return 0;
    }

    int t = (*min_element (arr.begin (), arr.end ()) - 1) / 6;

    while (t-- > 0)
        for (auto &it : arr)
            it -= 6;

    int cnt = 0, pos = 0;

    while (cnt == 6 || arr[pos] > 1)
    {
        if (cnt++ != 6)
            arr[pos]--;
        else
            cnt = 0;

        pos = (pos + 1) % arr.size ();
    }

    cout << pos + 1 << endl;

    return 0;
}


#pragma gcc optimize("O3, unroll-loops")
#include<bits/stdc++.h>
using namespace std;
#define ff first
#define ss second
#define pb push_back
#define all(x) (x).begin(), (x).end()
typedef int64_t lld;
#define int lld
typedef pair<int, int> pii;
//#define endl '\n'

template<typename It>
ostream& outIt(ostream& out, It b, It e){
    for(It i = b; i != e; i++)
        out << (i==b?"":" ") << *i;
    return out;
}
template<typename T>
ostream& operator<<(ostream& out, vector<T>& v){
    return outIt(out << '[', all(v))<< ']';
}
template<typename T1, typename T2>
ostream& operator<<(ostream& out, pair<T1, T2> p){
    return out << '(' << p.ff << ", " << p.ss << ')';
}
template<typename T1, typename T2>
istream& operator>>(istream& in, pair<T1, T2>& p){
    return in >> p.ff >> p.ss;
}
vector<lld>ans;
int fpow(int a, int b, int mod){
    int ans = 1;
    if(b <= 0)return ans;
    do if(b&1)ans = (lld)ans * a % mod;
    while(a = (lld)a*a%mod, b>>=1);
    return ans;
}
//const int mod = 1000000007;
signed main(){cin.tie(0); ios_base::sync_with_stdio(0);
    int n;
    cin >> n;
    ans.resize(n+1); ans[0] = LLONG_MAX;
    int xax = fpow(7, n-2, n);
    for(int i = 1; i <= n; i++){
        int x;
        cin >> x;
        if(n%7 == 0){
            if(i%7 == 0)ans[i] = LLONG_MAX;
            else ans[i] = i + (lld)(x-1)*n;
        }else{
            lld next = ((lld)xax*i*7-i)%(7*n)+i; // next = 7k = i mod n
            assert(next >= i); assert(next%n == i%n); assert(next%7 == 0);
            //cout << i << " " << next << endl;
            if((next-i)/n >= x) ans[i] = i + (lld)(x-1)*n;
            else x-=(next-i)/n, ans[i] = (lld)(x/6*7+x%6+1)*n+next;
        }
    }
    //cout << ans << endl;
    cout << min_element(all(ans))-ans.begin() << endl;
}


#pragma gcc optimize("O3, unroll-loops")
#include<bits/stdc++.h>
using namespace std;
#define ff first
#define ss second
#define pb push_back
#define all(x) (x).begin(), (x).end()
typedef int64_t lld;
#define int lld
typedef pair<int, int> pii;
//#define endl '\n'

template<typename It>
ostream& outIt(ostream& out, It b, It e){
    for(It i = b; i != e; i++)
        out << (i==b?"":" ") << *i;
    return out;
}
template<typename T>
ostream& operator<<(ostream& out, vector<T>& v){
    return outIt(out << '[', all(v))<< ']';
}
template<typename T1, typename T2>
ostream& operator<<(ostream& out, pair<T1, T2> p){
    return out << '(' << p.ff << ", " << p.ss << ')';
}
template<typename T1, typename T2>
istream& operator>>(istream& in, pair<T1, T2>& p){
    return in >> p.ff >> p.ss;
}
vector<lld>ans;
int fpow(int a, int b, int mod){
    int ans = 1;
    if(b <= 0)return ans;
    do if(b&1)ans = (lld)ans * a % mod;
    while(a = (lld)a*a%mod, b>>=1);
    return ans;
}
int invmod(int a, int b, int mod, int s0 = 0, int s1 = 1){
    return b?invmod(b, a%b, mod, (s1-((lld)a/b*s0)%mod+mod)%mod, s0):s1;
}
//const int mod = 1000000007;
signed main(){cin.tie(0); ios_base::sync_with_stdio(0);
    int n;
    cin >> n;
    ans.resize(n+1); ans[0] = LLONG_MAX;
    int xax = invmod(7, n, n);
    //if(n > 2 && n%7 != 0)assert(xax*7 % n == 1);
    for(int i = 1; i <= n; i++){
        int x;
        cin >> x;
        if(n%7 == 0){
            if(i%7 == 0)ans[i] = LLONG_MAX;
            else ans[i] = i + (lld)(x-1)*n;
        }else{
            lld next = ((lld)xax*i*7-i)%(7*n)+i; // next = 7k = i mod n
            assert(next >= i);
            assert(next%n == i%n);
            assert(next%7 == 0);
            //cout << i << " " << next << endl;
            if((next-i)/n >= x) ans[i] = i + (lld)(x-1)*n;
            else x-=(next-i)/n, ans[i] = (lld)(x/6*7+x%6+1)*n+next;
        }
    }
    //cout << ans << endl;
    cout << min_element(all(ans))-ans.begin() << endl;
}


#include<bits/stdc++.h>
#define pp pair<int,int>
#define MZ 1000000007
using namespace std;
long long k;
int numx[35],numy[35],numk[35];
long long sum[35][2][2][2],num[35][2][2][2];
long long ask(long long x,long long y)
{
    long long ans=0;
    long long z=k;
    if(x<0 || y<0) return 0;
    memset(sum,0,sizeof(sum));
    memset(num,0,sizeof(num));
    for(int i=0;i<30;i++)
    {
        numx[i]=x%2;
        numy[i]=y%2;
        numk[i]=z%2;
        x>>=1;
        y>>=1;
        z>>=1;
    }
    num[30][1][1][1]=1;
    sum[30][1][1][1]=0;
    int im,jm;
    for(int lens=30;lens>=0;lens--)
        for(int i=0;i<2;i++)
            for(int j=0;j<2;j++)
                for(int kk=0;kk<2;kk++)
                if(num[lens][i][j][kk])
                {
                    if(lens==0)
                        ans=(ans+num[lens][i][j][kk]+sum[lens][i][j][kk])%MZ;
                    im=jm=1;
                    if(i)
                        im=numx[lens-1];
                    if(j)
                        jm=numy[lens-1];
                    for(int nowi=0;nowi<=im;nowi++)
                        for(int nowj=0;nowj<=jm;nowj++)
                        {
                            if(!kk || (nowi^nowj)<=numk[lens-1])
                            {
                                num[lens-1][(nowi==im && i)][(nowj==jm && j)][(nowi^nowj==numk[lens-1]) && kk]=(num[lens-1][(nowi==im && i)][(nowj==jm && j)][(nowi^nowj==numk[lens-1]) && kk]+num[lens][i][j][kk])%MZ;
                                sum[lens-1][(nowi==im && i)][(nowj==jm && j)][(nowi^nowj==numk[lens-1]) && kk]=(sum[lens-1][(nowi==im && i)][(nowj==jm && j)][(nowi^nowj==numk[lens-1]) && kk]+(sum[lens][i][j][kk]<<1)+(nowi^nowj)*num[lens][i][j][kk])%MZ;
                            }
                        }
                }
    return ans;
}
int main()
{
    int q;
    long long x1,y1,x2,y2;
    scanf("%d",&q);
    while(q--)
    {
        scanf("%lld%lld%lld%lld%lld",&x1,&y1,&x2,&y2,&k);
        x1--;
        y1--;
        x2--;
        y2--;
        k--;
        printf("%lld\n",(ask(x2,y2)-ask(x2,y1-1)-ask(x1-1,y2)+ask(x1-1,y1-1)+MZ)%MZ);

    }
    return 0;
}


#include <bits/stdc++.h>
#define base 1000000007LL
#define ll long long
#define X first
#define Y second
#define pb push_back
#define EPS 1e-9
#define all(a) (a).begin(), (a).end()
#define sz(a) int((a).size())
#define ms(s, n) memset(s, n, sizeof(s))
#define FOR(i,a,b) for (int i = (a); i <= (b); i++)
#define FORE(i,a,b) for (int i = (a); i >= (b); i--)
#define FORALL(it, a) for (__typeof((a).begin()) it = (a).begin(); it != (a).end(); it++)
using namespace std;
typedef pair<int, int> II;
typedef pair<II, int> III;

const ll MODD = 1e9 + 7;

ll solve(ll u, ll v, ll k, ll o = 0)
{
    if (u > v) swap(u, v);
    if (u < 1 || k < 1) return 0;
    ll p = 1, res = 0;
    while (p*2 <= v) p *= 2;
    ll tmp = min(p, k);

    if (u <= p) {
        res = ((tmp*(tmp+1)/2 % base) * u) % base;
        res = (res + (o * tmp % base) * u % base + solve(u, v-p, k-p, o+p)) % base;
    }
    else {
        res = ((tmp*(tmp+1)/2 % base) * p) % base;
        res = (res + o * tmp % base * p % base) % base;
        res = (res + solve(u-p, v-p, k-p, o) + solve(p, v-p, k-p, o+p) + solve(u-p, p, k-p, o+p)) % base;
    }
    return res;
}

int main()
{
    ll q, a, b, u, v, k;
    ios::sync_with_stdio(0);
    freopen("inp.txt", "r", stdin);
    //freopen("out.txt", "w", stdout);
    /*FOR(i,1,10) {
        FOR(j,1,10) cout << ((i-1) ^ (j-1)) + 1 << " ";
        cout << endl;
    }*/
    cin >> q;
    while (q--) {
        cin >> a >> b >> u >> v >> k;
        ll res = (solve(u,v,k) + solve(a-1,b-1,k)) % base;
        res = (res - solve(a-1,v,k) - solve(u,b-1,k) + base*base) % base;
        cout << res << endl;
    }
    return 0;
}


#include<iostream>
#include<map>
#define BASE 1000000007;
using namespace std;
map<pair<__int32, __int32>, __int32> storedvalue;
__int32 findvalue(__int32 i, __int32 j)
{
	__int32 result;
	pair<__int32, __int32> index = make_pair(i, j);
	if (storedvalue.count(index))return storedvalue[index];
	if (i > j)return findvalue(j,i);
	else if (i == 1)result = j;
	else if (i == j)result = 1;
	else if (j == i + 1 && i % 2 == 1)result = 2;
	else if (i == 2 && j % 2 == 0)result = j - 1;
	else if (i == 2 && j % 2 == 1)result = j + 1;
	else if (j % 4 == 1 || j % 4 == 2)result = 2*((i-1)/2) + findvalue((i-1)%2+1,j);
	else if (j % 4 == 3 || j % 4 == 0)result = -2 * ((i - 1) / 2) + findvalue((i - 1) % 2 + 1, j);
	else result = 0;
	storedvalue.insert(make_pair(index, result));
	return result;
}

int main()
{
	int q;
	cin >> q;
	for (int i = 0; i < q; i++)
	{
		__int32 x1, y1, x2, y2, K;
		cin >> x1 >> y1 >> x2 >> y2 >> K;
		int ans = 0;
		for (__int32 j = x1; j <= x2; j++)
		{
			for (__int32 k = y1; k <= y2; k++)
			{
				__int32 temp = findvalue(j, k);
				if (temp > K)continue;
				else ans = (ans + temp) % BASE;
			}
		}
		cout << ans << endl;
	}
}


#include<iostream>
#include<map>
#define BASE 1000000007;
using namespace std;
map<pair<__int32, __int32>, __int32> storedvalue;
__int32 findvalue(__int32 i, __int32 j)
{
	__int32 result;
	pair<__int32, __int32> index = make_pair(i, j);
	if (storedvalue.count(index))return storedvalue[index];
	if (i > j)result = findvalue(j,i);
	else if (i == 1)result = j;
	else if (i == j)result = 1;
	else if (j == i + 1 && i % 2 == 1)result = 2;
	else if (i == 2 && j % 2 == 0)result = j - 1;
	else if (i == 2 && j % 2 == 1)result = j + 1;
	else if (j % 4 == 1 || j % 4 == 2)result = 2 + findvalue(i-2,j);
	else if (j % 4 == 3 || j % 4 == 0)result = -2 + findvalue(i - 2, j);
	else result = 0;
	storedvalue.insert(make_pair(index, result));
	return result;
}

int main()
{
	int q;
	cin >> q;
	for (int i = 0; i < q; i++)
	{
		__int32 x1, y1, x2, y2, K;
		cin >> x1 >> y1 >> x2 >> y2 >> K;
		int ans = 0;
		for (__int32 j = x1; j <= x2; j++)
		{
			for (__int32 k = y1; k <= y2; k++)
			{
				__int32 temp = findvalue(j, k);
				if (temp > K)continue;
				else ans = (ans + temp) % BASE;
			}
		}
		cout << ans << endl;
	}
}


#include <bits/stdc++.h>

#define left nadnlassad
#define right asdaslknd
#define y1 kjdajasjdsas

#define pb push_back
#define mp make_pair

#define f first
#define s second

#define ll long long
#define ld long double
#define ull unsigned ll

#define _hash pair<ll, ull>
#define pii pair<int, int>
#define prr pair<pii, pii>

#define sqr(x) (x * 1LL * x)

#define vec vector<int>
#define sz(v) int(v.size())
#define all(v) v.begin(), v.end()
#define upper(v, x) (upper_bound(all(v), x) - v.begin())
#define lower(v, x) (lower_bound(all(v), x) - v.begin())
#define iter set<int>::iterator
#define _bits(x) __builtin_popcountll(x)

using namespace std;

const int nx[8] = {2, -2, -2, 2, 1, 1, -1, -1};
const int ny[8] = {1, 1, -1, -1, 2, -2, -2, 2};

const ll LINF = (ll) 2e18;
const int INF = 1e9 + 7;

const int N = 2e5 + 100;
const int MAXN = 5e7 + 50;
const double EPS = 1e-9, PI = 2 * acos(0.0);
pii a[N];
int t[N];
int n, m;
vector<pii> all;
multiset<int> st;

int main() {
   #define fn "stones"
   #ifdef sony
      freopen("input.txt", "r", stdin);
      //freopen("output1.txt", "w", stdout);
   #else
     // freopen(fn".in", "r", stdin);
     // freopen(fn".out", "w", stdout);
   #endif // sony
   srand(time(NULL));
   scanf("%d%d", &n, &m);
   for(int i = 1; i <= n; i++) {
      int x;
      scanf("%d", &x);
      all.pb({x, 0});
   }
   int ans = 0;
   for(int i = 1; i <= m; i++) {
      scanf("%d%d", &a[i].s, &a[i].f);
      all.pb(mp(a[i].s - a[i].f, -i));
      all.pb(mp(a[i].s + a[i].f, i));
   }
   sort(all(all));
   for(auto it : all) {
      if(it.s == 0) {
         iter i = st.lower_bound(it.f);
         if(i == st.end())
            continue;
         st.erase(i);
         ans++;
      } else if(it.s < 0) {
         st.insert(a[-it.s].s + a[-it.s].s);
      } else {
         st.erase(st.find(it.f));
      }
   }
   printf("%d", ans);
   return 0;
}


#include "bits/stdc++.h"

using namespace std;

#define x first
#define y second
#define pb push_back
#define mp make_pair
#define all(a) (a).begin(), (a).end()
#define rall(a) (a).rbegin(), (a).rend()
#define sz(a) int((a).size())
#define sqr(x) ((x)*(x))
#define forn(i, n) for (int i = 0; i < int(n); i++)
#define NAME "34"
#define FREOPEN freopen(NAME"", "r", stdin); freopen(NAME".txt", "w", stdout);
#define Freopen freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);

typedef unsigned int unt;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;
typedef long double geom;

const ll MOD = 1e9 + 7;
const int INF = 2e9;
const ll INF64 = 3e18;
const ld EPS = 1e-12;
const ld PI = 3.1415926535897932384620;
const ll MD = 925262732;
const ll T = 634521;
const int N = 300100;
const int M = 5001;

ll n, m, x[N];
pll a[N];
multiset < ll > s;
pll d[N];

int main()
{
    cin >> n >> m;
    int ans = 0;
    forn(i, n)
    {
        scanf("%I64d", &x[i]);
    }
    sort(x, x + n);
    forn(i, m)
    {
        scanf("%I64d %I64d", &a[i].x, &a[i].y);
        d[i].x = a[i].x - a[i].y;
        d[i].y = a[i].x + a[i].y;
    }
    sort(d, d + m);
    int j = 0;
    forn(i, n)
    {
        int xx = x[i];
        while (j < m && d[j].x <= xx)
        {
            s.insert(d[j].y);
            j++;
        }
        multiset < ll > :: iterator it = s.begin();
        while (*it < xx)
        {
            s.erase(it);
            it = s.begin();
            if (it == s.end())
                break;
        }
         it = s.begin();
         if (it != s.end())
         {
             ans++;
             s.erase(it);
         }

    }

    cout << ans;
    return 0;
}

/*

*/


#include <bits/stdc++.h>

#define left nadnlassad
#define right asdaslknd
#define y1 kjdajasjdsas

#define pb push_back
#define mp make_pair

#define f first
#define s second

#define ll long long
#define ld long double
#define ull unsigned ll

#define _hash pair<ll, ull>
#define pii pair<int, int>
#define prr pair<pii, pii>

#define sqr(x) (x * 1LL * x)

#define vec vector<int>
#define sz(v) int(v.size())
#define all(v) v.begin(), v.end()
#define upper(v, x) (upper_bound(all(v), x) - v.begin())
#define lower(v, x) (lower_bound(all(v), x) - v.begin())
#define iter set<int>::iterator
#define _bits(x) __builtin_popcountll(x)

using namespace std;

const int nx[8] = {2, -2, -2, 2, 1, 1, -1, -1};
const int ny[8] = {1, 1, -1, -1, 2, -2, -2, 2};

const ll LINF = (ll) 2e18;
const int INF = 1e9 + 7;

const int N = 2e5 + 100;
const int MAXN = 5e7 + 50;
const double EPS = 1e-9, PI = 2 * acos(0.0);
pii a[N];
int t[N];
int n, m;

int main() {
   #define fn "stones"
   #ifdef sony
      freopen("input.txt", "r", stdin);
      //freopen("output1.txt", "w", stdout);
   #else
     // freopen(fn".in", "r", stdin);
     // freopen(fn".out", "w", stdout);
   #endif // sony
   srand(time(NULL));
   scanf("%d%d", &n, &m);
   set<int> st;
   for(int i = 1; i <= n; i++) {
      int x;
      scanf("%d", &x);
      st.insert(x);
   }
   int cur_time = 0;
   int ans = 0;
   for(int i = 1; i <= m; i++) {
      scanf("%d%d", &a[i].s, &a[i].f);
   }
   sort(a + 1, a + m + 1);
   for(int i = 1; i <= m; i++) {
      int cur_pos = a[i].s, max_time = a[i].f;
      iter it = st.lower_bound(cur_pos);
      iter it1 = it;
      if(it1 != st.begin())
         it1--;
      if(it != st.end() && abs(*it - cur_pos) < abs(*it1 - cur_pos)){
         if(abs(*it - cur_pos) <= max_time) {
            ans++;
            st.erase(it);
         }
      } else {
         if(abs(*it1 - cur_pos) <= max_time) {
            ans++;
            st.erase(it1);
         }
      }
   }
   printf("%d", ans);
   return 0;
}


#include <iostream>
#include <cstdio>
#include <queue>
#include <string>
#include <cmath>
#include <vector>
#include <set>
#include <queue>
#include <map>
#include <cstring>
#include <stack>
#include <algorithm>

using namespace std;

int u[20001];
int t[20001];

int main() {
	//freopen ("input.txt", "r", stdin);
	int m, n;
	cin >> n >> m;
	int a;
	vector <pair <int, int>> v;
	for (int i = 0; i < n; i++) {
		cin >> a;
		v.push_back(make_pair(a, 0));
	}
	int count = 0;
	for (int i = 1; i <= m; i++) {
		cin >> u[i] >> t[i];
		v.push_back(make_pair(u[i] - t[i], -i));
		v.push_back(make_pair(u[i] + t[i], i));
	}
	sort (v.begin(), v.end());
	set <pair <int, int>> st;
	for (int i = 0; i < v.size(); i++) {
		int index = v[i].second;
		if (index < 0) {
			index = -index;
			st.insert(make_pair(u[index] + t[index], index));
		}
		else if (index == 0) {
			if (st.size() > 0) {
				count++;
				st.erase(st.begin());
			}
		}
		else {
			st.erase(v[i]);
		}
	}
	cout << count << endl;
}


#include <iostream>
using namespace std;

#define FC0 1
#define FC1 8
#define FCQ 6

char formula[1000003];

int fcEval(char opchar, int fcA, int fcB){
	int fcRet = 0;
	for (int apair = 0; apair < 4; apair++){
		if (((fcA >> apair) & 1) == 1){
			for (int bpair = 0; bpair < 4; bpair++){
				if (((fcB >> bpair) & 1) == 1){
					int rpair = -1;
					switch (opchar){
						case '&':
							rpair = apair & bpair;
							break;
						case '|':
							rpair = apair | bpair;
							break;
						case '^':
							rpair = apair ^ bpair;
							break;
					}
					fcRet |= (1 << rpair);
				}
			}
		}
	}
	return fcRet;
}

int fcParse(int start, int& end){
	if (formula[start] == '0') { /*printf("fc0");*/ end = start + 1; return FC0; }
	if (formula[start] == '1') { /*printf("fc1");*/ end = start + 1; return FC1; }
	if (formula[start] == '?') { /*printf("fc?");*/ end = start + 1; return FCQ; }

	if (formula[start] == '(') {
		//printf("(");
		int opi;
		int fcA = fcParse(start+1, opi);
		char opchar = formula[opi];
		//printf(" %c ", opchar);
		int bend;
		int fcB = fcParse(opi+1, bend);
		end = bend + 1;
		int evalue = fcEval(opchar, fcA, fcB);
		//printf(" = %d)", evalue);
		return evalue;
	}
	return -1;

}

int main(){
	int n;
	scanf("%d\n", &n);
	fgets(formula, 1000001, stdin);
	int waste;
	if ((fcParse(0, waste) & 2) != 0){
		printf("YES");
	} else {
		printf("NO");
	}
}


#include<iostream>
#include <cstdio>
#include <cstring>
using namespace std;

int i,j,k,n,l,ans,temp;
char c;
char expr[2000000];

int gettype(int p, int q)
{
    int x,left,right;
    if (p==q)
    {
        if (expr[p]=='0') return 0;
        if (expr[p]=='1') return 1;
        if (expr[p]=='?') return 4;
    }
    k=0;
    for (i=p+1; i<=q-1; i++)
    {
        if (expr[i]=='(') k++;
        if (expr[i]==')') k--;
        if (expr[i]=='|'||expr[i]=='&'||expr[i]=='^')
            if (k==0) x=i;
    }
    left=gettype(p+1,x-1);
    right=gettype(x+1,q-1);
    if (left>right)
    {
        temp=left;
        left=right;
        right=temp;
    }
    if (expr[x]=='|')
    {
        if (left==0) return right;
        if (left==1) return 1;
        if (left==2&&right==2) return 2;
        return 3;
    }
    if (expr[x]=='&')
    {
        if (left==0) return 0;
        if (left==1) return right;
        if (left==2&&right==2) return 2;
        return 3;
    }
    if (expr[x]=='^')
    {
        if (left==0||left==2) return right;
        if (left==1)
            if (right==1) return 0; else return right;
        if (left==3) return 3;
        if (left==4) return 2;
    }
}

main()
{
    scanf("%d",&n);
    l=0;
    scanf("%c",&c);
    while (c=='\n') scanf("%c",&c);
    while (c!='\n')
    {
        l++;
        expr[l]=c;
        scanf("%c",&c);
    }
    ans=gettype(1,l);
    if (ans>=3) printf("YES\n"); else printf("NO\n");
    //system("pause");
}


#include <stdio.h>
#include <string.h>

using namespace std;

int colonyN, type[1000005];
char input[3000005], tmpInput[1000005];

int rec(int start){
	int depth=0;
	int type=0, Type[2], tested=0, startNext, oper;
	//0=Says nothing
	//1=0/1
	//2=Done!
	//3=0
	//4=1
	if(input[start] == '?' && input[start+1] == ')')
		return 1;
	if(input[start] == '0' && input[start+1] == ')')
		return 3;
	if(input[start] == '1' && input[start+1] == ')')
		return 4;
	for(int i=start; depth >= 0; ++i){
		if(input[i] == '('){
			++depth;
		}
		if(input[i] == ')'){
			--depth;
			if(depth == 0){
				if(!tested){
					Type[tested++]=rec(start+1);
				}
				else{
					Type[tested++]=rec(startNext);
				}
			}
		}
		if(depth == 0 && input[i] != ')' && input[i] != ')'){
			if(input[i] == '&')
				oper=2;
			if(input[i] == '|')
				oper=1;
			if(input[i] == '^')
				oper=0;
			startNext=i+2;
		}
	}
	if((Type[0] == 3 || Type[1] == 3) && oper == 2)
		return 3;
	if((Type[0] == 4 || Type[1] == 4) && oper == 1)
		return 4;
	if(Type[0]+Type[1] == 7){
		if(oper == 2)
			return 3;
		return 4;
	}
	if(Type[0] == 4 && Type[1] == 4){
		if(oper == 0)
			return 3;
		return 4;
	}
	if(Type[0] == 3 && Type[1] == 3){
		return 3;
	}
	if(Type[0] == 2 || Type[1] == 2)
		return 2;
	if(oper && (Type[0] == 1 || Type[1] == 1))
		return 2;
	if(oper == 1)
		return 0;
	if(Type[0] == Type[1])
		return 0;
	return 1;
}

int main()
{
	scanf("%d", &colonyN);
	scanf("%s", tmpInput);
	if(!tmpInput[0]){
		printf("NO");
		return 0;
	}
	int L=0;
	for(int i=0; tmpInput[i]; ++i){
		if(tmpInput[i] == '?'){
			input[L++]='(';
			input[L++]='?';
			input[L++]=')';
		}
		else if(tmpInput[i] == '0'){
			input[L++]='(';
			input[L++]='0';
			input[L++]=')';
		}
		else if(tmpInput[i] == '1'){
			input[L++]='(';
			input[L++]='1';
			input[L++]=')';
		}
		else{
			input[L++]=tmpInput[i];
		}
	}
	int ans;
	if(input[0] == '(')
		ans=rec(1);
	else{
		int i;
		for(i=0; input[i]; ++i);
		input[i]=')';
		input[i+1]=0;
		ans=rec(0);
	}
	if(ans == 1 || ans == 2)
		printf("YES");
	else
		printf("NO");
	return 0;
}


#include<cstdio>
#include<algorithm>
using namespace std;
const int N=3e3+10;
int tot,n,m,si[N],a[N],b[N],head[N],nex[N<<1],to[N<<1];
void add(int u,int v){to[++tot]=v;nex[tot]=head[u];head[u]=tot;}
pair<int,int>dp[N][N];
void dfs(int u,int p)
{
    si[u]=1;
    if(b[u]>0) dp[u][1]={1,b[u]};
    else dp[u][1]={0,b[u]};
    bool flag=true;
    for(int i=head[u];i;i=nex[i])
    {
        int v=to[i];if(v==p) continue;
        dfs(v,u);
        for(int j=si[u];j>=1;j--)
        {
            for(int k=1;k<=si[v];k++)
            {
                if(flag)
                {
                    //cout<<dp[v][k].second+b[u]<<' '<<dp[v][k].second<<endl;
                    dp[u][k]={dp[v][k].first+(dp[v][k].second+b[u]<=0&&dp[v][k].second>0?-1:0)+(dp[v][k].second+b[u]>0&&dp[v][k].second<=0),dp[v][k].second+b[u]};
                    dp[u][k+j]=max(dp[u][k+j],{dp[v][k].first+(b[u]>0),b[u]});
                }
                else
                {
                    dp[u][j+k]=max(dp[u][j+k],{dp[u][j].first+dp[v][k].first,dp[u][j].second});
                    dp[u][j+k]=max(dp[u][j+k],{dp[u][j].first+dp[v][k].first+(dp[u][j].second>0&&dp[v][k].second>0?-1:0)+(dp[u][j].second+dp[v][k].second<=0&&(dp[u][j].second>0||dp[v][k].second>0)?-1:0),dp[u][j].second+dp[v][k].second});
                }
            }
            flag=false;
        }
        si[u]+=si[v];
    }
}
int main()
{
    int t;scanf("%d",&t);
    while(t--)
    {
        tot=0;memset(head,0,sizeof(head));
        scanf("%d%d",&n,&m);
        for(int i=1;i<=n;i++) scanf("%d",&a[i]);
        for(int i=1;i<=n;i++) scanf("%d",&b[i]),b[i]-=a[i];
        for(int i=1;i<n;i++)
        {
            int u,v;scanf("%d%d",&u,&v);add(u,v);add(v,u);
        }
        memset(dp,0,sizeof(dp));
        dfs(1,0);
        printf("%d\n",dp[1][m].first);
    }
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f;
const ll linf=0x3f3f3f3f3f3f3f3f;
const int maxn=3e3+10;
const ll mod=1e9+7;
int n,m,ta[maxn],tb[maxn],sz[maxn];
vector<int>v[maxn];
struct DP
{
    int a=0;
    ll b=-linf;
}dp[maxn][maxn];
bool operator<(DP a,DP b)
{
    if(a.a!=b.a)return a.a<b.a;
    return a.b<b.b;
}
void dfs(int x,int f)
{
    sz[x]=1;
    dp[x][0]={0,tb[x]-ta[x]};
    for(auto y:v[x])if(y!=f)
    {
        dfs(y,x);
        DP tmp[maxn];
        for(int i=0;i<sz[x];i++)
            for(int j=0;j<=sz[y];j++)
                tmp[i+j]=max(tmp[i+j],(DP){dp[x][i].a+dp[y][j].a,dp[x][i].b+dp[y][j].b});

        sz[x]+=sz[y];
        for(int i=0;i<sz[x];i++)dp[x][i]=tmp[i];
    }
    dp[x][sz[x]]={dp[x][sz[x]-1].a+(dp[x][sz[x]-1].b>0),0};
//
//    cout<<x<<endl;
//    for(int i=0;i<=sz[x];i++)
//    {
//        cout<<i<<' '<<dp[x][i].a<<' '<<dp[x][i].b<<endl;
//    }
}

int main()
{
//    freopen("in.txt","r",stdin);
    int t;
    for(scanf("%d",&t);t--;)
    {
        scanf("%d%d",&n,&m);
        for(int i=1;i<=n;i++)scanf("%d",ta+i);
        for(int i=1;i<=n;i++)scanf("%d",tb+i);
        for(int i=0;i<n-1;i++)
        {
            int a,b;
            scanf("%d%d",&a,&b);
            v[a].push_back(b);
            v[b].push_back(a);
        }
        dfs(1,0);
        printf("%d\n",dp[1][m-1].a+(dp[1][m-1].b>0));
    }
    return 0;
}


// Your day breaks, your mind aches
// You find that all the words of kindness linger on
// When she no longer needs you
//#pragma GCC optimize ("Ofast,unroll-loops")
//#pragma GCC target ("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#include <bits/stdc++.h>
#include <unistd.h>
using namespace std;
#define fastio ios::sync_with_stdio(0);cin.tie(0)
#define debug(x) cout << #x << " = " << x << endl
#define For(i,a,b) for (int i = a; i < b; i++)
#define roF(i,a,b) for (int i = a; i >= b; i--)
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define all(v) (v).begin(),(v).end()

typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair<int, ll> ii;
typedef vector<int> vi;
typedef vector<ii> vii;

const int N = 3e3 + 5;
const ll INF = 1e18;
const ld EPS = 10e-9;

mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
ll random(ll a, ll b) { return uniform_int_distribution<ll> (a, b) (rng); }

int n, m, b[N], w[N], sz[N];
vi adj[N];
bool used[N];
ii dp[N][N], temp[N];
/*
dp[i][j] : (num, sum) Par obtenido al dividir el subarbol con raiz en i en j aldeas
num : max aldeas (distintas de i) donde #wasps > #bees
sum : max (#wasps - #bees) en el subarbol con raiz en i
*/

void init() {
	For(i,0,n) {
		used[i] = false;
		adj[i].clear();
	}
}

void DFS(int u) {
	used[u] = true;
	sz[u] = 1;
	dp[u][1] = mp(0, w[u] - b[u]); // (Aun no se procesan aldeas debajo, diferencia en el nodo)
	for (int v : adj[u]) {
		if (not used[v]) {
			DFS(v);
			int s = sz[u] + s[v] + 1;
			For(i,0,s) temp[i] = mp(-1, 0LL);
			For(x,1,sz[u]+1) {
				For(y,1,sz[v]+1) {
					int z = x + y - 1;
					temp[z] = max(temp[z], {dp[u][x].ff + dp[v][y], dp[u][x].ss + dp[v][y].ss});
					z = x + y;
					temp[z] = max(temp[z], {dp[u][x].ff + (dp[v][y].ff + (dp[v][y].ss > 0 ? 1 : 0)), dp[u][x].ss});
				}
			}
			For(i,0,s) dp[u][i] = temp[i];
			sz[u] += sz[v];
		}
	}
}

void solve() {
	cin >> n >> m;
	init();
	For(i,0,n) cin >> b[i];
	For(i,0,n) cin >> w[i];
	For(i,0,n-1) {
		int u, v;
		cin >> u >> v;
		u--;
		v--;
		adj[u].pb(v);
		adj[v].pb(u);
	}
	DFS(0);
	int ans = dp[0][m].ff + (dp[0][m].ss > 0);
	cout << ans << endl;
}

int main() {
	fastio;
	int t;
	cin >> t;
	while (t--) solve();
	return 0;
}


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

const int maxn=3005;
struct node{
    long long r,l;
    node(long long r,long long l):r(r),l(l){}
    node():r(),l(){}
    bool operator<(const node& o) const{
        if(r==o.r) return l<o.l;
        else return r<o.r;
    }
    node operator+(const node& o) const{
        return node(r+o.r,l+o.l);
    }
}dp[maxn][maxn],g[maxn];
vector<int> E[maxn];
long long siz[maxn],w[maxn],b[maxn];
int n,m;

void dfs(int x,int fa){
    dp[x][1]=node(0,w[x]-b[x]);
    if(dp[x][1].l>0) dp[x][1].r++;
    siz[x]=1;
    for(auto i:E[x]){
        if(i==fa) continue;
        dfs(i,x);
        for(int j=1;j<=m;j++) g[j]=node(-1,0);
        for(int j=1;j<=siz[x];j++){
            for(int k=1;k<=siz[i];k++){
                node t1,t2;
                t1=t2=dp[i][k];
                if(dp[x][j].l>0 && t1.l>0) t1.r--;
                if(dp[x][j].l+t1.l<=0 && (dp[x][j].l>0 || t1.l>0)) t1.r--;
                t2.l=0;
                g[j+k-1]=max(g[j+k-1],dp[x][j]+t1);
                g[j+k]=max(g[j+k],dp[x][j]+t2);
            }
        }
        siz[x]+=siz[i];
        for(int j=1;j<=siz[x];j++) dp[x][j]=g[j];
    }
}

void getdata(){
    cout<<n<<" "<<m<<endl;
    for(int i=26;i<=n;i++) cout<<b[i]<<" ";
    cout<<endl;
    for(int i=1;i<=n;i++) cout<<w[i]<<" ";
    cout<<endl;
    for(int i=1;i<=n;i++){
        cout<<"##"<<i<<" ";
        for(auto j:E[i]) cout<<j<<" ";
        cout<<endl;
    }
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);

    int T;
    cin>>T;
    while(T--){
        cin>>n>>m;
        for(int i=1;i<=n;i++){
            E[i].clear();
            for(int j=1;j<=m;j++)
                dp[i][j]=node(-1,0);
        }
        for(int i=1;i<=n;i++) cin>>b[i];
        for(int i=1;i<=n;i++) cin>>w[i];
        for(int i=1;i<n;i++){
            int x,y;
            cin>>x>>y;
            E[x].push_back(y);
            E[y].push_back(x);
        }
        dfs(1,0);
        if(T==19) getdata();
        cout<<dp[1][m].r<<'\n';
    }
}

/*
35 11
28530167 185244144 681335998 91458241 851385120 503949225 518858842 712992285 586745481 957375672 123450580 40918933 731279260 237094228 183288105 357785131 450619968 812208437 266738488 135278385 411517534 938282644 1303256 319299683 3552999 565857743


#include <bits/stdc++.h>

#define MOD 1000000007

using namespace std;

int expo(int a, int b) {
    if(!b) return 1;
    if(b & 1) return 1LL * a * expo(1LL * a * a % MOD, b >> 1) % MOD;
    return expo(1LL * a * a % MOD, b >> 1);
}

int inv_mod(int x) { return expo(x, MOD - 2);}

int i2 = inv_mod(2), i10 = inv_mod(10);

struct number {
    int v, p;
    number(int v, int p) : v(v), p(p) {}
};

number concat(number a, number b) {
    return number((1LL * a.v * b.p + b.v) % MOD, 1LL * a.p * b.p % MOD);
}

int remainder(string& str, int mod) {
    int rem = 0;
    for(char c : str) {
        rem = (10LL * rem + (c - '0')) % mod;
    }
    return rem;
}

number parse(string& str);

number c(int l, int r, int k, int p10eL, int rem_l, int rem_r) {
    int prod = expo(p10eL, (rem_r - 1 + MOD - 1) % (MOD - 1));
    int FR, FL;

    if(k == 1) {
        FR = 1LL * r * (r + 1) % MOD * i2 % MOD;
        FL = 1LL * l * (l - 1 + MOD) % MOD * i2 % MOD;
    } else {
        int kr = expo(k, rem_r), kl1 = expo(k, (rem_l - 1 + MOD - 1) % (MOD - 1)), ik1 = inv_mod((k - 1 + MOD) % MOD);
        FR = (1LL * r * kr % MOD * ik1 % MOD
                - 1LL * kr * ik1 % MOD * ik1 % MOD
                + MOD) % MOD;

        FL = (1LL * (l - 1 + MOD) * kl1 % MOD * ik1 % MOD
                - 1LL * kl1 * ik1 % MOD * ik1 % MOD
                + MOD) % MOD;
    }

    return number(1LL * prod * (FR - FL + MOD) % MOD, expo(p10eL, (rem_r - rem_l + 1 + MOD) % MOD));
}

number C(number l, number r, string& str_l, string& str_r) {
    if(str_l.size() == str_r.size()) {
        return c(l.v, r.v, inv_mod(l.p), l.p, remainder(str_l, MOD - 1), remainder(str_r, MOD - 1));
    } else {
        int mid  = 0, mid_rem = 0, rem_l = remainder(str_l, MOD - 1), rem_r = remainder(str_r, MOD - 1);
        for(char c : str_l) {
            mid = (10LL * mid + 9) % MOD;
            mid_rem = (10LL * mid_rem + 9) % (MOD - 1);
        }

        int k = inv_mod(l.p), p10eL = l.p;
        number ret = c(l.v, mid, k, p10eL, rem_l, mid_rem);
        for(int i = str_l.size() + 1; i < str_r.size(); i++) {
            k = 1LL * k * i10 % MOD;
            p10eL = 10LL * p10eL % MOD;

            l.v = (mid + 1) % MOD;
            rem_l = (mid_rem + 1) % (MOD - 1);

            mid = (10LL * mid + 9) % MOD;
            mid_rem = (10LL * mid_rem + 9) % (MOD - 1);

            ret = concat(ret, c(l.v, mid, k, p10eL, rem_l, mid_rem));
        }

        k = 1LL * k * i10 % MOD;
        p10eL = 10LL * p10eL % MOD;

        l.v = (mid + 1) % MOD;
        rem_l = (mid_rem + 1) % (MOD - 1);

        ret = concat(ret, c(l.v, r.v, k, p10eL, rem_l, rem_r));
        return ret;
    }
}

number rep(number x, number y, string& str_x) {
    if(y.p == 1) { /// 10^L % MOD == 1
        return number(1LL * x.v * y.v % MOD, 1);
    } else {
        int rem = remainder(str_x, MOD - 1);
        int new_pot = expo(y.p, rem);
        return number(1LL * y.v * ((new_pot - 1 + MOD) % MOD) % MOD * inv_mod((y.p - 1 + MOD) % MOD) % MOD, new_pot);
    }
}

number parse_term(string& str) {
    number a1(0, 1), a2(0, 1);
    int which = 0; /// 0: x | 1: x-y | 2: x(y)
    string t1, t2;

    for(char c : str) {
        if(which == 0) {
            if(c == '-') which = 1;
            else if(c == '(') which = 2;
            else {
                a1 = concat(a1, number(c - '0', 10));
                t1 += c;
            }
        } else if(which == 1) {
            a2 = concat(a2, number(c - '0', 10));
            t2 += c;
        } else {
            t2 += c;
        }
    }

    if(which == 0) return a1;
    else if(which == 1) return C(a1, a2, t1, t2);
    else {
        t2.pop_back(); /// last bracket
        a2 = parse(t2);
        return rep(a1, a2, t1);
    }
}

/// expression
number parse(string& str) {
    string tmp;
    number ret(0, 1);
    int brackets = 0;

    for(char c : str) {
        if(c == '+' && brackets == 0) {
            ret = concat(ret, parse_term(tmp));
            tmp = "";
        } else {
            tmp += c;
            if(c == '(') brackets++;
            if(c == ')') brackets--;
        }

    }

    ret = concat(ret, parse_term(tmp));
    return ret;
}

char s[100010];
string str;

int main() {
    scanf("%s", s); str = s;
    number ans = parse(str);
    printf("%d\n", ans.v);
    return 0;
}


#include <bits/stdc++.h>
#define fst first
#define snd second
#define fore(i,a,b) for(int i=a,ThxDem=b;i<ThxDem;++i)
#define pb push_back
#define ALL(s) s.begin(),s.end()
#define FIN ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define SZ(s) int(s.size())
using namespace std;
typedef long long ll;
typedef pair<int,int> ii;

const int MAXN=100010;
ll MOD=1e9+7,pw[MAXN];
int jsum[MAXN],jmin[MAXN],jpar[MAXN],topar[MAXN];
string s;

ll fpow(ll base, ll exp) {
	ll result = 1;
	while(exp){
		if(exp & 1) result = (result*base) % MOD;
		exp >>= 1;
		base = (base*base) % MOD;
	}
	return result;
}

ll sum(ll x, ll y){return (x+y)%MOD;}
ll sub(ll x, ll y){return (x-y+MOD)%MOD;}
ll mul(ll x, ll y){return x*y%MOD;}
ll divv(ll x, ll y){return x*fpow(y,MOD-2)%MOD;}

struct num{
	ll len,val;	//Stored as {10^len, val%MOD}
	num(ll len, ll val):len(len),val(val){}
	num(){}
	num concat(num x){return num(mul(len,x.len),sum(mul(val,x.len),x.val));}
};

num ran[MAXN];

void preproc(){
	fore(i,0,SZ(s)) jsum[i]=jmin[i]=jpar[i]=topar[i]=SZ(s);
	int dep=0;
	stack<ii> sum,mn,open; stack<int> par;
	for(int i=SZ(s)-1;i>=0;i--){
		if(s[i]==')') par.push(i), dep++;
		if(s[i]=='('){
			while(SZ(sum)&&sum.top().snd==dep) sum.pop();
			while(SZ(mn)&&mn.top().snd==dep) mn.pop();
			topar[i]=par.top(); par.pop(); dep--;
			open.push({i,dep});
		}
		if(SZ(open)&&open.top().snd==dep) jpar[i]=open.top().fst;
		if(SZ(sum)&&sum.top().snd==dep) jsum[i]=sum.top().fst;
		if(SZ(mn)&&mn.top().snd==dep) jmin[i]=mn.top().fst;
		if(s[i]=='+') sum.push({i,dep});
		if(s[i]=='-') mn.push({i,dep});
	}
}

num getnum(int l, int r){	// generates the number in this range
	num ans(pw[r-l+1],0);
	fore(i,l,r+1) ans.val=sum(mul(ans.val,10),s[i]-'0');
	return ans;
}

num range(num x, num y){	// x(x+1)....(y-1)(y) -> len(x)=len(y)
	ll rl1=sum(sub(y.val,x.val),1);
	ll rl2=sum(sub(y.val,x.val),2);
	num ans(fpow(x.len,rl1),0);

	ll v=sub(fpow(x.len,rl1),1);
	v=mul(sum(y.val,1),v);
	v=divv(v,sub(x.len,1));

	ll v2=mul(rl1,fpow(x.len,rl2));
	ll v3=mul(rl2,fpow(x.len,rl1));
	v2=divv(sum(sub(v2,v3),1),fpow(sub(x.len,1),2));

	v=sub(v,v2);
	ans.val=v;
	return ans;
}

num get_ran(int l1, int r1, int l2, int r2){
	int lle=r1-l1+1, lri=r2-l2+1;
	num x=getnum(l1,r1),y=getnum(l2,r2);
	if(lle==lri) return range(x,y);
	num fir(pw[lle],sub(pw[lle],1));	//999... lle times
	num sec(pw[lri],pw[lri-1]);					//10^lri

	num ans=range(x,fir);	//first part
	num lst=range(sec,y);	//last part

	fore(i,lle+1,lri) ans=ans.concat(ran[i]);	//mid parts
	ans=ans.concat(lst);

	return ans;
}

num copy(num x, num y){	// concat x times number y
	num ans(fpow(y.len,x.val),0);
	if(y.len%MOD==1) ans.val=x.val;
	else ans.val=divv(sub(fpow(y.len,x.val),1),sub(y.len,1));
	ans.val=mul(ans.val,y.val);
	return ans;
}

num solve(int l, int r){
	if(l>r) return num(1,0);
	if(jsum[l]<=r){	//split in +
		num lef=solve(l,jsum[l]-1), rig=solve(jsum[l]+1,r);
		return lef.concat(rig);
	}
	if(jmin[l]<=r){	//split in -
		num lef=solve(l,jmin[l]-1), rig=solve(jmin[l]+1,r);
		return get_ran(l,jmin[l]-1,jmin[l]+1,r);
	}
	if(jpar[l]<=r){	//split in (
		num lef=solve(l,jpar[l]-1), rig=solve(jpar[l]+1,r-1);
		return copy(lef,rig);
	}
	return getnum(l,r); // I'm in number
}

int main(){FIN;
	pw[0]=1; fore(i,1,MAXN) pw[i]=mul(10,pw[i-1]);
	cin>>s;
	fore(i,2,SZ(s)+1){
		num l(pw[i],pw[i-1]);
		num r(pw[i],sub(pw[i],1));
		ran[i]=range(l,r);
	}
	preproc();
	num ans=solve(0,SZ(s)-1);
	cout << ans.val << "\n";
}


#include <bits/stdc++.h>

#define FOR(i,a,b) for (int i = (int)(a); i < (int)(b); ++i)
#define REP(i,n) FOR(i,0,n)
#define pb push_back
#define x first
#define y second

#define TRACE(x) cerr << #x << " = " << x << endl
#define _ << " _ " <<

using namespace std;

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

const int Mod = 1e9+7;
int add(int x, int y){x += y; if (x >= Mod) return x-Mod; return x;}
int mul(int x, int y){return (int)((ll)x*y%Mod);}
int sub(int x, int y){x -= y; if (x < 0) return x+Mod; return x;}
int pot(int x, int y){
  int r = 1;
  while (y){
    if (y&1) r = mul(r, x);
    x = mul(x, x), y >>= 1;
  } return r;
}
int inv(int x){assert(x != 0); return pot(x, Mod-2);}

const int Mod2 = 1e9+6;
int add2(int x, int y){x += y; if (x >= Mod2) return x-Mod2; return x;}
int mul2(int x, int y){return (int)((ll)x*y%Mod2);}
int sub2(int x, int y){x -= y; if (x < 0) return x+Mod2; return x;}

pii concat(pii a, pii b){
  return {add(mul(a.x, pot(10, b.y)), b.x), add2(a.y, b.y)};
}

pii cast(string s){
  pii sol = {0, 0};
  for (auto t : s)
    sol = {add(mul(sol.x, 10), t-'0'), add2(sol.y, 1)};
  return sol;
}

pii concatself(pii a, int b){
  if (b == 0) return {0, 0};
  pii sol = a;
  REP(i,b-1) sol = concat(sol, a);
  return sol;
}

void inc(string &s){
  int pos = (int)s.size()-1;
  while (s[pos] == '9')
    s[pos--] = '0';
  if (pos == -1) s.insert(s.begin(), '1');
  else ++s[pos];
}

pii kojikurac2(string &a, string &b){
  if (a.size() == b.size()){
    int len = (int)a.size();

    vector<int> delta(len);
    REP(i,len) delta[i] =  b[i]-'0';
    REP(i,len) delta[i] -= a[i]-'0';
    for (int i = len-1; i >= 0; --i)
      if (delta[i] < 0)
	delta[i] += 10, --delta[i-1];

    // explen = len * delta % mod2

    int del2 = 0;
    int del1 = 0;
    for (auto t : delta)
      del2 = add2(mul2(del2, 10), t),
	del1 = add(mul(del1, 10), t);
    int explen = mul2(del2, len);

    // expmod = neka suma - neka druga suma
    int lambda = pot(10, del2);

    int mod1 = 0;
    int mod2 = 0;
    int bb = 0;
    for (auto t : b)
      bb = add(mul(bb, 10), t-'0');

    if (lambda == 1) mod1 = mul(bb, add(del1, 1));
    else mod1 = mul(bb, mul(sub(pot(lambda, add2(del2, 1)), 1), inv(sub(lambda, 1))));

    if (lambda == 1) mod2 = mul(mul(del1, add(del1, 1)), inv(2));
    else {
      int tmp = inv(sub(1, lambda));
      tmp = mul(mul(tmp, lambda), tmp);
      mod2 = sub(sub(tmp, mul(tmp, pot(lambda, add2(0, del2)))), mul(del1, mul(pot(lambda, add2(del2, 1)), inv(sub(1, lambda)))));
    }

    int expmod = sub(mod1, mod2);

    return {expmod, explen};
  } else {

    string aa(a.size(), '9');
    string bb = '1' + string(a.size(), '0');
    return concat(kojikurac2(a, aa), kojikurac2(bb, b));

  }
}

pii kojikurac(string &a, string &b){
  return kojikurac2(a, b);
  pii sol = cast(a);
  while (a != b){
    inc(a);
    sol = concat(sol, cast(a));
  } return sol;
}

string s;
int pos = 0;

string number(){
  string sol;
  while (s[pos] >= '0' && s[pos] <= '9')
    sol.pb(s[pos++]);
  return sol;
}

pii expression();

pii term(){
  string tmp = number();
  if (s[pos] == '-'){
    ++pos;
    string tmp2 = number();
    return kojikurac(tmp, tmp2);
  } else if (s[pos] == '('){
    ++pos;
    pii tmp2 = expression();
    ++pos;
    pii sol = {0, 0};
    for (auto t : tmp){
      sol = concat(concatself(sol, 10), concatself(tmp2, t-'0'));
    } return sol;
  } else {
    return cast(tmp);
  }
}

pii expression(){
  pii sol = {0, 0};
  while (true){
    sol = concat(sol, term());
    if (s[pos] != '+') break;
    ++pos;
  }
  return sol;
}

int main(){
  ios_base::sync_with_stdio(false);

  cin >> s;
  s.pb('#');
  pii sol = expression();
  cout << sol.x << endl;

  return 0;
}


#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <cassert>

using namespace std;

const int N = 1e5 + 7;
const int MOD = 1e9 + 7;
const int DEBUG = true;

typedef pair<int, int> EXP_VAL;

#define plus PLUS
#define minus MINUS

vector<int> plus[N], minus[N];
int power10[N][2], ones[N];
int match[N];
char s[N];
int n;

EXP_VAL pad[N][10], all[N];

int power(int a, int b, int mod = MOD) {
	int ret = 1;
	for (; b; b >>= 1) {
		if (b & 1) {
			ret = 1LL * ret * a % mod;
		}
		a = 1LL * a * a % mod;
	}
	return ret;
}

EXP_VAL concat(EXP_VAL a, EXP_VAL b) {
	return {(1LL * a.first * b.second % MOD + b.first) % MOD,
		1LL * a.second * b.second % MOD};
}

EXP_VAL parse_exp(int dep, int l, int r);

int parse_number(int l, int r, int mod) {
	if (DEBUG) cout << "parse number " << string(s + l, s + r + 1) << endl;
	int ret = 0;
	for (int i = l; i <= r; i++) {
		ret = (ret * 10LL + s[i] - '0') % mod;
	}
	return ret;
}

int sum(int a, int b) {
	// return a^0 + ... a^(b-1) % MOD
	int upper = power(a, b, MOD) + MOD - 1;
	int lower = a + MOD - 1;
	return 1LL * upper % MOD * power(lower % MOD, MOD - 2, MOD) % MOD;
}

EXP_VAL brute_force(int x) {
	EXP_VAL ret = {0, 1};
	for (int i = 1; i <= x; i++) {
		int p = 1, t = i;
		while (t) {
			(p *= 10) %= MOD;
			t /= 10;
		}
		ret = concat(ret, {i, p});
	}
	return ret;
}

EXP_VAL get_pad(int pre, int m) {
	if (pre == 0) return {0, power10[m][0]};
	if (pad[pre][m].first != -1) return pad[pre][m];
	EXP_VAL &ret = pad[pre][m];
	ret = {0, 1};
	auto v = get_pad(pre - 1, m);
	int s = sum(power10[m][0], power10[pre - 1][1]);
	for (int i = 0; i < 10; i++) {
		auto vv = v;
		vv.first += 1LL * i * power10[pre - 1][0] % MOD * s % MOD;
		vv.first %= MOD;
		ret = concat(ret, vv);
	}
	return ret;
}

EXP_VAL get_pad(int pre, int m, int h) {
	if (pre == 0) return {h, power10[m][0]};
	auto v = get_pad(pre, m);
	v.first += 1LL * h * sum(power10[m][0], power10[pre][1]) % MOD;
	v.first %= MOD;
	return v;
}

EXP_VAL get_all(int i) {
	if (i == 0) return {0, 1};
	if (all[i].first != -1) return all[i];
	EXP_VAL &ret = all[i];
	ret = get_all(i - 1);
	for (int h = 1; h <= 9; h++) {
		auto v = get_pad(i - 1, i, 1LL * h * power10[i - 1][0] % MOD);
		ret = concat(ret, v);
	}
	return ret;
}

EXP_VAL calc(string s, int op = 0) {
	if (DEBUG) cout << "parse calc " << s << " op = " << op << endl;
	static int a[N];
	int m = s.size();
	for (int i = 0; i < m; i++) {
		a[i] = s[m - i - 1] - '0';
	}
	if (s == "0") op = 0;
	if (op) {
		a[0]--;
		for (int i = 0; i < m; i++) {
			if (a[i] < 0) {
				a[i] += 10;
				a[i + 1]--;
			}
		}
		while (m > 1 && a[m - 1] == 0) m--;
	}
	EXP_VAL ret = {0, 1};
	int high = 0;
	for (int i = m - 1; i >= 0; i--) {
		for (int j = 0; j < a[i]; j++) {
			if (j == 0 && i == m - 1) {
				ret = concat(ret, get_all(i));
			} else {
				auto v = get_pad(i, m, (high + 1LL * power10[i][0] * j % MOD) % MOD);
				ret = concat(ret, v);
			}
		}
		high += 1LL * power10[i][0] * a[i] % MOD;
		high %= MOD;
	}
	ret = concat(ret, {high, power10[m][0]});
	if (DEBUG) cout << "result = " << ret.first << " " << ret.second << endl;
	return ret;
}

EXP_VAL parse_term(int dep, int l, int r) {
	if (DEBUG) cout << "parse term " << string(s + l, s + r + 1) << endl;
	if (s[r] == ')') {
		int p = match[r];
		auto e = parse_exp(dep + 1, p + 1, r - 1);
		int number = parse_number(l, p - 1, MOD - 1);
		return {1LL * e.first * sum(e.second, number) % MOD, power(e.second, number)};
	} else {
		int i = upper_bound(minus[dep].begin(), minus[dep].end(), r) - minus[dep].begin() - 1;
		if (i < 0 || minus[dep][i] < l) return {parse_number(l, r, MOD), power10[r - l + 1][0]};
		int p = minus[dep][i];
		auto eval_l = calc(string(s + l, s + p), 1);
		auto eval_r = calc(string(s + p + 1, s + r + 1));
		int second = 1LL * eval_r.second * power(eval_l.second, MOD - 2) % MOD;
		int first = eval_r.first - 1LL * eval_l.first * second % MOD;
		if (first < 0) first += MOD;
		return {first, second};
	}
}

EXP_VAL parse_exp(int dep, int l, int r) {
	if (DEBUG) cout << "parse exp " << string(s + l, s + r + 1) << endl;
	// found plus;
	int i = upper_bound(plus[dep].begin(), plus[dep].end(), r) - plus[dep].begin() - 1;
	if (i < 0 || plus[dep][i] < l) return parse_term(dep, l, r);
	int p = plus[dep][i];
	auto a = parse_exp(dep, l, p - 1), b = parse_term(dep, p + 1, r);
	return concat(a, b);
}

void prepare() {
	memset(pad, -1, sizeof(pad));
	memset(all, -1, sizeof(all));
	power10[0][0] = power10[0][1] = 1;
	ones[0] = 0;
	for (int i = 0; i < n; i++) {
		power10[i + 1][0] = power10[i][0] * 10LL % MOD;
		power10[i + 1][1] = power10[i][1] * 10LL % (MOD - 1);
		ones[i + 1] = (ones[i] * 10LL + 1) % MOD;
	}
}

int main() {
	scanf("%s", s);
	n = strlen(s);
	prepare();
	vector<int> stack;
	for (int i = 0, cur = 0; i < n; i++) {
		switch (s[i]) {
		case '(' : cur++; stack.push_back(i); break;
		case ')' : cur--; match[stack.back()] = i, match[i] = stack.back(); stack.pop_back(); break;
		case '+' : plus[cur].push_back(i); break;
		case '-' : minus[cur].push_back(i); break;
		}
	}
	cout << parse_exp(0, 0, n - 1).first << endl;
	return 0;
}


#include <cmath>
#include <map>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <set>
#include <bitset>
#include <memory.h>
#include <functional>
#include <queue>
#include <fstream>
#include <ctime>
#include <deque>
#include <utility>
#include <stack>
#include <sstream>
#include <list>
#include <cctype>
#include <numeric>
#include <iomanip>
#include <assert.h>
using namespace std;
#define sqr(_) ((_)*(_))

typedef pair<int, int> Pii;
typedef pair<Pii, Pii> Ppp;
#define x first
#define y second
#define mp make_pair
#define pb push_back

typedef long long LL;

const int MAXN = (int)2e5 + 10, INF = (int)2e9;

struct Graph
{
	int id, next, dis;
}g[MAXN * 4];
Ppp e[MAXN];
int n, m, st[MAXN], dis[MAXN], f[MAXN];
int head, tail, que[MAXN * 100];
bool ins[MAXN];

void init()
{
	scanf("%d%d", &n, &m);
	for (int i = 1; i <= m; ++i)
	{
		int a, b, c, d;
		scanf("%d%d%d%d", &a, &b, &c, &d);
		e[i] = mp(mp(a, b), mp(c, d));
	}
}
void Add(int tot, int x, int y, int z)
{
	g[tot].id = y, g[tot].dis = z, g[tot].next = st[x], st[x] = tot;
}
int getf(int x)
{
	if (f[x] == x) return x;
	f[x] = getf(f[x]);
	return f[x];
}
bool exLoop(int m)
{
	for (int i = 1; i <= n; ++i)
		dis[i] = INF, ins[i] = 0;
	head = 0; tail = 0;
	for (int i = 1; i <= n; ++i)
//		que[i] = i, ins[i] = 1;
		if (!ins[getf(i)])
		{
			que[++tail] = getf(i);
			dis[getf(i)] = 0;
			ins[getf(i)] = 1;
		}
	while (head < tail)
	{
		int x = que[++head];
		ins[x] = 0;
		for (int i = st[x]; i != -1; i = g[i].next)
			if (dis[x] + g[i].dis < dis[g[i].id])
			{
				dis[g[i].id] = dis[x] + g[i].dis;
				if (!ins[g[i].id])
				{
					ins[g[i].id] = 1;
					que[++tail] = g[i].id;
					if (tail > 4 * (n + m))
						return 0;
				}
			}
	}
	return 1;
}
void Calc(int m)
{
	head = 0, tail = 1;
	for (int i = 1; i <= n; ++i)
		dis[i] = INF, ins[i] = 0;
	dis[1] = 0, ins[1] = 1, que[1] = 1;
	while (head < tail)
	{
		int x = que[++head];
		ins[x] = 0;
		for (int i = st[x]; i != -1; i = g[i].next)
			if (dis[x] + g[i].dis < dis[g[i].id])
			{
				dis[g[i].id] = dis[x] + g[i].dis;
				if (!ins[g[i].id])
				{
					ins[g[i].id] = 1;
					que[++tail] = g[i].id;
				}
			}
	}
}
map<Pii, int> h;
bool check(int m, bool flag)
{
	static int id[MAXN];
	memset(st, -1, sizeof(st));
	for (int i = 1; i <= n; ++i)
		f[i] = i, id[i] = i;
	h.clear();
	for (int i = 1; i <= m; ++i)
	{
		int x = e[i].x.x, y = e[i].x.y;
		if (x > y) swap(x, y);
		f[getf(x)] = getf(y);
		if (h.find(mp(x, y)) != h.end())
			if (h[mp(x, y)] == e[i].y.x * e[i].y.y)
				continue ;
			else
			return 0;
		Add(i * 2, x, y, e[i].y.x * e[i].y.y);
		Add(i * 2 + 1, y, x, -e[i].y.x * e[i].y.y);
	}
	if (!exLoop(m))
		return 0;
	for (int i = 1; i <= n; ++i)
		if (dis[i] < dis[getf(i)])
		{
			int fa = getf(i);
			f[i] = i, f[fa] = i;
		}
	for (int i = 1; i <= n; ++i)
		if (getf(i) != getf(1) && getf(i) != getf(n))
		{
			++m;
			Add(m * 2, 1, getf(i), 0);
			Add(m * 2 + 1, getf(i), 1, 0);
//			cout << 1 << " " << getf(i) << endl;
//			f[getf(i)] = getf(1);
		}
	if (getf(1) != getf(n))
	{
		++m;
		Add(m * 2, 1, n, INF - 1);
		Add(m * 2 + 1, n, 1, -INF + 1);
	}
//	puts("");
	Calc(m);
	for (int i = 1; i <= n; ++i)
	{
		for (int j = st[i]; j != -1; j = g[j].next)
			if (dis[i] + g[j].dis > dis[g[j].id])
				return 0;
		if (dis[i] + (i != n) > dis[n])
			return 0;
		if (!dis[i] && i != 1 && getf(i) == getf(1))
			return 0;
		if (dis[i] < 0)
			return 0;
	}
	if (!flag)
		return 1;
	if (dis[n] == INF - 1)
		puts("UNKNOWN");
	else
	printf("%d\n", dis[n]);
	return 1;
}
int Find(int l, int r)
{
	while (l <= r)
	{
		int mid = (l + r) >> 1;
		if (check(mid, 0))
			l = mid + 1;
		else
			r = mid - 1;
//		cout << l << " " << r << endl;
	}
	return r;
}
void solve()
{
	int Tohka = Find(1, m);
	if (Tohka < m)
		printf("BAD %d\n", Tohka + 1);
	else
		check(m, 1);
}
int main()
{
#ifndef ONLINE_JUDGE
	freopen("input.txt", "r", stdin), freopen("output.txt", "w", stdout);
#endif

	init();
	solve();

	fclose(stdin);
	fclose(stdout);
	return 0;
}


#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cstring>
#define MAXN 100005
#define INF 0x7ffffff
using namespace std ;
typedef long long LL ;

int N, M ;
int fa[MAXN], dis[MAXN], mn[MAXN] ;
int all, out[MAXN] ;

int find(int x)
{
	int tmp = fa[x] ;
	if(tmp == x) return x ;
	fa[x] = find(fa[x]) ;
	dis[x] = dis[tmp]+dis[x] ;
	return fa[x] ;
}

void Bad(int x)
{
	printf("BAD %d\n", x) ;
	exit(0) ;
}

int main()
{
	int i, j ;
	int fr, to, w, b, tmp ;
	int t1, t2 ;
	scanf("%d %d", &N, &M) ;
	for(i = 1; i <= N; i ++)
		fa[i] = i, mn[i] = INF ;
	for(i = 1; i <= M; i ++)
	{
		scanf("%d %d %d %d", &fr, &to, &w, &b) ;
		tmp = w*b ;
		if((t1=find(fr)) != (t2=find(to)))
		{
			if(t1 > t2) swap(fr, to), swap(t1, t2), tmp = -tmp ;
			fa[t2] = t1 ;
			dis[t2] = dis[fr]+tmp-dis[to] ;
			mn[t1] = min(mn[t1], min(0, mn[t2])+dis[t2]) ;
			if(t1 == 1 && mn[t1] <= 0)
				Bad(i) ;
		}
		else
		{
			if(dis[fr]+tmp != dis[to])
				Bad(i) ;
		}
	}
	if(find(N) != 1)
		printf("UNKNOWN\n") ;
	else
		printf("%d\n", dis[N]) ;
	//system("pause") ;
	return 0 ;
}


#include <cmath>
#include <map>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <set>
#include <bitset>
#include <memory.h>
#include <functional>
#include <queue>
#include <fstream>
#include <ctime>
#include <deque>
#include <utility>
#include <stack>
#include <sstream>
#include <list>
#include <cctype>
#include <numeric>
#include <iomanip>
#include <assert.h>
using namespace std;
#define sqr(_) ((_)*(_))

typedef pair<int, int> Pii;
typedef pair<Pii, Pii> Ppp;
#define x first
#define y second
#define mp make_pair
#define pb push_back

typedef long long LL;

const int MAXN = (int)2e5 + 10, INF = (int)2e9;

struct Graph
{
	int id, next, dis;
}g[MAXN * 4];
Ppp e[MAXN];
int n, m, st[MAXN], dis[MAXN], f[MAXN];
int head, tail, que[MAXN * 100];
bool ins[MAXN];

void init()
{
	scanf("%d%d", &n, &m);
	for (int i = 1; i <= m; ++i)
	{
		int a, b, c, d;
		scanf("%d%d%d%d", &a, &b, &c, &d);
		e[i] = mp(mp(a, b), mp(c, d));
	}
}
void Add(int tot, int x, int y, int z)
{
	g[tot].id = y, g[tot].dis = z, g[tot].next = st[x], st[x] = tot;
}
int getf(int x)
{
	if (f[x] == x) return x;
	f[x] = getf(f[x]);
	return f[x];
}
bool exLoop(int m)
{
	for (int i = 1; i <= n; ++i)
		dis[i] = INF, ins[i] = 0;
	head = 0; tail = 0;
	for (int i = 1; i <= n; ++i)
//		que[i] = i, ins[i] = 1;
		if (!ins[getf(i)])
		{
			que[++tail] = getf(i);
			dis[getf(i)] = 0;
			ins[getf(i)] = 1;
		}
	while (head < tail)
	{
		int x = que[++head];
		ins[x] = 0;
		for (int i = st[x]; i != -1; i = g[i].next)
			if (dis[x] + g[i].dis < dis[g[i].id])
			{
				dis[g[i].id] = dis[x] + g[i].dis;
				if (!ins[g[i].id])
				{
					ins[g[i].id] = 1;
					que[++tail] = g[i].id;
					if (tail > 4 * (n + m))
						return 0;
				}
			}
	}
	return 1;
}
void Calc(int m)
{
	head = 0, tail = 1;
	for (int i = 1; i <= n; ++i)
		dis[i] = INF, ins[i] = 0;
	dis[1] = 0, ins[1] = 1, que[1] = 1;
	while (head < tail)
	{
		int x = que[++head];
		ins[x] = 0;
		for (int i = st[x]; i != -1; i = g[i].next)
			if (dis[x] + g[i].dis < dis[g[i].id])
			{
				dis[g[i].id] = dis[x] + g[i].dis;
				if (!ins[g[i].id])
				{
					ins[g[i].id] = 1;
					que[++tail] = g[i].id;
				}
			}
	}
}
bool check(int m, bool flag)
{
	static int id[MAXN];
	memset(st, -1, sizeof(st));
	for (int i = 1; i <= n; ++i)
		f[i] = i, id[i] = i;
	for (int i = 1; i <= m; ++i)
	{
		f[getf(e[i].x.x)] = getf(e[i].x.y);
		Add(i * 2, e[i].x.x, e[i].x.y, e[i].y.x * e[i].y.y);
		Add(i * 2 + 1, e[i].x.y, e[i].x.x, -e[i].y.x * e[i].y.y);
	}
	if (!exLoop(m))
		return 0;
	for (int i = 1; i <= n; ++i)
		if (dis[i] < dis[getf(i)])
		{
			int fa = getf(i);
			f[i] = i, f[fa] = i;
		}
	for (int i = 1; i <= n; ++i)
		if (getf(i) != getf(1) && getf(i) != getf(n))
		{
			++m;
			Add(m * 2, 1, getf(i), 0);
			Add(m * 2 + 1, getf(i), 1, 0);
//			cout << 1 << " " << getf(i) << endl;
//			f[getf(i)] = getf(1);
		}
	if (getf(1) != getf(n))
	{
		++m;
		Add(m * 2, 1, n, INF - 1);
		Add(m * 2 + 1, n, 1, -INF + 1);
	}
//	puts("");
	Calc(m);
	for (int i = 1; i <= n; ++i)
	{
		for (int j = st[i]; j != -1; j = g[j].next)
			if (dis[i] + g[j].dis > dis[g[j].id])
				return 0;
		if (dis[i] + (i != n) > dis[n])
			return 0;
		if (!dis[i] && i != 1 && getf(i) == getf(1))
			return 0;
		if (dis[i] < 0)
			return 0;
	}
	if (!flag)
		return 1;
	if (dis[n] == INF - 1)
		puts("UNKNOWN");
	else
	printf("%d\n", dis[n]);
	return 1;
}
int Find(int l, int r)
{
	while (l <= r)
	{
		int mid = (l + r) >> 1;
		if (check(mid, 0))
			l = mid + 1;
		else
			r = mid - 1;
//		cout << l << " " << r << endl;
	}
	return r;
}
void solve()
{
	int Tohka = Find(1, m);
	if (Tohka < m)
		printf("BAD %d\n", Tohka + 1);
	else
		check(m, 1);
}
int main()
{
#ifndef ONLINE_JUDGE
	freopen("input.txt", "r", stdin), freopen("output.txt", "w", stdout);
#endif

	init();
	solve();

	fclose(stdin);
	fclose(stdout);
	return 0;
}


#include <cmath>
#include <map>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <set>
#include <bitset>
#include <memory.h>
#include <functional>
#include <queue>
#include <fstream>
#include <ctime>
#include <deque>
#include <utility>
#include <stack>
#include <sstream>
#include <list>
#include <cctype>
#include <numeric>
#include <iomanip>
#include <assert.h>
using namespace std;
#define sqr(_) ((_)*(_))

typedef pair<int, int> Pii;
typedef pair<Pii, Pii> Ppp;
#define x first
#define y second
#define mp make_pair
#define pb push_back

typedef long long LL;

const int MAXN = (int)2e5 + 10, INF = (int)2e9;

struct Graph
{
	int id, next, dis;
}g[MAXN * 4];
Ppp e[MAXN];
int n, m, st[MAXN], dis[MAXN], f[MAXN];
int head, tail, que[MAXN * 100];
bool ins[MAXN];

void init()
{
	scanf("%d%d", &n, &m);
	for (int i = 1; i <= m; ++i)
	{
		int a, b, c, d;
		scanf("%d%d%d%d", &a, &b, &c, &d);
		e[i] = mp(mp(a, b), mp(c, d));
	}
}
void Add(int tot, int x, int y, int z)
{
	g[tot].id = y, g[tot].dis = z, g[tot].next = st[x], st[x] = tot;
}
int getf(int x)
{
	if (f[x] == x) return x;
	f[x] = getf(f[x]);
	return f[x];
}
bool exLoop(int m)
{
	for (int i = 1; i <= n; ++i)
		dis[i] = INF, ins[i] = 0;
	head = 0; tail = 0;
	for (int i = 1; i <= n; ++i)
//		que[i] = i, ins[i] = 1;
		if (!ins[getf(i)])
		{
			que[++tail] = getf(i);
			dis[getf(i)] = 0;
			ins[getf(i)] = 1;
		}
	while (head < tail)
	{
		int x = que[++head];
		ins[x] = 0;
		for (int i = st[x]; i != -1; i = g[i].next)
			if (dis[x] + g[i].dis < dis[g[i].id])
			{
				dis[g[i].id] = dis[x] + g[i].dis;
				if (!ins[g[i].id])
				{
					ins[g[i].id] = 1;
					que[++tail] = g[i].id;
					if (tail > 4 * (n + m))
						return 0;
				}
			}
	}
	return 1;
}
void Calc(int m)
{
	head = 0, tail = 1;
	for (int i = 1; i <= n; ++i)
		dis[i] = INF, ins[i] = 0;
	dis[1] = 0, ins[1] = 1, que[1] = 1;
	while (head < tail)
	{
		int x = que[++head];
		ins[x] = 0;
		for (int i = st[x]; i != -1; i = g[i].next)
			if (dis[x] + g[i].dis < dis[g[i].id])
			{
				dis[g[i].id] = dis[x] + g[i].dis;
				if (!ins[g[i].id])
				{
					ins[g[i].id] = 1;
					que[++tail] = g[i].id;
				}
			}
	}
}
map<Pii, int> h;
bool check(int m, bool flag)
{
	static int id[MAXN];
	memset(st, -1, sizeof(st));
	for (int i = 1; i <= n; ++i)
		f[i] = i, id[i] = i;
	h.clear();
	for (int i = 1; i <= m; ++i)
	{
		int x = e[i].x.x, y = e[i].x.y, z = e[i].y.x * e[i].y.y;
		if (x > y)
			swap(x, y), z *= -1;
		f[getf(x)] = getf(y);
		if (h.find(mp(x, y)) != h.end())
			if (h[mp(x, y)] == z)
				continue ;
			else
			return 0;
		h[mp(x, y)] = z;
		Add(i * 2, x, y, z);
		Add(i * 2 + 1, y, x, -z);
	}
	if (!exLoop(m))
		return 0;
	for (int i = 1; i <= n; ++i)
		if (dis[i] < dis[getf(i)])
		{
			int fa = getf(i);
			f[i] = i, f[fa] = i;
		}
	for (int i = 1; i <= n; ++i)
		if (getf(i) != getf(1) && getf(i) != getf(n))
		{
			++m;
			Add(m * 2, 1, getf(i), 0);
			Add(m * 2 + 1, getf(i), 1, 0);
//			cout << 1 << " " << getf(i) << endl;
//			f[getf(i)] = getf(1);
		}
	if (getf(1) != getf(n))
	{
		++m;
		Add(m * 2, 1, n, INF - 1);
		Add(m * 2 + 1, n, 1, -INF + 1);
	}
//	puts("");
	Calc(m);
	for (int i = 1; i <= n; ++i)
	{
		for (int j = st[i]; j != -1; j = g[j].next)
			if (dis[i] + g[j].dis > dis[g[j].id])
				return 0;
		if (dis[i] + (i != n) > dis[n])
			return 0;
		if (!dis[i] && i != 1 && getf(i) == getf(1))
			return 0;
		if (dis[i] < 0)
			return 0;
	}
	if (!flag)
		return 1;
	if (dis[n] == INF - 1)
		puts("UNKNOWN");
	else
	printf("%d\n", dis[n]);
	return 1;
}
int Find(int l, int r)
{
	while (l <= r)
	{
		int mid = (l + r) >> 1;
		if (check(mid, 0))
			l = mid + 1;
		else
			r = mid - 1;
//		cout << l << " " << r << endl;
	}
	return r;
}
void solve()
{
	int Tohka = Find(1, m);
	if (Tohka < m)
		printf("BAD %d\n", Tohka + 1);
	else
		check(m, 1);
}
int main()
{
#ifndef ONLINE_JUDGE
	freopen("input.txt", "r", stdin), freopen("output.txt", "w", stdout);
#endif

	init();
	solve();

	fclose(stdin);
	fclose(stdout);
	return 0;
}


#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<queue>

using namespace std;

const int N=500,INF=1<<30;
int nxt[N],a[N][N],n,x,rank[N][N],now;
char s[10];
queue <int> q;

void init()
{
	scanf("%d",&n);
	for (int i=1;i<=n;i++)
		for (int j=1;j<=n;j++)
			scanf("%d",&a[i][j]);
	puts("B");fflush(stdout);
	scanf("%s",s);
	if(s[0]=='I')
	{
		for (int i=1;i<=n;i++)
			for (int j=1;j<=n;j++)
				a[i][j]=-a[i][j];
	}
	scanf("%d",&x);
	if(x>n)
		for (int i=1;i<=n;i++)
			for (int j=1;j<=n;j++)
				a[i][j]=-a[i][j];
}

bool cmp(int x,int y)
{
	return a[now][x-n]>a[now][y-n];
}

void prework()
{
	for (int i=1;i<=n;i++)
	{
		for (int j=1;j<=n;j++)
			rank[i][j]=j+n;
		now=i;
		sort(rank[i]+1,rank[i]+1+n,cmp);
		q.push(i);
	}
//	for (int i=1;i<=n;i++,putchar('\n'))
//		for (int j=1;j<=n;j++)
//			printf("%d ",rank[i][j]);
	for (int i=1;i<=n;i++)
		a[0][i]=a[i][0]=INF;
	while(!q.empty())
	{
		int x=q.front();q.pop();
		if(x==0) continue;
		while(nxt[x]==0)
		{
			int girl=rank[x][++*rank[x]];
			if(a[x][girl-n]<a[nxt[girl]][girl-n])
				nxt[nxt[girl]]=0,q.push(nxt[girl]),nxt[girl]=x,nxt[x]=girl;
		}
//		for (int i=1;i<=n;i++)
//			printf("%d ",nxt[i]);puts("");
	}
}

void work()
{
	prework();
	for (int i=1;;i++)
	{
		if(x==-1) return;
		printf("%d\n",nxt[x]);fflush(stdout);
		scanf("%d",&x);
	}

}

int main()
{
	int T;
	scanf("%d",&T);
	while(T--)
	{
		init();
		work();
	}
	return 0;
}


#include <bits/stdc++.h>
#define M 105
#define MP std::make_pair
#define PB push_back
#define FI first
#define SE second
#define INF 1000000005
typedef long long ll;
int n, a[M][M], match[M];
std::vector <int> Vec[M];
int read() {
	int ans = 0; char c = getchar();
	while (c < '0' || c > '9') c = getchar();
	while (c >= '0' && c <= '9') ans = ans * 10 + c - '0', c = getchar();
	return ans;
}
void Write(int x) {
	if (x < 10) putchar(x + '0');
	else Write(x / 10), putchar(x % 10 + '0');
}
int max(int x, int y) {return x > y ? x : y;}
int min(int x, int y) {return x < y ? x : y;}
void solve() {
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= n; j++) Vec[i].PB(j + n), Vec[i + n].PB(j);
		std::sort(Vec[i].begin(), Vec[i].end(), [&](int x, int y) {return a[i][x] > a[i][y];});
		std::sort(Vec[i + n].begin(), Vec[i + n].end(), [&](int x, int y) {return a[x][i + n] < a[y][i + n];});
	}
	for (int _ = 0; _ < n; _++)
		for (int i = 1; i <= n; i++) {
			if (match[i]) continue;
			if (!match[Vec[i][_]]) match[i] = Vec[i][_], match[Vec[i][_]] = i;
			else if (a[match[Vec[i][_]]][Vec[i][_]] > a[i][Vec[i][_]])
				match[match[Vec[i][_]]] = 0, match[i] = Vec[i][_], match[Vec[i][_]] = i;
		}
	return;
}
int main() {
	std::cin >> t;
	while (t--) {
		std::cin >> n;
		for (int i = 1; i <= n; i++)
			for (int j = 1; j <= n; j++) a[i][j + n] = read();
		std::cout << 'B' << std::endl;
		char c; std::cin >> c;
		if (c == 'I')
			for (int i = 1; i <= n; i++)
				for (int j = 1; j <= n; j++) a[i][j] = -a[i][j];
		int tmp; std::cin >> tmp;
		if (tmp > n)
			for (int i = 1; i <= n; i++)
				for (int j = 1; j <= n; j++) a[i][j] = -a[i][j];
		solve();
		do {
			std::cout << match[tmp] << std::endl;
			std::cin >> tmp;
		}while (tmp != -1);
		for (int i = 1; i <= n * 2; i++) match[i] = 0, Vec[i].clear();
	}
	return 0;
}


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

// io
#define get(i) scanf("%d", &i)
#define flush fflush(stdin)

// manipulations
#define f(i, n) for (int i = 0; i < n; i++)
#define fr(i, n) for (int i = n - 1; i >= 0; i--)
#define ff(i, a, b) for (int i = a; i <= b; i++)
#define lowbit(x) (x & -x)
#define sz(x) int((x).size())

// built-in
#define bitcount __builtin_popcount
#define gcd __gcd

// short
#define pb push_back
#define fill(arr, a) memset(arr, a, sizeof(arr))

// useful bits
#define IN(i, l, r) (l <= i && i <= r)
#define relax(a, b) (a) = max((a), (b))
#define relaxi(a, b) (a) = min((a), (b))

using ll = long long;
using ld = long double;
using vi = vector<int>;
using vll = vector<ll,ll>;
using pii = pair<int,int>;
using pll = pair<ll,ll>;

ll modpow(ll a, ll b, ll mod = (ll) (1e9 + 7))
{if (!b) return 1; a %= mod; return modpow(a * a % mod, b / 2, mod) * (b & 1 ? a : 1) % mod;}

// for rand
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
// use uniform_int_distribution<int>(0, i)(rng)

const int DEBUG = 0;
const int mxn = 100, mxm = 2500;
int n,m;
int p[mxn];
vi adj[mxn];
int a[mxm], b[mxm], c[mxm];

void flip() {
	f(i,n) swap(adj[i],adj[i+n]);
	f(e,m) a[e]+=n, b[e]-=n;
}

void flipSign() {
	f(i,m) c[i]*=-1;
}

int fi(int v) {
	int e = adj[v][p[v]];
	return a[e]^b[e]^v;
}

void solve() {
	cin>>n; m=0;
	f(i,n) {
		f(j,n) {
			a[m]=i; b[m]=j+n;
			adj[a[m]].pb(m); adj[b[m]].pb(m);
			cin>>c[m++];
		}
	}
	cout << "B" << endl;
	flush;
	string cmd; cin>>cmd;
	if (cmd == "D") flipSign();
	int s; cin >> s; s--;
	if (s >= n) flip();
	s %= n;
	auto cmp = [](int a, int b){
		return c[a]<c[b];
	};
	f(i,n) sort(begin(adj[i]),end(adj[i]),cmp);
	fill(p,0);
	bool found = 1;
	while (found) {
		f(i,n) p[i+n]=-1;
		f(i,n) {
			int e = adj[i][p[i]];
			int w = a[e]^b[e]^i;
			if (p[w] < c[e])
				p[w] = c[e];
		}
		found=0;
		f(i,n) {
			int e = adj[i][p[i]];
			int w = a[e]^b[e]^i;
			if (p[w] != c[e]) p[i]++, found = 1;
		}
	}
	s++;
	do {
		if (s == -1) break;
		cout << fi(--s)+1 << endl;
		flush;
	} while (cin>>s);
}

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

#ifdef LOCAL
	if (DEBUG) freopen("input.txt", "r", stdin);
	if (DEBUG) freopen("output.txt", "w", stdout);
	clock_t start = clock();
#endif

	int t; cin >> t;
	while (t--)
		solve();

#ifdef LOCAL
	cout << setprecision(12) << ld(clock()-start) / CLOCKS_PER_SEC << endl;
#endif

	return 0;
}


#include <bits/stdc++.h>
using namespace std;
int read();

int n;
char t[102];
int w[102][102], rnk[102][102], pos[102];

vector<int> p[102];
queue<int> q;

void init() {
    for (int i = 1; i <= n; ++i) {
        p[i].clear(), p[i + n].clear();
        for (int j = 1; j <= n; ++j)
            p[i].push_back(j + n), p[i + n].push_back(j);
        sort(p[i].begin(), p[i].end(),
             [&](int a, int b) { return w[i][a] > w[i][b]; });
        sort(p[i + n].begin(), p[i + n].end(),
             [&](int a, int b) { return w[a][i] < w[b][i]; });
        q.push(i), pos[i] = 0, pos[i + n] = n;
        for (int j = 0; j < n; ++j)
            rnk[j][p[i][j]] = j, rnk[i + n][p[i + n][j]] = j;
    }

    while (!q.empty()) {
        int u = q.front(), v;
        while (pos[v = p[u][pos[u]]] < rnk[v][u]) ++pos[u];
        if (pos[v] < n) q.push(p[v][pos[v]]);
        pos[v] = rnk[v][u];
    }
}

int main() {
    for (int T = read(); T; --T) {
        n = read();
        for (int i = 1; i <= n; ++i)
            for (int j = 1; j <= n; ++j) w[i][j] = read();
        printf("B\n"), fflush(stdout), scanf("%s", t);
        if (t[0] == 'D')
            for (int i = 1; i <= n; ++i)
                for (int j = 1; j <= n; ++j) w[i][j] = -w[i][j];
        init();
        for (int u = read(); ~u; u = read()) printf("%d\n", p[u][pos[u]]);
    }
    return 0;
}

int read() {
    int x = 0, f = 1;
    char c = getchar();
    while (c < '0' || c > '9') f = (c == '-') ? -1 : f, c = getchar();
    while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}


#include <bits/stdc++.h>
#define uint unsigned int
#define vint vector <int>
#define pb push_back
#define clr(a) memset(a, 0, sizeof a)
#define fir first
#define sec second
#define mkp make_pair
#define hash_t unsigned long long
#define vhash vector <hash_t>
using namespace std;

const int MaxN = 1010, MaxM = 2010;
const hash_t base = 300007;
hash_t rand_val[MaxN];

class Graph {
public:
	int en[MaxN], next[MaxM], to[MaxM], tot;
	int lab[MaxN];
	void add_edge(int x, int y) {
		next[++tot] = en[x];
		en[x] = tot;
		to[tot] = y;
	}
	void clear() {
		clr(en);
		tot = 0;
		clr(lab);
	}
}	Gu, Gv;
typedef pair <hash_t, int> h_node;
struct Status {
	int ker;
	vector <h_node> u, v;
};
vector <Status> Su, Sv;
vector < pair <int, int> > ans;
vint stk;

int n, total;
bool vis[MaxN], done[MaxN];

void read_graph(Graph &G) {
	int m;
	scanf("%d", &m);
	map <int, int> hash;
	int total = 0;
	for (int i = 1; i <= m; ++i) {
		int u, v;
		scanf("%d%d", &u, &v);
		if (!hash.count(u)) hash[u] = ++total;
		if (!hash.count(v)) hash[v] = ++total;
		u = hash[u];
		v = hash[v];
		G.add_edge(u, v);
		G.add_edge(v, u);
	}
}

int size[MaxN], mx[MaxN];
int dfs_size(Graph &G, int now) {
	vis[now] = 1;
	size[now] = 1;
	mx[now] = 0;
	stk.pb(now);
	for (int i = G.en[now]; i; i = G.next[i])
		if (!vis[G.to[i]]) {
			int tmp = dfs_size(G, G.to[i]);
			size[now] += tmp;
			mx[now] = max(mx[now], tmp);
		}
	return size[now];
}

pair <int, int> get_gra(Graph &G, int root, int u) {
	clr(vis);
	vis[u] = 1;
	stk.clear();
	int sz = dfs_size(G, root);
	pair <int, int> ret(0, 0);
	int mn = sz;
	for (auto i : stk) {
		mx[i] = max(mx[i], sz - size[i]);
		mn = min(mn, mx[i]);
	}
	for (auto i : stk)
		if (mx[i] == mn) {
			if (ret.fir == 0) ret.fir = i;
			else ret.sec = i;
		}
	return ret;
}

hash_t vec_hash(vhash &s) {
	sort(s.begin(), s.end());
	hash_t ret = 0;
	for (uint i = 0; i < s.size(); ++i)
		ret = (ret * base + s[i]) ^ (s[i] * base + rand_val[i]);
	return ret;
}

hash_t dfs_hash(Graph &G, int now) {
	vis[now] = done[now] = 1;
	vhash v;
	for (int i = G.en[now]; i; i = G.next[i])
		if (!vis[G.to[i]]) v.pb(dfs_hash(G, G.to[i]));
	v.pb(0);
	return vec_hash(v);
}

hash_t get_hash(Graph &G, int root, int u = 0) {
	pair <int, int> gra = get_gra(G, root, u);
	if (gra.sec == 0) {
		clr(vis);
		vis[u] = 1;
		return dfs_hash(G, gra.fir);
	} else {
		vhash v;
		clr(vis);
		vis[u] = 1;
		vis[gra.sec] = vis[gra.fir] = 1;
		v.pb(dfs_hash(G, gra.fir));
		v.pb(dfs_hash(G, gra.sec));
		return vec_hash(v);
	}
	return 0;
}

int relabel(Graph &G, int now, int flag = 0) {
	if (flag) stk.pb(now);
	vis[now] = 1;
	G.lab[now] = ++total;
	for (int i = G.en[now]; i; i = G.next[i])
		if (!vis[G.to[i]])
			ans.pb(mkp(G.lab[now], relabel(G, G.to[i], flag)));
	return G.lab[now];
}

h_node set_xor(vector <h_node> &u, vector <h_node> &v) {
	if (u.size() < v.size() || u.size() > v.size() + 1) return mkp(0, -1);
	multiset <hash_t> s;
	h_node ret(0, 0);
	for (auto i : v) s.insert(i.fir);
	for (auto i : u) {
		auto t = s.find(i.fir);
		if (t == s.end()) {
			if (ret.sec != 0) return mkp(0, -1);
			else ret = i;
		} else s.erase(t);
	}
	if (u.size() == v.size() && ret.sec != 0) return mkp(0, -1);
	return ret;
}

bool check(Status Su, Status Sv) {
	h_node com_u, com_v;
	com_u = set_xor(Su.u, Sv.v);
	com_v = set_xor(Sv.u, Su.v);
	if (com_u.sec == -1 || com_v.sec == -1 || com_u.fir != com_v.fir) return 0;
	if ((com_u.sec == 0) ^ (com_v.sec == 0)) return 0;

	total = 2;

	int u = Su.ker, v = Sv.ker;
	for (int i = Gu.en[u]; i; i = Gu.next[i])
		if (Gu.to[i] != com_u.sec) {
			clr(vis);
			vis[Su.ker] = 1;
			ans.pb(mkp(1, relabel(Gu, Gu.to[i])));
		}

	for (int i = Gv.en[v]; i; i = Gv.next[i])
		if (Gv.to[i] != com_v.sec) {
			clr(vis);
			vis[Sv.ker] = 1;
			ans.pb(mkp(2, relabel(Gv, Gv.to[i])));
		}

	if (com_u.sec == 0) ans.pb(mkp(1, 2));
	else {
		stk.clear();
		clr(vis);
		vis[Su.ker] = 1;
		ans.pb(mkp(1, relabel(Gu, com_u.sec, 1)));

		clr(vis);
		vis[Sv.ker] = 1;
		hash_t hv = dfs_hash(Gv, com_v.sec);

		for (auto i : stk) {
			clr(vis);
			vis[Su.ker] = 1;
			if (dfs_hash(Gu, i) == hv) {
				ans.pb(mkp(2, Gu.lab[i]));
				break;
			}
		}
	}
	return 1;
}

void work(Graph &G, vector <Status> &S) {
	for (int u = 1; u < n; ++u) {
		Status now;
		now.ker = u;

		clr(done);
		done[u] = 1;
		for (int i = G.en[u]; i; i = G.next[i])
			now.u.pb(mkp(get_hash(G, G.to[i], u), G.to[i]));
		for (int i = 1; i < n; ++i)
			if (!done[i]) now.v.pb(mkp(get_hash(G, i, u), i));
		S.pb(now);
	}
}

void solve() {
	ans.clear();
	Gu.clear();
	Gv.clear();
	Su.clear();
	Sv.clear();

	scanf("%d%*d", &n);
	read_graph(Gu);
	read_graph(Gv);
	for (int i = 0; i <= n; ++i) rand_val[i] = ((hash_t)rand() << 15) ^ rand();

	work(Gu, Su);
	work(Gv, Sv);
	for (auto i : Su)
		for (auto j : Sv)
			if (check(i, j)) {
//				assert(int(ans.size()) == n - 1);
				if (int(ans.size()) != n - 1) continue;
				puts("YES");
				for (auto e : ans) printf("%d %d\n", e.fir, e.sec);
				return;
			}
	puts("NO");
}

int main() {
	int t;
	scanf("%d", &t);
	while (t--) solve();
	return 0;
}


#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <cstring>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <list>
#include <cassert>
#include <ctime>
#include <climits>
using namespace std;

#define PB push_back
#define MP make_pair
#define SZ(v) ((int)(v).size())
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
#define FORE(i,a,b) for(int i=(a);i<=(b);++i)
#define REPE(i,n) FORE(i,0,n)
#define FORSZ(i,a,v) FOR(i,a,SZ(v))
#define REPSZ(i,v) REP(i,SZ(v))
typedef long long ll;
typedef unsigned long long ull;
ll gcd(ll a,ll b) { return b==0?a:gcd(b,a%b); }

const int MAXF=2;
const int MAXN=1000;
const int MAXM=MAXN-2;
const int MAXTN=MAXN-2;
const int MAXTM=MAXTN-1;
const int MAXRT=MAXN-1+2*MAXM;
const int MAXRTN=10+MAXTN;
const int MAXRTNSUM=MAXF*MAXRT*MAXRTN+2*MAXTN;

typedef struct RT {
	int root,u,v,vv;
} RT;
typedef struct RF {
	int n;
	int par[MAXRTNSUM];
	int chead[MAXRTNSUM];
	int cnxt[MAXRTNSUM];
	int coff[MAXRTNSUM];
	int ccnt[MAXRTNSUM];
	int cidx[MAXRTNSUM];
	int id[MAXRTNSUM];
	int d[MAXRTNSUM];
	int q[MAXRTNSUM],qhead,qtail;
	int orig[MAXRTNSUM];

	RF() { n=0; }
	int addNode(int p,int o) { assert(n<MAXRTNSUM); int ret=n++; par[ret]=p,chead[ret]=-1,cnxt[ret]=-1,orig[ret]=o; if(p!=-1) cnxt[ret]=chead[p],chead[p]=ret; return ret; }
	void print(int at) { printf("("); for(int to=chead[at];to!=-1;to=cnxt[to]) print(to); printf(")"); }

	int cidcmp(const int &a,const int &b) {
		for(int i=0;i<ccnt[a]||i<ccnt[b];++i) {
			if(i>=ccnt[a]) return -1; if(i>=ccnt[b]) return +1;
			int aa=id[cidx[coff[a]+i]],bb=id[cidx[coff[b]+i]]; if(aa!=bb) return aa<bb?-1:+1;
		}
		return 0;
	}
	struct cidless { RF* rf; cidless(RF* rf):rf(rf) {} bool operator()(const int &a,const int &b) { return rf->cidcmp(a,b)<0; } } ;
	vector<int> calcids(vector<RT> t) {
		int nt=SZ(t); //bool dbg=true;
		qhead=qtail=0; REP(i,nt) { int at=t[i].root; d[at]=0,q[qhead++]=at; }
		while(qtail<qhead) { int at=q[qtail++]; for(int to=chead[at];to!=-1;to=cnxt[to]) d[to]=d[at]+1,q[qhead++]=to; } int nq=qtail;
		int nc=0; REP(i,nq) { int at=q[i]; coff[at]=nc,ccnt[at]=0; for(int to=chead[at];to!=-1;to=cnxt[to]) ++ccnt[at],++nc; }
		int dmx=d[q[nq-1]];
		//if(dbg) printf("nq=%d dmx=%d\n",nq,dmx);
		int c=nq,b=nq,a=nq;
		while(a>0&&d[q[a-1]]==dmx) --a;
		FOR(i,a,b) { int at=q[i]; id[at]=0; }
		for(int cd=dmx-1;cd>=0;--cd) {
			c=b,b=a; while(a>0&&d[q[a-1]]==cd) --a; //if(dbg) printf("\t%d..%d..%d\n",a,b,c);
			FOR(i,b,c) { int at=q[i]; cidx[coff[par[at]]++]=at; }
			FOR(i,a,b) { int at=q[i]; for(int to=chead[at];to!=-1;to=cnxt[to]) --coff[at]; }
			sort(q+a,q+b,cidless(this));
			FOR(i,a,b) { int at=q[i]; id[at]=i==a?0:id[q[i-1]]+(cidcmp(at,q[i-1])==0?0:1); }
			//FOR(i,a,b) { int at=q[i]; printf("%d = [",at); REP(j,ccnt[at]) printf("%d%c",id[cidx[coff[at]+j]],j+1<ccnt[at]?',':']'); if(ccnt[at]==0) printf("]"); printf(" ->  %d\n",id[at]); }
		}
		vector<int> ret(nt,-1); REP(i,nt) ret[i]=id[t[i].root]; return ret;
	}
} RF;
RF rf;

//bool dbg=false;
typedef struct T {
	int n,m,root;
	int ghead[MAXTN],gnxt[2*MAXTM],gto[2*MAXTM];
	int orig[MAXTN];
	int d1[MAXTN],d2[MAXTN],d3[MAXTN];
	int q[MAXTN],qhead,qtail;

	void init(int o) { n=1,m=0; root=0; ghead[0]=-1,orig[0]=o; }
	int addNode(int p,int o) { assert(n<MAXTN); int ret=n++; ghead[ret]=-1,orig[ret]=o; if(p!=-1) { gnxt[m]=ghead[ret],ghead[ret]=m,gto[m]=p,++m; gnxt[m]=ghead[p],ghead[p]=m,gto[m]=ret,++m; }  return ret; }
	vector<int> calcCenters(int rt) {
		REP(i,n) d1[i]=INT_MAX; qhead=qtail=0; d1[rt]=0,q[qhead++]=rt;
		while(qtail<qhead) { int at=q[qtail++]; for(int x=ghead[at];x!=-1;x=gnxt[x]) { int to=gto[x]; if(d1[to]!=INT_MAX) continue; d1[to]=d1[at]+1; q[qhead++]=to; } }
		int u=rt; REP(i,n) if(d1[i]!=INT_MAX&&d1[i]>d1[u]) u=i;
		//if(dbg) { REP(i,n) printf("%d=%d ",orig[i],d1[i]); printf("-> %d\n",orig[u]); }
		REP(i,n) d2[i]=INT_MAX; qhead=qtail=0; d2[u]=0,q[qhead++]=u;
		while(qtail<qhead) { int at=q[qtail++]; for(int x=ghead[at];x!=-1;x=gnxt[x]) { int to=gto[x]; if(d2[to]!=INT_MAX) continue; d2[to]=d2[at]+1; q[qhead++]=to; } }
		int v=u; REP(i,n) if(d2[i]!=INT_MAX&&d2[i]>d2[v]) v=i;
		//if(dbg) { REP(i,n) printf("%d=%d ",orig[i],d2[i]); printf("-> %d\n",orig[v]); }
		REP(i,n) d3[i]=INT_MAX; qhead=qtail=0; d3[v]=0,q[qhead++]=v;
		while(qtail<qhead) { int at=q[qtail++]; for(int x=ghead[at];x!=-1;x=gnxt[x]) { int to=gto[x]; if(d3[to]!=INT_MAX) continue; d3[to]=d3[at]+1; q[qhead++]=to; } }
		int w=v; REP(i,n) if(d3[i]!=INT_MAX&&d3[i]>d3[w]) w=i;
		//if(dbg) { REP(i,n) printf("%d=%d ",orig[i],d3[i]); printf("-> %d\n",orig[w]); }
		vector<int> ret; REP(i,n) if(d2[i]+d3[i]==d2[v]&&d2[v]-1<=2*d2[i]&&2*d2[i]<=d2[v]+1) ret.PB(i); return ret;
	}
	void appendTo(int at,int par,int idx) {
		for(int x=ghead[at];x!=-1;x=gnxt[x]) { int to=gto[x]; if(to==par) continue; int nidx=rf.addNode(idx,orig[to]); appendTo(to,at,nidx); }
	}
} T;
T t;

typedef struct F {
	int n,m;
	vector<vector<int> > adj;
	bool done[MAXN];

	void input(int _n) { n=_n; adj=vector<vector<int> >(n,vector<int>()); scanf("%d",&m); REP(i,m) { int a,b; scanf("%d%d",&a,&b); --a,--b; adj[a].PB(b); adj[b].PB(a); } }
	void buildTree(int at,int idx) {
		done[at]=true; REPSZ(i,adj[at]) { int to=adj[at][i]; if(done[to]) continue; int nidx=t.addNode(idx,to); buildTree(to,nidx); }
	}
	// ( ((u+)) ((uv)()) ((v+)()()) )
	RT createCanonical(int u,int v,int vv,bool swp) {
		//dbg=false; if(!swp&&u==3&&v==4&&vv==2) dbg=true; if(swp&u==4&&v==3&&vv==1) dbg=true;
		RT ret; ret.u=u; ret.v=v; ret.vv=vv; ret.root=rf.addNode(-1,-1);
		int rt=ret.root,a=rf.addNode(rt,-1),b=rf.addNode(rt,-1),c=rf.addNode(rt,-1);
		a=rf.addNode(a,-1); rf.addNode(b,-1),b=rf.addNode(b,-1); rf.addNode(c,-1),rf.addNode(c,-1),c=rf.addNode(c,-1);
		REP(i,n) done[i]=false; done[u]=true; done[v]=true;
		REPSZ(i,adj[v]) {
			//if(swp&&u==0&&v==3&&vv==2) printf("building %d\n",adj[v][i]);
			t.init(adj[v][i]); buildTree(adj[v][i],t.root);
			vector<int> centers=t.calcCenters(t.root);
			//if(swp&&u==0&&v==3&&vv==2) { REPSZ(j,centers) printf("\t%d\n",t->orig[centers[j]]); }
			int par=adj[v][i]==vv?b:swp?a:c,bj=0;
			FORSZ(j,1,centers) {
				int on=rf.n;
				RT a; a.root=rf.addNode(-1,centers[bj]); t.appendTo(centers[bj],-1,a.root);
				RT b; b.root=rf.addNode(-1,centers[j]); t.appendTo(centers[j],-1,b.root);
				vector<RT> c; c.PB(a); c.PB(b); vector<int> id=rf.calcids(c); if(id[1]<id[0]) bj=j;
				rf.n=on;
			}
			{ int ridx=rf.addNode(par,t.orig[centers[bj]]); t.appendTo(centers[bj],-1,ridx); }
		}
		REP(i,n) if(!done[i]) {
			//if(!swp&&u==3&&v==0&&vv==1) printf("building %d\n",i);
			t.init(i); buildTree(i,t.root);
			vector<int> centers=t.calcCenters(t.root);
			int par=swp?c:a,bj=0;
			FORSZ(j,1,centers) {
				int on=rf.n;
				RT a; a.root=rf.addNode(-1,centers[bj]); t.appendTo(centers[bj],-1,a.root);
				RT b; b.root=rf.addNode(-1,centers[j]); t.appendTo(centers[j],-1,b.root);
				vector<RT> c; c.PB(a); c.PB(b); vector<int> id=rf.calcids(c); if(id[1]<id[0]) bj=j;
				rf.n=on;
			}
			{ int ridx=rf.addNode(par,t.orig[centers[bj]]); t.appendTo(centers[bj],-1,ridx); }
		}
		return ret;
	}
	vector<RT> createAll(bool swp) {
		int u=-1; REP(i,n) if(SZ(adj[i])==0) { u=i; break; } assert(u!=-1);
		vector<RT> ret; ret.reserve(n-1+2*m);
		REP(v,n) if(v!=u) {
			//if(!swp&&(u!=8||v!=3)) continue;
			//if(swp&&(u!=1||v!=5)) continue;
			ret.PB(createCanonical(u,v,-1,swp));
			REPSZ(i,adj[v]) ret.PB(createCanonical(u,v,adj[v][i],swp));
		}
		return ret;
	}
	void print(RT a,RT b,F &fb) {
		queue<pair<int,int> > q; q.push(MP(a.root,b.root));
		vector<int> ab(n,-1),ba(n,-1); ab[a.u]=b.v,ba[b.v]=a.u; ab[a.v]=b.u,ba[b.u]=a.v;
		while(!q.empty()) {
			int ai=q.front().first,bi=q.front().second; q.pop(); //printf("%d=%d\n",ai,bi); if(ai==0&&bi==0) exit(1);
			if(rf.orig[ai]!=-1&&rf.orig[bi]!=-1) ab[rf.orig[ai]]=rf.orig[bi],ba[rf.orig[bi]]=rf.orig[ai];
			REP(k,rf.ccnt[ai]) q.push(MP(rf.cidx[rf.coff[ai]+k],rf.cidx[rf.coff[bi]+k]));
		}
		//REP(i,n) printf("%d->%d\n",i,ab[i]);
		//REP(i,n) printf("%d<-%d\n",ba[i],i);
		REP(i,n) REPSZ(j,adj[i]) if(i<adj[i][j]) printf("%d %d\n",i+1,adj[i][j]+1);
		int x=ab[a.u]; REPSZ(j,fb.adj[x]) { int y=fb.adj[x][j]; printf("%d %d\n",a.u+1,ba[y]+1); }
		if(a.vv==-1) printf("%d %d\n",a.u+1,a.v+1);
	}
} F;

int qq;
int n,nf;
F f[2];

void input() {
	scanf("%d%d",&n,&nf);
	REP(i,nf) f[i].input(n);
}

bool solve() {
	if(qq!=1) printf("n=%d\n",n);
	vector<RT> a=f[0].createAll(false);
	vector<RT> b=f[1].createAll(true);
	vector<RT> c; REPSZ(i,a) c.PB(a[i]); REPSZ(i,b) c.PB(b[i]);
	if(qq!=1) printf("rf.n=%d\n",rf.n);
	vector<int> id=rf.calcids(c);
	if(qq!=1) printf("ids\n");
	//REPSZ(i,c) { printf("%d %2d (%d,%d,%2d): ",i<SZ(a)?0:1,i<SZ(a)?i:i-SZ(a),c[i].u,c[i].v,c[i].vv); rf.print(c[i].root); printf(" = %d\n",id[i]); }
	map<int,int> mp; REPSZ(i,a) if(mp.count(id[i])==0) mp[id[i]]=i;
	REPSZ(j,b) if(mp.count(id[SZ(a)+j])) {
		int i=mp[id[SZ(a)+j]]; //printf("a%d with b%d\n",i,j);
		printf("YES\n");
		if(qq==1) f[0].print(a[i],b[j],f[1]);
		rf.n=0;
		return true;
	}
	rf.n=0;
	printf("NO\n"); return false;
}

void run() {
	input();
	solve();
}

void test() {
	while(true) {
		int n=1000;
		vector<int> par(n,-1);
		FOR(i,1,n) par[i]=rand()%i;
		int u=rand()%n,v=rand()%(n-1); if(v>=u) ++v;
		REP(i,2) {
			f[i].n=n;
			f[i].adj=vector<vector<int> >(n);
		}
		FOR(j,1,n) {
			if(j!=u&&par[j]!=u) f[0].adj[j].PB(par[j]),f[0].adj[par[j]].PB(j);
			if(j!=v&&par[j]!=v) f[1].adj[j].PB(par[j]),f[1].adj[par[j]].PB(j);
		}
		if(!solve()) {
			printf("1\n");
			printf("%d %d\n",n,2);
			REP(i,2) {
				int m=0; REP(j,n) REPSZ(k,f[i].adj[j]) if(j<f[i].adj[j][k]) ++m;
				printf("%d\n",m); REP(j,n) REPSZ(k,f[i].adj[j]) if(j<f[i].adj[j][k]) printf("%d %d\n",j+1,f[i].adj[j][k]+1);
			}
			break;
		}
	}
}

int main() {
	int n; scanf("%d",&n); qq=n; FORE(i,1,n) run();
	//printf("%d\n",MAXRTNSUM); test();
	return 0;
}


#include<cstdio>
#include<vector>
#include<map>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=1010,oo=1000000000;
int i,j,k,n,m,Test,nm,ch,Fg,na,nb,ta,tb,tt,x,y,num,xx,yy,tx,ty,Txy;
int f[N],g[N];
map<vector<int>,int> Map;
map<int,int> P;
struct edge { int s,n;};
struct cc {
	int x,hs;
	bool operator < (const cc &n) const {
		if (hs==n.hs) return x<n.x;
		return hs<n.hs;
	}
};
void R(int &x) {
	x=0;ch=getchar();
	while (ch<'0' || '9'<ch) ch=getchar();
	while ('0'<=ch && ch<='9') x=x*10+ch-'0',ch=getchar();
}
int getf(int x) {
	if (f[x]==x) return x;
	return f[x]=getf(f[x]);
}
struct forest {
	int i,j,k,m,En,size,rt1,rt2,mi1,mi2;
	int h[N],z[N],sz[N],hs[N];
	edge E[N<<1];
	vector<int> A;
	vector<cc> Tmp[N];
	void clear() {
		En=0;
		memset(h,0,sizeof h);
	}
	void E_add(int x,int y) {
		E[++En].s=y;E[En].n=h[x];h[x]=En;
		E[++En].s=x;E[En].n=h[y];h[y]=En;
	}
	void get_size(int x,int F) {
		sz[x]=1;
		for (int k=h[x];k;k=E[k].n) if (E[k].s!=F) {
			get_size(E[k].s,x);
			sz[x]+=sz[E[k].s];
		}
	}
	void get_root(int x,int F) {
		int k,ma=size-sz[x];
		for (k=h[x];k;k=E[k].n) if (E[k].s!=F) {
			get_root(E[k].s,x);
			if (sz[E[k].s]>ma) ma=sz[E[k].s];
		}
		if (ma<mi1) {
			mi2=mi1;
			rt2=rt1;
			mi1=ma;
			rt1=x;
		}
		else {
			if (ma<mi2) {
				mi2=ma;
				rt2=x;
			}
		}
	}
	int get_hash(int x) {
		z[x]=1;
		vector<int> A;
		for (int k=h[x];k;k=E[k].n) if (!z[E[k].s]) A.push_back(get_hash(E[k].s));
		sort(A.begin(),A.end());
		if (!Map[A]) Map[A]=++nm;
		return hs[x]=Map[A];
	}
	int Js() {
		memset(z,0,sizeof z);
		A.clear();
		for (i=1;i<=n;i++) if (!z[i]) {
			get_size(i,0);
			size=sz[i];
			mi1=mi2=oo;
			get_root(i,0);
			if (mi1!=mi2) A.push_back(get_hash(rt1));
			else {
				vector<int> tmp;
				tmp.push_back(-1);
				z[rt2]=1;
				tmp.push_back(get_hash(rt1));
				z[rt2]=0;
				tmp.push_back(get_hash(rt2));
				sort(tmp.begin(),tmp.end());
				if (!Map[tmp]) Map[tmp]=++nm;
				A.push_back(Map[tmp]);
			}
		}
		sort(A.begin(),A.end());
		if (!Map[A]) Map[A]=++nm;
		return Map[A];
	}
	void work(int x) {
		memset(z,0,sizeof z);
		z[x]=1;
		A.clear();
		get_size(x,0);
		for (k=h[x];k;k=E[k].n) {
			size=sz[E[k].s];
			mi1=mi2=oo;
			get_root(E[k].s,x);
			if (mi1!=mi2) A.push_back(get_hash(rt1));
			else {
				vector<int> tmp;
				tmp.push_back(-1);
				z[rt2]=1;
				tmp.push_back(get_hash(rt1));
				z[rt2]=0;
				tmp.push_back(get_hash(rt2));
				sort(tmp.begin(),tmp.end());
				if (!Map[tmp]) Map[tmp]=++nm;
				A.push_back(Map[tmp]);
			}
		}
		A.push_back(1);
		sort(A.begin(),A.end());
	}
	void dfs(int x,int F,int tmp) {
		int t=++num,k,tt;
		for (k=h[x];k;k=E[k].n) if (E[k].s!=F && E[k].s!=tmp) {
			tt=num+1;
			dfs(E[k].s,x,tmp);
			printf("%d %d\n",t,tt);
		}
	}
	void dfs2(int x,int F,int tmp,int xx) {
		int t=++num,k;
		cc a;
		if (x==xx) Txy=num;
		for (k=h[x];k;k=E[k].n) if (E[k].s!=F && E[k].s!=tmp) {
			a.x=E[k].s;a.hs=hs[E[k].s];
			Tmp[x].push_back(a);
		}
		sort(Tmp[x].begin(),Tmp[x].end());
		for (k=0;k<Tmp[x].size();k++) dfs2(Tmp[x][k].x,x,tmp,xx);
	}
	int find_x(int x,int y) {
		for (k=h[x];k;k=E[k].n) {
			size=sz[E[k].s];
			mi1=mi2=oo;
			get_root(E[k].s,x);
			if (mi1!=mi2) if (hs[rt1]==y) return E[k].s;
			else {
				vector<int> tmp;
				tmp.push_back(-1);
				z[rt2]=1;
				tmp.push_back(hs[rt1]);
				z[rt2]=0;
				tmp.push_back(hs[rt2]);
				sort(tmp.begin(),tmp.end());
				if (Map[tmp]==y) return E[k].s;
			}
		}
	}
} A,B,C;
bool check() {
	int i,j,k,na,nb,nc,fg;
	A.work(x);
	B.work(y);
	j=0;k=0;fg=0;
	for (i=0;i<C.A.size();i++) {
		nc=1;
		while (i+1<C.A.size() && C.A[i+1]==C.A[i]) i++,nc++;
		na=nb=0;
		while (j<A.A.size() && A.A[j]==C.A[i]) j++,na++;
		while (k<B.A.size() && B.A[k]==C.A[i]) k++,nb++;
		if (nc!=na+nb) {
			if (!na || !nb) return 0;
			if (na+nb-1!=nc) return 0;
			if (fg) return 0;
			fg=C.A[i];
		}
	}
	if (!fg) {
		if (A.sz[x]+B.sz[y]!=n) return 0;
		puts("YES");
		num=0;
		A.dfs(x,0,0);
		printf("%d %d\n",1,num+1);
		B.dfs(y,0,0);
		return 1;
	}
	else {
		xx=A.find_x(x,fg);
		yy=B.find_x(y,fg);
		if (A.sz[x]+B.sz[y]-A.sz[xx]!=n) return 0;
		puts("YES");
		num=0;
		if (A.mi1!=A.mi2) {
			A.dfs2(A.rt1,0,x,xx);
			tx=Txy;
		}
		else {
			if (A.hs[A.rt1]<A.hs[A.rt2]) {
				A.dfs2(A.rt1,0,x,xx);
				A.dfs2(A.rt2,0,x,xx);
			}
			else {
				A.dfs2(A.rt2,0,x,xx);
				A.dfs2(A.rt1,0,x,xx);
			}
			tx=Txy;
		}
		num=0;
		if (B.mi1!=B.mi2) {
			B.dfs2(B.rt1,0,y,yy);
			ty=Txy;
		}
		else {
			if (B.hs[B.rt1]<B.hs[B.rt2]) {
				B.dfs2(B.rt1,0,y,yy);
				B.dfs2(B.rt2,0,y,yy);
			}
			else {
				B.dfs2(B.rt2,0,y,yy);
				B.dfs2(B.rt1,0,y,yy);
			}
			ty=Txy;
		}
		num=0;
		if (A.mi1!=A.mi2) A.dfs(A.rt1,0,x);
		else {
			if (A.hs[A.rt1]<A.hs[A.rt2]) {
				A.dfs(A.rt1,0,x);
				A.dfs(A.rt2,0,x);
			}
			else {
				A.dfs(A.rt2,0,x);
				A.dfs(A.rt1,0,x);
			}
		}
		printf("%d %d\n",num+1,tx);
		A.dfs(x,0,xx);
		printf("%d %d\n",num+1,ty);
		A.dfs(y,0,yy);
	}
}
int main() {
	R(Test);
	while (Test--) {
		R(n);R(k);Fg=na=nb=ta=tb=nm=0;
		Map.clear();
		A.clear();B.clear();
		R(A.m);
		for (i=1;i<=n;i++) f[i]=i;
		for (i=1;i<=A.m;i++) {
			R(x);R(y);
			A.E_add(x,y);
			if (getf(x)!=getf(y)) f[f[x]]=f[y];
			else Fg=1;
		}
		for (i=1;i<=n;i++) {
			if (A.h[i]) na++;
			else if (!ta) ta=i;
		}
		if (na>=n) Fg=1;
		R(B.m);
		for (i=1;i<=n;i++) f[i]=i;
		for (i=1;i<=B.m;i++) {
			R(x);R(y);
			B.E_add(x,y);
			if (getf(x)!=getf(y)) f[f[x]]=f[y];
			else Fg=1;
		}
		for (i=1;i<=n;i++) {
			if (B.h[i]) nb++;
			else if (!tb) tb=i;
		}
		if (nb>=n) Fg=1;
		if (Fg) {
			puts("NO");
			continue;
		}
		x=0;y=0;
		P.clear();
		for (i=1;i<=n;i++) if (A.h[i]) {
			C.clear();
			for (j=1;j<=n;j++) if (j!=i)
				for (k=A.h[j];k;k=A.E[k].n) if (A.E[k].s!=i && j<A.E[k].s) C.E_add(j,A.E[k].s);
			tt=C.Js();
			if (!P[tt]) P[tt]=i;
		}
		if (na+2<=n) {
			C.clear();
			for (j=1;j<=n;j++) if (j!=ta)
				for (k=A.h[j];k;k=A.E[k].n) if (A.E[k].s!=ta && j<A.E[k].s) C.E_add(j,A.E[k].s);
			tt=C.Js();
			if (!P[tt]) P[tt]=ta;
		}
		for (i=1;i<=n;i++) if (B.h[i]) {
			C.clear();
			for (j=1;j<=n;j++) if (j!=i)
				for (k=B.h[j];k;k=B.E[k].n) if (B.E[k].s!=i && j<B.E[k].s) C.E_add(j,B.E[k].s);
			tt=C.Js();
			if (P[tt]) {
				x=P[tt];
				y=i;
				if (check()) break;
				else x=0;
			}
		}
		if (!x && nb+2<=n) {
			C.clear();
			for (j=1;j<=n;j++) if (j!=tb)
				for (k=B.h[j];k;k=B.E[k].n) if (B.E[k].s!=tb && j<B.E[k].s) C.E_add(j,B.E[k].s);
			tt=C.Js();
			if (P[tt]) {
				x=P[tt];
				y=tb;
				if (!check()) x=0;
			}
		}
		if (!x) {
			puts("NO");
			continue;
		}
	}
}