#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
struct node{
	int h;
	LL d,c;
};
node per[6];
inline bool cmp(node a,node b){
	long long x1=b.c;
	x1=x1*a.d;
	long long x2=a.c;	
	x2=x2*b.d;
	if(x1!=x2)
		return x1>x2;
	else	
		return  a.c<b.c;
}
LL L;
LL ans,sav;
LL sum[7];
void gao(int temp,LL dam,LL cost){
	if(dam>=L){
		if(ans==-1 || cost<ans || (cost==ans && sav>dam))
			ans=cost,sav=dam;
		return ;
	}
	if(temp>5) return ;
	if(sum[temp]+dam<L) return ;
	LL res=L-dam;
	res=res/per[temp].d;
	res=res*per[temp].c;
	res=res+cost;	
	if( ans!=-1 && res > ans)  return ;
	for(int i=per[temp].h;i>=0;i--)
		gao(temp+1,dam+i*per[temp].d,cost+i*per[temp].c);
	return ;
}

int main(){
	int T;
	scanf("%d",&T);
	while(T--){
		scanf("%lld",&L);
		for(int i=1;i<=5;i++)
			scanf("%d%lld%lld",&per[i].h,&per[i].d,&per[i].c);
		sum[6]=0;
		sort(per+1,per+6,cmp);
		for(int i=5;i>0;i--){
			long long t1=per[i].d;
			t1=t1*per[i].h;
			sum[i]=sum[i+1]+t1;
		}
		if(sum[1]<L){
			puts("We are doomed!!");
			continue;
		}
		ans=-1;
		sav=-1;
		gao(1,0,0);
		printf("%lld %lld\n",ans,sav);
	}
	return 0;
}