#include <iostream>
#include <fstream>
using namespace std;
const int MAXN(10001), MOD(20123), MAXM(101);
int n,m,ans=0,lt[MAXN]={0},f[MAXN][MAXM]={0},a,b;
bool flag[MAXN][MAXM] = {0};
main()
{
ifstream fin("treasures.in");
ofstream fout("treasures.out");
#define cin fin
#define cout fout
// ios::sync_with_stdio(false);
cin >> n >> m;
for (int i = 1; i <= n; ++i)
for (int j = 0; j < m; ++j){
cin >> flag[i][j] >> f[i][j];
if (flag[i][j])
lt[i]++;
}
cin >> a;
for (int i = 1; i < n; ++i){
ans = (ans + f[i][a]) % MOD;
b = f[i][a--] % lt[i];
if (! b)
b = lt[i];
int x = 0;
while (x != b){
a++;
if (a == m)
a = 0;
if (flag[i][a])
x++;
}
}
ans = (ans + f[n][a]) % MOD;
cout << ans;
fin.close();
fout.close();
}