Problem:
壁
２XXX年、突然出現した天敵の侵入を防ぐために、人類は壁を作りその中に逃げ込んだ。その結果、人類の活動領域はその壁で囲まれた範囲に限定されてしまった。この領域は、上空から見ると
W
×
H
の長方形である。領域内部には
x
軸あるいは
y
軸に対して平行な壁がいくつか設置されている。活動領域の例を下図に示す。
人類は活動領域内を自由に移動することができるが、壁を越えるためには一定量の資源を消費しなければならない。ただし、壁を越えることはできるが（図中の (1)）、壁の交点を越えること (2)、壁や活動領域の境界の上を移動すること (3)、活動領域外に出ること (4) はできない。
領域内部の壁の情報といくつかの始点と終点の組を入力し、始点から終点へ移動するために越えなければならない壁の数の最小値を計算するプログラムを作成しなさい。ただし、壁は幅のない線分とします。
入力
入力は１つのデータセットからなる。入力データは以下の形式で与えられる。
W
H
M
px
1
py
1
qx
1
qy
1
px
2
py
2
qx
2
qy
2
:
px
M
py
M
qx
M
qy
M
Q
sx
1
sy
1
gx
1
gy
1
sx
2
sy
2
gx
2
gy
2
:
sx
Q
sy
Q
gx
Q
gy
Q
1行目に領域の横の長さと縦の長さを表す整数
W
,
H
(2 ≤
W,H
≤ 1,000,000,000) と壁の数
M
(0 ≤
M
≤ 100) が与えられる。
続く
M
行に壁を表す線分の情報が与えられる。各行に与えられる４つの整数
px
i
,
py
i
,
qx
i
,
qy
i
(0 ≤
px
i
,
qx
i
≤
W
, 0 ≤
py
i
,
qy
i
≤
H
) はそれぞれ
i
番目の線分の端点の
x
座標、
y
座標、もうひとつの端点の
x
座標、
y
座標を表す。
続く1行に質問の数
Q
(1 ≤
Q
≤ 100) が与えられる。続く
Q
行に各質問が与えられる。各質問に含まれる４つの整数
sx
i
,
sy
i
,
gx
i
,
gy
i
(0 <
sx
i
,
gx
i
<
W
, 0 <
sy
i
,
gy
i
<
H
) はそれぞれ始点の
x
座標、
y
座標、終点の
x
座標、
y
座標を表す。
入力は以下の条件を満たす。
各線分は
x
軸あるいは
y
軸に対して平行であり、長さは1以上である。
２つの互いに平行な線分が同じ点あるいは線分を共有することはない。
スタート地点、ゴール地点は壁上にあることはない。
どの線分も活動領域の境界と線分を共有することはない。
出力
質問ごとに、壁を越える回数の最小値を出力する。
入出力例
入力例 1
5 6 5
0 2 5 2
0 3 5 3
0 4 3 4
1 4 1 6
3 0 3 6
2
2 5 4 1
2 5 4 5
出力例 1
3
1
入力例 2
4 4 0
1
1 1 2 2
出力例 2
0
入力例 3
4 7 3
0 2 2 2
3 3 4 3
0 5 4 5
3
1 1 1 3
1 1 1 4
1 1 1 6
出力例 3
0
0
1

Submitted solutions:

code_snippet: #include <bits/stdc++.h>
using namespace std;
vector<int> dx = {1, 0, -1, 0};
vector<int> dy = {0, 1, 0, -1};
int main(){
  int W, H, M;
  cin >> W >> H >> M;
  vector<int> px(M), py(M), qx(M), qy(M);
  for (int i = 0; i < M; i++){
    cin >> px[i] >> py[i] >> qx[i] >> qy[i];
  }
  vector<int> x;
  for (int i = 0; i < M; i++){
    x.push_back(px[i]);
    x.push_back(qx[i]);
  }
  x.push_back(0);
  x.push_back(W);
  sort(x.begin(), x.end());
  x.erase(unique(x.begin(), x.end()), x.end());
  for (int i = 0; i < M; i++){
    px[i] = lower_bound(x.begin(), x.end(), px[i]) - x.begin();
    qx[i] = lower_bound(x.begin(), x.end(), qx[i]) - x.begin();
  }
  W = lower_bound(x.begin(), x.end(), W) - x.begin();
  vector<int> y;
  for (int i = 0; i < M; i++){
    y.push_back(py[i]);
    y.push_back(qy[i]);
  }
  y.push_back(0);
  y.push_back(H);
  sort(y.begin(), y.end());
  y.erase(unique(y.begin(), y.end()), y.end());
  for (int i = 0; i < M; i++){
    py[i] = lower_bound(y.begin(), y.end(), py[i]) - y.begin();
    qy[i] = lower_bound(y.begin(), y.end(), qy[i]) - y.begin();
  }
  H = lower_bound(y.begin(), y.end(), H) - y.begin();
  vector<vector<vector<int>>> c(4, vector<vector<int>>(W, vector<int>(H, 0)));
  for (int i = 0; i < M; i++){
    if (px[i] == qx[i]){
      if (py[i] > qy[i]){
        swap(py[i], qy[i]);
      }
      for (int j = py[i]; j < qy[i]; j++){
        c[0][px[i] - 1][j] = 1;
        c[2][px[i]][j] = 1;
      }
    }
    if (py[i] == qy[i]){
      if (px[i] > qx[i]){
        swap(px[i], qx[i]);
      }
      for (int j = px[i]; j < qx[i]; j++){
        c[1][j][py[i] - 1] = 1;
        c[3][j][py[i]] = 1;
      }
    }
  }
  int Q;
  cin >> Q;
  for (int i = 0; i < Q; i++){
    int sx, sy, gx, gy;
    cin >> sx >> sy >> gx >> gy;
    sx = lower_bound(x.begin(), x.end(), sx) - x.begin() - 1;
    gx = lower_bound(x.begin(), x.end(), gx) - x.begin() - 1;
    sy = lower_bound(y.begin(), y.end(), sy) - y.begin() - 1;
    gy = lower_bound(y.begin(), y.end(), gy) - y.begin() - 1;
    vector<vector<int>> d(W, vector<int>(H, -1));
    deque<tuple<int, int, int>> dq;
    dq.push_back(make_tuple(0, sx, sy));
    while (!dq.empty()){
      int dd = get<0>(dq.front());
      int cx = get<1>(dq.front());
      int cy = get<2>(dq.front());
      dq.pop_front();
      if (d[cx][cy] == -1){
        d[cx][cy] = dd;
        for (int j = 0; j < 4; j++){
          int x2 = cx + dx[j];
          int y2 = cy + dy[j];
          if (0 <= x2 && x2 < W && 0 <= y2 && y2 < H){
            if (c[j][cx][cy] == 0){
              dq.push_front(make_tuple(dd, x2, y2));
            } else {
              dq.push_back(make_tuple(dd + 1, x2, y2));
            }
          }
        }
      }
    }
    cout << d[gx][gy] << endl;
  }
}
accuracy: 1
time_ms: 30
memory_kb: 3796
final_rank: 3

code_snippet: #include <bits/stdc++.h>
using namespace std;
vector<int> dx = {1, 0, -1, 0};
vector<int> dy = {0, 1, 0, -1};
int main(){
  int W, H, M;
  cin >> W >> H >> M;
  vector<int> px(M), py(M), qx(M), qy(M);
  for (int i = 0; i < M; i++){
    cin >> px[i] >> py[i] >> qx[i] >> qy[i];
  }
  vector<int> x;
  for (int i = 0; i < M; i++){
    x.push_back(px[i]);
    x.push_back(qx[i]);
  }
  x.push_back(0);
  x.push_back(W);
  sort(x.begin(), x.end());
  x.erase(unique(x.begin(), x.end()), x.end());
  for (int i = 0; i < M; i++){
    px[i] = lower_bound(x.begin(), x.end(), px[i]) - x.begin();
    qx[i] = lower_bound(x.begin(), x.end(), qx[i]) - x.begin();
  }
  W = lower_bound(x.begin(), x.end(), W) - x.begin();
  vector<int> y;
  for (int i = 0; i < M; i++){
    y.push_back(py[i]);
    y.push_back(qy[i]);
  }
  y.push_back(0);
  y.push_back(H);
  sort(y.begin(), y.end());
  y.erase(unique(y.begin(), y.end()), y.end());
  for (int i = 0; i < M; i++){
    py[i] = lower_bound(y.begin(), y.end(), py[i]) - y.begin();
    qy[i] = lower_bound(y.begin(), y.end(), qy[i]) - y.begin();
  }
  H = lower_bound(y.begin(), y.end(), H) - y.begin();
  vector<vector<vector<int>>> c(4, vector<vector<int>>(W, vector<int>(H, 0)));
  for (int i = 0; i < M; i++){
  	if (px[i] == qx[i]){
  	  if (py[i] > qy[i]){
  	    swap(py[i], qy[i]);
  	  }
  	  for (int j = py[i]; j < qy[i]; j++){
  	    c[0][px[i] - 1][j] = 1;
  	    c[2][px[i]][j] = 1;
  	  }
  	}
    if (py[i] == qy[i]){
      if (px[i] > qx[i]){
        swap(px[i], qx[i]);
      }
      for (int j = px[i]; j < qx[i]; j++){
        c[1][j][py[i] - 1] = 1;
        c[3][j][py[i]] = 1;
      }
    }
  }
  int Q;
  cin >> Q;
  for (int i = 0; i < Q; i++){
    int sx, sy, gx, gy;
    cin >> sx >> sy >> gx >> gy;
    sx = lower_bound(x.begin(), x.end(), sx) - x.begin() - 1;
    gx = lower_bound(x.begin(), x.end(), gx) - x.begin() - 1;
    sy = lower_bound(y.begin(), y.end(), sy) - y.begin() - 1;
    gy = lower_bound(y.begin(), y.end(), gy) - y.begin() - 1;
    vector<vector<int>> d(W, vector<int>(H, -1));
    deque<tuple<int, int, int>> dq;
    dq.push_back(make_tuple(0, sx, sy));
    while (!dq.empty()){
      int dd = get<0>(dq.front());
      int cx = get<1>(dq.front());
      int cy = get<2>(dq.front());
      dq.pop_front();
      if (d[cx][cy] == -1){
        d[cx][cy] = dd;
        for (int j = 0; j < 4; j++){
          int x2 = cx + dx[j];
          int y2 = cy + dy[j];
          if (0 <= x2 && x2 < W && 0 <= y2 && y2 < H){
            if (c[j][cx][cy] == 0){
              dq.push_front(make_tuple(dd, x2, y2));
            } else {
              dq.push_back(make_tuple(dd + 1, x2, y2));
            }
          }
        }
      }
    }
    cout << d[gx][gy] << endl;
  }
}
accuracy: 1
time_ms: 40
memory_kb: 3800
final_rank: 4

code_snippet: #include <atomic>
#include<bits/stdc++.h>
#define rep(i,a,...) for(int i = (a)*(strlen(#__VA_ARGS__)!=0);i<(int)(strlen(#__VA_ARGS__)?__VA_ARGS__:(a));++i)
#define per(i,a,...) for(int i = (strlen(#__VA_ARGS__)?__VA_ARGS__:(a))-1;i>=(int)(strlen(#__VA_ARGS__)?(a):0);--i)
#define foreach(i, n) for(auto &i:(n))
#define all(x) (x).begin(), (x).end()
#define bit(x) (1ll << (x))
#define lambda(RES_TYPE, ...) (function<RES_TYPE(__VA_ARGS__)>)[&](__VA_ARGS__) -> RES_TYPE
#define method(FUNC_NAME, RES_TYPE, ...) function<RES_TYPE(__VA_ARGS__)> FUNC_NAME = lambda(RES_TYPE, __VA_ARGS__)
using namespace std;
using ll = long long;
using pii = pair<int,int>;
using pll = pair<ll,ll>;
//const ll MOD = (ll)1e9+7;
const ll MOD = 998244353;
const int INF = (ll)1e9+7;
const ll INFLL = (ll)1e18;
template<class t>
using vvector = vector<vector<t>>;
template<class t>
using vvvector = vector<vector<vector<t>>>;
template<class t>
using priority_queuer = priority_queue<t, vector<t>, greater<t>>;
template<class t, class u> bool chmax(t &a, u b){if(a<b){a=b;return true;}return false;}
template<class t, class u> bool chmin(t &a, u b){if(a>b){a=b;return true;}return false;}
#ifdef DEBUG
#define debug(x) cout<<"LINE "<<__LINE__<<": "<<#x<<" = "<<x<<endl;
#else
#define debug(x) (void)0
#endif

namespace templates{
    ll modpow(ll x, ll b,ll mod=MOD){
        ll res = 1;
        while(b){
            if(b&1)res = res * x % mod;
            x = x * x % mod;
            b>>=1;
        }
        return res;
    }

    ll modinv(ll x){
        return modpow(x, MOD-2);
    }

    bool was_output = false;

    void print();
    template <class t> void print(const vector<t> &);
    template <class t, class u> void print(const pair<t, u> &);
    template <class t> void print(const t&);
    template <class Head, class... Tail> void print(const Head&, const Tail&...);

    template <class t> void println(const vector<vector<t>>&);
    template <class t> void println(const vector<t>&);
    template <class t> void println(const t&);
    template <class Head, class... Tail> void println(const Head&, const Tail&...);
    void println();
    void newline();

    void print(){
        return;
    }

    template <class t>
    void print(const vector<t>&x){
        for(const t&i:x)print(i);
    }
    template <class t, class u>
    void print(const pair<t,u>&p){
        print(p.first);
        print(p.second);
    }
    template <class t>
    void print(const t&x){
        if(was_output)cout<<" ";
        cout<<x;
        was_output = true;
    }
    template <class Head, class... Tail>
    void print(const Head&head,const Tail&...tail){
        print(head);
        print(tail...);
    }

    template<class t>
    void println(const vector<vector<t>>&x){
        for(vector<t> i:x)println(i);
    }
    template<class t>
    void println(const vector<t>&x){
        for(const t&i:x)print(i);
        println();
    }
    template <class t>
    void println(const t&x){
        print(x);
        println();
    }
    void println(){
        if(was_output){
            cout << endl;
            was_output = false;
        }
    }
    template <class Head, class... Tail>
    void println(const Head&head,const Tail&...tail){
        print(head);
        println(tail...);
    }

    void newline(){
        was_output = true;
        println();
    }

    template<class t>
    istream& operator>>(istream&is, vector<t>&x){
        for(auto &i:x)is >> i;
        return is;
    }

    template<class t, class u>
    istream& operator>>(istream&is, pair<t, u>&x){
        is >> x.first >> x.second;
        return is;
    }

    template<class t>
    ostream& operator<<(ostream&os, vector<t> &v){
        os << "{";
        for(t &i:v){
            os << i << ", ";
        }
        os << "}";
        return os;
    }

    template<class t = long long>
    t in(){
        t res; cin >> res; return res;
    }

    template<class t>
    vector<t> sorted(vector<t> line,function<bool(t,t)> comp=[](t a,t b){return a<b;}){
        sort(line.begin(),line.end(),comp);
        return line;
    }

    template<class t>
    vector<t> reversed(vector<t> line){
        reverse(line.begin(),line.end());
        return line;
    }
    string reversed(string str){
        reverse(str.begin(),str.end());
        return str;
    }

