#include <iostream>
#include <cstdio>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
//英语 抄博友程序 排序
struct nod{string s;int num;
}da[100010];
bool cmp(nod a, nod b)
{if(a.num==b.num){return a.s<b.s;}else{return a.num<b.num;}
}
int main()
{int T;cin>>T;int tag=0;while(T--){tag++;int n,m,l;cin>>n>>m>>l;for(int i=0;i<l;i++){string t;cin>>t;for(int j=0;j<t.size();j++){if(t[j]==':'||t[j]==','){t[j]=' ';}}istringstream iss(t);int a,b; iss>>da[i].s>>a>>b;int rw=n;int hf=0;//博友程序while(u/2>=m&&(u-u/2)*a>=b) while((rw/2)>=m && (rw/2)*a>b) 也ac while((rw/2)>=m && (rw/2)*a>=b)//抄博友程序 {rw=rw/2;hf=hf+b;}hf=hf+(rw-m)*a;//抄博友程序 da[i].num=hf; }sort(da,da+l,cmp);cout<<"Case "<<tag<<endl;for(int i=0;i<l;i++){cout<<da[i].s<<" "<<da[i].num<<endl;}} return 0;
}