/*
Pranshul Agarwal
B.tech CSE Graduate
MNNIT Allahabad
*/
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
#define inc(i,a,n) for(int i=a;i<=n;i++)
#define in(n) scanf("%d",&n)
#define in2(n,m) scanf("%d%d",&n,&m)
int dp[1445][725][2];
bool hash1[2][1445];
bool is_valid(int cur, int cam, int duty){
int jam = cur - cam;
return (hash1[duty][cur] && cam<=720 && jam<=720);
}
int fun(int cur, int cam, int duty){
if(cur == 1441)return 0;
if(!is_valid(cur, cam, duty)) return 1000000;
if(dp[cur][cam][duty]!=-1)return dp[cur][cam][duty];
int ans = fun(cur+1,cam + (duty == 0), duty);
ans = min(ans, 1+ fun(cur+1, cam + (1-duty == 0), 1-duty));
return dp[cur][cam][duty]=ans;
}
int main()
{
int a,b,t,start,end;
in(t);
inc(d,1,t)
{
in2(a,b);
inc(i,0,1441){
hash1[0][i] = hash1[1][i] = true;
}
memset(dp,-1,sizeof(dp));
while(a--){
in2(start,end);
start++,end++;
inc(i,start,end-1)
hash1[0][i] = false;
}
while(b--){
in2(start,end);
start++,end++;
inc(i,start,end-1){
hash1[1][i] = false;
}
}
int ans = fun(1,1,0);
ans = min(ans,fun(1,0,1));
printf("Case #%d: %d\n",d,ans);
}
return 0;
}
LyogCglQcmFuc2h1bCBBZ2Fyd2FsCglCLnRlY2ggQ1NFIEdyYWR1YXRlCglNTk5JVCBBbGxhaGFiYWQKKi8KCgojaW5jbHVkZSA8YWxnb3JpdGhtPgojaW5jbHVkZSA8Y3N0ZGlvPgojaW5jbHVkZSA8Y3N0cmluZz4KdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCiNkZWZpbmUgaW5jKGksYSxuKSBmb3IoaW50IGk9YTtpPD1uO2krKykKCiNkZWZpbmUgaW4obikgc2NhbmYoIiVkIiwmbikKI2RlZmluZSBpbjIobixtKSBzY2FuZigiJWQlZCIsJm4sJm0pCgppbnQgZHBbMTQ0NV1bNzI1XVsyXTsKCmJvb2wgaGFzaDFb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