解释待填。
#include
#include
using std::tr1::unordered_map;
typedef long long ll;
using namespace std;
#define rep(i,a,b) for(register ll i=a;i<=b;++i)
#define per(i,a,b) for(register ll i=a;i>=b;--i)
inline ll read(){bool f=0;ll x=0;char ch;do{ch=getchar();f|=(ch=='-');}while(!isdigit(ch));do{x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}while(isdigit(ch));return f?-x:x;}
inline void write(ll x){if(x<0)x=-x,putchar('-');if(x>9)write(x/10);putchar(x%10+'0');}
inline void writesp(ll x){write(x);putchar(' ');}
inline void writeln(ll x){write(x);puts("");}
const int mod=1e9+7;
ll mul_mod(ll a,ll b,ll md){return a*b%md;}
ll pow_mod(ll a,ll b,ll mod){ll res=1;while(b){if(b&1)res=res*a%mod;b>>=1;a=a*a%mod;}return res%mod;}
ll exgcd(ll a,ll b,ll& x,ll& y){if(!b){x=1;y=0;return a;}ll res=exgcd(b,a%b,y,x);y-=x*(a/b);return res;}
ll inv(ll a,ll b){ll x,y;ll res=exgcd(a,b,x,y);return res==1?(x%b+b)%b:-1;}
ll log_mod(ll a,ll b,ll p){unordered_map mp;mp.clear();a%=p;b%=p;int s=sqrt(p)+1,tmp=1;rep(j,0,s-1){mp[tmp]=j;tmp=tmp*a%p;}ll x,y;exgcd(tmp,p,x,y);x=(x+p)%p;tmp=b;rep(j,0,s){ll ans=(mp.find(tmp)==mp.end()?-1:mp[tmp]);if(ans>=0)return ans+j*s;tmp=tmp*x%p;}return -1;}
const int maxb=505;
int n,m,k,b,r,x[maxb],y[maxb];
set >bset;
int Count(){int c=0;rep(i,1,b)if(x[i]!=m&&!bset.count(make_pair(x[i]+1,y[i])))++c;c+=n;rep(i,1,b)if(x[i]==1)--c;return mul_mod(pow_mod(k,c,mod),pow_mod(k-1,(ll)n*m-b-c,mod),mod);}
int doit(){int cnt=Count();if(cnt == r) return m;int c=0;rep(i,1,b)if(x[i]==m)++c;++m;cnt=mul_mod(mul_mod(cnt,pow_mod(k,c,mod),mod),pow_mod(k-1,n-c,mod),mod);if(cnt==r)return m;return log_mod(pow_mod(k-1,n,mod),mul_mod(r,inv(cnt,mod),mod),mod)+m;}
int main()
{int T=read();rep(k,1,T){n=read(),k=read(),b=read(),r=read();bset.clear();m=1;rep(i,1,b){x[i]=read(),y[i]=read();m=max(m,x[i]);bset.insert(make_pair(x[i],y[i]));}printf("Case %d: %d\n",k,doit());}return 0;}