#include <bits/stdc++.h>
using namespace std;
struct room{
bool f;
long long sum;
}R[100010][1010];
long long n,m,sb,*b,ans;
int main(){
cin>>n>>m;
b=new long long[n+1];
for(int i=1;i<=n;i++){
for(int j=0;j<m;j++){
cin>>R[i][j].f>>R[i][j].sum;
b[i]+=R[i][j].f;
}
}
cin>>sb;
int i=1;
while(i<=n){
long long t=R[i][sb].sum;
ans=(ans+t)%20123;
t=t%b[i];
if(t==0)t=b[i];
for(int j=0;j<=t;){
if(R[i][sb].f){
j++;
}
if(j>=t)break;
sb++;
sb=(sb+m)%m;
}
i++;
}
cout<<ans%20123;
return 0;
}