#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <array>
#include <stdint.h>
#include <set>
#include <unordered_map>
#include <map>
#include <bitset>
#include <string>
#include <cmath>
#include <queue>
#include <iterator>
#include <iomanip>
#include <numeric>
//#include "dmSegmentTree.hpp"

#include <random>
#include <functional>
#include <xutility>

namespace dmDataStructure
{

	struct dmMin
	{

		template<class T>
		T operator()(const T a, const T b)
		{
			return std::min(a, b);
		}
	};

	struct dmMax
	{
		template<class T>
		T operator()(const T a, const T b)
		{
			return std::max(a, b);
		}
	};

	struct dmMinPaired
	{
		template<class T>
		std::pair<T, int> operator()(const std::pair<T, int>& a, const std::pair<T, int>& b)
		{
			if (a.first < b.first)
				return a;
			if (a.first > b.first)
				return b;
			return std::make_pair(a.first, b.second + a.second);
		}
	};

	struct dmMaxPaired
	{
		template<class T>
		std::pair<T, int> operator()(const std::pair<T, int>& a, const std::pair<T, int>& b)
		{
			if (a.first > b.first)
				return a;
			if (a.first < b.first)
				return b;
			return std::make_pair(a.first, b.second + a.second);
		}
	};

	int GetBitNumber(std::int64_t n)
	{
		if (n == 0)
			return 0;

		int msb = 0;
		n = n / 2;
		while (n != 0) {
			n = n / 2;
			msb++;
		}
		return msb;
	}

	template <class T1, class T2>
	T1 GetValue(const std::pair<T1, T2>& pr)
	{
		return pr.first;
	}

	template <class T>
	T GetValue(const T& v)
	{
		return v;
	}

	template <class T1, class T2, class T3>
	void SetValue(std::pair<T1, T2>& src, const T3 val, const std::int64_t number = 0)
	{
		src.first = val;
		if (number == 0)
			return;
		src.second = number;
	}

	template <class T1, class T2>
	void SetValue(T1& src, const T2 value, const std::int64_t number = 0)
	{
		number;
		src = value;
	}

	template <class T, class T1>
	typename std::enable_if<std::is_arithmetic<T>::value, T>::type MakeType(const T1& src)
	{
		return T(src);
	}
	template <class T, class T1>
	typename std::enable_if<!std::is_arithmetic<T>::value, T>::type MakeType(const T1& src)
	{
		return T(src, 1);
	}

	template <
		class T,
		const T zeroValue,
		class F,
		const bool isLazy = false,
		const bool isIncrement = true,
		const bool usePair = false>
		class dmSegmentTree
	{
	public:
		typedef typename std::conditional<usePair, std::pair<T, int>, T>::type DataType;
		dmSegmentTree(const size_t n)
			: m_objectCount(n), m_tree(n * 2, zeroValue), m_lazyData(), m_isSum(false)
		{
			if (isLazy)
			{
				m_lazyData.resize(n, 0);
				m_modified.resize(n, false);
			}
			m_isSum = GetValue(DataType()) == zeroValue;
			m_height = GetBitNumber(n) + 1;
		}

		dmSegmentTree(const std::vector<T>& objects)
			: m_objectCount(objects.size()), m_tree(objects.size() * 2, MakeType<DataType>(zeroValue)), m_lazyData(), m_isSum(false)
		{
			if (isLazy)
			{
				m_lazyData.resize(objects.size(), MakeType<DataType>(0));
				m_modified.resize(objects.size(), false);
			}
			m_isSum = GetValue(DataType()) == zeroValue;
			m_height = GetBitNumber(objects.size()) + 1;
			Build(objects);
		}

		void Build(const std::vector<T>& objects)
		{
			for (size_t i = objects.size(); i < m_tree.size(); ++i)
			{
				m_tree[i] = MakeType<DataType>(objects[i - objects.size()]);
			}
			for (std::int64_t i = objects.size() - 1; i > 0; --i)
			{
				m_tree[i] = m_f(m_tree[i * 2], m_tree[i * 2 + 1]);
			}
		}

		void CalcLazy(const std::int64_t idx, const std::int64_t elementCount)
		{
			if (!m_modified[idx])
			{
				m_tree[idx] = m_f(m_tree[idx * 2], m_tree[idx * 2 + 1]);
			}
			else
			{
				if (isIncrement)
				{
					if (m_isSum)
					{

						m_tree[idx] = m_f(m_tree[idx * 2], m_tree[idx * 2 + 1]);
						SetValue(m_tree[idx], GetValue(m_tree[idx]) + GetValue(m_lazyData[idx]) * elementCount);
					}
					else
					{
						m_tree[idx] = m_f(m_tree[idx * 2], m_tree[idx * 2 + 1]);
						SetValue(m_tree[idx], GetValue(m_tree[idx]) + GetValue(m_lazyData[idx]));
					}
				}
				else
				{
					if (m_isSum)
					{
						SetValue(m_tree[idx], GetValue(m_lazyData[idx]) * elementCount, elementCount);
					}
					else
					{
						SetValue(m_tree[idx], GetValue(m_lazyData[idx]), elementCount);
					}
				}
			}
		}

		void ApplyLazy(const std::int64_t idx,
			const DataType value, const std::int64_t elementCount)
		{
			if (isIncrement)
			{
				if (m_isSum)
				{
					SetValue(m_tree[idx], GetValue(m_tree[idx]) + GetValue(value) * elementCount);

				}
				else
				{
					SetValue(m_tree[idx], GetValue(m_tree[idx]) + GetValue(value));
				}
			}
			else
			{
				if (m_isSum)
				{
					SetValue(m_tree[idx], GetValue(value) * elementCount);
				}
				else
				{
					SetValue(m_tree[idx], GetValue(value), elementCount);
				}
			}
			if (idx < m_objectCount)
			{
				if (isIncrement)
				{
					SetValue(m_lazyData[idx], GetValue(m_lazyData[idx]) + GetValue(value));
				}
				else
				{
					SetValue(m_lazyData[idx], GetValue(value), elementCount);
				}
				m_modified[idx] = true;
			}
		}

		void BuildLazy(const std::int64_t left, const std::int64_t right) {
			std::int64_t elementCount = 2;

			std::int64_t l = left + m_objectCount;
			std::int64_t r = right + m_objectCount;
			for (; l > 1; elementCount *= 2)
			{
				l = l / 2;
				r = r / 2;
				for (std::int64_t i = r; i >= l; --i)
				{
					CalcLazy(i, elementCount);
				}
			}
		}
		// 0 1 2 1 3 5     1 2 3 4 5 6
		void PushLazy(const std::int64_t left, const std::int64_t right)
		{
			std::int64_t layer = m_height;
			std::int64_t elementCount = 1 << (m_height - 1);
			std::int64_t l = left + m_objectCount;
			std::int64_t r = right + m_objectCount;
			for (; layer > 0; --layer, elementCount /= 2)
			{
				for (std::int64_t i = l >> layer; i <= r >> layer; ++i)
				{
					if (m_modified[i])
					{
						ApplyLazy(i * 2, m_lazyData[i], elementCount);
						ApplyLazy(i * 2 + 1, m_lazyData[i], elementCount);
						SetValue(m_lazyData[i], 0);
						m_modified[i] = false;
					}
				}
			}
		}

		void Modify(const int idx, const DataType& value)
		{
			if (isLazy)
				throw std::exception("function available only in usual mod");
			std::int64_t cur = m_objectCount + idx;
			if (isIncrement)
			{
				m_tree[cur] += value;
			}
			else
			{
				m_tree[cur] = value;
			}

			std::int64_t parent = cur / 2;
			while (parent != 0)
			{
				const std::int64_t nextToCur = cur % 2 == 0 ? cur + 1 : cur - 1;
				m_tree[parent] = m_f(m_tree[cur], m_tree[nextToCur]);
				cur = parent;
				parent = cur / 2;
			}
		}

		void ModifyLazy(
			const std::int64_t left, const std::int64_t right, const T& value)
		{
			if (!isLazy)
				throw std::exception("function available only in lazy mod");
			PushLazy(left, left);
			PushLazy(right, right);
			std::int64_t l0 = left, r0 = right, k = 1;

			std::int64_t l = m_objectCount + left;
			std::int64_t r = m_objectCount + right;

			for (; l <= r; l = (l + 1) / 2, r = (r - 1) / 2)
			{
				if (l % 2 != 0)
				{
					ApplyLazy(l, MakeType<DataType>(value), k);
				}
				if (r % 2 == 0)
				{
					ApplyLazy(r, MakeType<DataType>(value), k);
				}
				k = k * 2;
			}
			BuildLazy(l0, l0);
			BuildLazy(r0, r0);
		}

		DataType Query(const std::int64_t left, const std::int64_t right)
		{
			if (isLazy)
				throw std::exception("function available only in usual mod");
			std::int64_t l = left + m_objectCount;
			std::int64_t r = right + m_objectCount;
			DataType resL = MakeType<DataType>(zeroValue);
			DataType resR = MakeType<DataType>(zeroValue);
			if (left == right)
				return m_tree[l];
			for (; l <= r; l = (l + 1) / 2, r = (r - 1) / 2)
			{
				if (l % 2 != 0)
				{
					resL = m_f(resL, m_tree[l]);
				}
				if (r % 2 == 0)
				{
					resR = m_f(m_tree[r], resR);
				}
			}
			return m_f(resL, resR);
		}

		DataType QueryLazy(const std::int64_t left, const std::int64_t right)
		{
			if (!isLazy)
				throw std::exception("function available only in lazy mod");
			PushLazy(left, left);
			PushLazy(right, right);
			std::int64_t l = left + m_objectCount;
			std::int64_t r = right + m_objectCount;
			DataType resL = MakeType<DataType>(zeroValue);
			DataType resR = MakeType<DataType>(zeroValue);
			if (left == right)
				return m_tree[l];
			for (; l <= r; l = (l + 1) / 2, r = (r - 1) / 2)
			{
				if (l % 2 != 0)
				{
					resL = m_f(resL, m_tree[l]);
				}
				if (r % 2 == 0)
				{
					resR = m_f(m_tree[r], resR);
				}
			}
			return m_f(resL, resR);
		}

	private:
		std::vector<DataType> m_tree;
		std::vector<DataType> m_lazyData;
		std::vector<bool> m_modified;
		F m_f;
		bool m_isSum;
		std::int64_t m_height;
		std::int64_t m_objectCount;
	};

}

using namespace std;

#define ALL(x) (x).begin(),(x).end()
#define SZ(x) ((int)(x).size())
#define rep(i,a,b) for(int64_t i=(a);i<=(b);++i)
#define per(i,a,b) for(int64_t i=(a);i>=(b);--i)
#define forn(i, n) for(int64_t i = 0; i < int64_t(n); i++)

template <class T>
vector<T> ReadVec(const int count, const T inc = 0)
{
	vector<T> res(count);
	forn(i, count)
	{
		std::cin >> res[i];
		res[i] += inc;
	}
	return res;
}

template <class T>
void PrintVecOneLine(const vector<T>& src)
{
	forn(i, src.size())
	{
		std::cout << src[i];
		if (i + 1 != src.size())
			std::cout << " ";
	}
	std::cout << "\n";
}

template <class T>
void PrintVecManyLine(const vector<T>& src)
{
	forn(i, src.size())
	{
		std::cout << src[i] << "\n";
	}
}

int main()
{
#ifdef HOME
	freopen("input.txt", "r", stdin);
#else
	std::ios_base::sync_with_stdio(0); std::cin.tie(0); std::cout.tie(0);
	std::cout.setf(std::ios::fixed); std::cout.precision(20);
#endif
	int k;
	cin >> k;
	std::array<int64_t, 6> F;
	for (auto& v : F)
	{
		cin >> v;
	}
	std::array<std::vector<int64_t>, 6> dp;
	{
		for (int i = 0; i < 6; ++i)
		{
			dp[i] = std::vector<int64_t>(1000000);
		}
	}
	int64_t pow = 100000;
	/*
		0 0 9
		0 0 9
		0 0 9
		0 3 6

	*/
	for (int64_t pos = 0; pos < 6; ++pos)
	{
		for (int64_t value = 0; value < 100; value += pow)
		{
			int64_t idx = 0;
			for (int64_t sum = 0; sum <= 9 * (k - 1); sum += 3, ++idx)
			{
				for (int64_t digit = 0; digit < 10; ++digit)
				{
					int64_t curAdd = sum * pow + digit * pow;

					if(curAdd > value || (value - curAdd)  % (pow * 10) != 0 )
						continue;
					const int64_t idxToAdd = digit % 3 != 0 && digit != 0 ? 0 : (digit / 3);
					dp[pos][value] = max(dp[pos][value], (pos == 0 ? ((idx + idxToAdd)* F[5 - pos]) :  (dp[pos - 1][value - curAdd] + (idx + idxToAdd) * F[5 - pos])));
				}
			}
		}
		pow /= 10;
	}
	int t;
	cin >> t;
	while (t--)
	{
		int total;
		cin >> total;
		cout << dp[5][total]<< endl;
	}

	return 0;
}


#include<bits/stdc++.h>
#define db double
#define fi first
#define se second
using namespace std;

const int N=75005;
const db eps=0.05;
bool zero(db x){
	return x>-eps&&x<eps;
}
struct P{
	db x,y;
	P operator +(const P &a)const{
		return (P){x+a.x,y+a.y};
	}
	P operator -(const P &a)const{
		return (P){x-a.x,y-a.y};
	}
	P operator *(const P &a)const{
		return (P){x*a.x-y*a.y,x*a.y+y*a.x};
	}
	P operator /(const db &a)const{
		return (P){x/a,y/a};
	}

	db sqrlen()const{
		return x*x+y*y;
	}
	db len()const{
		return sqrt(x*x+y*y);
	}
	P operator /(const P &a)const{
		return (P){x*a.x+y*a.y,-x*a.y+y*a.x}/a.len()/a.len();
	}

	bool operator <(const P &a)const{
		if (zero(x-a.x)){
			if(zero(y-a.y)) return 0;
			return y<a.y;
		}
		return x<a.x;
	}
	bool operator ==(const P &a)const{
		return zero(x-a.x)&&zero(y-a.y);
	}
}a[N],b[N];

#define pdi pair<db,int>
#define pii pair<int,int>
pdi A[N],B[N];
vector<pii> v;
map<P,int> mp;
int n,n1,n2;
int fa[N],fb[N];

void check(int xa,int xb,int ya,int yb){
	P r=(a[xb]-a[xa])/(b[yb]-b[ya]);
	P c=a[xa]-b[ya]*r;
	int cnt1=0,cnt0=0;
	for (int i=1;i<=n2;i++){
		P p=b[i]*r+c;
		if (mp.find(p)!=mp.end()) cnt1++;
		else cnt0++;
		if (cnt0+0.9*n>n2) break;
		if (1.0*cnt1/(cnt0+cnt1)<0.1&&cnt0+cnt1>25) break;
	}
	if (cnt1<0.9*n) return;
	for (int j=1;j<=n2;j++){
		P cur=b[j]*r+c;
		if (mp.find(cur)!=mp.end()){
			int nxt=mp[cur];
			if (v.size()<n&&!fa[nxt]&&!fb[j]){
				v.push_back(pii(nxt,j));
				fa[nxt]=1; fb[j]=1;
			}
		}
	}
	int ii=1,jj=1;
	for (;v.size()<n;){
		for (;fa[ii];ii++);
		for (;fb[jj];jj++);
		v.push_back(pii(ii,jj));
		ii++; jj++;
	}
	for (int i=0;i<n;i++)
		printf("%d %d\n",v[i].fi,v[i].se);
	exit(0);
}

void solve(int x,int y){
	for (int i=1;i<=n1;i++)
		A[i]=pdi((a[x]-a[i]).len(),i);
	for (int i=1;i<=n2;i++)
		B[i]=pdi((b[i]-b[y]).len(),i);
	sort(A+1,A+n1+1);
	sort(B+1,B+n2+1);
	int j=2;
	for (int i=2;i<n1;i++){
		for (;j<n2&&B[j].fi+1<A[i].fi;j++);
		for (int t=j;B[t].fi<A[i].fi+3&&t<n2;t++){
			check(x,A[i].se,y,B[t].se);
			check(x,A[i].se,B[t].se,y);
		}
	}
}

int rnd(){
	int x=0;
	for (int i=1;i<=3;i++)
		x=x*1000+rand()%1000;
	return x;
}
int main(){
	srand(time(NULL));
	scanf("%d",&n);
	scanf("%d",&n1);
	for (int i=1;i<=n1;i++){
		double x,y;
		scanf("%lf%lf",&x,&y);
		a[i]=(P){x,y};
		mp[a[i]]=i;
	}
	scanf("%d",&n2);
	for (int i=1;i<=n2;i++){
		double x,y;
		scanf("%lf%lf",&x,&y);
		b[i]=(P){x,y};
	}
	for (;;){
		int x=rnd()%n1+1;
		int y=rnd()%n2+1;
		solve(x,y);
	}
}#include <iostream>
using namespace std;