    long long gcd(long long a,long long b){
        while(b){
            a %= b;
            swap(a,b);
        }
        return a;
    }

    long long lcm(long long a,long long b){
        return a / gcd(a,b) * b;
    }

    class output_initializer{
    public:
        output_initializer(){
            ios::sync_with_stdio(false);
            cin.tie(nullptr);
            cout << setprecision(20);
        }
    };output_initializer OUTPUT_INITIALIZER_INSTANCE = output_initializer();
}

using namespace templates;


map<int,int> compress(set<int> v){
    map<int,int> res;
    foreach(i,v)res[i]=0;
    int cnt =  0;
    foreach(i,res){
        i.second = cnt;
        cnt += 2;
    }
    return res;
}

template <class type = long long>
class dijkstra{
public:
    using E = pair<int,type>;
    using S = pair<type,int>;
	int n;
	vvector<E> edges;
	vector<type> fast;
    type inf;
	dijkstra(int N,type inf=numeric_limits<type>::max()>>1):n(N),inf(inf){
		edges.resize(n);
	}

	void add_edge(int from, int to, type cost, bool rev=false){
		edges[from].emplace_back(to, cost);
        if(rev){
            edges[to].emplace_back(from, cost);
        }
	}

	void solve(int start){
		priority_queuer<S> pq;
		fast.assign(n, inf);
		pq.emplace(0, 0);
		fast[start] = 0;
		pq.emplace(0, start);
		while(pq.size()){
			S d = pq.top();
			pq.pop();
			if(d.first!=fast[d.second])continue;
            for(E e:edges[d.second]){
				type next_time = d.first + e.second;
				int to = e.first;
				if(fast[to] <= next_time)continue;
				fast[to] = next_time;
				pq.emplace(next_time, to);
			}
		}
	}

    type operator[](int p){
        return fast[p];
    }
};


vector<int> func(){
    int w = in();
    int h = in();
    int m = in();
    vector<pii> s1s(m);
    vector<pii> s2s(m);
    rep(i,m){
        s1s[i] = in<pii>();
        s2s[i] = in<pii>();
    }
    map<int,int> cx;
    map<int,int> cy;
    {
        set<int> xs;
        set<int> ys;
        xs.emplace(0);
        ys.emplace(0);
        xs.emplace(w);
        ys.emplace(h);
        foreach(i,s1s)xs.emplace(i.first);
        foreach(i,s2s)xs.emplace(i.first);
        foreach(i,s1s)ys.emplace(i.second);
        foreach(i,s2s)ys.emplace(i.second);
        cx = compress(xs);
        cy = compress(ys);
    }
    method(get_x,int,int x){
        auto itr = cx.lower_bound(x);
        if(itr->first==x)return itr->second;
        return itr->second - 1;
    };
    method(get_y,int,int y){
        auto itr = cy.lower_bound(y);
        if(itr->first==y)return itr->second;
        return itr->second - 1;
    };
    method(toint,int,int y,int x){
        return x + (cx.rbegin()->second + 1) * y;
    };
    h = cy.rbegin()->second+1;
    w = cx.rbegin()->second+1;
    dijkstra<int> di(toint(h,w));
    vvector<char> board(h,vector<char>(w,false));
    rep(i,m){
        int py = get_y(s1s[i].second);
        int px = get_x(s1s[i].first);
        int gy = get_y(s2s[i].second);
        int gx = get_x(s2s[i].first);
        rep(y,min(py,gy),max(py,gy)+1){
            rep(x,min(px,gx),max(px,gx)+1){
                board[y][x] = true;
            }
        }
    }
    int dx[]={1,0,-1,0};
    int dy[]={0,-1,0,1};
    rep(i,h){
        rep(j,w){
            rep(k,4){
                int ni = i + dy[k];
                int nj = j + dx[k];
                if(0 <= ni and ni < h and 0 <= nj and nj < w){
                    di.add_edge(toint(i,j),toint(ni,nj),board[ni][nj] ? 1 : 0);
                }
            }
        }
    }
    int q = in();
    vector<int> res;
    rep(i,q){
        int sx = in();
        int sy = in();
        int gx = in();
        int gy = in();
        di.solve(toint(get_y(sy),get_x(sx)));
        res.emplace_back(di[toint(get_y(gy),get_x(gx))]);
    }
    return res;
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    foreach(i,func()){
        println(i);
    }
    return 0;
}
accuracy: 1
time_ms: 390
memory_kb: 8720
final_rank: 11

code_snippet: #include <bits/stdc++.h>
using namespace std;

using ll = long long int;
using ull = unsigned long long int;
using P = pair<int, int>;
using P3 = pair<int,P>;
using PP = pair<P, P>;
constexpr int INF32 = 1 << 29;
constexpr ll INF64 = 1LL << 62;
constexpr ll MOD = 1000000007;
// constexpr ll MOD = 998244353;
constexpr int di[] = {0, 1, 0, -1};
constexpr int dj[] = {1, 0, -1, 0};
constexpr int di8[] = {0, 1, 1, 1, 0, -1, -1, -1};
constexpr int dj8[] = {1, 1, 0, -1, -1, -1, 0, 1};
constexpr double EPS = 1e-10;
const double PI = acos(-1);

#define ALL(v) (v).begin(),(v).end()
#define REP(i,n) for(int i=0,i_len=n; i<i_len; ++i)

template<typename T1,typename T2> bool chmax(T1 &a, T2 b) { if (a<b) { a=b; return 1; } return 0; }
template<typename T1,typename T2> bool chmin(T1 &a, T2 b) { if (b<a) { a=b; return 1; } return 0; }

void compress(vector<int> &v, map<int,int> &zip){
    sort(ALL(v));
    v.erase(unique(ALL(v)),v.end());
    int n = v.size();
    REP(i,n){
        zip[v[i]] = i;
    }
}

int solve(){
    int H, W, M;
    cin >> W >> H >> M;
    vector<int> xs = {0,W}, ys = {0,H};
    vector<PP> lines, query;
    for(int i=0;i<M;i++){
        int px, py, qx, qy;
        cin >> px >> py >> qx >> qy;
        lines.emplace_back(P(px,py),P(qx,qy));
        xs.emplace_back(min(px,W));
        xs.emplace_back(max(px-1,0));
        xs.emplace_back(min(qx,W));
        xs.emplace_back(max(qx-1,0));
        ys.emplace_back(min(py,H));
        ys.emplace_back(max(py-1,0));
        ys.emplace_back(min(qy,H));
        ys.emplace_back(max(qy-1,0));
    }
    int Q;
    cin >> Q;
    for(int i=0;i<Q;i++){
        int sx, sy, gx, gy;
        cin >> sx >> sy >> gx >> gy;
        query.emplace_back(P(sx,sy),P(gx,gy));
        xs.emplace_back(sx);
        xs.emplace_back(gx);
        ys.emplace_back(sy);
        ys.emplace_back(gy);
    }
    map<int,int> cxs, cys;
    compress(xs, cxs);
    compress(ys, cys);
    int h = (int)ys.size()-1, w = (int)xs.size()-1;
    vector<vector<vector<int> > > cost(h, vector<vector<int> >(w, vector<int>(4,0)));
    REP(i,M){
        int px, py, qx, qy;
        px = lines[i].first.first;
        py = lines[i].first.second;
        qx = lines[i].second.first;
        qy = lines[i].second.second;
        if(px == qx){
            int lb = cys[py], ub = cys[qy];
            int x = cxs[px];
            if(lb > ub) swap(lb, ub);
            for(int y=lb;y<ub;y++){
                cost[y][x-1][0] = 1;
                cost[y][x][2] = 1;
            }
        }else{
            int lb = cxs[px], ub = cxs[qx];
            int y = cys[py];
            if(lb > ub) swap(lb, ub);
            for(int x=lb;x<ub;x++){
                cost[y-1][x][1] = 1;
                cost[y][x][3] = 1;
            }
        }
    }
    vector<vector<int> > d(h,vector<int>(w));
    REP(i,Q){
        int sx, sy, gx, gy;
        sx = cxs[query[i].first.first];
        sy = cys[query[i].first.second];
        gx = cxs[query[i].second.first];
        gy = cys[query[i].second.second];
        REP(y,h) fill(d[y].begin(), d[y].end(), INF32);
        deque<P> que;
        que.push_back(P(sx,sy));
        d[sy][sx] = 0;
        while(!que.empty()){
            P pos = que.front();
            que.pop_front();
            int x = pos.first, y = pos.second;
            REP(k,4){
                int ny = y+di[k], nx = x+dj[k];
                if(ny<0 || ny>=h || nx<0 || nx>=w) continue;
                if(chmin(d[ny][nx], d[y][x]+cost[y][x][k])){
                    if(cost[y][x][k]==0) que.push_front(P(nx,ny));
                    else que.push_back(P(nx,ny));
                }
            }
        }
        cout << d[gy][gx] << endl;
    }
    return 0;
}

int main(){
    cin.tie(0); ios::sync_with_stdio(0); cout<<fixed<<setprecision(20);
    // int t; cin >> t; for(int i=0;i<t;i++) solve();
    // while(!solve());
    solve();
    return 0;
}
accuracy: 1
time_ms: 380
memory_kb: 16324
final_rank: 14

code_snippet: #include<iostream>
#include<vector>
#include<algorithm>
#include<deque>
using namespace std;
int H,W,N,Q;
vector<int>X,Y;
int a[111],b[111],c[111],d[111];
int D[222][222];
bool check(const vector<pair<int,int> >&A,int x)
{
	auto it=upper_bound(A.begin(),A.end(),make_pair(x,(int)1e9));
	if(it!=A.begin())
	{
		it--;
		if(it->first<=x&&x<it->second)return true;
		else return false;
	}
	return false;
}
main()
{
	cin>>H>>W>>N;
	for(int i=0;i<N;i++)cin>>a[i]>>b[i]>>c[i]>>d[i];
	a[N]=0;b[N]=0;c[N]=H;d[N]=0;
	a[N+1]=0;b[N+1]=0;c[N+1]=0;d[N+1]=W;
	a[N+2]=H;b[N+2]=0;c[N+2]=H;d[N+2]=W;
	a[N+3]=0;b[N+3]=W;c[N+3]=H;d[N+3]=W;
	N+=4;
	for(int i=0;i<N;i++)
	{
		X.push_back(a[i]);
		Y.push_back(b[i]);
		X.push_back(c[i]);
		Y.push_back(d[i]);
	}
	sort(X.begin(),X.end());
	X.erase(unique(X.begin(),X.end()),X.end());
	sort(Y.begin(),Y.end());
	Y.erase(unique(Y.begin(),Y.end()),Y.end());
	vector<vector<pair<int,int> > >EX(X.size()),EY(Y.size());
	for(int i=0;i<N;i++)
	{
		int ai=lower_bound(X.begin(),X.end(),a[i])-X.begin();
		int bi=lower_bound(Y.begin(),Y.end(),b[i])-Y.begin();
		int ci=lower_bound(X.begin(),X.end(),c[i])-X.begin();
		int di=lower_bound(Y.begin(),Y.end(),d[i])-Y.begin();
		if(ai==ci)EX[ai].push_back(minmax(bi,di));
		else EY[bi].push_back(minmax(ai,ci));
	}
	H=X.size()-1;W=Y.size()-1;
	for(int i=0;i<H;i++)sort(EX[i].begin(),EX[i].end());
	for(int i=0;i<W;i++)sort(EY[i].begin(),EY[i].end());
	cin>>Q;
	for(;Q--;)
	{
		int sx,sy,gx,gy;
		{
			int isx,isy,igx,igy;
			cin>>isx>>isy>>igx>>igy;
			sx=upper_bound(X.begin(),X.end(),isx)-X.begin()-1;
			sy=upper_bound(Y.begin(),Y.end(),isy)-Y.begin()-1;
			gx=upper_bound(X.begin(),X.end(),igx)-X.begin()-1;
			gy=upper_bound(Y.begin(),Y.end(),igy)-Y.begin()-1;
		}
		for(int i=0;i<H;i++)for(int j=0;j<W;j++)D[i][j]=1e9;
		D[sx][sy]=0;
		deque<pair<int,int> >P;
		P.push_back(make_pair(sx,sy));
		while(!P.empty())
		{
			int x=P.front().first,y=P.front().second;
			P.pop_front();
			if(x>0)
			{
				int c=check(EX[x],y);
				int nxt=D[x][y]+c;
				if(D[x-1][y]>nxt)
				{
					D[x-1][y]=nxt;
					if(c)P.push_back(make_pair(x-1,y));
					else P.push_front(make_pair(x-1,y));
				}
			}
			if(y>0)
			{
				int c=check(EY[y],x);
				int nxt=D[x][y]+c;
				if(D[x][y-1]>nxt)
				{
					D[x][y-1]=nxt;
					if(c)P.push_back(make_pair(x,y-1));
					else P.push_front(make_pair(x,y-1));
				}
			}
			if(x+1<H)
			{
				int c=check(EX[x+1],y);
				int nxt=D[x][y]+c;
				if(D[x+1][y]>nxt)
				{
					D[x+1][y]=nxt;
					if(c)P.push_back(make_pair(x+1,y));
					else P.push_front(make_pair(x+1,y));
				}
			}
			if(y+1<W)
			{
				int c=check(EY[y+1],x);
				int nxt=D[x][y]+c;
				if(D[x][y+1]>nxt)
				{
					D[x][y+1]=nxt;
					if(c)P.push_back(make_pair(x,y+1));
					else P.push_front(make_pair(x,y+1));
				}
			}
		}
		cout<<D[gx][gy]<<endl;
	}
}
accuracy: 1
time_ms: 50
memory_kb: 3252
final_rank: 2

code_snippet: #include <bits/stdc++.h>
#define rep(i,n)for(int i=0;i<(n);i++)
using namespace std;
typedef long long ll;
typedef pair<int,int>P;

const int MOD=1000000007;
const int INF=0x3f3f3f3f;
const ll INFL=0x3f3f3f3f3f3f3f3f;

int px[200],py[200],qx[200],qy[200];
int sx[200],sy[200],gx[200],gy[200];

int dx[]{1,-1,0,0},dy[]{0,0,1,-1};

