#include<cstdio>
#include<algorithm>
using namespace std;
int to[10001][101]={0};
bool up[10001][101]={0};
int num[10001]={0};
int n,m,s;
int ans=0;
int main(){
freopen("treasures.in","r",stdin);
freopen("treasures.out","w",stdout);
scanf("%d%d",&n,&m);
for (int i=1;i<=n;i++){
for (int j=1;j<=m;j++){
scanf("%d%d",&up[i][j],&to[i][j]);
num[i]+=up[i][j];
}
}
scanf("%d",&s);
s++;
int mod=20123;
for (int i=1;i<=n;i++){
ans=(ans+to[i][s]) % mod;
// if (i>n) break;
// printf("%d\n",s);
int cnt=to[i][s]%num[i];
if (cnt==0) cnt=num[i];
int x=s;
for (int j=1;j<=m;j++){
// printf("%d ",x);
if (up[i][x]==1) cnt--;
if (cnt<=0) break;
else x=(x%m)+1;
}
// printf("\n");
s=x;
}
printf("%d",ans);
return 0;
}