int main() {
	// your code goes here
	return 0;
}


#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#include <string>
#include <bitset>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <algorithm>
#include <sstream>
#include <stack>
#include <iomanip>
using namespace std;
#define pb push_back
#define mp make_pair
typedef pair<int,int> pii;
typedef long long ll;
typedef long double ld;
typedef vector<int> vi;
#define fi first
#define se second
#define fe first
#define FO(x) {freopen(#x".in","r",stdin);freopen(#x".out","w",stdout);}
#define Edg int M=0,fst[SZ],vb[SZ],nxt[SZ];void ad_de(int a,int b){++M;nxt[M]=fst[a];fst[a]=M;vb[M]=b;}void adde(int a,int b){ad_de(a,b);ad_de(b,a);}
#define Edgc int M=0,fst[SZ],vb[SZ],nxt[SZ],vc[SZ];void ad_de(int a,int b,int c){++M;nxt[M]=fst[a];fst[a]=M;vb[M]=b;vc[M]=c;}void adde(int a,int b,int c){ad_de(a,b,c);ad_de(b,a,c);}
#define es(x,e) (int e=fst[x];e;e=nxt[e])
#define esb(x,e,b) (int e=fst[x],b=vb[e];e;e=nxt[e],b=vb[e])
typedef pair<ld,ld> pnt;
#define SZ 1234567
int n,n1,n2; pnt p1[SZ],p2[SZ];
pair<ld,pii> ps[5050666]; int pn=0;
inline ld dis(pnt x) {return x.fi*x.fi+x.se*x.se;}
inline ld ang(pnt x) {return atan2l(x.se,x.fi);}
inline pnt operator - (pnt a,pnt b) {return pnt(a.fi-b.fi,a.se-b.se);}
inline pnt operator + (pnt a,pnt b) {return pnt(a.fi+b.fi,a.se+b.se);}
inline ld dis(pnt x,pnt y) {return dis(x-y);}
ld co,si;
/*
pnt rot(pnt g,ld t) {return pnt
(g.fi*cos(t)-g.se*sin(t),
g.fi*sin(t)+g.se*cos(t));}*/
inline pnt rot(pnt g) {return pnt
(g.fi*co-g.se*si,
g.fi*si+g.se*co);}
pair<pnt,int> q1[SZ];
bool vis[SZ];
void chk(pnt a1,pnt a2,pnt b1,pnt b2)
{
	//先减去a1，然后转，然后加上b1
	ld x1=ang(a2-a1),x2=ang(b2-b1);
	co=cosl(x2-x1); si=sinl(x2-x1);
	for(int i=1;i<=n1;++i)
		q1[i].fi=rot(p1[i]-a1)+b1,q1[i].se=i,vis[i]=0;
	sort(q1+1,q1+n1+1);
	vector<pii> rs;
	int fail=0;
	for(int i=1;i<=n2;++i)
	{
		int o=lower_bound(q1+1,q1+n1+1,mp(p2[i],0))-q1;
		bool s=0;
		for(int j=max(o-10,1);j<=min(o+10,n1);++j)
		{
			if(dis(q1[j].fi,p2[i])<1&&!vis[q1[j].se])
			{
				rs.pb(pii(q1[j].se,i));
				fail=0; s=1; vis[q1[j].se]=1; break;
			}
		}
		if(!s) ++fail;
		if(fail>100) return;
	}
	random_shuffle(rs.begin(),rs.end());
	if(rs.size()>=n*0.95)
	{
		if(rs.size()>n) rs.resize(n);
		for(int _=0;_<rs.size();++_)
			printf("%d %d\n",rs[_].fi,rs[_].se);
		for(int _=rs.size();_<n;++_)
			printf("1 1\n");
		exit(0);
	}
}
pnt md; ld gg[SZ];
bool cmp(int a,int b) {return gg[a]<gg[b];}
int main()
{
	co=cosl(233); si=sinl(233);
	cin>>n>>n1;
	for(int i=1;i<=n1;++i)
		cin>>p1[i].fi>>p1[i].se,p1[i]=rot(p1[i]);
	cin>>n2;
	for(int i=1;i<=n2;++i)
		cin>>p2[i].fi>>p2[i].se,p2[i]=rot(p2[i]);
	for(int i=1;i<=n1&&pn<5000000;++i)
	{
		md=p1[i]; vector<int> rs;
		for(int j=1;j<=n1;++j) if(j!=i)
			rs.pb(j),gg[j]=ang(p1[j]-md);
		sort(rs.begin(),rs.end(),cmp);
		for(unsigned _=0;_<rs.size();++_)
		{
			int x=rs[_],y=rs[(_+1)%rs.size()];
			ps[++pn]=mp(dis(p1[x],p1[y]),pii(x,y));
		}
	}
	sort(ps+1,ps+1+pn);
	for(int w=1;w<=n2;++w)
	{
		md=p2[w]; vector<int> rs;
		for(int j=1;j<=n2;++j) if(j!=w)
			rs.pb(j),gg[j]=ang(p2[j]-md);
		sort(rs.begin(),rs.end(),cmp);
		int uu=0;
		for(unsigned _=0;_<rs.size();++_)
		{
		int i=rs[_],j=rs[(_+1)%rs.size()];
		ld dx=dis(p2[i],p2[j]);
		int s=lower_bound(ps+1,ps+1+pn,mp(dx,pii(0,0)))-ps;
		for(int k=max(s-20,1);k<=min(s+20,pn);++k)
		if(fabsl(dx-ps[k].fi)<0.001)
		{
			chk(p1[ps[k].se.fi],p1[ps[k].se.se],p2[i],p2[j]);
			chk(p1[ps[k].se.fi],p1[ps[k].se.se],p2[j],p2[i]);
			++uu; if(uu>20&&n>10000) break;
		}
		}
	}
	throw "GG";
}


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

#define LL long long
#define LD long double
#define SC(t,x) static_cast<t>(x)
#define AR(t) vector < t >
#define PII pair < int, int >
#define PLL pair < LL, LL >
#define PIL pair < int, LL >
#define PLI pair < LL, int >
#define MP make_pair
#define PB push_back
#define PF push_front
#define POB pop_back
#define POF pop_front
#define FF first
#define SS second
#define INIT(ar,val) memset ( ar, val, sizeof ( ar ) )
#define lp(loop,start,end) for ( int loop = start; loop < end; ++loop )
#define lpd(loop,start,end) for ( int loop = start; loop > end; --loop )
#define lpi(loop,start,end) for ( int loop = start; loop <= end; ++loop )
#define lpdi(loop,start,end) for ( int loop = start; loop >= end; --loop )
#define qmax(a,b) (((a)>(b))?(a):(b))
#define qmin(a,b) (((a)<(b))?(a):(b))
#define qabs(a) (((a)>=0)?(a):(-(a)))

const int INF = 0x3fffffff;
const int SINF = 0x7fffffff;
const long long LINF = 0x3fffffffffffffff;
const long long SLINF = 0x7fffffffffffffff;
const int MAXN = 50007;
int MAXS = 997;
const int MAXSS = 510007;
const LD PI = acos ( -1.0 );
//const LD EPS = 1e-9;
const LD EPS = 0.015;
const LD RATIO = 0.95;

struct cT
{
	cT () : x ( 0 ), y ( 0 ) {}
	cT ( LD _x, LD _y ) : x ( _x ), y ( _y ) {}

	cT operator + ( const cT &a ) const
	{
		return cT ( x + a.x, y + a.y );
	}

	void operator += ( const cT &a )
	{
		( *this ) = ( *this ) + a;
	}

	cT operator - ( const cT &a ) const
	{
		return cT ( x - a.x, y - a.y );
	}

	void operator -= ( const cT &a )
	{
		( *this ) = ( *this ) - a;
	}

	LD ang ()
	{
		return atan2 ( y, x );
	}

	LD abs ()
	{
		return x * x + y * y;
	}

	LD len ()
	{
		return sqrt ( abs () );
	}

	cT rot ( LD ang )
	{
		LD ca = cos ( ang ), sa = sin ( ang );
		return cT ( x * ca - y * sa, x * sa + y * ca );
	}

	bool operator < ( const cT &a ) const
	{
		return x < a.x;
	}

	LD x, y;
}c1[MAXN], c2[MAXN], r2[MAXN];

int n, n1, n2;
pair < cT, int > s1[MAXN];
pair < LD, PII > s2[MAXSS];
int ans2[MAXN];
bool vis1[MAXN];

void init ();
void input ();
void work ();

void check ( int a11, int a12, int a21, int a22 );

int main()
{
	init();
	input();
	work();
}

void init ()
{
	// Init Everything Here

	ios::sync_with_stdio ( false );
}

void input ()
{
	// input method

	scanf ( "%d", &n );
	scanf ( "%d", &n1 );
	double tx, ty;
	lpi ( i, 1, n1 ) scanf ( "%lf%lf", &tx, &ty ), c1[i].x = tx, c1[i].y = ty;
	scanf ( "%d", &n2 );
	lpi ( i, 1, n2 ) scanf ( "%lf%lf", &tx, &ty ), c2[i].x = tx, c2[i].y = ty;
}

void work ()
{
	// main work

	MAXS = qmin ( MAXS, n );

	lpi ( i, 1, n1 ) s1[i] = MP ( c1[i], i );
	sort ( s1+1, s1+1+n1 );

	int k2 = 0;
	lpi ( i, 1, MAXS ){
		lpi ( j, i+1, MAXS ){
			s2[++k2] = MP ( ( c2[j] - c2[i] ).len (), MP ( i, j ) );
		}
	}

	sort ( s2+1, s2+1+k2 );
	LD nd;
	int np;
	lpi ( i, 1, MAXS ){
		lpi ( j, 1, MAXS ){
			if ( i ^ j ){
				nd = ( c1[j] - c1[i] ).len ();
				np = lower_bound ( s2+1, s2+1+k2, MP ( nd, MP ( 0, 0 ) ) ) - s2;
				lpi ( k, np, k2 ){
					if ( s2[k].FF - nd < EPS ) check ( i, j, s2[k].SS.FF, s2[k].SS.SS );
					else break;
				}
				lpd ( k, np-1, 0 ){
					if ( nd - s2[k].FF < EPS ) check ( i, j, s2[k].SS.FF, s2[k].SS.SS );
					else break;
				}
			}
		}
	}
}

void check ( int a11, int a12, int a21, int a22 )
{
	LD ang1 = ( c1[a12] - c1[a11] ).ang (), ang2 = ( c2[a22] - c2[a21] ).ang ();
	LD ang = ang1 - ang2;
	lpi ( i, 1, n2 ) r2[i] = c2[i].rot ( ang );
//	lpi ( i, 1, n2 ) cerr << "(" << r2[i].x << "," << r2[i].y << ") "; cerr << endl;
	cT d = c1[a11] - r2[a21];
	lpi ( i, 1, n2 ) r2[i] += d;

	INIT ( ans2, 0 );
	INIT ( vis1, 0 );

//	cerr << a11 << " " << a12 << " " << a21 << " " << a22 << endl;
//	cerr << ang << endl;
//	lpi ( i, 1, n2 ) cerr << "(" << r2[i].x << "," << r2[i].y << ") "; cerr << endl;

	int np, cc = 0;
	lpi ( i, 1, n2 ){
		np = lower_bound ( s1+1, s1+1+n1, MP ( r2[i], 0 ) ) - s1;
		lpi ( k, np, n1 ){
			if ( s1[k].FF.x - r2[i].x < EPS ){
				if ( qabs ( s1[k].FF.y - r2[i].y ) < EPS && !vis1[s1[k].SS] ){
					ans2[i] = s1[k].SS;
					vis1[s1[k].SS] = true;
					break;
				}
			}else break;
		}
		if ( !ans2[i] ){
			lpd ( k, np-1, 0 ){
				if ( r2[i].x - s1[k].FF.x < EPS ){
					if ( qabs ( s1[k].FF.y - r2[i].y ) < EPS && !vis1[s1[k].SS] ){
						ans2[i] = s1[k].SS;
						vis1[s1[k].SS] = true;
						break;
					}
				}else break;
			}
		}
		if ( ans2[i] ) ++cc;
	}

	if ( cc > RATIO * n ){
		int nc = 0;
		lpi ( i, 1, n2 ){
			if ( ans2[i] ){
				printf ( "%d %d\n", ans2[i], i );
				if ( ++nc == n ) break;
			}
		}
		if ( nc < n ){
			int i1 = 1;
			lpi ( i, 1, n2 ){
				if ( !ans2[i] ){
					while ( vis1[i1] ) ++i1;
					printf ( "%d %d\n", i1, i );
					vis1[i1] = true;
					if ( ++nc == n ) break;
				}
			}
		}
		exit ( 0 );
	}
}


#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
typedef long long LL;
const double EPS = 1e-9, INF = 1e15, PI = acos(-1.0);
#define FOR(i,s,e) for(int i=s;i<e;i++)
#define flt(x,y) ((x)<(y)-EPS)
#define fgt(x,y) flt(y,x)
#define fle(x,y) !fgt(x,y)
#define fge(x,y) !flt(x,y)
#define feq(x,y) (fabs((x)-(y))<EPS)

#define chkMn(x,y) x=min(x,y)
#define chkMx(x,y) x=max(x,y)

double sq(double x) { return x*x; }

struct P{
        double x, y;
        P(){ }
        P(double x,double y):x(x),y(y){ }
        void eat(){ scanf("%lf%lf",&x,&y); }
        P operator+(const P &p)const{ return P(x+p.x, y+p.y); }
        P operator-(const P &p)const{ return P(x-p.x, y-p.y); }
        P operator*(double k){ return P(x*k, y*k); }
        double operator*(P p){ return x*p.x + y*p.y; }
        double operator^(P p){ return x*p.y - y*p.x; }
        double mag2() { return x*x+y*y; }
        double mag(){ return sqrt(mag2()); }
        bool operator<(const P &p)const {
                if (feq(x,p.x)) return flt(y,p.y);
                return flt(x,p.x);
        }
        bool operator==(const P &p)const {
                return feq(x,p.x) && feq(y,p.y);
        }
        P rot(){ return P(-y,x); }
        P rot(double the) {
                return P(x*cos(the)-y*sin(the), x*sin(the)+y*cos(the));
        }
        P nor(){
                if (feq(mag(),0))       return *this;
                return *this*(1./mag());
        }
        P ref(P n) { // 2010-08-21: Reflect about vector "n"
                n = n.nor();
                return n*(n*(*this))*2 - *this;
        }
        void out() { printf("(%f,%f)\n", x, y); }
};

// ComputeIntersection
bool ssi(P a, P b, P c, P d, P &res) {
        P cd = d-c, ab = b-a;
        if (feq(cd^ab, 0))                      return 0;
        double t = ((a^ab) - (c^ab)) / (cd^ab);
        double s = ((c^cd) - (a^cd)) / (ab^cd);
        res = c + cd*t;
        return 1;
}

// Strictly ccw
bool Ccw(P a, P b, P c) { return fgt((b-a)^(c-a), 0); }

// Lie on segment
bool Btw(P a,P b,P c) { return feq((a-c).mag(), (b-a).mag()+(c-b).mag()); }

double Ang(P a, P b) {
        double res = atan2(a^b, a*b);
        if (flt(res, 0)) res += 2*PI;
        return res;
}

P p[2036], dir[2036];
P a, b;
double the[2036], spd[2036];
double low[2036];
int n, k;

int main() {
        a.eat();
        b.eat();
        scanf("%d", &n);
        FOR(i,0,n) {
                p[i].eat();
                scanf("%lf%lf", the+i, spd+i);
                dir[i]=P(cos(the[i]),sin(the[i]));
        }
        scanf("%d", &k);
        double len=(a-b).mag();
        FOR(i,0,n) {
                low[i]=0;
                if (fgt(spd[i],0))
                FOR(j,0,2036+1) {
                        P c=a+(b-a)*(j/2036.0);
                        double ang=Ang(c-p[i],dir[i]);
                        ang=min(ang, 2*PI-ang);
                        low[i]=max(low[i], len*(j/2036.0) / (ang/spd[i]));
                }
        }
        sort(low, low+n);
        double ans = k==n ? 0 : low[n-1-k];
        printf("%.20f\n", ans);
        return 0;
}