int lwb(int x,vector<int>&v){
	return lower_bound(v.begin(),v.end(),x)-v.begin();
}
int main(){
	int w,h,m;scanf("%d%d%d",&w,&h,&m);
	w*=2;h*=2;
	vector<int>xs,ys;
	xs.push_back(0);xs.push_back(1);
	xs.push_back(w-1);xs.push_back(w);
	ys.push_back(0);ys.push_back(1);
	ys.push_back(h-1);ys.push_back(h);
	rep(i,m){
		scanf("%d%d%d%d",&px[i],&py[i],&qx[i],&qy[i]);
		px[i]*=2;py[i]*=2;qx[i]*=2;qy[i]*=2;
		for(int j=-1;j<=1;j++){
			xs.push_back(px[i]+j);xs.push_back(qx[i]+j);
			ys.push_back(py[i]+j);ys.push_back(qy[i]+j);
		}
	}
	int q;cin>>q;
	rep(i,q){
		scanf("%d%d%d%d",&sx[i],&sy[i],&gx[i],&gy[i]);
		sx[i]*=2;sy[i]*=2;gx[i]*=2;gy[i]*=2;
		xs.push_back(sx[i]);xs.push_back(gx[i]);
		ys.push_back(sy[i]);ys.push_back(gy[i]);
	}
	sort(xs.begin(),xs.end());
	xs.erase(unique(xs.begin(),xs.end()),xs.end());
	sort(ys.begin(),ys.end());
	ys.erase(unique(ys.begin(),ys.end()),ys.end());
	int W=xs.size(),H=ys.size();
	vector<vector<int>>B(H,vector<int>(W));
	rep(i,m){
		px[i]=lwb(px[i],xs);
		py[i]=lwb(py[i],ys);
		qx[i]=lwb(qx[i],xs);
		qy[i]=lwb(qy[i],ys);
		if(px[i]==qx[i]){
			if(py[i]>qy[i])swap(py[i],qy[i]);
			for(int j=py[i];j<=qy[i];j++){
				B[j][px[i]]=1;
			}
		}
		else{
			if(px[i]>qx[i])swap(px[i],qx[i]);
			for(int j=px[i];j<=qx[i];j++){
				B[py[i]][j]=1;
			}
		}
	}
	rep(i,H)rep(j,W){
		if(i==0||j==0||i==H-1||j==W-1)B[i][j]=1;
	}
	rep(i,q){
		sx[i]=lwb(sx[i],xs);
		sy[i]=lwb(sy[i],ys);
		gx[i]=lwb(gx[i],xs);
		gy[i]=lwb(gy[i],ys);
		vector<vector<int>>D(H,vector<int>(W,INF));
		deque<P>que;
		D[sy[i]][sx[i]]=0;
		que.push_back(P(sy[i],sx[i]));
		while(!que.empty()){
			P p=que.front();que.pop_front();
			rep(k,4){
				int nx=p.first+dx[k],ny=p.second+dy[k];
				if(0<=nx&&nx<H&&0<=ny&&ny<W&&D[nx][ny]==INF){
					if(B[nx][ny]){
						D[nx][ny]=D[p.first][p.second]+1;
						que.push_back(P(nx,ny));
					}
					else{
						D[nx][ny]=D[p.first][p.second];
						que.push_front(P(nx,ny));
					}
				}
			}
		}
		printf("%d\n",D[gy[i]][gx[i]]);
	}
}
accuracy: 1
time_ms: 540
memory_kb: 6272
final_rank: 12

code_snippet: #include <iostream>
#include <algorithm>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <numeric>
#include <bitset>
#include <cmath>

static const int MOD = 1000000007;
using ll = long long;
using u32 = unsigned;
using u64 = unsigned long long;
using namespace std;

template<class T> constexpr T INF = ::numeric_limits<T>::max()/32*15+208;

int main() {
    int W, H, n;
    cin >> W >> H >> n;
    vector<int> zy = {0, H}, zx = {0, W};
    vector<array<int, 3>> A, B;
    for (int i = 0; i < n; ++i) {
        int x1, y1, x2, y2;
        cin >> x1 >> y1 >> x2 >> y2;
        zx.emplace_back(x1);
        zx.emplace_back(x2);
        zy.emplace_back(y1);
        zy.emplace_back(y2);
        if(x1 == x2){
            B.emplace_back(array<int, 3>{x1, y1, y2});
        }else {
            A.emplace_back(array<int, 3>{x1, x2, y1});
        }
    }

    sort(zy.begin(), zy.end());
    zy.erase(unique(zy.begin(), zy.end()), zy.end());
    sort(zx.begin(), zx.end());
    zx.erase(unique(zx.begin(), zx.end()), zx.end());
    auto fx = [&](int x){ return lower_bound(zx.begin(),zx.end(), x) - zx.begin(); };
    auto fy = [&](int y){ return lower_bound(zy.begin(),zy.end(), y) - zy.begin(); };
    int h = zy.size(), w = zx.size();
    vector<vector<pair<int, int>>> P(h), Q(w);
    for (int i = 0; i < A.size(); ++i) {
        P[fy(A[i][2])].emplace_back(A[i][0], A[i][1]);
    }
    for (int i = 0; i < B.size(); ++i) {
        Q[fx(B[i][0])].emplace_back(B[i][1], B[i][2]);
    }
    auto f = [&](int i, int j){ return i*(w-1)+j; };
    vector<vector<pair<int, int>>> G((h-1)*(w-1));
    vector<int> S(w+1);
    for (int i = 1; i < h-1; ++i) {
        fill(S.begin(),S.end(), 0);
        for (auto &&j : P[i]) {
            S[fx(j.first)]++;
            S[fx(j.second+1)-1]--;
        }
        for (int j = 0; j < w-1; ++j) {
            G[f(i-1, j)].emplace_back(f(i, j), S[j]);
            G[f(i, j)].emplace_back(f(i-1, j), S[j]);
            S[j+1] += S[j];
        }
    }
    S.resize(h+1);
    for (int i = 1; i < w-1; ++i) {
        fill(S.begin(),S.end(), 0);
        for (auto &&j : Q[i]) {
            S[fy(j.first)]++;
            S[fy(j.second+1)-1]--;
        }
        for (int j = 0; j < h-1; ++j) {
            G[f(j, i-1)].emplace_back(f(j, i), S[j]);
            G[f(j, i)].emplace_back(f(j, i-1), S[j]);
            S[j+1] += S[j];
        }
    }
    int q;
    cin >> q;
    for (int i = 0; i < q; ++i) {
        int x1, y1, x2, y2;
        cin >> x1 >> y1 >> x2 >> y2;
        int s = f(fy(y1+1)-1, fx(x1+1)-1), g = f(fy(y2+1)-1, fx(x2+1)-1);
        vector<int> dist((h-1)*(w-1), INF<int>);
        dist[s] = 0;
        deque<int> que;
        que.emplace_back(s);
        while(!que.empty()){
            int x = que.front(); que.pop_front();
            for (auto &&j : G[x]) {
                if(j.second == 0){
                    if(dist[j.first] > dist[x]){
                        dist[j.first] = dist[x];
                        que.emplace_front(j.first);
                    }
                }else {
                    if(dist[j.first] > dist[x]+1){
                        dist[j.first] = dist[x]+1;
                        que.emplace_back(j.first);
                    }
                }
            }
        }
        cout << dist[g] << "\n";
    }
    return 0;
}
accuracy: 1
time_ms: 30
memory_kb: 4372
final_rank: 5

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll=long long;
using ld=long double;
using ull=unsigned long long;
using uint=unsigned int;
using pcc=pair<char,char>;
using pii=pair<int,int>;
using pll=pair<ll,ll>;
using pdd=pair<double,double>;
using tuplis=pair<ll,pll>;
using tuplis2=pair<pll,ll>;
template<class T> using pq=priority_queue<T,vector<T>,greater<T>>;
const ll LINF=0x1fffffffffffffff;
const ll MINF=0x7fffffffffff;
const int INF=0x3fffffff;
const ll MOD=1000000007;
const ll MODD=998244353;
const ld DINF=numeric_limits<ld>::infinity();
const ld EPS=1e-9;
const ld PI=3.141592653589793238462643383279;
const vector<ll>four{0,1,0,-1,0};
#define _overload4(_1,_2,_3,_4,name,...) name
#define _overload3(_1,_2,_3,name,...) name
#define _rep1(n) for(ll i=0;i<n;++i)
#define _rep2(i,n) for(ll i=0;i<n;++i)
#define _rep3(i,a,b) for(ll i=a;i<b;++i)
#define _rep4(i,a,b,c) for(ll i=a;i<b;i+=c)
#define rep(...) _overload4(__VA_ARGS__,_rep4,_rep3,_rep2,_rep1)(__VA_ARGS__)
#define _rrep1(n) for(ll i=(n)-1;i>=0;i--)
#define _rrep2(i,n) for(ll i=(n)-1;i>=0;i--)
#define _rrep3(i,a,b) for(ll i=(b)-1;i>=a;i--)
#define _rrep4(i,a,b,c) for(ll i=a+(b-a-1)/c*c;i>=a;i-=c)
#define rrep(...) _overload4(__VA_ARGS__,_rrep4,_rrep3,_rrep2,_rrep1)(__VA_ARGS__)
#define each(i,a) for(auto &i:a)
#define sum(...) accumulate(range(__VA_ARGS__),0LL)
#define dsum(...) accumulate(range(__VA_ARGS__),double(0))
#define _range(i) (i).begin(),(i).end()
#define _range2(i,k) (i).begin(),(i).begin()+k
#define _range3(i,a,b) (i).begin()+a,(i).begin()+b
#define range(...) _overload3(__VA_ARGS__,_range3,_range2,_range)(__VA_ARGS__)
#define _rrange(i) (i).rbegin(),(i).rend()
#define _rrange2(i,k) (i).rbegin(),(i).rbegin()+k
#define _rrange3(i,a,b) (i).rbegin()+a,(i).rbegin()+b
#define rrange(...) _overload3(__VA_ARGS__,_rrange3,_rrange2,_rrange)(__VA_ARGS__)
#define elif else if
#define unless(a) if(!(a))
#define mp make_pair
#define mt make_tuple
#define INT(...) int __VA_ARGS__;in(__VA_ARGS__)
#define LL(...) ll __VA_ARGS__;in(__VA_ARGS__)
#define ULL(...) ull __VA_ARGS__;in(__VA_ARGS__)
#define STR(...) string __VA_ARGS__;in(__VA_ARGS__)
#define CHR(...) char __VA_ARGS__;in(__VA_ARGS__)
#define DBL(...) double __VA_ARGS__;in(__VA_ARGS__)
#define vec(type,name,...) vector<type> name(__VA_ARGS__)
#define VEC(type,name,size) vector<type> name(size);in(name)
#define vv(type,name,h,...) vector<vector<type>>name(h,vector<type>(__VA_ARGS__))
#define VV(type,name,h,...) vector<vector<type>>name(h,vector<type>(__VA_ARGS__));in(name)
#define vvv(type,name,h,w,...) vector<vector<vector<type>>>name(h,vector<vector<type>>(w,vector<type>(__VA_ARGS__)))
inline constexpr ll gcd(ll a,ll b){if(!a||!b)return 0;while(b){ll c=b;b=a%b;a=c;}return a;}
inline constexpr ll lcm(ll a,ll b){if(!a||!b)return 0;return a*b/gcd(a,b);}
template<class T> inline constexpr T min(vector<T> &v){return *min_element(range(v));}
inline char min(string &v){return *min_element(range(v));}
template<class T> inline constexpr T max(vector<T> &v){return *max_element(range(v));}
inline char max(string &v){return *max_element(range(v));}
inline constexpr ll intpow(ll a,ll b){ll ans=1;for(ll i=1;b;i*=2){if(b&i){b^=i;ans*=a;}a*=a;}return ans;}
template<typename T>
inline constexpr bool chmin(T &mn,const T &cnt){if(mn>cnt){mn=cnt;return 1;}else return 0;}
template<typename T>
inline constexpr bool chmax(T &mx,const T &cnt){if(mx<cnt){mx=cnt;return 1;}else return 0;}
template<class T> unordered_map<T,ll> press(vector<T> &a){ auto b = a; sort(range(b)); b.erase(unique(range(b)), b.end()); unordered_map<T,ll> ans; rep(b.size()) ans[b[i]] = i; each(i, a) i = ans[i]; return ans; }
template<class T> map<T,ll> press_map(vector<T> &a){ auto b = a; sort(range(b)); b.erase(unique(range(b)), b.end()); map<T,ll> ans; rep(b.size()) ans[b[i]] = i; each(i, a) i = ans[i]; return ans; }
inline int scan(){ return getchar(); }
inline void scan(int &a){ scanf("%d", &a); }
inline void scan(unsigned &a){ scanf("%u", &a); }
inline void scan(long &a){ scanf("%ld", &a); }
inline void scan(long long &a){ scanf("%lld", &a); }
inline void scan(unsigned long long &a){ scanf("%llu", &a); }
inline void scan(char &a){ cin >> a; }
inline void scan(float &a){ scanf("%f", &a); }
inline void scan(double &a){ scanf("%lf", &a); }
inline void scan(long double &a){ scanf("%Lf", &a); }
inline void scan(vector<bool> &vec){ for(unsigned i = 0; i < vec.size(); i++) { int a; scan(a); vec[i] = a; } }
inline void scan(string &a){ cin >> a; }
template<class T> inline void scan(vector<T> &vec);
template<class T, size_t size> inline void scan(array<T, size> &vec);
template<class T, class L> inline void scan(pair<T, L> &p);
template<class T, size_t size> inline void scan(T (&vec)[size]);
template<class T> inline void scan(vector<T> &vec){ for(auto &i : vec) scan(i); }
template<class T, size_t size> inline void scan(array<T, size> &vec){ for(auto &i : vec) scan(i); }
template<class T, class L> inline void scan(pair<T, L> &p){ scan(p.first); scan(p.second); }
template<class T, size_t size> inline void scan(T (&vec)[size]){ for(auto &i : vec) scan(i); }
template<class T> inline void scan(T &a){ cin>>a; }
inline void in(){}
template <class Head, class... Tail> inline void in(Head &head, Tail&... tail){ scan(head); in(tail...); }
inline void print(){ putchar(' '); }
inline void print(const bool &a){ printf("%d", a); }
inline void print(const int &a){ printf("%d", a); }
inline void print(const unsigned &a){ printf("%u", a); }
inline void print(const long &a){ printf("%ld", a); }
inline void print(const long long &a){ printf("%lld", a); }
inline void print(const unsigned long long &a){ printf("%llu", a); }
inline void print(const char &a){ printf("%c", a); }
inline void print(const char a[]){ printf("%s", a); }
inline void print(const float &a){ printf("%.15f", a); }
inline void print(const double &a){ printf("%.15f", a); }
inline void print(const long double &a){ printf("%.15Lf", a); }
template<class T> void print(const vector<T> &vec);
template<class T, size_t size> void print(const array<T, size> &vec);
template<class T, class L> void print(const pair<T, L> &p);
template<class T, size_t size> inline void print(const T (&vec)[size]);
template<class T> void print(const vector<T> &vec){ if(vec.empty()) return; print(vec[0]); for(auto i = vec.begin(); ++i != vec.end(); ){ putchar(' '); print(*i); } }
template<class T, size_t size> void print(const array<T, size> &vec){ print(vec[0]); for(auto i = vec.begin(); ++i != vec.end(); ){ putchar(' '); print(*i); } }
template<class T, class L> void print(const pair<T, L> &p){ print(p.first); putchar(' '); print(p.second); }
template<class T, size_t size> inline void print(const T (&vec)[size]){ print(vec[0]); for(auto i = vec; ++i != end(vec); ){ putchar(' '); print(*i); } }
template<class T> inline void print(const T &a){ cout << a; }
inline int out(){ putchar('\n'); return 0; }
template<class T> inline int out(const T &t){ print(t); putchar('\n'); return 0; }
template<class Head, class... Tail> inline int out(const Head &head, const Tail&... tail){ print(head); putchar(' '); out(tail...); return 0; }
template <class T> inline void err(T t){cerr<<t<<'\n';}
template<class Head, class... Tail> inline void err(const Head &head, const Tail&... tail){ cerr<<head<<' '; err(tail...); }
inline void err(){cerr<<'\n';}
inline int first(const bool &i){return out(i?"first":"second");}
inline int yes(const bool &i){return out(i?"yes":"no");}
inline int Yes(const bool &i){return out(i?"Yes":"No");}
inline int YES(const bool &i){return out(i?"YES":"NO");}
inline int Yay(const bool &i){return out(i?"Yay!":":(");}
inline int Possible(const bool &i){return out(i?"Possible":"Impossible");}
inline int POSSIBLE(const bool &i){return out(i?"POSSIBLE":"IMPOSSIBLE");}
inline void Case(ll i){printf("Case #%lld: ",i);}



