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
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>

int n,m,q;
long long x;
std::vector<std::vector<std::string>> patern;
std::string pat;
std::vector<std::vector<bool>>pionowo_blokady,poziomo_blokady;
int main(){
    std::ios_base::sync_with_stdio(0);
    std::cin>>n>>m>>q;
    patern.resize(n);
    for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
            std::cin>>pat;
            patern[i].push_back(pat);
        }
    }
    pionowo_blokady.resize(n);
    //pionowo
    for(int i=0;i<n;i++){
        int filters[9]={0,0,3,7,15,31,63,127,255};
        for(int j=0;j<m;j++){
            int acc=0;
            for(int k=patern[i][j].size()-1;k>=0;k--){
                acc*=2;
                acc+=(patern[i][j][k]=='1');
            }
            filters[patern[i][j].size()]&=acc;
        }
        for(int d=0;d<840;d++){//840
            bool pr=false;
            for(int j=2;j<9;j++){
                if((filters[j]&(1<<(d%j)))==0){
                    pr=true;
                }
            }
            pionowo_blokady[i].emplace_back(!pr);
            //std::cout<<!pr;
        }
        //std::cout<<std::endl;
    }
    poziomo_blokady.resize(m);
    for(int i=0;i<m;i++){
        int filters[9]={0,0,3,7,15,31,63,127,255};
        for(int j=0;j<n;j++){
            int acc=0;
            for(int k=patern[j][i].size()-1;k>=0;k--){
                acc*=2;
                acc+=(patern[j][i][k]=='0');
            }
            filters[patern[j][i].size()]&=acc;
        }
        for(int d=0;d<840;d++){//840
            bool pr=false;
            for(int j=2;j<9;j++){
                if((filters[j]&(1<<(d%j)))==0){
                    pr=true;
                }
            }
            poziomo_blokady[i].emplace_back(!pr);
            //std::cout<<!pr;
        }
        //std::cout<<std::endl;
    }
    int a,b,c,d;
    long long t;
    for(int i=0;i<q;i++){
        std::cin>>t>>a>>b>>c>>d;
        long long t1=t;
        long long t2=t;
        int in=(a<c?1:-1);
        if(in==-1){
            a--;
            c--;
        }
        while(a!=c){
            if(pionowo_blokady[a][t1%840]==0)
                a+=in;
            else
                t1++;
        }
        in=(b<d?1:-1);
        if(in==-1){
            b--;
            d--;
        }
        while(b!=d){
            if(poziomo_blokady[b][t2%840]==0)
                b+=in;
            else
                t2++;
        }
        std::cout<<std::max(t1,t2)<<std::endl;
    }
    
    return 0;
}