#include<iostream>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<stdio.h>
#include<cassert>
using namespace std;
const double pi=acos(-1.00),eps=1e-9;
struct point
{
    double x,y,w,a;
};
point st,en,tank[11111];
int n,k;
void norm(double &theta)
{
    while(theta<-pi+eps)
       theta+=2*pi;
    while(theta>pi+eps)
       theta-=2*pi;
}
bool check(double v)
{
    int i,j,s,p,q,nk=0,it;
    double now_t,theta,dist,T;
    double ltheta,rtheta,dtheta,low,high,mid,mt,vs,fs,bs,mx,my,fx,fy;
    bool ft;
    dist=sqrt((en.x-st.x)*(en.x-st.x)+(en.y-st.y)*(en.y-st.y));
    T=dist/v;
    for(i=0;i<n;i++)
    {
    	double ds=((tank[i].x-st.x)*(en.y-st.y)-(tank[i].y-st.y)*(en.x-st.x));
    	if(fabs(ds)<eps)
    	{
	    	bool fk=false;
	    	if(tank[i].x<=max(st.x,en.x)+eps&&tank[i].x>=min(st.x,en.x)-eps&&tank[i].y<=max(st.y,en.y)+eps&&tank[i].y>=min(st.y,en.y)-eps)
	    	    fk=true;
	        if(fk)
	        {
	           nk++;
	           continue;
			}
		}
        theta=atan2(en.y-tank[i].y,en.x-tank[i].x);
        rtheta=theta;
        while(theta<tank[i].a-eps)
            theta+=2*pi;
        now_t=(theta-tank[i].a)/tank[i].w;
        ltheta=atan2(st.y-tank[i].y,st.x-tank[i].x);
        if(ltheta>rtheta)
            dtheta=rtheta+2*pi-ltheta;
        else
            dtheta=rtheta-ltheta;
        ft=false;
        if(dtheta>pi)
            swap(ltheta,rtheta);
        if(ltheta<rtheta+eps)
        {
	       if(tank[i].a<rtheta+eps&&tank[i].a>ltheta-eps)
		  	    ft=true;
        }
        else
        {
        	if(tank[i].a<rtheta+eps||tank[i].a>ltheta-eps)
        	    ft=true;
        }
		if(tank[i].w==0)
		{
			if(ft)
			  nk++;
            continue;
		}
		else
        {
        	assert(!ft);
			while(ltheta<tank[i].a-eps)
			   ltheta+=2*pi;
	        while(rtheta<tank[i].a-eps)
               rtheta+=2*pi;
       	  theta=atan2(en.y-st.y,en.x-st.x);
			low=(ltheta-tank[i].a)/tank[i].w;
			high=T;
			if(low>high)
			  continue;
     			mt=low;
    			fs=(st.x+v*cos(theta)*mt-tank[i].x)*sin(tank[i].a+tank[i].w*mt)-(st.y+v*sin(theta)*mt-tank[i].y)*cos(tank[i].a+tank[i].w*mt);
    			mt=high;
    			bs=(st.x+v*cos(theta)*mt-tank[i].x)*sin(tank[i].a+tank[i].w*mt)-(st.y+v*sin(theta)*mt-tank[i].y)*cos(tank[i].a+tank[i].w*mt);
    			if((fs<1e-4&&bs>-1e-4)||(fs>-1e-4&&bs<1e-4))
    			{
    		    	nk++;
    				continue;
    			}
    			for(it=0;it<100;it++)
	    		{
	    			mx=mt=(2*low+high)/3.;
	    			fx=(st.x+v*cos(theta)*mt-tank[i].x)*sin(tank[i].a+tank[i].w*mt)-(st.y+v*sin(theta)*mt-tank[i].y)*cos(tank[i].a+tank[i].w*mt);
	    		    my=mt=(low+2*high)/3.;
	    		    fy=(st.x+v*cos(theta)*mt-tank[i].x)*sin(tank[i].a+tank[i].w*mt)-(st.y+v*sin(theta)*mt-tank[i].y)*cos(tank[i].a+tank[i].w*mt);
	    			if((fs>0&&fx>fy)||(fs<0&&fx<fy))
		    	        low=mx;
                    else
                        high=my;
	    		}
		    	mt=0.5*(low+high);
		    	fx=(st.x+v*cos(theta)*mt-tank[i].x)*sin(tank[i].a+tank[i].w*mt)-(st.y+v*sin(theta)*mt-tank[i].y)*cos(tank[i].a+tank[i].w*mt);
		    	if((fs>0&&fx<1e-4)||(fs<0&&fx>-1e-4))
		    	{
			    	nk++;
			    	continue;
		    	}
		    	assert(dtheta<pi);
		    	assert(now_t>T+1e-4);
		}
        if(nk>k)
           return false;
    }
    return nk<=k;
}
int main()
{
    int i,j,s,p,q;
    double low,high,mid;
    scanf("%lf%lf%lf%lf",&st.x,&st.y,&en.x,&en.y);
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
       scanf("%lf%lf%lf%lf",&tank[i].x,&tank[i].y,&tank[i].a,&tank[i].w);
       norm(tank[i].a);
    }
    scanf("%d",&k);
    low=0;
    high=1e9;
    while(low<high-eps)
    {
        mid=(low+high)*0.5;
        if(check(mid))
           high=mid;
        else
           low=mid+eps;
    }
    printf("%.20f\n",(low+high)*0.5);
    return 0;
}


#include<iostream>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<stdio.h>
#include<cassert>
using namespace std;
const double pi=acos(-1.00),eps=1e-9;
const int bound=1000;
struct point
{
    double x,y,w,a;
};
point st,en,tank[11111];
int n,k;
void norm(double &theta)
{
    while(theta<=-pi)
       theta+=2*pi;
    while(theta>pi)
       theta-=2*pi;
}
bool check(double v)
{
    int i,j,s,p,q,nk=0;
    double now_t,theta,T,dist=sqrt((st.x-en.x)*(st.x-en.x)+(st.y-en.y)*(st.y-en.y));
    double ltheta,rtheta,dtheta,low,high,mid,mt,vs,fs,bs,mx,my,fx,fy;
    int it;
    bool ft;
    T=dist/v;
//  printf("n")
    for(i=0;i<n;i++)
    {
    	double ds=((tank[i].x-st.x)*(en.y-st.y)-(tank[i].y-st.y)*(en.x-st.x));
    	if(fabs(ds)<eps)
    	{
	    	bool fk=false;
	    	if(tank[i].x<=max(st.x,en.x)+eps&&tank[i].x>=min(st.x,en.x)-eps&&tank[i].y<=max(st.y,en.y)+eps&&tank[i].y>=min(st.y,en.y)-eps)
	    	    fk=true;
	        if(fk)
	        {
	           nk++;
	           continue;
			}
		}
        theta=atan2(en.y-tank[i].y,en.x-tank[i].x);
        rtheta=theta;
        ltheta=atan2(st.y-tank[i].y,st.x-tank[i].x);
        if(ltheta>rtheta)
            dtheta=rtheta+2*pi-ltheta;
        else
            dtheta=rtheta-ltheta;
        ft=false;
        if(dtheta>pi)
            swap(ltheta,rtheta);
        if(ltheta<rtheta+eps)
        {
	       if(tank[i].a<rtheta+eps&&tank[i].a>ltheta-eps)
		  	    ft=true;
        }
        else
        {
        	if(tank[i].a<rtheta+eps||tank[i].a>ltheta-eps)
        	    ft=true;
        }
		if(tank[i].w==0)
		{
			if(ft)
			  nk++;
            continue;
		}
		else
        {
            if(theta<tank[i].a-1e-9)
               theta+=2*pi-tank[i].a;
            else
               theta-=tank[i].a;
            now_t=theta/tank[i].w;
            if(!ft&&now_t<T+eps)
            {
               nk++;
               continue;
			}
			if(ft&&now_t>T-eps)
			{
               nk++;
			   continue;
			}
			while(ltheta<tank[i].a-eps)
			   ltheta+=2*pi;
	        while(rtheta<tank[i].a-eps)
               rtheta+=2*pi;
         	theta=atan2(en.y-st.y,en.x-st.x);
			low=(ltheta-tank[i].a)/tank[i].w;
			high=(rtheta-tank[i].a)/tank[i].w;
			if(ltheta>rtheta)
			     low=0;
			mt=low;
			fs=(st.x+v*cos(theta)*mt-tank[i].x)*sin(tank[i].a+tank[i].w*mt)-(st.y+v*sin(theta)*mt-tank[i].y)*cos(tank[i].a+tank[i].w*mt);
			mt=high;
			bs=(st.x+v*cos(theta)*mt-tank[i].x)*sin(tank[i].a+tank[i].w*mt)-(st.y+v*sin(theta)*mt-tank[i].y)*cos(tank[i].a+tank[i].w*mt);
			if((fs<1e-4&&bs>-1e-4)||(fs>-1e-4&&bs<1e-4))
			{
		    	nk++;
				continue;
			}
			for(it=0;it<50;it++)
			{
				mx=mt=(2*low+high)/3.;
				fx=(st.x+v*cos(theta)*mt-tank[i].x)*sin(tank[i].a+tank[i].w*mt)-(st.y+v*sin(theta)*mt-tank[i].y)*cos(tank[i].a+tank[i].w*mt);
			    my=mt=(low+2*high)/3.;
			    fy=(st.x+v*cos(theta)*mt-tank[i].x)*sin(tank[i].a+tank[i].w*mt)-(st.y+v*sin(theta)*mt-tank[i].y)*cos(tank[i].a+tank[i].w*mt);
				if((fs>0&&fx>fy)||(fs<0&&fx<fy))
			        low=mx;
                else
                    high=my;
			}
			assert(high-low<1e-6);
			mt=0.5*(low+high);
			fx=(st.x+v*cos(theta)*mt-tank[i].x)*sin(tank[i].a+tank[i].w*mt)-(st.y+v*sin(theta)*mt-tank[i].y)*cos(tank[i].a+tank[i].w*mt);
			if((fs>0&&fx<1e-4)||(fs<0&&fx>-1e-4))
			{
				nk++;
				continue;
			}
            if(ltheta>rtheta)
   	   	    {
    	   	   	low=(ltheta-tank[i].a)/tank[i].w;
    	   	   	high=2*pi/tank[i].w;
    	   	   	mt=low;
    	   	   	fs=(st.x+v*cos(theta)*mt-tank[i].x)*sin(tank[i].a+tank[i].w*mt)-(st.y+v*sin(theta)*mt-tank[i].y)*cos(tank[i].a+tank[i].w*mt);
    	   	   	mt=high;
		    	bs=(st.x+v*cos(theta)*mt-tank[i].x)*sin(tank[i].a+tank[i].w*mt)-(st.y+v*sin(theta)*mt-tank[i].y)*cos(tank[i].a+tank[i].w*mt);
	     		if((fs<1e-4&&bs>-1e-4)||(fs>-1e-4&&bs<1e-4))
	    		{
	    	    	nk++;
	    			continue;
	    		}
	    		for(it=0;it<50;it++)
	    		{
	    			double mx,my,fx,fy;
	    			mx=mt=(2*low+high)/3.;
	    			fx=(st.x+v*cos(theta)*mt-tank[i].x)*sin(tank[i].a+tank[i].w*mt)-(st.y+v*sin(theta)*mt-tank[i].y)*cos(tank[i].a+tank[i].w*mt);
	    		    my=mt=(low+2*high)/3.;
	    		    fy=(st.x+v*cos(theta)*mt-tank[i].x)*sin(tank[i].a+tank[i].w*mt)-(st.y+v*sin(theta)*mt-tank[i].y)*cos(tank[i].a+tank[i].w*mt);
	    			if((fs>0&&fx>fy)||(fs<0&&fx<fy))
	    		        low=mx;
                    else
                        high=my;
		    	}
		    	assert(high-low<1e-6);
	     		mt=0.5*(low+high);
	    		fx=(st.x+v*cos(theta)*mt-tank[i].x)*sin(tank[i].a+tank[i].w*mt)-(st.y+v*sin(theta)*mt-tank[i].y)*cos(tank[i].a+tank[i].w*mt);
	    		if((fs>0&&fx<1e-4)||(fs<0&&fx>-1e-4))
	    		{
	    			nk++;
	    			continue;
	    		}
		     }
		}
        if(nk>k)
           return false;
    }
    return nk<=k;
}
int main()
{
    int i,j,s,p,q;
    double low,high,mid;
    scanf("%lf%lf%lf%lf",&st.x,&st.y,&en.x,&en.y);
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
       scanf("%lf%lf%lf%lf",&tank[i].x,&tank[i].y,&tank[i].a,&tank[i].w);
       norm(tank[i].a);
    }
    scanf("%d",&k);
    low=0;
    high=1e9;
    while(low<high-eps)
    {
        mid=(low+high)*0.5;
        if(check(mid))
           high=mid;
        else
           low=mid+eps;
    }
    printf("%.20f\n",(low+high)*0.5);
    return 0;
}


#include<iostream>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<stdio.h>
using namespace std;
const double pi=acos(-1.00),eps=1e-9;
struct point
{
    double x,y,w,a;
};
point st,en,tank[11111];
int n,k;
void norm(double &theta)
{
    while(theta<=-pi)
       theta+=2*pi;
    while(theta>pi)
       theta-=2*pi;
}
bool check(double v)
{
    int i,j,s,p,q,nk=0;
    double now_t,theta,T,dist=sqrt((st.x-en.x)*(st.x-en.x)+(st.y-en.y)*(st.y-en.y));
    double ltheta,rtheta,dtheta;
    bool ft;
    T=dist/v;
//  printf("n")
    for(i=0;i<n;i++)
    {
    	double ds=((tank[i].x-st.x)*(en.y-st.y)-(tank[i].y-st.y)*(en.x-st.x));
    	if(fabs(ds)<eps)
    	{
	    	bool fk=false;
	    	if(tank[i].x<=max(st.x,en.x)+eps&&tank[i].x>=min(st.x,en.x)-eps&&tank[i].y<=max(st.y,en.y)+eps&&tank[i].y>=min(st.y,en.y)-eps)
	    	    fk=true;
	        assert(!fk);
	    }
        theta=atan2(en.y-tank[i].y,en.x-tank[i].x);
        rtheta=theta;
        ltheta=atan2(st.y-tank[i].y,st.x-tank[i].x);
        if(ltheta>rtheta)
            dtheta=rtheta+2*pi-ltheta;
        else
            dtheta=rtheta-ltheta;
        ft=false;
        if(dtheta>pi)
            swap(ltheta,rtheta);
        if(ltheta<rtheta+eps)
        {
	       if(tank[i].a<rtheta+eps&&tank[i].a>ltheta-eps)
		  	    ft=true;
        }
        else
        {
        	if(tank[i].a<rtheta+eps||tank[i].a>ltheta-eps)
        	    ft=true;
        }
		if(tank[i].w==0)
            continue;
        else
        {
            if(theta<tank[i].a-1e-9)
               theta+=2*pi-tank[i].a;
            else
               theta-=tank[i].a;
            now_t=theta/tank[i].w;
            if(!ft&&now_t<T+eps)
               nk++;
            if(ft&&now_t>T-eps)
               nk++;
        }
        if(nk>k)
           return false;
    }
    return true;
}
int main()
{
    int i,j,s,p,q;
    double low,high,mid;
    scanf("%lf%lf%lf%lf",&st.x,&st.y,&en.x,&en.y);
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
       scanf("%lf%lf%lf%lf",&tank[i].x,&tank[i].y,&tank[i].a,&tank[i].w);
       norm(tank[i].a);
    }
    scanf("%d",&k);
    low=0;
    high=1e9;
    while(low<high-eps)
    {
        mid=(low+high)*0.5;
        if(check(mid))
           high=mid;
        else
           low=mid+eps;
    }
    printf("%.20f\n",(low+high)*0.5);
    return 0;
}


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

void No(){
	puts("No solution");
	exit(0);
}

const int maxn=400005;
const int H1=20160224;
const int mod1=998244353;
const int H2=23333333;
const int mod2=1e9+7;
int n,m,a,b,c,d;
char sa[2],sb[2],p[4];
int ch[256],cnt[4];
class Hashint{
public:
	int h1,h2;
	Hashint():h1(0),h2(0){}
	Hashint(int _h1,int _h2):h1(_h1),h2(_h2){}
	Hashint operator+(const Hashint &o)const{
		return Hashint(h1+o.h1>=mod1?h1+o.h1-mod1:h1+o.h1,h2+o.h2>=mod2?h2+o.h2-mod2:h2+o.h2);
	}
	Hashint operator-(const Hashint &o)const{
		return Hashint(h1-o.h1<0?h1-o.h1+mod1:h1-o.h1,h2-o.h2<0?h2-o.h2+mod2:h2-o.h2);
	}
	Hashint operator*(const Hashint &o)const{
		return Hashint(1LL*h1*o.h1%mod1,1LL*h2*o.h2%mod2);
	}
	bool operator<(const Hashint &o)const{
		return h1<o.h1||(h1==o.h1&&h2<o.h2);
	}
	bool operator!=(const Hashint &o)const{
		return h1!=o.h1||h2!=o.h2;
	}
}H(H1,H2),pw[maxn];
int ansr[maxn],ansc[maxn];
inline int f(int x){
	if(x<m)return 0;
	else if(x<n+m)return 1;
	else if(x<n+2*m)return 2;
	else return 3;
}
inline int g(int x){
	return x-p[f(x)];
}