#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template<class T> using gpp_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template<class T, class L> using gpp_map = tree<T, L, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
signed main(){
    LL(w,h,m);
    VV(ll,a,m,4);
    gpp_set<ll>x,y;
    x.insert(0);
    y.insert(0);
    x.insert(w);
    y.insert(h);
    each(i,a){
        x.insert(i[0]);
        y.insert(i[1]);
        x.insert(i[2]);
        y.insert(i[3]);
    }
    ll X=x.size()-1,Y=y.size()-1;
    vv(ll,tate,X,Y-1);
    vv(ll,yoko,X-1,Y);
    each(i,a){
        i[0]=x.order_of_key(i[0]);
        i[1]=y.order_of_key(i[1]);
        i[2]=x.order_of_key(i[2]);
        i[3]=y.order_of_key(i[3]);
        if(i[0]==i[2]){
            rep(j,i[1],i[3])yoko[i[0]-1][j]=1;
        }
        if(i[1]==i[3]){
            rep(j,i[0],i[2])tate[j][i[1]-1]=1;
        }
    }
    LL(q);
    rep(_,q){
        vv(ll,cost,X,Y,LINF);
        vv(bool,visit,X,Y);
        VEC(ll,a,4);
        a[0]=x.order_of_key(a[0])-1;
        a[1]=y.order_of_key(a[1])-1;
        a[2]=x.order_of_key(a[2])-1;
        a[3]=y.order_of_key(a[3])-1;
        cost[a[0]][a[1]]=0;
        pq<tuplis>q;
        q.push({0,{a[0],a[1]}});
        while(q.size()){
            ll x,y;
            tie(x,y)=q.top().second;
            q.pop();
            if(visit[x][y])continue;
            visit[x][y]=1;
            if(x>0)if(chmin(cost[x-1][y],cost[x][y]+yoko[x-1][y]))q.push({cost[x-1][y],{x-1,y}});
            if(y>0)if(chmin(cost[x][y-1],cost[x][y]+tate[x][y-1]))q.push({cost[x][y-1],{x,y-1}});
            if(x+1<X)if(chmin(cost[x+1][y],cost[x][y]+yoko[x][y]))q.push({cost[x+1][y],{x+1,y}});
            if(y+1<Y)if(chmin(cost[x][y+1],cost[x][y]+tate[x][y]))q.push({cost[x][y+1],{x,y+1}});
        }
        out(cost[a[2]][a[3]]);
    }
}
accuracy: 0.42857142857142855
time_ms: 150
memory_kb: 3396
final_rank: 16

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll=long long;
using ld=long double;
using ull=unsigned long long;
using uint=unsigned int;
using pcc=pair<char,char>;
using pii=pair<int,int>;
using pll=pair<ll,ll>;
using pdd=pair<double,double>;
using tuplis=pair<ll,pll>;
using tuplis2=pair<pll,ll>;
template<class T> using pq=priority_queue<T,vector<T>,greater<T>>;
const ll LINF=0x1fffffffffffffff;
const ll MINF=0x7fffffffffff;
const int INF=0x3fffffff;
const ll MOD=1000000007;
const ll MODD=998244353;
const ld DINF=numeric_limits<ld>::infinity();
const ld EPS=1e-9;
const ld PI=3.141592653589793238462643383279;
const vector<ll>four{0,1,0,-1,0};
#define _overload4(_1,_2,_3,_4,name,...) name
#define _overload3(_1,_2,_3,name,...) name
#define _rep1(n) for(ll i=0;i<n;++i)
#define _rep2(i,n) for(ll i=0;i<n;++i)
#define _rep3(i,a,b) for(ll i=a;i<b;++i)
#define _rep4(i,a,b,c) for(ll i=a;i<b;i+=c)
#define rep(...) _overload4(__VA_ARGS__,_rep4,_rep3,_rep2,_rep1)(__VA_ARGS__)
#define _rrep1(n) for(ll i=(n)-1;i>=0;i--)
#define _rrep2(i,n) for(ll i=(n)-1;i>=0;i--)
#define _rrep3(i,a,b) for(ll i=(b)-1;i>=a;i--)
#define _rrep4(i,a,b,c) for(ll i=a+(b-a-1)/c*c;i>=a;i-=c)
#define rrep(...) _overload4(__VA_ARGS__,_rrep4,_rrep3,_rrep2,_rrep1)(__VA_ARGS__)
#define each(i,a) for(auto &i:a)
#define sum(...) accumulate(range(__VA_ARGS__),0LL)
#define dsum(...) accumulate(range(__VA_ARGS__),double(0))
#define _range(i) (i).begin(),(i).end()
#define _range2(i,k) (i).begin(),(i).begin()+k
#define _range3(i,a,b) (i).begin()+a,(i).begin()+b
#define range(...) _overload3(__VA_ARGS__,_range3,_range2,_range)(__VA_ARGS__)
#define _rrange(i) (i).rbegin(),(i).rend()
#define _rrange2(i,k) (i).rbegin(),(i).rbegin()+k
#define _rrange3(i,a,b) (i).rbegin()+a,(i).rbegin()+b
#define rrange(...) _overload3(__VA_ARGS__,_rrange3,_rrange2,_rrange)(__VA_ARGS__)
#define elif else if
#define unless(a) if(!(a))
#define mp make_pair
#define mt make_tuple
#define INT(...) int __VA_ARGS__;in(__VA_ARGS__)
#define LL(...) ll __VA_ARGS__;in(__VA_ARGS__)
#define ULL(...) ull __VA_ARGS__;in(__VA_ARGS__)
#define STR(...) string __VA_ARGS__;in(__VA_ARGS__)
#define CHR(...) char __VA_ARGS__;in(__VA_ARGS__)
#define DBL(...) double __VA_ARGS__;in(__VA_ARGS__)
#define vec(type,name,...) vector<type> name(__VA_ARGS__)
#define VEC(type,name,size) vector<type> name(size);in(name)
#define vv(type,name,h,...) vector<vector<type>>name(h,vector<type>(__VA_ARGS__))
#define VV(type,name,h,...) vector<vector<type>>name(h,vector<type>(__VA_ARGS__));in(name)
#define vvv(type,name,h,w,...) vector<vector<vector<type>>>name(h,vector<vector<type>>(w,vector<type>(__VA_ARGS__)))
inline constexpr ll gcd(ll a,ll b){if(!a||!b)return 0;while(b){ll c=b;b=a%b;a=c;}return a;}
inline constexpr ll lcm(ll a,ll b){if(!a||!b)return 0;return a*b/gcd(a,b);}
template<class T> inline constexpr T min(vector<T> &v){return *min_element(range(v));}
inline char min(string &v){return *min_element(range(v));}
template<class T> inline constexpr T max(vector<T> &v){return *max_element(range(v));}
inline char max(string &v){return *max_element(range(v));}
inline constexpr ll intpow(ll a,ll b){ll ans=1;for(ll i=1;b;i*=2){if(b&i){b^=i;ans*=a;}a*=a;}return ans;}
template<typename T>
inline constexpr bool chmin(T &mn,const T &cnt){if(mn>cnt){mn=cnt;return 1;}else return 0;}
template<typename T>
inline constexpr bool chmax(T &mx,const T &cnt){if(mx<cnt){mx=cnt;return 1;}else return 0;}
template<class T> unordered_map<T,ll> press(vector<T> &a){ auto b = a; sort(range(b)); b.erase(unique(range(b)), b.end()); unordered_map<T,ll> ans; rep(b.size()) ans[b[i]] = i; each(i, a) i = ans[i]; return ans; }
template<class T> map<T,ll> press_map(vector<T> &a){ auto b = a; sort(range(b)); b.erase(unique(range(b)), b.end()); map<T,ll> ans; rep(b.size()) ans[b[i]] = i; each(i, a) i = ans[i]; return ans; }
inline int scan(){ return getchar(); }
inline void scan(int &a){ scanf("%d", &a); }
inline void scan(unsigned &a){ scanf("%u", &a); }
inline void scan(long &a){ scanf("%ld", &a); }
inline void scan(long long &a){ scanf("%lld", &a); }
inline void scan(unsigned long long &a){ scanf("%llu", &a); }
inline void scan(char &a){ cin >> a; }
inline void scan(float &a){ scanf("%f", &a); }
inline void scan(double &a){ scanf("%lf", &a); }
inline void scan(long double &a){ scanf("%Lf", &a); }
inline void scan(vector<bool> &vec){ for(unsigned i = 0; i < vec.size(); i++) { int a; scan(a); vec[i] = a; } }
inline void scan(string &a){ cin >> a; }
template<class T> inline void scan(vector<T> &vec);
template<class T, size_t size> inline void scan(array<T, size> &vec);
template<class T, class L> inline void scan(pair<T, L> &p);
template<class T, size_t size> inline void scan(T (&vec)[size]);
template<class T> inline void scan(vector<T> &vec){ for(auto &i : vec) scan(i); }
template<class T, size_t size> inline void scan(array<T, size> &vec){ for(auto &i : vec) scan(i); }
template<class T, class L> inline void scan(pair<T, L> &p){ scan(p.first); scan(p.second); }
template<class T, size_t size> inline void scan(T (&vec)[size]){ for(auto &i : vec) scan(i); }
template<class T> inline void scan(T &a){ cin>>a; }
inline void in(){}
template <class Head, class... Tail> inline void in(Head &head, Tail&... tail){ scan(head); in(tail...); }
inline void print(){ putchar(' '); }
inline void print(const bool &a){ printf("%d", a); }
inline void print(const int &a){ printf("%d", a); }
inline void print(const unsigned &a){ printf("%u", a); }
inline void print(const long &a){ printf("%ld", a); }
inline void print(const long long &a){ printf("%lld", a); }
inline void print(const unsigned long long &a){ printf("%llu", a); }
inline void print(const char &a){ printf("%c", a); }
inline void print(const char a[]){ printf("%s", a); }
inline void print(const float &a){ printf("%.15f", a); }
inline void print(const double &a){ printf("%.15f", a); }
inline void print(const long double &a){ printf("%.15Lf", a); }
template<class T> void print(const vector<T> &vec);
template<class T, size_t size> void print(const array<T, size> &vec);
template<class T, class L> void print(const pair<T, L> &p);
template<class T, size_t size> inline void print(const T (&vec)[size]);
template<class T> void print(const vector<T> &vec){ if(vec.empty()) return; print(vec[0]); for(auto i = vec.begin(); ++i != vec.end(); ){ putchar(' '); print(*i); } }
template<class T, size_t size> void print(const array<T, size> &vec){ print(vec[0]); for(auto i = vec.begin(); ++i != vec.end(); ){ putchar(' '); print(*i); } }
template<class T, class L> void print(const pair<T, L> &p){ print(p.first); putchar(' '); print(p.second); }
template<class T, size_t size> inline void print(const T (&vec)[size]){ print(vec[0]); for(auto i = vec; ++i != end(vec); ){ putchar(' '); print(*i); } }
template<class T> inline void print(const T &a){ cout << a; }
inline int out(){ putchar('\n'); return 0; }
template<class T> inline int out(const T &t){ print(t); putchar('\n'); return 0; }
template<class Head, class... Tail> inline int out(const Head &head, const Tail&... tail){ print(head); putchar(' '); out(tail...); return 0; }
template <class T> inline void err(T t){cerr<<t<<'\n';}
inline void err(){cerr<<'\n';}
inline int first(const bool &i){return out(i?"first":"second");}
inline int yes(const bool &i){return out(i?"yes":"no");}
inline int Yes(const bool &i){return out(i?"Yes":"No");}
inline int YES(const bool &i){return out(i?"YES":"NO");}
inline int Yay(const bool &i){return out(i?"Yay!":":(");}
inline int Possible(const bool &i){return out(i?"Possible":"Impossible");}
inline int POSSIBLE(const bool &i){return out(i?"POSSIBLE":"IMPOSSIBLE");}
inline void Case(ll i){printf("Case #%lld: ",i);}




signed main(){
    LL(w,h,m);
    set<ll>x,y;
    x.insert(0);
    x.insert(w);
    y.insert(0);
    y.insert(h);
    vector<pair<pll,pll>>tate,yoko;
    rep(m){
        LL(a,b,c,d);
        x.insert(a);
        y.insert(b);
        x.insert(c);
        y.insert(d);
        (b==d?yoko:tate).push_back({{a,b},{c,d}});
    }
    map<ll,ll>px,py;
    ll cnt=0;
    each(i,x)px[i]=cnt++;
    cnt=0;
    each(i,y)py[i]=cnt++;
    each(i,tate){
        i.first.first=px[i.first.first];
        i.second.first=px[i.second.first];
        i.first.second=py[i.first.second];
        i.second.second=py[i.second.second];
    }
    each(i,yoko){
        i.first.first=px[i.first.first];
        i.second.first=px[i.second.first];
        i.first.second=py[i.first.second];
        i.second.second=py[i.second.second];
    }
    vv(ll,ctate,x.size(),y.size());
    vv(ll,cyoko,x.size(),y.size());
    each(i,tate)rep(j,i.first.second,i.second.second)cyoko[i.first.first-1][j]=1;
    each(i,yoko)rep(j,i.first.first,i.second.first)ctate[j][i.first.second-1]=1;
    LL(q);
    rep(q){
        LL(a,b,c,d);
        a=(--px.lower_bound(a))->second;
        b=(--py.lower_bound(b))->second;
        c=(--px.lower_bound(c))->second;
        d=(--py.lower_bound(d))->second;
        vv(ll,cost,x.size(),y.size(),LINF);
        vv(bool,visit,x.size(),y.size());
        cost[a][b]=0;
        pq<tuplis>q;
        q.push({0,{a,b}});
        while(q.size()){
            ll a,b;
            tie(a,b)=q.top().second;
            q.pop();
            if(visit[a][b])continue;
            visit[a][b]=1;
            if(a>0)if(chmin(cost[a-1][b],cost[a][b]+cyoko[a-1][b]))q.push({cost[a-1][b],{a-1,b}});
            if(a+2<x.size())if(chmin(cost[a+1][b],cost[a][b]+cyoko[a][b]))q.push({cost[a+1][b],{a+1,b}});
            if(b>0)if(chmin(cost[a][b-1],cost[a][b]+ctate[a][b-1]))q.push({cost[a][b-1],{a,b-1}});
            if(b+2<y.size())if(chmin(cost[a][b+1],cost[a][b]+ctate[a][b]))q.push({cost[a][b+1],{a,b+1}});
        }
        out(cost[c][d]);
    }
}
accuracy: 0.42857142857142855
time_ms: 150
memory_kb: 3556
final_rank: 18

code_snippet: #include <cstdio>
#include <cstdint>
#include <cassert>
#include <vector>
#include <algorithm>
#include <utility>
#include <string>
#include <map>
#include <queue>
#include <tuple>
#include <deque>

constexpr size_t m1 = -1;
constexpr size_t di[] = {m1, 0, 1, 0};
constexpr size_t dj[] = {0, m1, 0, 1};

