1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;
const int MX=3005,MQ=100100;
int n,m,q,i,ls[MQ],rs[MQ],lt[MQ],rt[MQ],ans[MQ],f[MX][MX],stp[MX];
map<pii,vector<int>> lft,rgh;
char s[MX],t[MX];
long long lcnt,rcnt;
bool cmplft(int i, int j) { return rs[i]<rs[j]; }
bool cmprgh(int i, int j) { return ls[i]>ls[j]; }
int main() {
  scanf("%d%d%d",&n,&m,&q);
  scanf("%s",s+1);
  scanf("%s",t+1);
  for (i=0; i<q; i++) {
    scanf("%d%d%d%d",&ls[i],&rs[i],&lt[i],&rt[i]);
    lft[{ls[i],lt[i]}].push_back(i);
    rgh[{rs[i],rt[i]}].push_back(i);
  }
  lcnt=rcnt=0;
  for (auto it=lft.begin(); it!=lft.end(); ++it) {
    int lsz=it->first.first-2,ltz=it->first.second-2;
    vector<int>& v=it->second;
    sort(v.begin(),v.end(),cmplft);
    int mx=ltz;
    for (int j=int(v.size())-1; j>=0; --j) {
      mx=max(mx,rt[v[j]]);
      lcnt+=(rs[v[j]]-(j?rs[v[j-1]]:lsz))*(mx-ltz);
    }
  }
  for (auto it=rgh.begin(); it!=rgh.end(); ++it) {
    int rsz=it->first.first+2,rtz=it->first.second+2;
    vector<int>& v=it->second;
    sort(v.begin(),v.end(),cmprgh);
    int mn=rtz;
    for (int j=int(v.size())-1; j>=0; --j) {
      mn=min(mn,lt[v[j]]);
      rcnt+=((j?ls[v[j-1]]:rsz)-ls[v[j]])*(rtz-mn);
    }
  }
  if (lcnt<=rcnt) {
    for (auto it=lft.begin(); it!=lft.end(); ++it) {
      int lsz=it->first.first-1,ltz=it->first.second-1;
      int mx=ltz;
      vector<int>& v=it->second;
      for (int j=int(v.size())-1; j>=0; --j) {
        mx=max(mx,rt[v[j]]);
        int fin=(j?rs[v[j-1]]:lsz);
        for (i=rs[v[j]]; i>fin; --i) stp[i]=mx;
      }
      int rmx=rs[v.back()];
      for (i=lsz; i<=rmx; i++) f[i][ltz]=0;
      for (i=ltz; i<=mx; i++) f[lsz][i]=0;
      for (i=lsz+1; i<=rmx; ++i) for (int j=ltz+1; j<=stp[i]; ++j) {
        f[i][j]=max(f[i-1][j],f[i][j-1]);
        if (s[i]==t[j]) f[i][j]=max(f[i][j],f[i-1][j-1]+1);
      }
      for (int j: v) ans[j]=f[rs[j]][rt[j]];
    }
  } else for (auto it=rgh.begin(); it!=rgh.end(); ++it) {
    int rsz=it->first.first+1,rtz=it->first.second+1;
    int mn=rtz;
    vector<int>& v=it->second;
    for (int j=int(v.size())-1; j>=0; --j) {
      mn=min(mn,lt[v[j]]);
      int fin=(j?ls[v[j-1]]:rsz);
      for (i=ls[v[j]]; i<fin; ++i) stp[i]=mn;
      int rmn=ls[v.back()];
      for (i=rsz; i>=rmn; --i) f[i][rtz]=0;
      for (i=rtz; i>=mn; --i) f[rsz][i]=0;
      for (i=rsz-1; i>=rmn; --i) for (int j=rtz-1; j>=stp[i]; --j) {
        f[i][j]=max(f[i+1][j],f[i][j+1]);
        if (s[i]==t[j]) f[i][j]=max(f[i][j],f[i+1][j+1]+1);
      }
      for (int j: v) ans[j]=f[ls[j]][lt[j]];
    }
  }
  for (i=0; i<q; i++) printf("%d\n",ans[i]);
  return 0;
}