class Graph{
public:
	int v;
	int ver[maxn];
	vector<int>edge[maxn];
	bool vis[maxn];
	Hashint val[maxn];
	void addedge(int u,int v){
		edge[u].push_back(v);
		edge[v].push_back(u);
	}
	vector<pair<Hashint,int> >solve(){
		v=2*(n+m);
		vector<pair<Hashint,int> >res;
		for(int i=0;i<v;i++)if(!vis[i]){
			int j=i,len=0;
			while(!vis[j]){
				vis[j]=true;
				if(vis[edge[j][0]]&&vis[edge[j][1]])
					d=(edge[j][0]==i)?0:1;
				else
					d=vis[edge[j][0]]?1:0;
				ver[len]=j<<1|d;
				val[len++]=Hashint(f(j)+1,f(j)+1);
				j=edge[j][d];
			}
			Hashint cur=Hashint(0,0);
			for(int j=0;j<len;j++)cur=cur*H+val[j];
			pair<Hashint,int>now=make_pair(cur,ver[0]);
			for(int j=1;j<len;j++){
				cur=cur*H-pw[len]*val[j-1]+val[j-1];
				now=min(now,make_pair(cur,ver[j]));
			}
			reverse(ver,ver+len);
			reverse(val,val+len);
			cur=Hashint(0,0);
			for(int j=0;j<len;j++)cur=cur*H+val[j];
			now=min(now,make_pair(cur,ver[0]^1));
			for(int j=1;j<len;j++){
				cur=cur*H-pw[len]*val[j-1]+val[j-1];
				now=min(now,make_pair(cur,ver[j]^1));
			}
			res.push_back(now);
		}
		sort(res.begin(),res.end());
		for(int i=0;i<v;i++)vis[i]=false;
		return res;
	}
}G1,G2;

void update(int j1,int j2){
	if(f(j1)&1)ansr[g(j2)]=g(j1);
	else ansc[g(j2)]=g(j1);
}

int main(){
	scanf("%d%d",&n,&m);
	ch['T']=0;ch['R']=1;ch['B']=2;ch['L']=3;
	p[0]=0;p[1]=m;p[2]=n+m;p[3]=n+2*m;
	pw[0]=Hashint(1,1);
	for(int i=1;i<=2*(n+m);i++)pw[i]=pw[i-1]*H;
	for(int i=0;i<n+m;i++){
		scanf("%s%s%d%d",sa,sb,&c,&d);
		a=ch[sa[0]];b=ch[sb[0]];
		c--;d--;
		G1.addedge(p[a]+c,p[b]+d);
		if(abs(a-b)!=2){
			if(a==(b+1)%4)swap(a,b),swap(c,d);
			int nc=cnt[a],nd=cnt[a];
			if(a==0)nc=m-1-nc;
			if(a==1)nc=n-1-nc;
			if(b==2)nd=m-1-nd;
			if(b==3)nd=n-1-nd;
			assert(nc>=0&&nd>=0);
			G2.addedge(p[a]+nc,p[b]+nd);
			cnt[a]++;
		}
	}
	if(cnt[3]+cnt[0]!=cnt[1]+cnt[2]||cnt[0]+cnt[1]!=cnt[2]+cnt[3])No();
	if(cnt[3]+cnt[0]<m&&cnt[0]+cnt[1]<n)No();
	if(cnt[3]+cnt[0]<m){
		for(int i=0;i<m-cnt[0]-cnt[3];i++)
			G2.addedge(p[0]+cnt[3]+i,p[2]+cnt[2]+i);
	}
	if(cnt[0]+cnt[1]<n){
		for(int i=0;i<n-cnt[0]-cnt[1];i++)
			G2.addedge(p[1]+cnt[0]+i,p[3]+cnt[3]+i);
	}
	for(int i=0;i<m;i++)
		G1.addedge(p[0]+i,p[2]+i),G2.addedge(p[0]+i,p[2]+i);
	for(int i=0;i<n;i++)
		G1.addedge(p[1]+i,p[3]+i),G2.addedge(p[1]+i,p[3]+i);
	vector<pair<Hashint,int> >ans1=G1.solve();
	vector<pair<Hashint,int> >ans2=G2.solve();
	if(int(ans1.size())!=int(ans2.size()))No();
	for(int i=0;i<n;i++)ansr[i]=i;
	for(int i=0;i<m;i++)ansc[i]=i;
	for(int i=0;i<int(ans1.size());i++){
		if(ans1[i].first!=ans2[i].first)No();
		int j1=ans1[i].second>>1,d1=ans1[i].second&1;
		int j2=ans2[i].second>>1,d2=ans2[i].second&1;
		G1.vis[j1]=G2.vis[j2]=true;
		update(j1,j2);
		j1=G1.edge[j1][d1];j2=G2.edge[j2][d2];
		while(!G1.vis[j1]||!G2.vis[j2]){
			update(j1,j2);
			G1.vis[j1]=G2.vis[j2]=true;
			j1=G1.vis[G1.edge[j1][0]]?G1.edge[j1][1]:G1.edge[j1][0];
			j2=G2.vis[G2.edge[j2][0]]?G2.edge[j2][1]:G2.edge[j2][0];
		}
	}
	for(int i=0;i<n;i++)printf("%d%c",ansr[i]+1,i==n-1?'\n':' ');
	for(int i=0;i<m;i++)printf("%d%c",ansc[i]+1,i==m-1?'\n':' ');
	return 0;
}


#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <vector>
#define N 400010
#define For(i,x,y) for (i=x;i<=y;i++)
using namespace std;
int i,j,k,n,m,nn,flag,f5,t,S,num,last,fdan,fduo;
struct read {
	char p[2],s[2];
	int x,y;
	inline char gai(char x) {
		return x=='L'?'T':x=='R'?'B':x=='B'?'L':'R';
	}
	inline void change(char x,int &y) {
		if (x=='L') y=n-y+1;
		if (x=='R') y=n-y+1;
	}
	inline void fan() {
		change(p[0],x);
		change(s[0],y);
		p[0]=gai(p[0]);
		s[0]=gai(s[0]);
	}
} rea[N];
struct ww {
	int x,y,ty;
} a[N],zhi[N];
int dui[N],F[N],ty[10],st[10],type[N],an[N],ss[N][10],anx[N],any[N],len[N],id[N];
vector<int> x,y,X[N],Y[N];
/*
------------
|1 /  | \ 2|
| /   |  \ |
|/    |   \|
|\   5|   /|
| \   |  / |
|3 \  | / 4|
|   \ |/   |
------------ by zhj
BLRT
*/
inline void fail() {
	printf("No solution\n");
	exit(0);
}
inline void print() {
	int i;
	if (!flag) {
		For(i,1,n) printf("%d ",anx[i]); printf("\n");
		For(i,1,m) printf("%d ",any[i]); printf("\n");
	} else {
		for (i=m;i;i--) printf("%d ",m-any[i]+1); printf("\n");
		For(i,1,n) printf("%d ",anx[i]); printf("\n");
	}
}
inline void gai(char x,int &y) {
	if (x=='T') y+=n;
	if (x=='R') y+=nn;
	if (x=='B') y+=n+nn;
}
inline void into(char x,char y) {
	if (x>y) swap(x,y);
	if (x=='B'&&y=='L') ty[3]++;
	if (x=='B'&&y=='R') ty[4]++;
	if (x=='B'&&y=='T') ty[5]++;
	if (x=='L'&&y=='R') ty[6]++;
	if (x=='L'&&y=='T') ty[1]++;
	if (x=='R'&&y=='T') ty[2]++;
}
inline void pre() {
	For(i,1,nn) {
		scanf("%s%s%d%d",rea[i].p,rea[i].s,&rea[i].x,&rea[i].y);
		into(rea[i].p[0],rea[i].s[0]);
	}
	if (ty[5]&&ty[6]) fail();
	if (ty[6]) {
		For(i,1,nn) rea[i].fan();
		swap(n,m);
		flag=1;
	}
	memset(ty,0,sizeof(ty));
	For(i,1,nn) {
		char p=rea[i].p[0],s=rea[i].s[0];
		int x=rea[i].x,y=rea[i].y;
		gai(p,x);
		gai(s,y);
		dui[x]=y;
		dui[y]=x;
		into(p,s);
	}
	st[1]=0,st[2]=m,st[3]=n,st[5]=ty[1];
}
inline int shi(int x) {
	return x>nn?x-nn:x;
}
inline int rev(int x) {
	return x<=nn?x+nn:x-nn;
}
inline void jing(int x,int y) {
	if (x>y) swap(x,y);
	if (x<=n&&y<=nn) a[++t]=(ww){x,y,1};
	if (x>n&&x<=nn&&y>nn&&y<=nn+n) a[++t]=(ww){x,y,2};
	if (x<=n&&y>nn+n) a[++t]=(ww){x,y,3};
	if (x>nn&&x<=nn+n&&y>nn+n) a[++t]=(ww){x,y,4};
	if (x>n&&x<=nn&&y>nn+n) a[++t]=(ww){x,y,5};
}
void dfs(int x) {
	if (F[shi(x)]) return;
	int A=dui[x],B=rev(A);
	jing(x,A);
	if (a[t].ty==1||a[t].ty==3) num++;
	if (a[t].ty==2||a[t].ty==4) len[num]=last,last=0;
	if (a[t].ty==5) last++,zhi[a[t].x]=zhi[a[t].y]=(ww){last,num};
	F[shi(x)]=1;
	dfs(B);
}
inline void jia(int A) {
	if (A<=n) x.push_back(A);
	if (A>n&&A<=nn) y.push_back(A-n);
}
inline void work() {
	int s[10]={},i,j;
	x.clear(),y.clear();
	For(i,1,t) {
		ww A=a[i];
		s[A.ty]++;
		if (A.ty!=5) an[A.x]=an[A.y]=s[A.ty];
		type[A.x]=A.ty;
		type[A.y]=A.ty;
		jia(A.x),jia(A.y);
	}
	sort(x.begin(),x.end());
	sort(y.begin(),y.end());
	if (s[1]&&s[2]&&s[3]&&s[4]) {
		if (max(max(s[1],s[2]),max(s[3],s[4]))>1||s[5]) fail();
		int wa=0;
		For(i,1,t) {
			if (a[i].ty==1) wa+=(x[0]!=a[i].x)+(y[0]+n!=a[i].y);
			if (a[i].ty==4) wa+=(x[0]+nn==a[i].x)+(y[0]+n+nn==a[i].y);
		}
		if (wa&1) fail();
	}
	if (!s[1]&&!s[2]) {
		int A=a[1].x-n;
		any[st[5]+1]=A;
		st[5]++;
	} else if (!s[1]||!s[3]) {
		int s1,s2,ma=0; s1=s2=0;
		For(i,1,num) ma=max(ma,len[i]);
		For(i,1,num) s1+=len[i]!=ma&&len[i]+1!=ma,s2+=len[i]+1==ma;
		if (sum>1&&(s1||s2!=1)) fail();
		For(i,1,num) if (len[i]+1==ma) break;
		if (i!=num) {
			int sum=num;
			id[i]=sum;
			for (int k=i;;) {
				k--; sum--;
				if (!k) k=num;
				if (!sum) break;
				id[k]=sum;
			}
		} else For(i,1,num) id[i]=i;
		For(i,1,t) {
			ww A=a[i];
			if (A.ty==5) an[A.x]=an[A.y]=id[zhi[A.x].y]+(zhi[A.x].x-1)*num;
			else {
				an[A.x]=id[an[A.x]];
				an[A.y]=id[an[A.y]];
			}
		}
		if (num>1&&f5||fduo) fail();
		if (f5&&ma!=fdan) fail();
		fdan=ma;
		if (num>1) fduo=1;
		int tmp=s[1]?1:2;
		if (f5&&f5!=tmp) fail();
		f5=tmp;
		++S;
		X[S]=x,Y[S]=y;
		For(i,1,9) ss[S][i]=s[i];
	} else {
		for (i=0;i<x.size();i++) {
			int A=x[i],B=type[A];
			if (B==1) anx[st[1]+an[A]]=A;
			if (B==3) anx[st[3]-s[3]+an[A]]=A;
		}
		for (i=0;i<y.size();i++) {
			int A=y[i],C=A+n,B=type[C];
			if (B==1) any[st[1]+an[C]]=A;
			if (B==2) any[st[2]-s[2]+an[C]]=A;
		}
		st[1]+=s[1],st[2]-=s[2],st[3]-=s[3];
	}
}
inline void tian() {
	int s[10];
	if (!fduo) {
		For(j,1,S) {
			for (i=0;i<Y[j].size();i++) {
				int A=Y[j][i],C=A+n,B=type[C];
				if (B==5) an[C]=j+(zhi[C].x-1)*S;
			}
		}
	}
	For(j,1,S) {
		For(i,1,9) s[i]=ss[j][i];
		for (i=0;i<X[j].size();i++) {
			int A=X[j][i],B=type[A];
			if (B==1) anx[st[1]+an[A]]=A;
			if (B==3) anx[st[3]-s[3]+an[A]]=A;
		}
		for (i=0;i<Y[j].size();i++) {
			int A=Y[j][i],C=A+n,B=type[C];
			if (B==1) any[st[1]+an[C]]=A;
			if (B==2) any[st[2]-s[2]+an[C]]=A;
			if (B==5) any[st[5]+an[C]]=A;
		}
		st[1]+=s[1],st[2]-=s[2],st[3]-=s[3];
	}
}
int main() {
	scanf("%d%d",&n,&m);
	nn=n+m;
	pre();
	For(i,1,nn) if (!F[i]) {
		t=num=last=0;
		dfs(i);
		work();
	}
	tian();
	print();
	return 0;
}