void append(std::map<int, size_t>& m, int x) {
  m[x-1], m[x], m[x+1];
}

int neko(std::vector<std::string> const& s,
         size_t si, size_t sj, size_t gi, size_t gj) {

  size_t h = s.size();
  size_t w = s[0].length();

  using zahyo = std::pair<size_t, size_t>;
  int inf = 1e9;
  std::vector<std::vector<int>> dp(h, std::vector<int>(w, inf));
  dp[si][sj] = 0;
  std::deque<zahyo> q;
  q.emplace_front(si, sj);
  while (!q.empty()) {
    size_t i, j;
    std::tie(i, j) = q.front();
    q.pop_front();
    bool breakable = (s[i][j] == '.');
    for (int k = 0; k < 4; ++k) {
      size_t ni = i + di[k];
      size_t nj = j + dj[k];
      if (!(ni < h && nj < w)) continue;
      int cost = 0;
      if (s[ni][nj] == '#') {
        if (!breakable) continue;
        cost = 1;
      }
      if (dp[ni][nj] > dp[i][j] + cost) {
        dp[ni][nj] = dp[i][j] + cost;
        if (cost == 0) {
          q.emplace_front(ni, nj);
        } else {
          q.emplace_back(ni, nj);
        }
        if (ni == gi && nj == gj) {
          // for (size_t i = 0; i < h; ++i)
          //   for (size_t j = 0; j < w; ++j) {
          //     if (dp[i][j] == inf) fprintf(stderr, "##");
          //     else fprintf(stderr, "%2d", dp[i][j]);
          //     fprintf(stderr, "%c", j+1<w? ' ':'\n');
          //   }
          return dp[ni][nj];
        }
      }
    }
  }

  assert(false);
  // return dp[gi][gj];
}

int main() {
  size_t h, w, m;
  scanf("%zu %zu %zu", &w, &h, &m);

  std::map<int, size_t> xs, ys;
  std::vector<int> px(m), py(m), qx(m), qy(m);
  xs[0], xs[2*w], ys[0], ys[2*h];
  for (size_t i = 0; i < m; ++i) {
    scanf("%d %d %d %d", &px[i], &py[i], &qx[i], &qy[i]);
    if (px[i] > qx[i]) std::swap(px[i], qx[i]);
    if (py[i] > qy[i]) std::swap(py[i], qy[i]);
    px[i] *= 2;
    py[i] *= 2;
    qx[i] *= 2;
    qy[i] *= 2;
  }

  size_t q;
  scanf("%zu", &q);
  std::vector<int> sx(q), sy(q), gx(q), gy(q);
  for (size_t i = 0; i < q; ++i) {
    scanf("%d %d %d %d", &sx[i], &sy[i], &gx[i], &gy[i]);
    // if (sx[i] > gx[i]) std::swap(sx[i], gx[i]);
    // if (sy[i] > gy[i]) std::swap(sy[i], gy[i]);
    sx[i] *= 2;
    sy[i] *= 2;
    gx[i] *= 2;
    gy[i] *= 2;
  }

  for (auto const& x: px) append(xs, x);
  for (auto const& x: qx) append(xs, x);
  for (auto const& x: sx) append(xs, x);
  for (auto const& x: gx) append(xs, x);

  for (auto const& y: py) append(ys, y);
  for (auto const& y: qy) append(ys, y);
  for (auto const& y: sy) append(ys, y);
  for (auto const& y: gy) append(ys, y);

  {
    size_t i = 0;
    for (auto& p: xs) p.second = i++;
    // for (auto& p: xs) {
    //   fprintf(stderr, "x: %d -> %zu\n", p.first, p.second);
    // }
  }
  {
    size_t i = 0;
    for (auto& p: ys) p.second = i++;
    // for (auto& p: ys) {
    //   fprintf(stderr, "y: %d -> %zu\n", p.first, p.second);
    // }
  }

  size_t hh = ys.size();
  size_t ww = xs.size();
  std::vector<std::string> s(hh, std::string(ww, '.'));
  for (size_t i = 0; i < m; ++i) {
    size_t pi = ys.at(py[i]);
    size_t pj = xs.at(px[i]);
    size_t qi = ys.at(qy[i]);
    size_t qj = xs.at(qx[i]);
    for (size_t ii = pi; ii <= qi; ++ii)
      for (size_t jj = pj; jj <= qj; ++jj)
        s[ii][jj] = '#';
  }

  s[ys.at(0)] = s[ys.at(2*h)] = std::string(ww, '#');
  s[0] = s[hh-1] = std::string(ww, '#');
  for (size_t i = 0; i < hh; ++i) {
    s[i][xs.at(0)] = s[i][xs.at(2*w)] = '#';
    s[i][0] = s[i][ww-1] = '#';
  }

  // for (size_t i = 0; i < hh; ++i)
  //   fprintf(stderr, "%s\n", s[i].c_str());

  for (size_t i = 0; i < q; ++i) {
    int res = neko(s, ys.at(sy[i]), xs.at(sx[i]), ys.at(gy[i]), xs.at(gx[i]));
    printf("%d\n", res);
  }
}
accuracy: 1
time_ms: 760
memory_kb: 9728
final_rank: 15

code_snippet: #include <queue>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
	int W, H, N, Q;
	cin >> W >> H >> N;
	vector<int> cx = { 0, W }, cy = { 0, H };
	vector<int> ax(N), ay(N), bx(N), by(N);
	for (int i = 0; i < N; ++i) {
		cin >> ax[i] >> ay[i] >> bx[i] >> by[i];
		cx.push_back(ax[i]);
		cy.push_back(ay[i]);
		cx.push_back(bx[i]);
		cy.push_back(by[i]);
	}
	sort(cx.begin(), cx.end());
	cx.erase(unique(cx.begin(), cx.end()), cx.end());
	sort(cy.begin(), cy.end());
	cy.erase(unique(cy.begin(), cy.end()), cy.end());
	W = cx.size() - 1;
	H = cy.size() - 1;
	vector<vector<bool> > vertline(W + 1, vector<bool>(H)), horzline(W, vector<bool>(W + 1));
	for (int i = 0; i < N; ++i) {
		ax[i] = lower_bound(cx.begin(), cx.end(), ax[i]) - cx.begin();
		ay[i] = lower_bound(cy.begin(), cy.end(), ay[i]) - cy.begin();
		bx[i] = lower_bound(cx.begin(), cx.end(), bx[i]) - cx.begin();
		by[i] = lower_bound(cy.begin(), cy.end(), by[i]) - cy.begin();
		if (ax[i] > bx[i]) swap(ax[i], bx[i]);
		if (ay[i] > by[i]) swap(ay[i], by[i]);
		if (ax[i] == bx[i]) {
			for (int j = ay[i]; j < by[i]; ++j) {
				horzline[ax[i]][j] = true;
			}
		}
		if (ay[i] == by[i]) {
			for (int j = ax[i]; j < bx[i]; ++j) {
				vertline[j][ay[i]] = true;
			}
		}
	}
	cin >> Q;
	while (Q--) {
		int sx, sy, gx, gy;
		cin >> sx >> sy >> gx >> gy;
		sx = lower_bound(cx.begin(), cx.end(), sx) - cx.begin() - 1;
		sy = lower_bound(cy.begin(), cy.end(), sy) - cy.begin() - 1;
		gx = lower_bound(cx.begin(), cx.end(), gx) - cx.begin() - 1;
		gy = lower_bound(cy.begin(), cy.end(), gy) - cy.begin() - 1;
		vector<vector<int> > d(W, vector<int>(H, -1));
		d[sx][sy] = 0;
		deque<pair<int, int> > que;
		que.push_back(make_pair(sx, sy));
		while (!que.empty()) {
			pair<int, int> u = que.front(); que.pop_front();
			int cur = d[u.first][u.second];
			if (u.first >= 1 && (d[u.first - 1][u.second] == -1 || d[u.first - 1][u.second] == cur + 1)) {
				if (horzline[u.first][u.second] && d[u.first - 1][u.second] == -1) {
					d[u.first - 1][u.second] = cur + 1;
					que.push_back(make_pair(u.first - 1, u.second));
				}
				if (!horzline[u.first][u.second]) {
					d[u.first - 1][u.second] = cur;
					que.push_front(make_pair(u.first - 1, u.second));
				}
			}
			if (u.first < W - 1 && (d[u.first + 1][u.second] == -1 || d[u.first + 1][u.second] == cur + 1)) {
				if (horzline[u.first + 1][u.second] && d[u.first + 1][u.second] == -1) {
					d[u.first + 1][u.second] = cur + 1;
					que.push_back(make_pair(u.first + 1, u.second));
				}
				if (!horzline[u.first + 1][u.second]) {
					d[u.first + 1][u.second] = cur;
					que.push_front(make_pair(u.first + 1, u.second));
				}
			}
			if (u.second >= 1 && (d[u.first][u.second - 1] == -1 || d[u.first][u.second - 1] == cur + 1)) {
				if (vertline[u.first][u.second] && d[u.first][u.second - 1] == -1) {
					d[u.first][u.second - 1] = cur + 1;
					que.push_back(make_pair(u.first, u.second - 1));
				}
				if (!vertline[u.first][u.second]) {
					d[u.first][u.second - 1] = cur;
					que.push_front(make_pair(u.first, u.second - 1));
				}
			}
			if (u.second < H - 1 && (d[u.first][u.second + 1] == -1 || d[u.first][u.second + 1] == cur + 1)) {
				if (vertline[u.first][u.second + 1] && d[u.first][u.second + 1] == -1) {
					d[u.first][u.second + 1] = cur + 1;
					que.push_back(make_pair(u.first, u.second + 1));
				}
				if (!vertline[u.first][u.second + 1]) {
					d[u.first][u.second + 1] = cur;
					que.push_front(make_pair(u.first, u.second + 1));
				}
			}
		}
		cout << d[gx][gy] << endl;
	}
	return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 3280
final_rank: 1

code_snippet: #include<bits/stdc++.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;


struct Info{
	void set(int arg_row1,int arg_row2,int arg_col1,int arg_col2){
		row1 = arg_row1;
		row2 = arg_row2;
		col1 = arg_col1;
		col2 = arg_col2;
	}
	int row1,row2,col1,col2;
};

struct Data{
	bool right_wall,under_wall;
};

struct State{
	State(int arg_row,int arg_col,int arg_sum_cost){
		row = arg_row;
		col = arg_col;
		sum_cost = arg_sum_cost;
	}
	bool operator<(const struct State &arg) const{ //壁を越えた回数の昇順(PQ)
		return sum_cost > arg.sum_cost;
	}

	int row,col,sum_cost;
};

int comp_H,comp_W; //座標圧縮後の高さと幅
int diff_row[4] = {-1,0,0,1},diff_col[4] = {0,-1,1,0};
int min_cost[500][500];
Info wall[100],query[100];
Data table[500][500];

bool rangeCheck(int row,int col){
	if(row >= 2 && row <= comp_H-2 && col >= 2 && col <= comp_W-2)return true;
	else{
		return false;
	}
}

int main(){

	int W,H,M;
	scanf("%d %d %d",&W,&H,&M);

	vector<int> ROW,COL;

	/*★外枠に注意!!★*/
	ROW.push_back(0);
	ROW.push_back(H);
	ROW.push_back(-BIG_NUM);
	ROW.push_back(BIG_NUM);

	COL.push_back(0);
	COL.push_back(W);
	COL.push_back(-BIG_NUM);
	COL.push_back(BIG_NUM);

	int row1,row2,col1,col2;
	for(int i = 0; i < M; i++){

		scanf("%d %d %d %d",&col1,&row1,&col2,&row2);

		if(row1 > row2)swap(row1,row2);
		if(col1 > col2)swap(col1,col2);

		wall[i].set(row1,row2,col1,col2);

		ROW.push_back(row1);
		ROW.push_back(row2);
		COL.push_back(col1);
		COL.push_back(col2);
	}

	int num_query;
	scanf("%d",&num_query);

	for(int i = 0; i < num_query; i++){
		scanf("%d %d %d %d",&query[i].col1,&query[i].row1,&query[i].col2,&query[i].row2);

		ROW.push_back(query[i].row1);
		ROW.push_back(query[i].row2);
		COL.push_back(query[i].col1);
		COL.push_back(query[i].col2);
	}

	sort(ROW.begin(),ROW.end());
	sort(COL.begin(),COL.end());

	ROW.erase(unique(ROW.begin(),ROW.end()),ROW.end());
	COL.erase(unique(COL.begin(),COL.end()),COL.end());

	map<int,int> INDEX_ROW,INDEX_COL;
	for(int i = 0; i < ROW.size(); i++){
		INDEX_ROW[ROW[i]] = i;
	}

	for(int i = 0; i < COL.size(); i++){
		INDEX_COL[COL[i]] = i;
	}

	//座標変換
	for(int i = 0; i < M; i++){
		wall[i].row1 = INDEX_ROW[wall[i].row1];
		wall[i].row2 = INDEX_ROW[wall[i].row2];
		wall[i].col1 = INDEX_COL[wall[i].col1];
		wall[i].col2 = INDEX_COL[wall[i].col2];
	}

	for(int i = 0; i < num_query; i++){
		query[i].row1 = INDEX_ROW[query[i].row1];
		query[i].row2 = INDEX_ROW[query[i].row2];
		query[i].col1 = INDEX_COL[query[i].col1];
		query[i].col2 = INDEX_COL[query[i].col2];
	}

	comp_H = ROW.size(),comp_W = COL.size();

	for(int row = 0; row < comp_H;row++){
		for(int col = 0; col < comp_W; col++){
			table[row][col].right_wall = false;
			table[row][col].under_wall = false;
		}
	}

	//外壁の情報を設定

	//上
	for(int col = 0; col < comp_W; col++){
		table[1][col].under_wall = true;
	}

	//左
	for(int row = 0; row < comp_H; row++){
		table[row][1].right_wall = true;
	}

	//下
	for(int col = 0; col < comp_W; col++){
		table[comp_H-2][col].under_wall = true;
	}

	//右
	for(int row = 0; row < comp_H; row++){
		table[row][comp_W-2].right_wall = true;
	}

	for(int i = 0; i < M; i++){
		if(wall[i].row1 == wall[i].row2){ //横線

			for(int col = wall[i].col1+1; col <= wall[i].col2; col++){
				table[wall[i].row1][col].under_wall = true;
			}
		}else{ //縦線

			for(int row = wall[i].row1+1; row <= wall[i].row2; row++){
				table[row][wall[i].col1].right_wall = true;
			}
		}
	}

	priority_queue<State> Q;
	int adj_row,adj_col,next_cost,add_cost;

	for(int i = 0; i < num_query; i++){
		for(int row = 0; row < comp_H; row++){
			for(int col = 0; col < comp_W; col++)min_cost[row][col] = BIG_NUM;
		}

		while(!Q.empty())Q.pop();

		min_cost[query[i].row1][query[i].col1] = 0;
		Q.push(State(query[i].row1,query[i].col1,0));

		while(!Q.empty()){
			if(Q.top().row == query[i].row2 && Q.top().col == query[i].col2){
				printf("%d\n",Q.top().sum_cost);
				break;
			}else if(Q.top().sum_cost > min_cost[Q.top().row][Q.top().col]){
				Q.pop();
			}else{

				for(int i = 0; i < 4; i++){
					adj_row = Q.top().row+diff_row[i];
					adj_col = Q.top().col+diff_col[i];

					if(!rangeCheck(adj_row,adj_col))continue;

					add_cost = 0;
					switch(i){
					case 0: //上
						if(table[adj_row][adj_col].under_wall)add_cost++;
						break;
					case 1: //左
						if(table[adj_row][adj_col].right_wall)add_cost++;
						break;
					case 2: //右
						if(table[Q.top().row][Q.top().col].right_wall)add_cost++;
						break;
					case 3: //下
						if(table[Q.top().row][Q.top().col].under_wall)add_cost++;
						break;
					}

					next_cost = Q.top().sum_cost+add_cost;
					if(min_cost[adj_row][adj_col] > next_cost){
						min_cost[adj_row][adj_col] = next_cost;
						Q.push(State(adj_row,adj_col,next_cost));
					}
				}
				Q.pop();
			}
		}
	}

	return 0;
}
accuracy: 1
time_ms: 370
memory_kb: 4416
final_rank: 9

