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
#include <bits/stdc++.h>
using namespace std;

const int INF=2*1e9;

struct edge
{
    int v;
    int type;
    int cross;
};

struct ver
{
    int num;
    int val;
};

bool operator<(ver a, ver b)
{
    if(a.val!=b.val)
        return a.val>b.val;
    return a.num>b.num;
}

priority_queue<ver> q;
vector<int> v;
vector<int> done;

int dijkstra(const vector<vector<edge>>& graph, const vector<string>& crossings, int t, int start, int finish, int n, int m)
{
    v.clear();
    done.clear();
    v.resize((n+1)*(m+1));
    fill(v.begin(),v.end(),INF);
    done.resize((n+1)*(m+1));
    fill(done.begin(),done.end(),0);

    v[start]=t;
    q.push({start,t});
    while(!q.empty())
    {
        ver x=q.top();
        q.pop();
        if(done[x.num]==0)
        {
            for(edge y:graph[x.num])
            {
                int d=x.val;
                while(crossings[y.cross][d%crossings[y.cross].length()]-'0'!=y.type)
                    ++d;
                v[y.v]=min(v[y.v],d);
                q.push({y.v,v[y.v]});
            }
        }
        done[x.num]=1;
    }
    return v[finish];
}

int main()
{
    ios_base::sync_with_stdio(false); cin.tie(); cout.tie(0);
    int n,m,q;
    cin>>n>>m>>q;
    vector<string> crossings(n*m);
    for(int i=0; i<n*m; ++i)
        cin>>crossings[i];
    
    vector<vector<edge>> graph((n+1)*(m+1));
    for(int i=0; i<n*m; ++i)
    {
        graph[i+i/m].push_back({i+i/m+1,1,i});
        graph[i+i/m+1].push_back({i+i/m,1,i});
        graph[i+i/m].push_back({i+i/m+m+1,0,i});
        graph[i+i/m+m+1].push_back({i+i/m,0,i});
        graph[i+i/m+1].push_back({i+i/m+m+2,0,i});
        graph[i+i/m+m+2].push_back({i+i/m+1,0,i});
        graph[i+i/m+m+1].push_back({i+i/m+m+2,1,i});
        graph[i+i/m+m+2].push_back({i+i/m+m+1,1,i});
    }

    for(int i=0; i<q; ++i)
    {
        int t,a,b,c,d;
        cin>>t>>a>>b>>c>>d;
        int start=a*(m+1)+b;
        int finish=c*(m+1)+d;
        cout<<dijkstra(graph,crossings,t,start,finish,n,m)<<endl;
    }
    return 0;
}