#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<stdio.h>
using namespace std;
struct point
{
    int x[2],id1,id2;
    bool operator <(const point &temp)const
    {
        if(x[1]==temp.x[1])
           return x[0]<temp.x[0];
        return x[1]<temp.x[1];
    }
};
point list[6][110000];
int n,m,cnt_list[6],po[4][110000],bs[4][110000],ie[4][110000];
char ss[]={'L','T','B','R'};
int pos[256],ps[4][4],cnt,per[2][110000];
char ch1,ch2;
bool vis[4][110000];
bool exchange(int ie1,int ie2,int id,int v_id1,int v_id2)
{
    int i,j,s,p,q,id1,id2,ip1,ip2,ip,nip,flag,f1,f2,tmp,nid,fg;
    ip=ps[ie1][ie2];
    if(ie1==0||ie1==3)
       flag=0;
    else
       flag=1;
    if(ie2==0||ie2==3)
       fg=0;
    else
       fg=1;

    if(list[ip][id].x[0]!=v_id1)
    {
        id1=po[ie1][v_id1];
        ip1=bs[ie1][v_id1];
        id2=list[ip][id].x[0];
        swap(per[flag][v_id1],per[flag][id2]);
        if(list[ip1][id1].id1==ie1&&list[ip1][id1].x[0]==v_id1)
        {
            swap(list[ip][id].x[0],list[ip1][id1].x[0]);
            po[ie1][list[ip][id].x[0]]=id;
            bs[ie1][list[ip][id].x[0]]=ip;
            po[ie1][list[ip1][id1].x[0]]=id1;
            bs[ie1][list[ip1][id1].x[0]]=ip1;
        }
        else
        {
            swap(list[ip][id].x[0],list[ip1][id1].x[1]);
            po[ie1][list[ip][id].x[0]]=id;
            bs[ie1][list[ip][id].x[0]]=ip;
            po[ie1][list[ip1][id1].x[1]]=id1;
            bs[ie1][list[ip1][id1].x[1]]=ip1;
        }
        id1=po[3-ie1][v_id1];
        ip1=bs[3-ie1][v_id1];
        tmp=id2;
        id2=po[3-ie1][tmp];
        ip2=bs[3-ie1][tmp];
        if(list[ip1][id1].id1==3-ie1&&list[ip1][id1].x[0]==v_id1)
            f1=0;
        else
            f1=1;
        if(list[ip2][id2].id2==3-ie1&&list[ip2][id2].x[0]==tmp)
            f2=0;
        else
            f2=1;
        swap(list[ip1][id1].x[f1],list[ip2][id2].x[f2]);
        po[3-ie1][list[ip1][id1].x[f1]]=id1;
        bs[3-ie1][list[ip1][id1].x[f1]]=ip1;
        po[3-ie1][list[ip2][id2].x[f2]]=id2;
        bs[3-ie1][list[ip2][id2].x[f2]]=ip2;
    //    ie2=list[ip][id].id2;
    }
    if(list[ip][id].x[1]!=v_id2)
    {
       // printf("ip=%d\n",ip);
        id1=po[ie2][v_id2];
        id2=list[ip][id].x[1];
        ip1=bs[ie2][v_id2];
        swap(per[fg][v_id2],per[fg][id2]);
    //  printf("1-flag=%d,v_id2=%d,id2=%d\n",1-flag,v_id2,id2);
        //printf("ip1=%d,id1=%d,id=%d,id2=%d\n",ip1,id1,id,id2);
        if(list[ip1][id1].id2==ie2&&list[ip1][id1].x[1]==v_id2)
        {
            swap(list[ip][id].x[1],list[ip1][id1].x[1]);
            po[ie2][list[ip][id].x[1]]=id;
            bs[ie2][list[ip][id].x[1]]=ip;
            po[ie2][list[ip1][id1].x[1]]=id1;
            bs[ie2][list[ip1][id1].x[1]]=ip1;
        }
        else
        {
            swap(list[ip][id].x[1],list[ip1][id1].x[0]);
            po[ie2][list[ip][id].x[1]]=id;
            bs[ie2][list[ip][id].x[1]]=ip;
            po[ie2][list[ip1][id1].x[0]]=id1;
            bs[ie2][list[ip1][id1].x[0]]=ip1;
        }
    //  printf("id=%d\n",id);
        id1=po[3-ie2][v_id2];
        ip1=bs[3-ie2][v_id2];
        tmp=id2;
        id2=po[3-ie2][tmp];
        ip2=bs[3-ie2][tmp];
        if(list[ip1][id1].id1==3-ie2&&list[ip1][id1].x[0]==v_id2)
            f1=0;
        else
            f1=1;
        if(list[ip2][id2].id1==3-ie2&&list[ip2][id2].x[0]==tmp)
            f2=0;
        else
            f2=1;
       // printf("ip1=%d,id1=%d,ip2=%d,id2=%d\n",ip1,id1,ip2,id2);
        swap(list[ip1][id1].x[f1],list[ip2][id2].x[f2]);
        po[3-ie2][list[ip1][id1].x[f1]]=id1;
        bs[3-ie2][list[ip1][id1].x[f1]]=ip1;
        po[3-ie2][list[ip2][id2].x[f2]]=id2;
        bs[3-ie2][list[ip2][id2].x[f2]]=ip2;
    }
}
int main()
{
    int i,j,s,p,q,id1,id2,id,ip,u1,u2,x[2];
    scanf("%d%d",&n,&m);
    for(i=0;i<4;i++)
        pos[ss[i]]=i;
    cnt=0;
    for(i=0;i<4;i++)
       for(j=i+1;j<4;j++)
            ps[i][j]=cnt++;
    memset(cnt_list,0,sizeof(cnt_list));
    for(i=0;i<n+m;i++)
    {
         ch1=getchar();
         while(!(ch1>='A'&&ch1<='Z'))
            ch1=getchar();
         ch2=getchar();
         while(!(ch2>='A'&&ch2<='Z'))
            ch2=getchar();
         scanf("%d%d",&id1,&id2);
         id1--;
         id2--;
         if(pos[ch1]>pos[ch2])
         {
            swap(ch1,ch2);
            swap(id1,id2);
         }
         id=ps[pos[ch1]][pos[ch2]];
         list[id][cnt_list[id]].id1=pos[ch1];
         list[id][cnt_list[id]].id2=pos[ch2];
         list[id][cnt_list[id]].x[0]=id1;
         list[id][cnt_list[id]++].x[1]=id2;
    }
    for(i=0;i<6;i++)
       sort(list[i],list[i]+cnt_list[i]);
    for(i=0;i<cnt_list[5]/2;i++)
       swap(list[5][i],list[5][cnt_list[5]-1-i]);
    for(i=0;i<6;i++)
    {
        for(j=0;j<cnt_list[i];j++)
        {
            id1=list[i][j].id1;
            id2=list[i][j].id2;
            x[0]=list[i][j].x[0];
            x[1]=list[i][j].x[1];
            po[id1][x[0]]=j;
            bs[id1][x[0]]=i;
            po[id2][x[1]]=j;
            bs[id2][x[1]]=i;
        }
    }
    id=ps[pos['L']][pos['T']];
    ip=ps[pos['B']][pos['R']];
    j=0;
    for(i=0;i<n;i++)
       per[0][i]=i;
    for(i=0;i<m;i++)
       per[1][i]=i;
    memset(vis,false,sizeof(vis));
    for(i=0;i<cnt_list[id];i++)
    {
         exchange(0,1,i,i,i);
         if(i>=cnt_list[5])
         {
             puts("No solution");
             return 0;
         }
         exchange(2,3,i,m-1-i,n-1-i);
    }
    for(i=0;i<6;i++)
       sort(list[i],list[i]+cnt_list[i]);

    for(i=0;i<6;i++)
    {
        for(j=0;j<cnt_list[i];j++)
        {
            id1=list[i][j].id1;
            id2=list[i][j].id2;
            x[0]=list[i][j].x[0];
            x[1]=list[i][j].x[1];
            po[id1][x[0]]=j;
            bs[id1][x[0]]=i;
            po[id2][x[1]]=j;
            bs[id2][x[1]]=i;
        }
    }
    if(cnt_list[id]<min(n,m))
    {
        for(i=0;i<cnt_list[1];i++)
        {
            exchange(0,2,i,n-1-i,i);
            if(i>=cnt_list[4])
            {
                 puts("No solution");
                 return 0;
            }
            exchange(1,3,i,m-1-i,i);
        }
    }
    if(cnt_list[0]+cnt_list[1]<min(n,m))
    {
         puts("No solution");
         return 0;
    }
     for(i=0;i<6;i++)
       sort(list[i],list[i]+cnt_list[i]);
    for(i=0;i<6;i++)
    {
        for(j=0;j<cnt_list[i];j++)
        {
            id1=list[i][j].id1;
            id2=list[i][j].id2;
            x[0]=list[i][j].x[0];
            x[1]=list[i][j].x[1];
            po[id1][x[0]]=j;
            bs[id1][x[0]]=i;
            po[id2][x[1]]=j;
            bs[id2][x[1]]=i;
        }
    }
    if(n<m)
        id=ps[1][2];
    else
        id=ps[0][3];
    for(i=0;i<cnt_list[id];i++)
    {
        if(n<m)
           exchange(1,2,i,i+cnt_list[0],i+cnt_list[1]);
        else
           exchange(0,3,i,i+cnt_list[0],i+cnt_list[1]);
    }
    for(i=0;i<n;i++)
       printf("%d ",per[0][i]+1);
    printf("\n");
    for(i=0;i<m;i++)
       printf("%d ",per[1][i]+1);
    printf("\n");
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
const int N=2e5+7,M=4e6+7;
int n,m,q,k,p[N],t[N],vs[N],siz[N],va[M],vb[M]; vector<int>v[N],w[N];
struct node {int t,f;}; vector<node>e[N];
struct note {int a,b;}gt[N];
struct nope {int a,b,t;};
priority_queue<nope>g[N];
inline int find(int u){
	if(vs[u]==u) return u; return vs[u]=find(vs[u]);
}
inline bool operator < (note a,note b){
	if(a.a==b.a) return a.b>b.b; return a.a<b.a;
}
inline bool operator < (nope a,nope b){
	if(a.t==b.t) return max(a.a,b.a)<max(b.a,b.b);
	return a.t>b.t;
}
set<note>f1[N],f2[N];
inline void updatea(int u,int c){
	note w; w.a=va[c]+t[u]*2+1,w.b=998244353;
	f2[u].insert(w);
	if((*f2[u].rbegin()).b==998244353) {f2[u].erase(w); return;};
	note e=(*(++f2[u].find(w))); f2[u].erase(w);
	if(find(e.b)==find(c)&&(*f2[u].rbegin()).b==e.b) return;
	if(find(e.b)==find(c)) e=(*(++f2[u].find(e)));

	nope v; v.a=c,v.b=e.b,v.t=(va[v.b]-va[v.a]+1)/2; g[u].push(v);
}
inline void updateb(int u,int c){
	note w; w.a=va[c]-t[u]*2-1,w.b=-998244353;
	f1[u].insert(w);

	if((*f1[u].begin()).b==-998244353) {f1[u].erase(w); return;};
	note e=(*(--f1[u].find(w)));
	f1[u].erase(w);
	if(find(e.b)==find(c)&&(*f1[u].begin()).b==e.b) return;
	if(find(e.b)==find(c)) e=(*(--f1[u].find(e)));
	nope v; v.a=e.b,v.b=c,v.t=(va[v.b]-va[v.a]+1)/2; g[u].push(v);
}
inline void update(int u,int k){
	while(g[u].size()){
		nope z=g[u].top();
		if(va[z.a]==-1||va[z.b]==-1) {g[u].pop(); continue;}
		if(z.t<=t[u]){
			g[u].pop(); continue;
		}
		if(z.t<=t[u]+k){
			note r; r.a=va[z.a],r.b=z.a; note w1,w2,h1,h2;
			w1.a=-1,w1.b=-1,w2.a=-1,w2.b=-1,h1.a=-1,h1.b=-1,h2.a=-1,h2.b=-1;
			if((*f1[u].begin()).b!=r.b) w1=(*(--f1[u].find(r)));
			if((*f1[u].rbegin()).b!=r.b) w2=(*(++f1[u].find(r)));
			f1[u].erase(r);
			note c; c.a=va[z.b],c.b=z.b;
			if((*f2[u].begin()).b!=c.b) h1=(*(--f2[u].find(c)));
			if((*f2[u].rbegin()).b!=c.b) h2=(*(++f2[u].find(c)));
			f2[u].erase(c);
			if(vb[z.a]+vb[z.b]<0){
				m++,va[m]=va[z.a],vb[m]=vb[z.a]+vb[z.b],vs[m]=vs[z.a]; c.a=va[m],c.b=m; f1[u].insert(c); updatea(u,m);
			}
			if(vb[z.a]+vb[z.b]>0){
				m++,va[m]=va[z.b],vb[m]=vb[z.a]+vb[z.b],vs[m]=vs[z.b]; c.a=va[m],c.b=m;
				f2[u].insert(c); updateb(u,m);
			}
			if(w1.b!=-1) updatea(u,w1.b);
			if(w2.b!=-1) updatea(u,w2.b);
			if(h1.b!=-1) updateb(u,h1.b);
			if(h2.b!=-1) updateb(u,h2.b);
			va[z.a]=-1,va[z.b]=-1;
			g[u].pop();
		}
		else break;
	}
	t[u]+=k;
}
inline int merge(int a,int b){
	if(siz[a]<siz[b]) swap(a,b); siz[a]+=siz[b];
	set<note>::iterator iter = f1[b].begin();
	while(iter!=f1[b].end()){
		note w=(*iter);
		m++,va[m]=w.a+t[b]-t[a],vb[m]=vb[w.b],va[w.b]=-1,w.a=va[m],w.b=m,vs[m]=m;
		f1[a].insert(w),iter++,updatea(a,m);
	}
	iter = f2[b].begin();
	while(iter!=f2[b].end()){
		note w=(*iter);
		m++,va[m]=w.a-t[b]+t[a],vb[m]=vb[w.b],va[w.b]=-1,w.a=va[m],w.b=m,vs[m]=m;
		f2[a].insert(w),iter++,updateb(a,m);
	}
	return a;
}
inline void dfs(int u,int fa){
	p[u]=u;
	for(int i=0;i<v[u].size();i++){
		int x=v[u][i];
		if(x==fa) continue;
		dfs(x,u);
		for(int c=0;c<e[x].size();c++){
			node s=e[x][c]; vs[m+1]=vs[m+2]=m+2;
			note v; m++,va[m]=s.t*2-t[p[x]],vb[m]=-s.f,v.a=va[m],v.b=m; f1[p[x]].insert(v),updatea(p[x],m);
			note q; m++,va[m]=s.t*2+t[p[x]]+1,vb[m]=s.f,q.a=va[m],q.b=m;  f2[p[x]].insert(q),updateb(p[x],m);
			siz[p[x]]++;
		}
		update(p[x],w[u][i]*2);
		p[u]=merge(p[u],p[x]);
	}
}
inline bool tmp(note a,note b){
	return a.a<b.a;
}
int main(){
	cin>>n; int a,b,c;
	for(int i=1;i<n;i++){
		scanf("%d%d%d",&a,&b,&c);
		v[a].push_back(b),v[b].push_back(a);
		w[a].push_back(c),w[b].push_back(c);
	}
	v[1].push_back(n+1),v[n+1].push_back(1);
	w[1].push_back(1),w[n+1].push_back(1);
	cin>>q;
	while(q--){
		scanf("%d%d%d",&a,&b,&c); node d;
		d.t=a,d.f=b; e[c].push_back(d);
	}
	dfs(n+1,0);
	set<note>::iterator iter = f1[p[n+1]].begin();
	while(iter!=f1[p[n+1]].end()){
		note w=(*iter); gt[++k]=w; gt[k].a+=t[p[n+1]];
		iter++;
	}
	iter = f2[p[n+1]].begin();
	while(iter!=f2[p[n+1]].end()){
		note w=(*iter); gt[++k]=w; gt[k].a-=t[p[n+1]];
		iter++;
	}
	sort(gt+1,gt+k+1,tmp); int sum=0,ans=0;
	for(int i=1;i<=k;i++){
		int j=i; sum+=vb[gt[i].b];
		while(gt[j+1].a==gt[i].a&&j+1<=k) sum+=vb[gt[j+1].b],j++;
		i=j; ans=max(ans,sum);
	}
	cout<<ans<<endl;
}


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

using ll=long long;
#define int ll

#define rng(i,a,b) for(int i=int(a);i<int(b);i++)
#define rep(i,b) rng(i,0,b)
#define gnr(i,a,b) for(int i=int(b)-1;i>=int(a);i--)
#define per(i,b) gnr(i,0,b)
#define pb push_back
#define eb emplace_back
#define a first
#define b second
#define bg begin()
#define ed end()
#define all(x) x.bg,x.ed
#ifdef LOCAL
#define dmp(x) cerr<<__LINE__<<" "<<#x<<" "<<x<<endl
#else
#define dmp(x) void(0)
#endif

template<class t,class u> void chmax(t&a,u b){if(a<b)a=b;}
template<class t,class u> void chmin(t&a,u b){if(b<a)a=b;}

template<class t> using vc=vector<t>;
template<class t> using vvc=vc<vc<t>>;

using pi=pair<int,int>;
using vi=vc<int>;

template<class t,class u>
ostream& operator<<(ostream& os,const pair<t,u>& p){
	return os<<"{"<<p.a<<","<<p.b<<"}";
}

template<class t> ostream& operator<<(ostream& os,const vc<t>& v){
	os<<"{";
	for(auto e:v)os<<e<<",";
	return os<<"}";
}

#define mp make_pair
#define mt make_tuple
#define one(x) memset(x,-1,sizeof(x))
#define zero(x) memset(x,0,sizeof(x))
#ifdef LOCAL
void dmpr(ostream&os){os<<endl;}
template<class T,class... Args>
void dmpr(ostream&os,const T&t,const Args&... args){
	os<<t<<" ";
	dmpr(os,args...);
}
#define dmp2(...) dmpr(cerr,"Line:",__LINE__,##__VA_ARGS__)
#else
#define dmp2(...) void(0)
#endif

using uint=unsigned;
using ull=unsigned long long;

template<int i,class T>
void print_tuple(ostream&,const T&){
}

template<int i,class T,class H,class ...Args>
void print_tuple(ostream&os,const T&t){
	if(i)os<<",";
	os<<get<i>(t);
	print_tuple<i+1,T,Args...>(os,t);
}

template<class ...Args>
ostream& operator<<(ostream&os,const tuple<Args...>&t){
	os<<"{";
	print_tuple<0,tuple<Args...>,Args...>(os,t);
	return os<<"}";
}

void print(ll x,int suc=1){
	cout<<x;
	if(suc==1)
		cout<<"\n";
	if(suc==2)
		cout<<" ";
}

ll read(){
	ll i;
	cin>>i;
	return i;
}

vi readvi(int n,int off=0){
	vi v(n);
	rep(i,n)v[i]=read()+off;
	return v;
}

template<class T>
void print(const vector<T>&v,int suc=1){
	rep(i,v.size())
		print(v[i],i==int(v.size())-1?suc:2);
}

string readString(){
	string s;
	cin>>s;
	return s;
}

template<class T>
T sq(const T& t){
	return t*t;
}

//#define CAPITAL
void yes(bool ex=true){
	#ifdef CAPITAL
	cout<<"YES"<<endl;
	#else
	cout<<"Yes"<<endl;
	#endif
	if(ex)exit(0);
}
void no(bool ex=true){
	#ifdef CAPITAL
	cout<<"NO"<<endl;
	#else
	cout<<"No"<<endl;
	#endif
	if(ex)exit(0);
}

constexpr ll ten(int n){
	return n==0?1:ten(n-1)*10;
}

const ll infLL=LLONG_MAX/3;

#ifdef int
const int inf=infLL;
#else
const int inf=INT_MAX/2-100;
#endif

int topbit(signed t){
	return t==0?-1:31-__builtin_clz(t);
}
int topbit(ll t){
	return t==0?-1:63-__builtin_clzll(t);
}
int botbit(signed a){
	return a==0?32:__builtin_ctz(a);
}
int botbit(ll a){
	return a==0?64:__builtin_ctzll(a);
}
int popcount(signed t){
	return __builtin_popcount(t);
}
int popcount(ll t){
	return __builtin_popcountll(t);
}
bool ispow2(int i){
	return i&&(i&-i)==i;
}
int mask(int i){
	return (int(1)<<i)-1;
}

bool inc(int a,int b,int c){
	return a<=b&&b<=c;
}

template<class t> void mkuni(vc<t>&v){
	sort(all(v));
	v.erase(unique(all(v)),v.ed);
}

ll rand_int(ll l, ll r) { //[l, r]
	#ifdef LOCAL
	static mt19937_64 gen;
	#else
    static random_device rd;
    static mt19937_64 gen(rd());
    #endif
    return uniform_int_distribution<ll>(l, r)(gen);
}

template<class t>
int lwb(const vc<t>&v,const t&a){
	return lower_bound(all(v),a)-v.bg;
}

int maxflow;

struct ysp{
	map<int,int> left,right;
	priority_queue<pi,vc<pi>,greater<pi>> qs;
	int lo,ro,qo;
	ysp():lo(0),ro(0),qo(0){}
	int size(){return left.size()+right.size();}
	void addqleft(int x){
		dmp(x);
		auto itr=right.lower_bound(x+lo-ro);
		if(itr!=right.ed){
			int d=itr->a+ro-(x+lo);
			assert(d%2==0);
			assert(d>=0);
			qs.emplace(d/2-qo,x);
		}
	}
	void addqright(int x){
		dmp(x);
		auto itr=left.upper_bound(x+ro-lo);
		if(itr!=left.bg){
			--itr;
			int d=x+ro-(itr->a+lo);
			assert(d%2==0);
			assert(d>=0);
			qs.emplace(d/2-qo,itr->a);
		}
	}
	void insertleft(int x,int v){
		if(v==0)return;
		assert(v>0);
		x-=lo;
		left[x]+=v;
		addqleft(x);
	}
	void insertright(int x,int v){
		if(v==0)return;
		assert(v>0);
		x-=ro;
		right[x]+=v;
		addqright(x);
	}
	void Expand(int w){
		dmp(qo);
		dmp(qs.size());
		while(w&&qs.size()){
			pi z=qs.top();qs.pop();
			z.a+=qo;
			dmp(z);
			int u=min(w,z.a);
			dmp(u);
			w-=u;
			z.a-=u;
			qo-=u;
			lo+=u;
			ro-=u;
			if(z.a==0){
				dmp2(z.b,z.b+lo-ro);
				auto l=left.find(z.b);
				auto r=right.find(z.b+lo-ro);
				if(l!=left.ed&&r!=right.ed){
					int y=min(l->b,r->b);
					maxflow+=y;
					int f=-1;
					l->b-=y;
					if(l->b==0)left.erase(l);
					else f=0;
					r->b-=y;
					if(r->b==0)right.erase(r);
					else f=1;
					if(f==0){
						addqleft(l->a);
					}else if(f==1){
						addqright(r->a);
					}
				}
			}else
				qs.emplace(z.a-qo,z.b);
		}
		qo-=w;
		lo+=w;
		ro-=w;
	}
	void show(){
		/*dmp(lo);
		for(auto kv:left)
			//dmp(kv);
			dmp(pi(kv.a+lo,kv.b));
		dmp(ro);
		for(auto kv:right)
			//dmp(kv);
			dmp(pi(kv.a+ro,kv.b));
		*/
	}
};

void merge(ysp&a,ysp&b){
	if(a.size()<b.size())swap(a,b);
	for(auto z:b.left)
		a.insertleft(z.a+b.lo,z.b);
	for(auto z:b.right)
		a.insertright(z.a+b.ro,z.b);
}

const int nmax=100010;

vc<pi> t[nmax];
vc<pi> obs[nmax];
ysp buf[nmax];

void dfs(int v,int p){
	sort(all(obs[v]));
	for(auto z:obs[v]){
		buf[v].insertright(z.a*2,z.b);
		buf[v].insertleft(z.a*2+2,z.b);
	}
	for(auto e:t[v])if(e.a!=p){
		dfs(e.a,v);
		buf[e.a].Expand(e.b*2);
		merge(buf[v],buf[e.a]);
	}
	dmp(v);
	dmp(maxflow);
	buf[v].show();
}

signed main(){
	cin.tie(0);
	ios::sync_with_stdio(0);
	cout<<fixed<<setprecision(20);

	const int vmax=ten(9);

	int n;cin>>n;
	rep(_,n-1){
		int u,v,l;cin>>u>>v>>l;
		u--;v--;
		l*=vmax;
		l-=2;
		t[u].eb(v,l);
		t[v].eb(u,l);
	}

	int ans=0;
	int k;cin>>k;
	rep(_,k){
		int d,f,p;cin>>d>>f>>p;
		d*=vmax;
		p--;
		obs[p].eb(d,f);
		ans+=f;
	}

	dfs(0,-1);
	dmp(maxflow);
	buf[0].show();
	buf[0].Expand(inf);
	dmp(maxflow);

	cout<<ans-maxflow<<endl;
}


#include <bits/stdc++.h>

using namespace std;

const int inf = 0x3f3f3f3f;

namespace flow {
struct edge_t {
  int to, cap, rev;

  edge_t(int t, int c, int r) {
    to = t;
    cap = c;
    rev = r;
  }
};

int n, source, sink, answer;
vector<vector<edge_t>> adj;
vector<int> dist, current;

void init(int v, int s, int t) {
  n = v;
  source = s;
  sink = t;
  answer = 0;
  adj.resize(n);
  dist.resize(n);
  current.resize(n);
}

void add(int x, int y, int c) {
  adj[x].push_back(edge_t(y, c, adj[y].size()));
  adj[y].push_back(edge_t(x, 0, adj[x].size() - 1));
}

bool bfs() {
  queue<int> q;
  for (int i = 0; i < n; ++i) {
    dist[i] = -1;
  }
  dist[source] = 0, q.push(source);
  while (!q.empty()) {
    int x = q.front();
    q.pop();
    for (auto e : adj[x]) {
      if (e.cap && !~dist[e.to]) {
        dist[e.to] = dist[x] + 1;
        if (e.to == sink) {
          return true;
        }
        q.push(e.to);
      }
    }
  }
  return false;
}

int dfs(int x, int f) {
  if (x == sink) {
    return f;
  }
  for (int &i = current[x]; ~i; --i) {
    edge_t &e = adj[x][i];
    if (e.cap && dist[e.to] == dist[x] + 1) {
      int w = dfs(e.to, min(e.cap, f));
      if (w) {
        e.cap -= w;
        adj[e.to][e.rev].cap += w;
        return w;
      }
    }
  }
  return 0;
}

int max_flow() {
  while (bfs()) {
    for (int i = 0; i < n; ++i) {
      current[i] = adj[i].size() - 1;
    }
    while (true) {
      int flow = dfs(source, inf);
      if (!flow) {
        break;
      }
      answer += flow;
    }
  }
  return answer;
}
}

using flow::source;
using flow::sink;
using flow::init;
using flow::add;
using flow::max_flow;

const int N = 100005;

int n, m, total, day[N], fish[N], lake[N], size[N], depth[N];
vector<pair<int, int>> edges, adj[N];
vector<int> all, event[N];
bool visit[N];

void find_root(int x, int p, int s, int &root) {
  bool flag = true;
  size[x] = 1;
  for (auto e : adj[x]) {
    int y = e.first;
    if (y != p && !visit[y]) {
      find_root(y, x, s, root);
      size[x] += size[y];
      flag &= size[y] <= s >> 1;
    }
  }
  flag &= size[x] >= s >> 1;
  if (flag) {
    root = x;
  }
}

void find_size(int x, int p, bool insert) {
  size[x] = 1;
  for (auto e : adj[x]) {
    int y = e.first;
    if (y != p && !visit[y]) {
      depth[y] = depth[x] + e.second;
      find_size(y, x, true);
      size[x] += size[y];
    }
  }
  if (insert) {
    for (auto i : event[x]) {
      all.push_back(i);
    }
  }
}

void divide(int x, int s) {
  int root;
  find_root(x, 0, s, root);
  visit[x = root] = true;
  depth[x] = 0;
  all.clear();
  find_size(x, 0, false);
  vector<pair<int, int>> by_sub;
  for (auto i : all) {
    by_sub.push_back(make_pair(day[i] - depth[lake[i]], i));
  }
  sort(by_sub.begin(), by_sub.end());
  for (int i = 1; i < by_sub.size(); ++i) {
    edges.emplace_back(total + i, total + i + 1);
  }
  for (int i = 0; i < by_sub.size(); ++i) {
    edges.emplace_back(total + i + 1, by_sub[i].second + m);
  }
  for (auto i : all) {
    int limit = day[i] + depth[lake[i]], bound = lower_bound(by_sub.begin(), by_sub.end(), make_pair(limit, 0)) - by_sub.begin();
    if (bound != by_sub.size()) {
      edges.emplace_back(i, total + bound + 1);
    }
  }
  for (auto i : event[x]) {
    int limit = day[i] + depth[lake[i]], bound = lower_bound(by_sub.begin(), by_sub.end(), make_pair(limit, 0)) - by_sub.begin();
    if (bound != by_sub.size()) {
      edges.emplace_back(i, total + bound + 1);
    }
  }
  total += by_sub.size();
  by_sub.clear();
  for (auto i : event[x]) {
    by_sub.push_back(make_pair(day[i] - depth[lake[i]], i));
  }
  sort(by_sub.begin(), by_sub.end());
  for (int i = 1; i < by_sub.size(); ++i) {
    edges.emplace_back(total + i, total + i + 1);
  }
  for (int i = 0; i < by_sub.size(); ++i) {
    edges.emplace_back(total + i + 1, by_sub[i].second + m);
  }
  for (auto i : all) {
    int limit = day[i] + depth[lake[i]], bound = lower_bound(by_sub.begin(), by_sub.end(), make_pair(limit, 0)) - by_sub.begin();
    if (bound != by_sub.size()) {
      edges.emplace_back(i, total + bound + 1);
    }
  }
  total += by_sub.size();
  by_sub.clear();
  for (auto i : event[x]) {
    by_sub.push_back(make_pair(day[i], i));
  }
  sort(by_sub.begin(), by_sub.end());
  for (int i = 1; i < by_sub.size(); ++i) {
    edges.emplace_back(total + i, total + i + 1);
    edges.emplace_back(by_sub[i - 1].second, total + i + 1);
  }
  for (int i = 0; i < by_sub.size(); ++i) {
    edges.emplace_back(total + i + 1, by_sub[i].second + m);
  }
  total += by_sub.size();
  for (auto e : adj[x]) {
    if (!visit[e.first]) {
      divide(e.first, size[e.first]);
    }
  }
}

int main() {
#ifdef wxh010910
  freopen("input.txt", "r", stdin);
#endif
  scanf("%d", &n);
  for (int i = 1; i < n; ++i) {
    int x, y, w;
    scanf("%d %d %d", &x, &y, &w);
    adj[x].push_back(make_pair(y, w));
    adj[y].push_back(make_pair(x, w));
  }
  scanf("%d", &m);
  for (int i = 1; i <= m; ++i) {
    scanf("%d %d %d", &day[i], &fish[i], &lake[i]);
    event[lake[i]].push_back(i);
  }
  total = m << 1 | 1;
  divide(1, n);
  init(total + 1, 0, m << 1 | 1);
  for (auto e : edges) {
    add(e.first, e.second, inf);
  }
  int answer = 0;
  for (int i = 1; i <= m; ++i) {
    add(source, i, fish[i]);
    add(i + m, sink, fish[i]);
    answer += fish[i];
  }
  printf("%d\n", answer - max_flow());
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define int LL
typedef long long LL;
#define pii pair <LL,LL>

const int RLEN=1<<18|1;
inline char nc() {
	static char ibuf[RLEN],*ib,*ob;
	(ib==ob) && (ob=(ib=ibuf)+fread(ibuf,1,RLEN,stdin));
	return (ib==ob) ? -1 : *ib++;
}
inline int rd() {
	char ch=nc(); int i=0,f=1;
	while(!isdigit(ch)) {if(ch=='-')f=-1; ch=nc();}
	while(isdigit(ch)) {i=(i<<1)+(i<<3)+ch-'0'; ch=nc();}
	return i*f;
}

const int N=1e5+50;
const LL INF=0x3f3f3f3f3f3f3f3f;

int n,q; LL det[N];
vector <pii> edge[N];
vector <pii> ask[N];

struct Myset {
	int id;
	struct data {
		LL first,second; int id;
		data(LL first,LL second,int id) : first(first), second(second), id(id) {}
		friend inline bool operator <(const data &a,const data &b) {
			int posa=a.first+((a.second>0) ? -det[a.id] : det[a.id]),
				posb=b.first+((b.second>0) ? -det[b.id] : det[b.id]);
			if(posa!=posb) return posa<posb;
			return a.second<b.second;
		}
	};
	typedef set <data> Set;
	typedef Set :: iterator it;
	inline it prev(it t) {return --t;}
	inline it suff(it t) {return ++t;}
	Set *s;
	set <pii> *dis;
	inline int sgn(int x) {return (x>0) ? 1 : 0;}
	Myset() {s=new Set; dis=new set <pii>;}
	inline LL getpos(it t) {return t->first+((t->second<0) ? det[t->id] : -det[t->id]);}
	inline void del_dis(it x,it y) {
		if(sgn(x->second) || !sgn(y->second)) return;
		dis->erase(dis->find(pii(y->first-x->first,y->first)));
	}
	inline void inc_dis(it x,it y) {
		if(sgn(x->second) || !sgn(y->second)) return;
		dis->insert(pii(y->first-x->first,y->first));
	}
	inline void _erase(it x) {
		if(x!=s->begin()) del_dis(prev(x),x);
		if(x!=--s->end()) del_dis(x,suff(x));
		if(x!=s->begin() && x!=--s->end()) inc_dis(prev(x),suff(x));
		s->erase(x);
	}
	inline void add(int pos,int d) {
		if(!d) return;
		it nxt=s->lower_bound(data(pos-det[id],-INF,id));
		if(nxt==s->end() || getpos(nxt) !=pos) {
			if(s->size()>=2 && getpos(s->begin())<pos && getpos(--s->end())>pos) del_dis(prev(nxt),nxt);
			data temp=data(pos+((d<0)?-det[id]:det[id]),d,id);
			it now=s->insert(temp).first;
			if(nxt!=s->end()) inc_dis(now,nxt);
			if(now!=s->begin()) inc_dis(prev(now),now);
		} else {
			data temp=*nxt; _erase(nxt);
			if(!(temp.second+d)) return;
			if(temp.second<0 && temp.second+d>0) temp.first+=2*det[id];
			if(temp.second>0 && temp.second+d<0) temp.first-=2*det[id];
			temp.second+=d;
			it nxt=s->insert(temp).first;
			if(nxt!=--s->end()) inc_dis(nxt,suff(nxt));
			if(nxt!=s->begin()) inc_dis(prev(nxt),nxt);
		}
	}
	inline void md(int pos,int d) {add(pos,d); add(pos+1,-d);}
	inline void mv(int d) {
		if(!d) return;
		while(dis->size() && dis->begin()->first<=(d+det[id])*2) {
			it nxt=s->lower_bound(data(dis->begin()->second-2*det[id],-INF,id));
			if(nxt->second==-prev(nxt)->second) _erase(prev(nxt)), _erase(nxt);
			else if(nxt->second>-prev(nxt)->second) {
				LL val=prev(nxt)->second;
				_erase(prev(nxt));
				add(nxt->first-det[id],val);
			} else {
				LL val=nxt->second; nxt=prev(nxt);
				_erase(suff(nxt));
				add(nxt->first+det[id],val);
			}
		} det[id]+=d;
	}
	inline void merge(Myset &b) {
		if(s->size()<b.s->size()) swap(s,b.s), swap(id,b.id), swap(dis,b.dis);
		for(it v=b.s->begin();v!=b.s->end();++v) {
			data temp=*v; temp.first+=(v->second<0) ? det[b.id] : -det[b.id];
			add(temp.first,temp.second);
		}// delete b.s; delete b.dis;
	}
	inline LL getval(LL pos) {
		it nxt=s->lower_bound(data(pos-det[id],-INF,id));
		if(nxt!=s->end() && getpos(nxt)==pos) return nxt->second;
		return 0;
	}
//	inline void pt() {
//		cerr<<"delta : "<<'\n';
//		for(it v=s->begin();v!=s->end();++v) cerr<<getpos(v)<<' '<<v->second<<'\n';
//		cerr<<"dis : "<<'\n';
//		for(auto v=dis->begin();v!=dis->end();++v) cerr<<v->first-2*det[id]<<' '<<v->second-det[id]<<'\n';
//		cerr<<'\n';
//	}
} s[N];

inline void dfs(int x,int f) {

	for(auto v:edge[x]) {
		if(v.first==f) continue;
		dfs(v.first,x);
		for(auto &d:ask[v.first]) {
			LL delta=max(0ll,max(-s[v.first].getval(d.first),s[v.first].getval(d.first+1)));
			d.second=max(0ll,d.second-delta);
		}
		s[v.first].mv(1);
		for(auto d:ask[v.first]) s[v.first].md(d.first,d.second);
		s[v.first].mv(v.second-1);

//		cerr<<v.first<<" : "<<'\n';
//		s[v.first].pt();

		s[x].merge(s[v.first]);
	}

}

signed main() {
	n=rd();
	for(int i=1;i<=n;i++) s[i].id=i;
	for(int i=1;i<n;i++) {
		int x=rd(), y=rd(), w=rd()*2;
		edge[x].push_back(pii(y,w));
		edge[y].push_back(pii(x,w));
	} edge[0].push_back(pii(1,2));
	q=rd();
	for(int i=1;i<=q;i++) {
		int d=2*rd(), f=rd(), p=rd();
		ask[p].push_back(pii(d,f));
	}
	dfs(0,0);
	if(!s[0].s) {puts("0"); return 0;}
	LL sum=0, mx=0;
	for(auto v=s[0].s->begin();v!=s[0].s->end();++v) {
		sum+=v->second;
		mx=max(mx,sum);
	} cout<<mx<<'\n';
}


#include <iostream>
#include <queue>
#include <algorithm>
#include <set>
#include <map>
#include <vector>
#include <string>
using namespace std;
#define F first
#define S second
const int N = 55;
const int inf = 1e9 + 5;
const int mod = 1e9 + 7;
typedef long long ll;
int n, m;
pair<int, int> gg[N];

int x[10], y[10];
int sz[1000];
vector<int> aa[1000];
bool vis[1000];
map<int, int> g, id;

void gao(int x, set<int> & s) {
    while (x > 0) {
        s.insert(x);
        x /= 2;
    }
}

void dfs(int x, long long b, ll & ans) {
    vis[x] = true;
    ans += b * sz[x];
    ans %= mod;
    for (int i: aa[x]) {
        if (!vis[i]) {
            dfs(i, b, ans);
        }
    }
    vis[x] = false;
}

int calc(int x) {
    int left = x;
    int right = x;
    int re = 0;
    while (true) {
        if (left > n) {
            return re;
        }
        re += min(right, n) - left + 1;
        right = right * 2 + 1;
        left = left * 2;
    }
    return re;
}

int brute(){
    set<int> s;
    long long ans = 0;
    memset(x, 0, sizeof(x));
    memset(y, 0, sizeof(y));
    memset(sz, 0, sizeof(sz));
    memset(aa, 0, sizeof(aa));
    memset(vis, 0, sizeof(vis));
    g.clear();
    id.clear();
        for (int i = 0; i < m; i++) {
            x[i] = gg[i].F;
            y[i] = gg[i].S;
            gao(x[i], s);
            gao(y[i], s);
        }
        s.insert(1);
        for (int i: s) {
            if (s.find(2 * i) == s.end() && s.find(2 * i + 1) == s.end()) {
                g[i] = calc(i);
            } else {
                g[i] = 1;
                if (2 * i <= n && s.find(2 * i) == s.end()) {
                    g[2 * i] = calc(2 * i);
                }
                if (2 * i + 1 <= n && s.find(2 * i + 1) == s.end()) {
                    g[2 * i + 1] = calc(2 * i + 1);
                }
            }
        }
        for (pair<int, int> sth: g) {
            int i = sth.first;
            int u = (int)id.size();
            id[i] = u;
            sz[u] = g[i];
        }
        int nn = (int)g.size();
        for (pair<int, int> sth: id) {
            int i = sth.first;
            if (i == 1) {
                continue;
            }
            int child = id[i];
            int father = id[i / 2];
            aa[child].push_back(father);
            aa[father].push_back(child);
        }
        for (int i = 0; i < m; i++) {
            int first = id[x[i]];
            int second = id[y[i]];
            aa[first].push_back(second);
            aa[second].push_back(first);
        }
        for (int i = 0; i < nn; i++) {
            dfs(i, sz[i], ans);
        }
        return (int)ans;
}
int levels = 1;
int le, re;
int lca(int a, int b){
    set<int> s;
    while(a > 0){
        s.insert(a);
        a /= 2;
    }
    while(b > 0){
        if(s.count(b)){
            return b;
        }
        b /= 2;
    }
    return 1;
}
int get(int v){
    int l = v;
    int r = v;
    int ans = 0;
    while(r < (1 << (levels - 1))){
         ans += r - l + 1;
        r = r * 2 + 1;
        l = l * 2;
    }
    r = min(r, re);
    l = max(le, l);
    if(l <= r)
        ans += r - l + 1;
    return ans;
}
vector<int> paths(int a, int b){
    vector<int> A, B;
    int p = lca(a, b);
    while(a != p){
        A.push_back(a);
        a /= 2;
    }
    while(b != p){
        B.push_back(b);
        b /= 2;
    }
    reverse(B.begin(), B.end());
    A.push_back(p);
    for(auto it : B){
        A.push_back(it);
    }
    return A;
}
void upd(int & a, int b){
    a += b;
    if(a >= mod) a -= mod;
}
int gdfs(int v, int p, set<int> & marked, set<int> & path){
    if(v < 1 || v > n) return 0;
    if(path.count(v)){
        return 0;
    }
    if(!marked.count(v)){
        return get(v);
    }
    int ans = 1;
    if(v / 2 != p)
        upd(ans, gdfs(v / 2, v, marked, path));
    if(v + v != p)
        upd(ans, gdfs(v + v, v, marked, path));
    if(v + v + 1 != p){
        upd(ans, gdfs(v + v + 1, v, marked, path));
    }
    return ans;
}
int fnd(vector<pair<int, int> > cur){
    vector<int> line;

    for(int i = 0; i < (int)cur.size(); ++i){
        line.push_back(cur[i].first);
        line.push_back(cur[i].second);
    }
    // if equal then answer will be zero
    for(int i = 0; i < (int)line.size(); ++i){
        for(int j = 0; j < (int)line.size(); ++j){
            if(abs(i - j) > 1){
                if(line[i] == line[j]) return 0;
            }
        }
    }
    set<int> path;
    for(int i = 0; i < (int)cur.size(); ++ i){
        path.insert(cur[i].F);
        path.insert(cur[i].S);
        if(i + 1 < (int)cur.size()){
            vector<int> path1 = paths(cur[i].S, cur[i + 1].F);
            for(auto it : path1){
                if(it != cur[i].S && path.count(it)){
                    return 0;
                }
                path.insert(it);
            }
        }
    }

    int a = line[0];
    int b = line.back();
    int p = lca(a, b);
    bool both = 1;
    vector<int> A;
    vector<int> B;
    while(a != (p / 2)){
        if(path.count(a)){
            if(a != line[0] && a != line.back()){
                both = 0;
                break;
            }
        }
        A.push_back(a);
        a /= 2;
    }
    while(b != (p / 2)){
        if(path.count(b)){
            if(b != line[0] && b != line.back()){
                both = 0;
                break;
            }
        }
        B.push_back(b);
        b /= 2;
    }
    a = line[0];
    b = line.back();
    set<int> marked;
    for(auto it : path){
        int cur = it;
        while(cur > 0){
            marked.insert(cur);
            cur /= 2;
        }
    }
    if(!both){
        path.erase(a);
        int cnt1 = gdfs(a, -1, marked, path);
        path.insert(a);

        path.erase(b);
        int cnt2 = gdfs(b, -1, marked, path);
        path.insert(b);
        return (cnt1 * 1ll * cnt2) % mod;
    }
    B.pop_back();
    reverse(B.begin(), B.end());
    for(auto it : B){
        A.push_back(it);
    }
    int ans = 0;
    int sz = (int)A.size();
    for(int i = 0; i + 1 < (int)A.size(); ++i){
        if(A[i] == a) path.erase(a);
        if(i > 0) path.insert(A[i - 1]);
        if(i + 1 < sz) path.insert(A[i + 1]);

        int cnt1 = gdfs(A[i], -1, marked, path);
        if(i > 0) path.erase(A[i - 1]);
        if(i + 1 < sz) path.erase(A[i + 1]);
        path.insert(a);
        path.erase(b);
        path.insert(A[i]);
        int cnt2 = gdfs(b, -1, marked, path);
        int cur_ans = (cnt1 * 1ll * cnt2) % mod;
        upd(ans, cur_ans);
        path.erase(A[i]);
        path.insert(a);
        path.insert(b);
    }
    return ans;
}
int solve(){
    levels = 1;
    while((1 << levels) - 1 < n) ++levels;
    int tmp = (1 << levels) - 1 - n;
    le = (1 << (levels - 1));
    re = (1 << levels) - 1 - tmp;
    int ans = (n * 1ll * n) % mod;
    //int ans = 0;
    vector<pair<vector<pair< int, int> >, int > > v;
    for(int msk = 1; msk < (1 << m); ++msk){
        int cnt = 0;
        vector<pair<int, int> > cur1;
        for(int i = 0; i < m; ++i){
            if((1 << i) & msk){
                cnt++;
                cur1.push_back(gg[i]);
            }
        }
        for(int new_msk = 0; new_msk < (1 << cnt); ++new_msk){
            vector<pair<int, int> > cur;
            for(int i = 0; i < cnt; ++i){
                if((1 << i) & new_msk){
                    cur.push_back(cur1[i]);
                }
                else{
                    cur.push_back({cur1[i].S, cur1[i].F});
                }
            }
            sort(cur.begin(), cur.end());
            do{
                v.push_back({cur, msk});
                //upd(ans, fnd(cur));
            }while(next_permutation(cur.begin(), cur.end()));
        }
    }
    sort(v.begin(), v.end());
    v.erase(unique(v.begin(), v.end()), v.end());
    for(auto it : v){
        upd(ans, fnd(it.first));
    }
    return ans;
}
int main(){
    // I HOPE ILYUSHA WILL NOT READ THIS
    cin >> n >> m;
    for(int i = 0; i < m; ++i){
        cin >> gg[i].F >> gg[i].S;
    }
    /*for(n = 10; n <= 20; ++n){
        m = 1;
        for(int i = 1; i <= n; ++i){
            for(int j = 1; j <= n; ++j){
                if(i == j) continue;
                gg[0] = {i, j};
                if(solve() != brute()){
                    cout << n << " " << m << endl;
                    cout << i << " " << j << endl;
                }
            }
        }
    }*/
    //cout << "LOL" << endl;
    /*n = 4;
    m = 1;
    gg[0] = {1, 2};
    cout << solve() << endl;
    //cout << brute() << endl;*/
    cout << solve() << endl;
    return 0;
}


#include<bits/stdc++.h>

typedef long long LL;
using namespace std;

const int mod = 1000000007, N = 1010;

set<int> s;
map<int, int> g, id;
vector<int> a[N];
bool vis[N];
int n, m, x[9], y[9], sz[N];
LL ans;

void Insert(int x) {
	for(; x; x >>= 1) s.insert(x);
}

void dfs(int t, LL b) {
	vis[t] = true;
	(ans += b * sz[t]) %= mod;
	for(int i: a[t]) {
		if(!vis[i]) dfs(i, b);
	}
	vis[t] = false;
}

int calc(int x) {
	int L = x, R = x, ret = 0;
	while(L <= n) {
		ret += min(R, n) - L + 1;
		L <<= 1;
		R = R << 1 | 1;
	}
	return ret;
}

int main() {
	scanf("%d%d", &n, &m);
	for(int i = 0; i < m; ++i) {
		scanf("%d%d", x + i, y + i);
		Insert(x[i]), Insert(y[i]);
	}
	s.insert(1);
	for(int i: s) {
		if(s.find(i << 1) == s.end() && s.find(i << 1 | 1) == s.end()) {
			g[i] = calc(i); //缩点 代表几个节点
		} else {
			g[i] = 1;
			if(i + i <= n && s.find(i << 1) == s.end()) {
				g[i << 1] = calc(i << 1);
			}
			if(i + i + 1 <= n && s.find(i + i + 1) == s.end()) {
				g[i + i + 1] = calc(i + i + 1);
			}
		}
	}
	for(pair<int, int> sth: g) {//离散化
		int i = sth.first, u = id.size();
		id[i] = u;//u为离散编号
		sz[u] = g[i];
	}
	int cnt = g.size();
	for(pair<int, int> sth: id) {
		int i = sth.first;
		if(i == 1) continue;
		int son = id[i], f = id[i >> 1];
		e[son].push_back(f);
		e[f].push_back(son);
	}
	for(int i = 0; i < m; ++i) {
		int fst = id[x[i]], snd = id[y[i]];
		e[fst].push_back(snd);
		e[snd].push_back(fst);
	}
	for(int i = 0; i < cnt; ++i) dfs(i, sz[i]);
	cout << ans << '\n';
	return 0;
}


#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<map>

using namespace std;

const int MAXN=255;

const int Mod=1000000007;
inline void add_mod(int &x,int y)
{
    x=(x+y<Mod ? x+y : x+y-Mod);
}

int u[MAXN],v[MAXN];

map<int,int> mp;
inline int get_id(int x)
{
    if(!mp[x])mp[x]=(int)mp.size();
    return mp[x];
}

vector<int> e[MAXN];
void add_edge(int u,int v)
{
    e[u].push_back(v);
    e[v].push_back(u);
}

inline int cal_size(int u,int n,int d)
{
    int t=u,c=0,res;
    while(t)c++,t>>=1;
    res=(1<<(d-c+1))-1,t=c;
    while(t<d)t++,u=u<<1|1;
    return res-max(min(u-n,1<<(d-c)),0);
}

int num[MAXN];
void pre_dp(int u,int f)
{
    for(auto &v:e[u])
    {
        if(v==f)continue;
        num[u]-=num[v];
        pre_dp(v,u);
    }
}

int vis[MAXN];
void dfs(int u,int &tot)
{
    add_mod(tot,num[u]);
    vis[u]=1;
    for(auto &v:e[u])
        if(!vis[v])dfs(v,tot);
    vis[u]=0;
}

int main()
{
    int n,m,d=0;
    scanf("%d%d",&n,&m);
    while((1<<d)<=n)d++;
    get_id(1);
    for(int i=0;i<m;i++)
    {
        scanf("%d%d",&u[i],&v[i]);
        int t=u[i];
        while(t)get_id(t),t>>=1;
        t=v[i];
        while(t)get_id(t),t>>=1;
    }
    for(auto &t:mp)
    {
        int u=t.first,id=t.second;
        if(u>1)add_edge(get_id(u),get_id(u>>1));
        num[id]=cal_size(u,n,d);
    }
    pre_dp(1,0);
    for(int i=0;i<m;i++)
        add_edge(get_id(u[i]),get_id(v[i]));
    int res=0;
    for(int i=1;i<=(int)mp.size();i++)
    {
        int tot=0;
        dfs(i,tot);
        add_mod(res,1LL*tot*num[i]%Mod);
    }
    printf("%d\n",res);
    return 0;
}


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

const int maxn=160;
typedef long long LL;

struct LINK
{
	int id, next;
};

struct connect
{
	int u, v;
};

int n, m;
int total, sum;
int now;
connect a[maxn];
int num[maxn];
map<int, int> hash;
int h[maxn];
LINK t[maxn*maxn*2];
LL size[maxn];
LL ans;
bool vis[maxn];

void insert(int cur)
{
	while (cur)
	{
		if (!hash[cur])
		{
			num[++sum]=cur;
			hash[cur]=sum;
		}
		else return;
		cur>>=1;
	}
}
void join(int u, int v)
{
	t[now].id=v; t[now].next=h[u]; h[u]=now++;
	t[now].id=u; t[now].next=h[v]; h[v]=now++;
}
void read()
{
	scanf("%d%d", &n, &m);
	total=0;
	while ((1<<total)-1<n) ++total;
	for (int i=1; i<=m; ++i)
	{
		scanf("%d%d", &a[i].u, &a[i].v);
		insert(a[i].u);
		insert(a[i].v);
	}
}
int calc_size(int cur)
{
	int height=0;
	int tmp=cur;
	while (tmp!=1)
	{
		++height;
		tmp>>=1;
	}

	int s=1;
	if ((cur<<1)<=n && !hash[cur<<1]) s+=(1<<(total-height))-1;
	if ((cur<<1 | 1)<=n && !hash[cur<<1 | 1]) s+=(1<<(total-height))-1;
	return s;
}
void build(int cur)
{
	while (cur!=1)
	{
		join(hash[cur], hash[cur>>1]);
		cur>>=1;
	}
}
void dfs(int cur)
{
	if (vis[cur]) return;
	ans+=size[cur];
	vis[cur]=true;
	for (int i=h[cur]; i>-1; i=t[i].next)
		dfs(t[i].id);
	vis[cur]=false;
}
void solve()
{
	for (int i=1; i<=sum; ++i)
	{
		size[i]=calc_size(num[i]);
		ans+=size[i]*size[i];
	}
	for (int i=1; i<=sum; ++i) h[i]=-1;
	for (int i=1; i<=sum; ++i)
		build(num[i]);
	for (int i=1; i<=m; ++i)
		join(hash[a[i].u], hash[a[i].v]);

	for (int i=1; i<=sum; ++i)
	{
		for (int j=1; j<=sum; ++j) vis[j]=false;
		dfs(i);
		ans-=size[i];
	}
	printf("%I64d\n", ans);
}
int main()
{
	read();
	if (m==0) printf("%I64d\n", LL(n)*LL(n));
	else solve();
	return 0;
}


#pragma comment(linker, "/STACK:256000000")

#define _CRT_SECURE_NO_DEPRECATE
#define _CRT_SECURE_NO_WARNINGS
#define _USE_MATH_DEFINES
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <assert.h>
#include <time.h>
#include <memory.h>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <utility>
#include <algorithm>
#include <random>
#include <unordered_set>
#include <unordered_map>

using namespace std;

typedef long long int64;
typedef unsigned long long uint64;
typedef pair<int, int> pii;
typedef pair<int64, int64> pll;
const int INF = (int)(1e9 + 1337);
const int64 LINF = (int64)(4e18);
const double EPS = 1e-11;
#define sq(x) ((x)*(x))
#define FAIL() ((*(int*)(0))++)
const int HMOD = 1000000009;
const int HBASE = 1003;

const int MAXN = 51;

//inline int add(int a, int b)
//{
//	a += b;
//	if (a >= HMOD)
//	{
//		a -= HMOD;
//	}
//	return a;
//}
//
//inline int sub(int a, int b)
//{
//	a -= b;
//	if (a  < 0)
//	{
//		a += HMOD;
//	}
//	return a;
//}
//
//inline int mul(int a, int b)
//{
//	return int64(a) * b % HMOD;
//}

int64 s;
int add[MAXN];
int64 dp[MAXN][MAXN << 1][2];
int64 ans;

int64 get_min_path(int64 x, int len)
{
	return x * ((1 << len) - 1);
}

int64 get_max_path(int64 x, int len)
{
	return x * ((1 << len) - 1) + add[len - 1];
}

int64 get_max_lca(int lena, int lenb)
{
	int64 l = 1LL, r = s, lca2 = 0;
	while (l <= r)
	{
		int64 mid = (l + r) >> 1;
		int64 sum = mid;
		if (lena)
		{
			sum += get_min_path(mid << 1, lena - 1);
		}
		if (lenb)
		{
			sum += get_min_path((mid << 1) + 1, lenb - 1);
		}
		if (sum <= s)
		{
			lca2 = mid;
			l = mid + 1;
		}
		else
		{
			r = mid - 1;
		}
	}
	return lca2;
}

int64 get_min_lca(int lena, int lenb)
{
	int64 l = 1LL, r = s, lca1 = LINF;
	while (l <= r)
	{
		int64 mid = (l + r) >> 1;
		int64 sum = mid;
		if (lena)
		{
			sum += get_max_path(mid << 1, lena - 1);
		}
		if (lenb)
		{
			sum += get_max_path((mid << 1) + 1, lenb - 1);
		}
		if (sum <= s)
		{
			lca1 = mid;
			r = mid - 1;
		}
		else
		{
			l = mid + 1;
		}
	}
	return lca1;
}

int64 calc_dp(int lena, int lenb, int pop, int64 som)
{
	memset(dp, 0, sizeof(dp));
	int slen = 1;
	while (1 << (slen + 1) <= som)
	{
		slen++;
	}
	dp[0][0][0] = 1;
	for (int l = 1; l <= slen; l++)
	{
		int la = (l == lena + 1 ? 1 : 0);
		int ra = (l == lena ? 0 : 1);
		int lb = (l == lenb || l == lenb + 1 ? 1 : 0);
		int rb = 1;
		for (int a = la; a <= ra; a++)
		{
			for (int b = lb; b <= rb; b++)
			{
				for (int m = 0; m <= 1; m++)
				{
					int cnt = a + b + m;
					if (((som >> (l - 1)) & 1LL) != int64(cnt & 1))
					{
						continue;
					}
					for (int p = a + b; p <= (l << 1); p++)
					{
						dp[l][p][(cnt >> 1) & 1] += dp[l - 1][p - a - b][m];
					}
				}
			}
		}
	}
	return dp[slen][pop][0];
}

void solve()
{
	scanf ("%lld", &s);
	for (int lena = 0; lena <= 50; lena++)
	{
		for (int lenb = 0; lenb <= 50; lenb++)
		{
			int64 lca1 = get_min_lca(lena, lenb);
			int64 lca2 = get_max_lca(lena, lenb);
			if (lca1 == 0 || lca2 == LINF)
			{
				break;
			}
			//assert(lca1 == lca2);
			printf("
			int64 sum = s - (lca1 - 1) * ((1 << (lena + 1)) + (1 << (lenb + 1)) - 3);
			sum++;
			for (int pop = 2; pop <= lena + lenb + 2; pop++)
			{
				int64 som = sum + pop;
				if (som <= 0 || som & 1LL)
				{
					continue;
				}
				som >>= 1;
				ans += calc_dp(lena, lenb, pop, som);
			}
		}
	}
	printf("%I64d\n", ans);
}

void precalc()
{
	for (int i = 1; i < MAXN; i++)
	{
		add[i] = add[i - 1] + ((1 << i) - 1);
	}
}

int main()
{
#ifdef _MY_DEBUG
	freopen("input.txt", "rt", stdin); freopen("output.txt", "wt", stdout);
#else

#endif
	srand(333);

	double st = clock();

	precalc();
	int t = 1;
	scanf ("%d", &t); for (int i = 0; i < t; i++)
	{
		solve();
	}

	//fprintf(stderr, "%.3lf\n", (clock() - st) / CLOCKS_PER_SEC);

	return 0;
}


#include<bits/stdc++.h>
#define fp(i,a,b) for(register int i=a,I=b+1;i<I;++i)
#define fd(i,a,b) for(register int i=a,I=b-1;i>I;--i)
#define go(u) for(register int i=fi[u],v=e[i].to;i;v=e[i=e[i].nx].to)
#define file(s) freopen(s".in","r",stdin),freopen(s".out","w",stdout)
template<class T>inline bool cmax(T&a,const T&b){return a<b?a=b,1:0;}
template<class T>inline bool cmin(T&a,const T&b){return a>b?a=b,1:0;}
using namespace std;
const int N=52;
typedef long long ll;
int m,p;ll n,ans,mi[N],f[N][2*N][2];
inline ll sub(ll a,ll b){return a>=b?a-b:a;}
inline ll calc(ll s,ll q,int a,int b,int t){
    memset(f[p],0,sizeof f[p]);f[p][0][0]=1;
    fp(i,1,log2(s)+1){
        int d=(s>>i)&1;p^=1;memset(f[p],0,sizeof f[p]);
        fp(j,0,2*i-2)fp(k,0,1)if(f[p^1][j][k])
            fp(x,0,1)if(!x||i<a)fp(y,0,1)if(!y||i<b)
                if((k+x+y)%2==d)f[p][j+x+y][(k+x+y)/2]+=f[p^1][j][k];
    }
    return f[p][t][0];
}
int main(){
    #ifndef ONLINE_JUDGE
        file("s");
    #endif
    scanf("%lld",&n);mi[0]=1;ll x,ret;
    while(mi[m-1]<=n)mi[m+1]=mi[m]<<1,++m;--m;
    fp(i,1,m)if((x=n/(mi[i]-1))>0){
        ret=n-x*(mi[i]-1);
        fd(j,i-1,0)ret=sub(ret,mi[j]-1);
        if(!ret)++ans;
    }
    fp(i,1,m)for(int j=1;mi[j]-1<=n;++j)
        if((x=(n-mi[j]+1)/(mi[i+1]+mi[j+1]-3))>0){
            ret=(n-mi[j]+1)-x*(mi[i+1]+mi[j+1]-3);
            if(!ret){++ans;continue;}
            if(i==1&&j==1){ans+=s==5*x+1;continue;}
            fp(k,1,i+j)if(~(ret+k)&1)
                ans+=calc(ret+k,x,i,j,k);
        }
    printf("%lld",ans);
return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define rep(i,j,k) for(int i=j;i<=k;++i)
typedef long long ll;
typedef double db;
ll bit[65],f[65][120][2];
inline ll dp(ll s,int tot,int h1,int h2){
	memset(f,0,sizeof f);f[0][0][0]=1;
	int ed=log2(s);
	rep(i,1,ed){
		ll d=(s>>i)&1;
		int ed=i*2-2;
		rep(j,0,ed) rep(k,0,1)
		f[i][j+p1+p2][(k+p1+p2)/2]+=f[i-1][j][k];
	}
	return f[ed][tot][0];
}
int main(){
	ll x,s,res,ans=0;
	int ed=0;
	scanf("%lld",&s);
	bit[0]=1;while(bit[ed]<=s) bit[++ed]=bit[ed-1]<<1;
	rep(i,1,ed){
		if(bit[i]-1>s) break;
		x=s%(bit[i]-1);
		for(int j=i;j>=1;--j) if(x>=bit[j]-1) x-=bit[j]-1;
		if(!x) ++ans;
	}
	rep(h1,1,ed-1){
		for(int h2=1;bit[h2]-1<=s&&h2<ed;++h2){
			x=(s-bit[h2]+1)/(bit[h1+1]+bit[h2+1]-3);
			if(x>0){
				res=(s-bit[h2]+1)%(bit[h1+1]+bit[h2+1]-3);
				if(res==0){
					++ans;continue;
				}
				if(h1==1&&h2==1){
					ans+=(s==x*5+1);continue;
				}
				rep(i,1,h1+h2) if((res+i)%2==0) ans+=dp(res+i,i,h1,h2);
			}
		}
	}
	printf("%lld",ans);
}


#include<iostream>
#include<fstream>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<time.h>
#include<algorithm>
#include<bitset>
#include<map>
#include<memory>
#include<list>
#include<set>
#include<stack>
#include<string>
#include<queue>
#include<utility>
#include<vector>

using namespace std;

int c[15];
int ma[305];
int cnt = 0;
const long long inf = 1999999999999999999ll;
struct matrix{
    long long a[75][75];
    friend matrix operator * (const matrix &a,const matrix &b){
        matrix c;
        for(int i = 0; i < cnt; i++){
            for (int j = 0; j < cnt; j++){
                c.a[i][j] = inf;
            }
        }
        for(int i = 0; i < cnt; i++){
            for(int j = 0; j < cnt; j++){
                for(int k = 0; k < cnt; k++){
                    c.a[i][k] = min(c.a[i][k],a.a[i][j]+b.a[j][k]);
                }
            }
        }
        return c;
    }
    matrix (){
        for(int i = 0; i < 75; i++){
            for(int j = 0; j < 75; j++){
                a[i][j] = inf;
            }
            a[i][i] = 0;
        }
    }
};

matrix a;
matrix mul(int x){
    if(x == 0){
        return matrix();
    }
    matrix b = mul(x/2);
    b = b*b;
    if(x % 2 == 1){
        b = b*a;
    }
    return b;
}

pair<int,int> p[75];

int main()
{
    int x,k;
    int n,q;
    scanf("%d%d%d%d",&x,&k,&n,&q);
    for(int i = 0; i < k; i++){
        scanf("%d",&c[i]);
    }
    memset(ma, -1, sizeof(ma));
    for (int i = 0; i < (1<<k); i++){
        int sum = 0;
        for(int j = 0; j < k; j++){
            if((1<<j) & i){
                sum++;
            }
        }
        if(sum == x){
            ma[i] = cnt++;
        }
    }
    for(int i = 0; i < cnt; i++){
        for(int j = 0; j < cnt; j++){
            a.a[i][j] = inf;
        }
    }
    for (int i = 0; i < (1<<k); i++){
        if(ma[i] == -1){
            continue;
        }
        if(i&1){
            //Может двигаться
            for(int j = 1; j <= k; j++){
                if((1<<j) & i){
                    continue;
                }
                a.a[ma[i]][ ma[ ((1<<j)^i)>>1 ] ] = c[j-1];
            }
        }
        else{
            a.a[ma[i]][ma[i>>1]] = 0;
        }
    }
    int now = 1;
    for(int i = 0; i < q; i++){
        scanf("%d%d",&p[i].first,&p[i].second);
    }
    sort(p, p+q);
    matrix xx;
    long long ans = 0;
    for(int i = 0; i < q; i++){
        if(p[i].first >= n-x+1){
            ans + =p[i].second;
            continue;
        }
        xx = xx*mul(p[i].first-now);
        now = p[i].first;
        for(int j = 1; j < (1<<k); j+=2){
            if(ma[j] != -1){
                for(int l = 0; l < cnt; l++){
                    xx.a[l][ma[j]] += p[i].second;
                }
            }
        }
    }
    xx = xx*mul(n-x+1-now);
    cout << xx.a[0][0]+ans << endl;
    return 0;
}


#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <map>
#include <queue>
using namespace std;
typedef long long ll;
typedef vector<vector<ll>> mat;
int x, k, p, q, B, curx, n;
ll c[10],w;
map<int, ll> mp;
vector<ll> dp,dpn;
vector<int> bitset;
mat a, o, p;
void pow2(mat &a) {
	for (int i : bitset)
			for (int j : bitset)
			    p[i][j]=1e18;
	for (int k : bitset) {
		for (int i : bitset)
			for (int j : bitset)
				p[i][j] = min(p[i][j], a[i][k] + a[k][j]);
	}
	swap(a,p);
}
void operator *=(vector<ll> &dp, mat &a) {
	for(int i:bitset)
	    dpn[i]=1e18;
	for (int i : bitset) {
		for (int j : bitset) {
			dpn[j] = min(dpn[j], dp[i] + a[i][j]);
		}
	}
	swap(dp, dpn);
}
void jump(ll to) {
	a = o;
	ll jump = to - curx;
	for (;jump;pow2(a), jump >>= 1) {
		if (jump & 1) dp *= a;
	}
	curx = to;
}
int main() {
	ios::sync_with_stdio(0), cin.tie(0);
	cin >> x >> k >> n >> q;
	B = 1 << k;
	dp.resize(B, 1e18);
	dpn.resize(B, 1e18);
	o.resize(B, vector<ll>(B, 1e18));
	p.resize(B, vector<ll>(B, 1e18));
	for (int b = 1;b < B;b++)
		if (__builtin_popcount(b) == x) bitset.push_back(b);
	dp[bitset[0]] = 0;
	for (int i = 1;i <= k;i++) cin >> c[i];
	for (int cur : bitset) {
		int next = cur >> 1;
		if (cur & 1) {
			for (int i = 1, b = 1;i <= k;i++, b <<= 1) if (~next & b) {
				o[cur][next | b] = c[i];
			}
		}
		else o[cur][next] = 0;
	}
	for (int i = 1;i <= q;i++) {
		cin >> p >> w;
		if (w) mp[p] = w;
	}
	mp[n + k - x + 1] = 0;
	curx = k;
	for (auto it = mp.begin();curx < n + k - x;) {
		if (it->first <= curx - k) {
			it++; continue;
		}
		if (it->first <= curx + 1) {
			for(int i:bitset)
			    dpn[i]=1e18;
			curx++;
			for (int cur : bitset) {
				int next = cur >> 1;
				if (cur & 1) {
					for (int i = 1, b = 1;i <= k;i++, b <<= 1) if (~next & b) {
						dpn[next | b] = min(dpn[next | b], dp[cur] + c[i] + (mp.count(curx - k + i) ? mp[curx - k + i] : 0));
					}
				}
				else dpn[next] = min(dpn[next], dp[cur]);
			}
			swap(dp, dpn);
		}
		else jump(it->first - 1);
	}
	printf("%lld", dp[bitset[0]]);
}