code_snippet: #include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <queue>
using namespace std;

int H, W, N, Q, px[109], py[109], qx[109], qy[109], sx[109], sy[109], gx[109], gy[109], dist[10009];
vector<int>X, Y; bool wall[1009][1009]; int col[1009][1009], cntw; vector<int>G[10009]; map<pair<int, int>, int>M;

void dfs(int cx, int cy) {
	col[cx][cy] = cntw;
	int dx[4] = { -1,0,1,0 }, dy[4] = { 0,1,0,-1 };
	for (int i = 0; i < 4; i++) {
		int fx = cx + dx[i], fy = cy + dy[i];
		if (fx < 0 || fy < 0 || fx >= X.size() || fy >= Y.size() || wall[fx][fy] == true || col[fx][fy] >= 1) continue;
		dfs(fx, fy);
	}
}
int solve(int cx, int cy) {
	for (int i = 0; i < 10009; i++)dist[i] = 9999999;
	queue<int>q; q.push(cx); dist[cx] = 0;
	while (!q.empty()) {
		int to1 = q.front(); q.pop();
		for (int i : G[to1]) {
			if (dist[i] > dist[to1] + 1) {
				dist[i] = dist[to1] + 1; q.push(i);
			}
		}
	}
	return dist[cy];
}

int main() {
	cin >> H >> W >> N;
	for (int i = 1; i <= N; i++) cin >> px[i] >> py[i] >> qx[i] >> qy[i];
	cin >> Q;
	for (int i = 1; i <= Q; i++) cin >> sx[i] >> sy[i] >> gx[i] >> gy[i];
	for (int i = 1; i <= N; i++) {
		px[i] *= 2; py[i] *= 2; qx[i] *= 2; qy[i] *= 2;
		if (px[i] > qx[i]) swap(px[i], qx[i]); if (py[i] > qy[i]) swap(py[i], qy[i]);
		if (px[i] >= 1) X.push_back(px[i] - 1); X.push_back(px[i]); if (px[i] < H * 2) X.push_back(px[i] + 1);
		if (qx[i] >= 1) X.push_back(qx[i] - 1); X.push_back(qx[i]); if (qx[i] < H * 2) X.push_back(qx[i] + 1);
		if (py[i] >= 1) Y.push_back(py[i] - 1); Y.push_back(py[i]); if (py[i] < W * 2) Y.push_back(py[i] + 1);
		if (py[i] >= 1) Y.push_back(qy[i] - 1); Y.push_back(qy[i]); if (qy[i] < W * 2) Y.push_back(qy[i] + 1);
	}
	for (int i = 1; i <= Q; i++) {
		sx[i] *= 2; sy[i] *= 2; gx[i] *= 2; gy[i] *= 2;
		X.push_back(sx[i]); Y.push_back(sy[i]);
		X.push_back(gx[i]); Y.push_back(gy[i]);
	}
	X.push_back(0); Y.push_back(0); X.push_back(H * 2); Y.push_back(W * 2);
	sort(X.begin(), X.end()); X.erase(unique(X.begin(), X.end()), X.end());
	sort(Y.begin(), Y.end()); Y.erase(unique(Y.begin(), Y.end()), Y.end());
	for (int i = 1; i <= N; i++) {
		px[i] = lower_bound(X.begin(), X.end(), px[i]) - X.begin();
		qx[i] = lower_bound(X.begin(), X.end(), qx[i]) - X.begin();
		py[i] = lower_bound(Y.begin(), Y.end(), py[i]) - Y.begin();
		qy[i] = lower_bound(Y.begin(), Y.end(), qy[i]) - Y.begin();
		if (px[i] == qx[i]) {
			for (int j = py[i]; j <= qy[i]; j++) wall[px[i]][j] = true;
		}
		if (py[i] == qy[i]) {
			for (int j = px[i]; j <= qx[i]; j++) wall[j][py[i]] = true;
		}
	}
	for (int i = 0; i < Y.size(); i++) wall[0][i] = true;
	for (int i = 0; i < Y.size(); i++) wall[X.size() - 1][i] = true;
	for (int i = 0; i < X.size(); i++) wall[i][0] = true;
	for (int i = 0; i < X.size(); i++) wall[i][Y.size() - 1] = true;
	for (int i = 1; i <= Q; i++) {
		sx[i] = lower_bound(X.begin(), X.end(), sx[i]) - X.begin();
		gx[i] = lower_bound(X.begin(), X.end(), gx[i]) - X.begin();
		sy[i] = lower_bound(Y.begin(), Y.end(), sy[i]) - Y.begin();
		gy[i] = lower_bound(Y.begin(), Y.end(), gy[i]) - Y.begin();
	}
	for (int i = 0; i < X.size(); i++) {
		for (int j = 0; j < Y.size(); j++) {
			if (wall[i][j] == true || col[i][j] >= 1) continue;
			cntw++; dfs(i, j);
		}
	}
	for (int i = 0; i < (int)X.size(); i++) {
		for (int j = 0; j < (int)Y.size() - 2; j++) {
			if (wall[i][j] == false && wall[i][j + 1] == true && wall[i][j + 2] == false && col[i][j] != col[i][j + 2]) {
				int d1 = col[i][j], d2 = col[i][j + 2];
				if (M[make_pair(d1, d2)] == 1) continue;
				M[make_pair(d1, d2)] = 1; G[d1].push_back(d2);
				M[make_pair(d2, d1)] = 1; G[d2].push_back(d1);
			}
		}
	}
	for (int i = 0; i < (int)Y.size(); i++) {
		for (int j = 0; j < (int)X.size() - 2; j++) {
			if (wall[j][i] == false && wall[j + 1][i] == true && wall[j + 2][i] == false && col[j][i] != col[j + 2][i]) {
				int d1 = col[j][i], d2 = col[j + 2][i];
				if (M[make_pair(d1, d2)] == 1) continue;
				M[make_pair(d1, d2)] = 1; G[d1].push_back(d2);
				M[make_pair(d2, d1)] = 1; G[d2].push_back(d1);
			}
		}
	}
	/*for (int i = 0; i < X.size(); i++) {
		for (int j = 0; j < Y.size(); j++) cout << (int)wall[i][j] << " "; cout << endl;
	}
	cout << endl;
	for (int i = 0; i < X.size(); i++) {
		for (int j = 0; j < Y.size(); j++) cout << col[i][j] << " "; cout << endl;
	}*/
	for (int i = 1; i <= Q; i++) {
		cout << solve(col[sx[i]][sy[i]], col[gx[i]][gy[i]]) << endl;
	}
	return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 11560
final_rank: 10

code_snippet: #include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#define mp make_pair
#define int long long
#define INF 1e+9
using namespace std;

typedef pair<int,int> POS;
typedef pair<int,POS> P;
int dx[] = {0,1,0,-1},dy[] = {-1,0,1,0};

signed main(){
	int w,h,m,q,px[100],py[100],qx[100],qy[100];
	bool ng[210][210][4] = {};
	vector<int> xs,ys;
	cin >> w >> h >> m;
	for(int i = 0;i < m;i++){
		cin >> px[i] >> py[i] >> qx[i] >> qy[i];
		if(px[i] > qx[i]) swap(px[i],qx[i]);
		if(py[i] > qy[i]) swap(py[i],qy[i]);
		xs.push_back(px[i]);
		ys.push_back(py[i]);
		xs.push_back(qx[i]);
		ys.push_back(qy[i]);
	}
	xs.push_back(0);
	xs.push_back(w);
	ys.push_back(0);
	ys.push_back(h);
	sort(xs.begin(),xs.end());
	sort(ys.begin(),ys.end());
	xs.erase(unique(xs.begin(),xs.end()),xs.end());
	ys.erase(unique(ys.begin(),ys.end()),ys.end());
	for(int i = 0;i < xs.size() - 1;i++){
		for(int j = 0;j < ys.size() - 1;j++){
			for(int k = 0;k < m;k++){
				if(px[k] <= xs[i] && xs[i + 1] <= qx[k]){
					if(ys[j] == py[k]) ng[i][j][0] = true;
					else if(ys[j + 1] == py[k]) ng[i][j][2] = true;
				}else if(py[k] <= ys[j] && ys[j + 1] <= qy[k]){
					if(xs[i] == px[k]) ng[i][j][3] = true;
					else if(xs[i + 1] == px[k]) ng[i][j][1] = true;
				}
			}
		}
	}
	cin >> q;
	for(int i = 0;i < q;i++){
		int sx,sy,gx,gy,x1,y1,x2,y2,d[210][210];
		cin >> sx >> sy >> gx >> gy;
		for(int j = 0;j <= 200;j++){
			for(int k = 0;k <= 200;k++) d[j][k] = INF;
		}
		for(int j = 0;j < xs.size() - 1;j++){
			if(xs[j] <= sx && sx <= xs[j + 1]) x1 = j;
			if(xs[j] <= gx && gx <= xs[j + 1]) x2 = j;
		}
		for(int j = 0;j < ys.size() - 1;j++){
			if(ys[j] <= sy && sy <= ys[j + 1]) y1 = j;
			if(ys[j] <= gy && gy <= ys[j + 1]) y2 = j;
		}
		priority_queue<P,vector<P>,greater<P> > que;
		que.push(mp(0,mp(x1,y1)));
		d[x1][y1] = 0;
		while(!que.empty()){
			P p = que.top();que.pop();
			int x = p.second.first,y = p.second.second;
			for(int j = 0;j < 4;j++){
				int nx = x + dx[j],ny = y + dy[j];
				if(nx >= 0 && nx < xs.size() - 1 && ny >= 0 && ny < ys.size() - 1 && d[nx][ny] > d[x][y] + ng[x][y][j]){
					d[nx][ny] = d[x][y] + ng[x][y][j];
					que.push(mp(d[nx][ny],mp(nx,ny)));
				}
			}
		}
		cout << d[x2][y2] << endl;
	}
}
accuracy: 1
time_ms: 170
memory_kb: 3760
final_rank: 6

code_snippet: #include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#define mp make_pair
#define int long long
#define INF 1e+9
using namespace std;

typedef pair<int,int> POS;
typedef pair<int,POS> P;
int dx[] = {0,1,0,-1},dy[] = {-1,0,1,0};

signed main(){
	int w,h,m,q,px[100],py[100],qx[100],qy[100];
	bool ng[200][200][4] = {};
	vector<int> xs,ys;
	cin >> w >> h >> m;
	for(int i = 0;i < m;i++){
		cin >> px[i] >> py[i] >> qx[i] >> qy[i];
		if(px[i] > qx[i]) swap(px[i],qx[i]);
		if(py[i] > qy[i]) swap(py[i],qy[i]);
		xs.push_back(px[i]);
		ys.push_back(py[i]);
		xs.push_back(qx[i]);
		ys.push_back(qy[i]);
	}
	xs.push_back(0);
	xs.push_back(w);
	ys.push_back(0);
	ys.push_back(h);
	sort(xs.begin(),xs.end());
	sort(ys.begin(),ys.end());
	xs.erase(unique(xs.begin(),xs.end()),xs.end());
	ys.erase(unique(ys.begin(),ys.end()),ys.end());
	for(int i = 0;i < xs.size() - 1;i++){
		for(int j = 0;j < ys.size() - 1;j++){
			for(int k = 0;k < m;k++){
				if(px[k] <= xs[i] && xs[i + 1] <= qx[k]){
					if(ys[j] == py[k]) ng[i][j][0] = true;
					else if(ys[j + 1] == py[k]) ng[i][j][2] = true;
				}else if(py[k] <= ys[j] && ys[j + 1] <= qy[k]){
					if(xs[i] == px[k]) ng[i][j][3] = true;
					else if(xs[i + 1] == px[k]) ng[i][j][1] = true;
				}
			}
		}
	}
	cin >> q;
	for(int i = 0;i < q;i++){
		int sx,sy,gx,gy,x1,y1,x2,y2,d[110][110];
		cin >> sx >> sy >> gx >> gy;
		for(int j = 0;j < xs.size();j++){
			for(int k = 0;k < ys.size();k++) d[j][k] = INF;
		}
		for(int j = 0;j < xs.size() - 1;j++){
			if(xs[j] <= sx && sx <= xs[j + 1]) x1 = j;
			if(xs[j] <= gx && gx <= xs[j + 1]) x2 = j;
		}
		for(int j = 0;j < ys.size() - 1;j++){
			if(ys[j] <= sy && sy <= ys[j + 1]) y1 = j;
			if(ys[j] <= gy && gy <= ys[j + 1]) y2 = j;
		}
		priority_queue<P,vector<P>,greater<P> > que;
		que.push(mp(0,mp(x1,y1)));
		d[x1][y1] = 0;
		while(!que.empty()){
			P p = que.top();que.pop();
			int x = p.second.first,y = p.second.second;
			for(int j = 0;j < 4;j++){
				int nx = x + dx[j],ny = y + dy[j];
				if(nx >= 0 && nx < xs.size() - 1 && ny >= 0 && ny < ys.size() - 1 && d[nx][ny] > d[x][y] + ng[x][y][j]){
					d[nx][ny] = d[x][y] + ng[x][y][j];
					que.push(mp(d[nx][ny],mp(nx,ny)));
				}
			}
		}
		cout << d[x2][y2] << endl;
	}
}
accuracy: 0.42857142857142855
time_ms: 150
memory_kb: 3412
final_rank: 17

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define REP(i,a) FOR(i,0,a)
typedef vector<int> vec;
typedef pair<int,int> P;
int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1};
const int MAX_M=100,MAX_Q=100,MAX_V=MAX_M*6;
int W,H,M,Q;
int px[MAX_M],py[MAX_M],qx[MAX_M],qy[MAX_M];
int sx[MAX_Q],sy[MAX_Q],gx[MAX_Q],gy[MAX_Q];

bool grid[(MAX_M+MAX_Q)*6][(MAX_M+MAX_Q)*6];
int grid2[(MAX_M+MAX_Q)*6][(MAX_M+MAX_Q)*6];

int V;
int G[MAX_V][MAX_V];
int dist[MAX_V];

void compress(int *x1,int *x2,int *x3,int *x4,int &w){
    vec v;
    REP(i,M){
        REP(j,3){
            int x=*(x1+i)+j-1;
            if (x>=0 && x<=w){
                v.push_back(x);
            }
            x=*(x2+i)+j-1;
            if (x>=0 && x<=w){
                v.push_back(x);
            }
        }
    }
    REP(i,Q){
        v.push_back(*(x3+i));
        v.push_back(*(x4+i));
    }
    sort(v.begin(),v.end());
    v.erase(unique(v.begin(),v.end()),v.end());
    REP(i,M){
        *(x1+i)=find(v.begin(),v.end(),*(x1+i))-v.begin();
        *(x2+i)=find(v.begin(),v.end(),*(x2+i))-v.begin();
    }
    REP(i,Q){
        *(x3+i)=find(v.begin(),v.end(),*(x3+i))-v.begin();
        *(x4+i)=find(v.begin(),v.end(),*(x4+i))-v.begin();
    }
    w=v.size();
}

void bfs(int s){
    queue<int> q;
    memset(dist,-1,sizeof(dist));
    dist[s]=0;
    q.push(s);
    while(!q.empty()){
        int v=q.front();
        q.pop();
        REP(i,V){
            if (G[v][i] && dist[i]==-1){
                dist[i]=dist[v]+1;
                q.push(i);
            }
        }
    }
}

void bfs2(int x,int y){
    queue<P> q;
    q.push(P(x,y));
    grid2[x][y]=V;
    while(!q.empty()){
        P p=q.front();
        q.pop();
        REP(i,4){
            int x2=p.first+dx[i],y2=p.second+dy[i];
            if (x2<0 || x2>=W || y2<0 || y2>=H) continue;
            if (!grid[x2][y2] && grid2[x2][y2]==-1){
                grid2[x2][y2]=V;
                q.push(P(x2,y2));
            }
        }
    }
}

int main(){
    scanf("%d %d %d",&W,&H,&M);
    W*=2;
    H*=2;
    REP(i,M){
        scanf("%d %d %d %d",&px[i],&py[i],&qx[i],&qy[i]);
        if (px[i]>qx[i]){
            swap(px[i],qx[i]);
        }
        if (py[i]>qy[i]){
            swap(py[i],qy[i]);
        }
        px[i]*=2;
        py[i]*=2;
        qx[i]*=2;
        qy[i]*=2;
    }
    scanf("%d",&Q);
    REP(i,Q){
        scanf("%d %d %d %d",&sx[i],&sy[i],&gx[i],&gy[i]);
        sx[i]*=2;
        sy[i]*=2;
        gx[i]*=2;
        gy[i]*=2;
    }
    compress(px,qx,sx,gx,W);
    compress(py,qy,sy,gy,H);
    REP(i,M){
        FOR(j,px[i],qx[i]+1){
            FOR(k,py[i],qy[i]+1){
                grid[j][k]=true;
            }
        }
    }
    memset(grid2,-1,sizeof(grid2));
    REP(x,W){
        REP(y,H){
            if (!grid[x][y] && grid2[x][y]==-1){
                bfs2(x,y);
                V++;
            }
        }
    }
    REP(x,W){
        REP(y,H){
            if (grid[x][y]){
                int x2,y2,x3,y3;
                int v,u;
                x2=x-1;
                x3=x+1;
                if (x2>=0 && x3<W && !grid[x2][y] && !grid[x3][y]){
                    v=grid2[x2][y];
                    u=grid2[x3][y];
                    G[v][u]=G[u][v]=1;
                }
                y2=y-1;
                y3=y+1;
                if (y2>=0 && y3<H && !grid[x][y2] && !grid[x][y3]){
                    v=grid2[x][y2];
                    u=grid2[x][y3];
                    G[v][u]=G[u][v]=1;
                }
            }
        }
    }
    REP(i,Q){
        bfs(grid2[sx[i]][sy[i]]);
        printf("%d\n",dist[grid2[gx[i]][gy[i]]]);
    }
    return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 10352
final_rank: 7

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> P;
#define pb push_back
#define fi first
#define sc second
typedef long long int ll;
ll W,H;
int M;
ll px[114];ll py[114];ll qx[114];ll qy[114];
vector<ll> x,y;
int Q;
int grid[701][701];
int s[500001];
int dx[4]={-1,0,0,1};
int dy[4]={0,-1,1,0};
int sx1,sy1,gx1,gy1;
int WW,HH;
vector<int>G[500001];
map<P,int> MAP;
/*
int dfs(int x1,int y1){
	f[x1][y1]=true;
	for(int k=0;k<4;k++){
		if(x1+dx[k]>=0&&x1+dx[k]<WW&&y1+dy[k]>=0&&y1+dy[k]<HH){
			if(!f[x1+dx[k]][y1+dy[k]])s[x1+dx[k]][y1+dy[k]]=min(s[x1][y1],dfs(x1+dx[k],y1+dy[k]));
		}
	}
	if(grid[x1][y1])s[x1][y1]++;
	printf("%d %d %d\n",x1,y1,s[x1][y1]);
	return s[x1][y1];
}*/
int main()
{
	scanf("%lld%lld%d",&W,&H,&M);W*=10;H*=10;
	x.pb(0);x.pb(W);
	y.pb(0);y.pb(H);
	for(int i=0;i<M;i++){
		scanf("%lld%lld%lld%lld",&px[i],&py[i],&qx[i],&qy[i]);
		px[i]*=10;py[i]*=10;qx[i]*=10;qy[i]*=10;
		if(px[i]!=0){
			x.pb(px[i]-1);
		}
		x.pb(px[i]);
		if(px[i]!=W){
			x.pb(px[i]+1);
		}
		
		if(qx[i]!=0){
			x.pb(qx[i]-1);
		}
		x.pb(qx[i]);
		if(qx[i]!=W){
			x.pb(qx[i]+1);
		}
		
		if(py[i]!=0){
			y.pb(py[i]-1);
		}
		y.pb(py[i]);
		if(py[i]!=H){
			y.pb(py[i]+1);
		}
		
		if(qy[i]!=0){
			y.pb(qy[i]-1);
		}
		y.pb(qy[i]);
		if(qy[i]!=H){
			y.pb(qy[i]+1);
		}
		
	}
	sort(x.begin(),x.end());
	sort(y.begin(),y.end());
	x.erase(unique(x.begin(),x.end()),x.end());
	y.erase(unique(y.begin(),y.end()),y.end());
	
	WW=(int)x.size();HH=(int)y.size();
	for(int i=0;i<M;i++){
		int ax=lower_bound(x.begin(),x.end(),px[i])-x.begin();
		int bx=lower_bound(x.begin(),x.end(),qx[i])-x.begin();
		int ay=lower_bound(y.begin(),y.end(),py[i])-y.begin();
		int by=lower_bound(y.begin(),y.end(),qy[i])-y.begin();
		if(ax>=bx)swap(ax,bx);
		if(ay>=by)swap(ay,by);
		for(int j=ax;j<=bx;j++){
			for(int k=ay;k<=by;k++){
				grid[j][k]=-1;
			}
		}
	}
	
	int index=1;
	for(int i=0;i<WW;i++){
		for(int j=0;j<HH;j++){
			if(grid[i][j]==0){
				queue<P> que;
				que.push(P(i,j));
				while(!que.empty()){
					P p=que.front();que.pop();
					if(grid[p.fi][p.sc]==index)continue;
					grid[p.fi][p.sc]=index;
					for(int k=0;k<4;k++){
						if(p.fi+dx[k]>=0&&p.fi+dx[k]<WW&&p.sc+dy[k]>=0&&p.sc+dy[k]<HH){
							if(grid[p.fi+dx[k]][p.sc+dy[k]]==0){
								que.push(P(p.fi+dx[k],p.sc+dy[k]));
							}
						}
					}
				}
				index++;
			}
		}
	}
	/*
	for(int i=0;i<HH;i++){
		for(int j=0;j<WW;j++){
			printf("%d ",grid[j][i]);
		}
		printf("\n");
	}*/
	
	for(int i=0;i<WW;i++){
		for(int j=0;j<HH;j++){
			if(grid[i][j]==-1){
				for(int k=0;k<4;k++){
					if(i+dx[k]>=0&&i-dx[k]>=0&&i+dx[k]<WW&&i-dx[k]<WW){
						if(j+dy[k]>=0&&j-dy[k]>=0&&j+dy[k]<HH&&j-dy[k]<HH){
							//printf("%d %d\n",i,j);
							int g1=grid[i+dx[k]][j+dy[k]];
							int g2=grid[i-dx[k]][j-dy[k]];
							if(g1!=-1&&g2!=-1&&MAP[P(g1,g2)]==0&&g1!=g2){
								G[g1-1].pb(g2-1);
								G[g2-1].pb(g1-1);
								MAP[P(g1,g2)]=1;
								MAP[P(g2,g1)]=1;
								//printf("%d %d\n",g1,g2);
							}
						}
					}
				}
			}
		}
	}
	
	scanf("%d",&Q);
	for(int i=0;i<Q;i++){
		for(int j=0;j<WW;j++){
			for(int k=0;k<HH;k++){
				s[j*HH+k]=2*(WW+HH)+1;
				//ds[j][k]=2*(WW+HH)+1;
				//f[j][k]=false;
			}
		}
		ll sx,sy,gx,gy;
		scanf("%lld%lld%lld%lld",&sx,&sy,&gx,&gy);
		sx*=10;sy*=10;gx*=10;gy*=10;
		
		sx1=lower_bound(x.begin(),x.end(),sx)-x.begin();
		gx1=lower_bound(x.begin(),x.end(),gx)-x.begin();
		sy1=lower_bound(y.begin(),y.end(),sy)-y.begin();
		gy1=lower_bound(y.begin(),y.end(),gy)-y.begin();
		
		//printf("%d:%d-%d:%d\n",sx1,sy1,gx1,gy1);
		int ss=grid[sx1][sy1]-1;
		int gg=grid[gx1][gy1]-1;
		priority_queue<P,vector<P>,greater<P> > que;
		que.push(make_pair(0,ss));
		//printf("%d %d\n",ss,gg);
		//printf("%d %d\n",sx1,sy1);
		//int n=0;
		
		while(!que.empty()){
			P p=que.top();que.pop();
			if(p.fi>=s[p.sc])continue;
			//printf("%d %d\n",p.sc.fi,p.sc.sc);
			s[p.sc]=p.fi;
			for(int j=0;j<(int)G[p.sc].size();j++){
				if(p.fi+1<s[G[p.sc][j]]){
					que.push(P(p.fi+1,G[p.sc][j]));
				}
			}
		}
		//printf("%d\n",n);
		printf("%d\n",s[gg]);
	}
	return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 16892
final_rank: 13

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> P;
#define pb push_back
#define fi first
#define sc second
typedef long long int ll;
ll W,H;
int M;
ll px[114];ll py[114];ll qx[114];ll qy[114];
vector<ll> x,y;
int Q;
int grid[701][701];
int s[500001];
int dx[4]={-1,0,0,1};
int dy[4]={0,-1,1,0};
int sx1,sy1,gx1,gy1;
int WW,HH;
vector<int>G[500001];
map<P,int> MAP;
/*
int dfs(int x1,int y1){
	f[x1][y1]=true;
	for(int k=0;k<4;k++){
		if(x1+dx[k]>=0&&x1+dx[k]<WW&&y1+dy[k]>=0&&y1+dy[k]<HH){
			if(!f[x1+dx[k]][y1+dy[k]])s[x1+dx[k]][y1+dy[k]]=min(s[x1][y1],dfs(x1+dx[k],y1+dy[k]));
		}
	}
	if(grid[x1][y1])s[x1][y1]++;
	printf("%d %d %d\n",x1,y1,s[x1][y1]);
	return s[x1][y1];
}*/
int main()
{
	scanf("%lld%lld%d",&W,&H,&M);W*=10;H*=10;
	x.pb(0);x.pb(W);
	y.pb(0);y.pb(H);
	for(int i=0;i<M;i++){
		scanf("%lld%lld%lld%lld",&px[i],&py[i],&qx[i],&qy[i]);
		px[i]*=10;py[i]*=10;qx[i]*=10;qy[i]*=10;
		if(px[i]!=0){
			x.pb(px[i]-1);
		}
		x.pb(px[i]);
		if(px[i]!=W){
			x.pb(px[i]+1);
		}
		
		if(qx[i]!=0){
			x.pb(qx[i]-1);
		}
		x.pb(qx[i]);
		if(qx[i]!=W){
			x.pb(qx[i]+1);
		}
		
		if(py[i]!=0){
			y.pb(py[i]-1);
		}
		y.pb(py[i]);
		if(py[i]!=H){
			y.pb(py[i]+1);
		}
		
		if(qy[i]!=0){
			y.pb(qy[i]-1);
		}
		y.pb(qy[i]);
		if(qy[i]!=H){
			y.pb(qy[i]+1);
		}
		
	}
	sort(x.begin(),x.end());
	sort(y.begin(),y.end());
	x.erase(unique(x.begin(),x.end()),x.end());
	y.erase(unique(y.begin(),y.end()),y.end());
	
	WW=(int)x.size();HH=(int)y.size();
	for(int i=0;i<M;i++){
		int ax=lower_bound(x.begin(),x.end(),px[i])-x.begin();
		int bx=lower_bound(x.begin(),x.end(),qx[i])-x.begin();
		int ay=lower_bound(y.begin(),y.end(),py[i])-y.begin();
		int by=lower_bound(y.begin(),y.end(),qy[i])-y.begin();
		//if(ax>=bx)swap(ax,bx);
		//if(ay>=by)swap(ay,by);
		for(int j=ax;j<=bx;j++){
			for(int k=ay;k<=by;k++){
				grid[j][k]=-1;
			}
		}
	}
	
	int index=1;
	for(int i=0;i<WW;i++){
		for(int j=0;j<HH;j++){
			if(grid[i][j]==0){
				queue<P> que;
				que.push(P(i,j));
				while(!que.empty()){
					P p=que.front();que.pop();
					if(grid[p.fi][p.sc]==index)continue;
					grid[p.fi][p.sc]=index;
					for(int k=0;k<4;k++){
						if(p.fi+dx[k]>=0&&p.fi+dx[k]<WW&&p.sc+dy[k]>=0&&p.sc+dy[k]<HH){
							if(grid[p.fi+dx[k]][p.sc+dy[k]]==0){
								que.push(P(p.fi+dx[k],p.sc+dy[k]));
							}
						}
					}
				}
				index++;
			}
		}
	}
	/*
	for(int i=0;i<HH;i++){
		for(int j=0;j<WW;j++){
			printf("%d ",grid[j][i]);
		}
		printf("\n");
	}*/
	
	for(int i=0;i<WW;i++){
		for(int j=0;j<HH;j++){
			if(grid[i][j]==-1){
				for(int k=0;k<4;k++){
					if(i+dx[k]>=0&&i-dx[k]>=0&&i+dx[k]<WW&&i-dx[k]<WW){
						if(j+dy[k]>=0&&j-dy[k]>=0&&j+dy[k]<HH&&j-dy[k]<HH){
							//printf("%d %d\n",i,j);
							int g1=grid[i+dx[k]][j+dy[k]];
							int g2=grid[i-dx[k]][j-dy[k]];
							if(g1!=-1&&g2!=-1&&MAP[P(g1,g2)]==0&&g1!=g2){
								G[g1-1].pb(g2-1);
								G[g2-1].pb(g1-1);
								MAP[P(g1,g2)]=1;
								MAP[P(g2,g1)]=1;
								//printf("%d %d\n",g1,g2);
							}
						}
					}
				}
			}
		}
	}
	
	scanf("%d",&Q);
	for(int i=0;i<Q;i++){
		for(int j=0;j<WW;j++){
			for(int k=0;k<HH;k++){
				s[j*HH+k]=2*(WW+HH)+1;
				//ds[j][k]=2*(WW+HH)+1;
				//f[j][k]=false;
			}
		}
		ll sx,sy,gx,gy;
		scanf("%lld%lld%lld%lld",&sx,&sy,&gx,&gy);
		sx*=10;sy*=10;gx*=10;gy*=10;
		
		sx1=lower_bound(x.begin(),x.end(),sx)-x.begin();
		gx1=lower_bound(x.begin(),x.end(),gx)-x.begin();
		sy1=lower_bound(y.begin(),y.end(),sy)-y.begin();
		gy1=lower_bound(y.begin(),y.end(),gy)-y.begin();
		
		//printf("%d:%d-%d:%d\n",sx1,sy1,gx1,gy1);
		int ss=grid[sx1][sy1]-1;
		int gg=grid[gx1][gy1]-1;
		priority_queue<P,vector<P>,greater<P> > que;
		que.push(make_pair(0,ss));
		//printf("%d %d\n",ss,gg);
		//printf("%d %d\n",sx1,sy1);
		//int n=0;
		
		while(!que.empty()){
			P p=que.top();que.pop();
			if(p.fi>=s[p.sc])continue;
			//printf("%d %d\n",p.sc.fi,p.sc.sc);
			s[p.sc]=p.fi;
			for(int j=0;j<(int)G[p.sc].size();j++){
				if(p.fi+1<s[G[p.sc][j]]){
					que.push(P(p.fi+1,G[p.sc][j]));
				}
			}
		}
		//printf("%d\n",n);
		printf("%d\n",s[gg]);
	}
	return 0;
}
accuracy: 0.42857142857142855
time_ms: 10
memory_kb: 16584
final_rank: 20

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> P;
#define pb push_back
#define fi first
#define sc second
typedef long long int ll;
ll W,H;
int M;
ll px[114];ll py[114];ll qx[114];ll qy[114];
vector<ll> x,y;
int Q;
int grid[501][501];
int s[250001];
int dx[4]={-1,0,0,1};
int dy[4]={0,-1,1,0};
int sx1,sy1,gx1,gy1;
int WW,HH;
vector<int>G[250001];
map<P,int> MAP;
/*
int dfs(int x1,int y1){
	f[x1][y1]=true;
	for(int k=0;k<4;k++){
		if(x1+dx[k]>=0&&x1+dx[k]<WW&&y1+dy[k]>=0&&y1+dy[k]<HH){
			if(!f[x1+dx[k]][y1+dy[k]])s[x1+dx[k]][y1+dy[k]]=min(s[x1][y1],dfs(x1+dx[k],y1+dy[k]));
		}
	}
	if(grid[x1][y1])s[x1][y1]++;
	printf("%d %d %d\n",x1,y1,s[x1][y1]);
	return s[x1][y1];
}*/
int main()
{
	scanf("%lld%lld%d",&W,&H,&M);W*=10;H*=10;
	x.pb(0);x.pb(W);
	y.pb(0);y.pb(H);
	for(int i=0;i<M;i++){
		scanf("%lld%lld%lld%lld",&px[i],&py[i],&qx[i],&qy[i]);
		px[i]*=10;py[i]*=10;qx[i]*=10;qy[i]*=10;
		if(px[i]!=0){
			x.pb(px[i]-1);
		}
		x.pb(px[i]);
		if(px[i]!=W){
			x.pb(px[i]+1);
		}
		
		if(qx[i]!=0){
			x.pb(qx[i]-1);
		}
		x.pb(qx[i]);
		if(qx[i]!=W){
			x.pb(qx[i]+1);
		}
		
		if(py[i]!=0){
			y.pb(py[i]-1);
		}
		y.pb(py[i]);
		if(py[i]!=H){
			y.pb(py[i]+1);
		}
		
		if(qy[i]!=0){
			y.pb(qy[i]-1);
		}
		y.pb(qy[i]);
		if(qy[i]!=H){
			y.pb(qy[i]+1);
		}
		
	}
	sort(x.begin(),x.end());
	sort(y.begin(),y.end());
	x.erase(unique(x.begin(),x.end()),x.end());
	y.erase(unique(y.begin(),y.end()),y.end());
	
	WW=(int)x.size();HH=(int)y.size();
	for(int i=0;i<M;i++){
		int ax=lower_bound(x.begin(),x.end(),px[i])-x.begin();
		int bx=lower_bound(x.begin(),x.end(),qx[i])-x.begin();
		int ay=lower_bound(y.begin(),y.end(),py[i])-y.begin();
		int by=lower_bound(y.begin(),y.end(),qy[i])-y.begin();
		if(ax>=bx)swap(ax,bx);
		if(ay>=by)swap(ay,by);
		for(int j=ax;j<=bx;j++){
			for(int k=ay;k<=by;k++){
				grid[j][k]=-1;
			}
		}
	}
	
	int index=1;
	for(int i=0;i<WW;i++){
		for(int j=0;j<HH;j++){
			if(grid[i][j]==0){
				queue<P> que;
				que.push(P(i,j));
				while(!que.empty()){
					P p=que.front();que.pop();
					if(grid[p.fi][p.sc]==index)continue;
					grid[p.fi][p.sc]=index;
					for(int k=0;k<4;k++){
						if(p.fi+dx[k]>=0&&p.fi+dx[k]<WW&&p.sc+dy[k]>=0&&p.sc+dy[k]<HH){
							if(grid[p.fi+dx[k]][p.sc+dy[k]]==0){
								que.push(P(p.fi+dx[k],p.sc+dy[k]));
							}
						}
					}
				}
				index++;
			}
		}
	}
	/*
	for(int i=0;i<HH;i++){
		for(int j=0;j<WW;j++){
			printf("%d ",grid[j][i]);
		}
		printf("\n");
	}*/
	
	for(int i=0;i<WW;i++){
		for(int j=0;j<HH;j++){
			if(grid[i][j]==-1){
				for(int k=0;k<4;k++){
					if(i+dx[k]>=0&&i-dx[k]>=0&&i+dx[k]<WW&&i-dx[k]<WW){
						if(j+dy[k]>=0&&j-dy[k]>=0&&j+dy[k]<HH&&j-dy[k]<HH){
							//printf("%d %d\n",i,j);
							int g1=grid[i+dx[k]][j+dy[k]];
							int g2=grid[i-dx[k]][j-dy[k]];
							if(g1!=-1&&g2!=-1&&MAP[P(g1,g2)]==0&&g1!=g2){
								G[g1-1].pb(g2-1);
								G[g2-1].pb(g1-1);
								MAP[P(g1,g2)]=1;
								MAP[P(g2,g1)]=1;
								//printf("%d %d\n",g1,g2);
							}
						}
					}
				}
			}
		}
	}
	
	scanf("%d",&Q);
	for(int i=0;i<Q;i++){
		for(int j=0;j<WW;j++){
			for(int k=0;k<HH;k++){
				s[j*HH+k]=100101001;
				//ds[j][k]=2*(WW+HH)+1;
				//f[j][k]=false;
			}
		}
		ll sx,sy,gx,gy;
		scanf("%lld%lld%lld%lld",&sx,&sy,&gx,&gy);
		sx*=10;sy*=10;gx*=10;gy*=10;
		
		sx1=lower_bound(x.begin(),x.end(),sx)-x.begin();
		gx1=lower_bound(x.begin(),x.end(),gx)-x.begin();
		sy1=lower_bound(y.begin(),y.end(),sy)-y.begin();
		gy1=lower_bound(y.begin(),y.end(),gy)-y.begin();
		
		//printf("%d:%d-%d:%d\n",sx1,sy1,gx1,gy1);
		int ss=grid[sx1][sy1]-1;
		int gg=grid[gx1][gy1]-1;
		priority_queue<P,vector<P>,greater<P> > que;
		que.push(make_pair(0,ss));
		//printf("%d %d\n",ss,gg);
		//printf("%d %d\n",sx1,sy1);
		//int n=0;
		
		while(!que.empty()){
			P p=que.top();que.pop();
			if(p.fi>=s[p.sc])continue;
			//printf("%d %d\n",p.sc.fi,p.sc.sc);
			s[p.sc]=p.fi;
			for(int j=0;j<(int)G[p.sc].size();j++){
				if(p.fi+1<s[G[p.sc][j]]){
					que.push(P(p.fi+1,G[p.sc][j]));
				}
			}
		}
		//printf("%d\n",n);
		printf("%d\n",s[gg]);
	}
	return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 10660
final_rank: 8

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> P;
#define pb push_back
#define fi first
#define sc second
typedef long long int ll;
ll W,H;
int M;
ll px[114];ll py[114];ll qx[114];ll qy[114];
vector<ll> x,y;
int Q;
int grid[401][401];
int s[250001];
int dx[4]={-1,0,0,1};
int dy[4]={0,-1,1,0};
int sx1,sy1,gx1,gy1;
int WW,HH;
vector<int>G[250001];
map<P,int> MAP;
/*
int dfs(int x1,int y1){
	f[x1][y1]=true;
	for(int k=0;k<4;k++){
		if(x1+dx[k]>=0&&x1+dx[k]<WW&&y1+dy[k]>=0&&y1+dy[k]<HH){
			if(!f[x1+dx[k]][y1+dy[k]])s[x1+dx[k]][y1+dy[k]]=min(s[x1][y1],dfs(x1+dx[k],y1+dy[k]));
		}
	}
	if(grid[x1][y1])s[x1][y1]++;
	printf("%d %d %d\n",x1,y1,s[x1][y1]);
	return s[x1][y1];
}*/
int main()
{
	scanf("%lld%lld%d",&W,&H,&M);W*=10;H*=10;
	x.pb(0);x.pb(W);
	y.pb(0);y.pb(H);
	for(int i=0;i<M;i++){
		scanf("%lld%lld%lld%lld",&px[i],&py[i],&qx[i],&qy[i]);
		px[i]*=10;py[i]*=10;qx[i]*=10;qy[i]*=10;
		if(px[i]!=0){
			x.pb(px[i]-1);
		}
		x.pb(px[i]);
		if(px[i]!=W){
			x.pb(px[i]+1);
		}
		
		if(qx[i]!=0){
			x.pb(qx[i]-1);
		}
		x.pb(qx[i]);
		if(qx[i]!=W){
			x.pb(qx[i]+1);
		}
		
		if(py[i]!=0){
			y.pb(py[i]-1);
		}
		y.pb(py[i]);
		if(py[i]!=H){
			y.pb(py[i]+1);
		}
		
		if(qy[i]!=0){
			y.pb(qy[i]-1);
		}
		y.pb(qy[i]);
		if(qy[i]!=H){
			y.pb(qy[i]+1);
		}
		
	}
	sort(x.begin(),x.end());
	sort(y.begin(),y.end());
	x.erase(unique(x.begin(),x.end()),x.end());
	y.erase(unique(y.begin(),y.end()),y.end());
	
	WW=(int)x.size();HH=(int)y.size();
	for(int i=0;i<M;i++){
		int ax=lower_bound(x.begin(),x.end(),px[i])-x.begin();
		int bx=lower_bound(x.begin(),x.end(),qx[i])-x.begin();
		int ay=lower_bound(y.begin(),y.end(),py[i])-y.begin();
		int by=lower_bound(y.begin(),y.end(),qy[i])-y.begin();
		if(ax>=bx)swap(ax,bx);
		if(ay>=by)swap(ay,by);
		for(int j=ax;j<=bx;j++){
			for(int k=ay;k<=by;k++){
				grid[j][k]=-1;
			}
		}
	}
	
	int index=1;
	for(int i=0;i<WW;i++){
		for(int j=0;j<HH;j++){
			if(grid[i][j]==0){
				queue<P> que;
				que.push(P(i,j));
				while(!que.empty()){
					P p=que.front();que.pop();
					if(grid[p.fi][p.sc]==index)continue;
					grid[p.fi][p.sc]=index;
					for(int k=0;k<4;k++){
						if(p.fi+dx[k]>=0&&p.fi+dx[k]<WW&&p.sc+dy[k]>=0&&p.sc+dy[k]<HH){
							if(grid[p.fi+dx[k]][p.sc+dy[k]]==0){
								que.push(P(p.fi+dx[k],p.sc+dy[k]));
							}
						}
					}
				}
				index++;
			}
		}
	}
	/*
	for(int i=0;i<HH;i++){
		for(int j=0;j<WW;j++){
			printf("%d ",grid[j][i]);
		}
		printf("\n");
	}*/
	
	for(int i=0;i<WW;i++){
		for(int j=0;j<HH;j++){
			if(grid[i][j]==-1){
				for(int k=0;k<4;k++){
					if(i+dx[k]>=0&&i-dx[k]>=0&&i+dx[k]<WW&&i-dx[k]<WW){
						if(j+dy[k]>=0&&j-dy[k]>=0&&j+dy[k]<HH&&j-dy[k]<HH){
							//printf("%d %d\n",i,j);
							int g1=grid[i+dx[k]][j+dy[k]];
							int g2=grid[i-dx[k]][j-dy[k]];
							if(g1!=-1&&g2!=-1&&MAP[P(g1,g2)]==0&&g1!=g2){
								G[g1-1].pb(g2-1);
								G[g2-1].pb(g1-1);
								MAP[P(g1,g2)]=1;
								MAP[P(g2,g1)]=1;
								//printf("%d %d\n",g1,g2);
							}
						}
					}
				}
			}
		}
	}
	
	scanf("%d",&Q);
	for(int i=0;i<Q;i++){
		for(int j=0;j<WW;j++){
			for(int k=0;k<HH;k++){
				s[j*HH+k]=100101001;
				//ds[j][k]=2*(WW+HH)+1;
				//f[j][k]=false;
			}
		}
		ll sx,sy,gx,gy;
		scanf("%lld%lld%lld%lld",&sx,&sy,&gx,&gy);
		sx*=10;sy*=10;gx*=10;gy*=10;
		
		sx1=lower_bound(x.begin(),x.end(),sx)-x.begin();
		gx1=lower_bound(x.begin(),x.end(),gx)-x.begin();
		sy1=lower_bound(y.begin(),y.end(),sy)-y.begin();
		gy1=lower_bound(y.begin(),y.end(),gy)-y.begin();
		
		//printf("%d:%d-%d:%d\n",sx1,sy1,gx1,gy1);
		int ss=grid[sx1][sy1]-1;
		int gg=grid[gx1][gy1]-1;
		priority_queue<P,vector<P>,greater<P> > que;
		que.push(make_pair(0,ss));
		//printf("%d %d\n",ss,gg);
		//printf("%d %d\n",sx1,sy1);
		//int n=0;
		
		while(!que.empty()){
			P p=que.top();que.pop();
			if(p.fi>=s[p.sc])continue;
			//printf("%d %d\n",p.sc.fi,p.sc.sc);
			s[p.sc]=p.fi;
			for(int j=0;j<(int)G[p.sc].size();j++){
				if(p.fi+1<s[G[p.sc][j]]){
					que.push(P(p.fi+1,G[p.sc][j]));
				}
			}
		}
		//printf("%d\n",n);
		printf("%d\n",s[gg]);
	}
	return 0;
}
accuracy: 0.42857142857142855
time_ms: 10
memory_kb: 10372
final_rank: 19