Problem:
毒の沼地
あなたはレトロなロールプレイングゲームで遊んでいる．このゲームのフィールドは縦 100 マス，横 100 マスのマス目状である．このフィールドの左から
x
列目，上から
y
行目のマスは
(x, y)
と表される．あなたが操作するキャラクターはフィールド内のいずれかのマスの上におり，フィールド内を上下左右に 1 マスずつ移動することができる．
あなたが操作するキャラクターはいま
(X
0
, Y
0
)
にいて，これから
N
箇所の目的地を順番に訪問する予定である．しかしながら，あなたはキャラクターを操作するとき，フィールドのマスの種類に注意してキャラクターを移動させなければならない．それぞれのマスは毒のある沼地か毒のない土地のどちらかである．キャラクターの移動先のマスが毒のある沼地の場合にはキャラクターはダメージを受け，移動先のマスが毒のない土地の場合にはダメージを受けない．あなたはキャラクターへのダメージを減らすため，適切に経路を選ぶことでキャラクターがダメージを受ける回数をできるだけ少なくしたい．ダメージの有無はキャラクターの移動先のマスの種類で決まること，例として，移動元のマスが毒のある沼地で移動先のマスが毒のない土地の場合にはキャラクターはダメージを受けないことに注意せよ．
あなたの分析によれば，左上を
(A, B)
，右下を
(C, D)
とする長方形の範囲内のマスは毒のない土地であり，それ以外のマスは毒のある沼地である．あなたのキャラクターが毒のある沼地からダメージを受ける回数を最小化するように
N
箇所の目的地を順番に訪問したとき，あなたの操作するキャラクターがダメージを受ける回数を求めよ．
Input
入力は最大で 50 個のデータセットからなる． 各データセットは次の形式で表される．
N
A
B
C
D
X
0
Y
0
X
1
Y
1
X
2
Y
2
...
X
N
Y
N
データセットは
N+3
行からなる．
1 行目は目的地の数
N
(
1 ≤ N ≤ 100
) を表す整数である．
2 行目は毒のない土地となっている長方形の範囲を表す整数
A
，
B
，
C
，
D
であり，
1 ≤ A ≤ C ≤ 100
，
1 ≤ B ≤ D ≤ 100
を満たす．キャラクターの移動先のマス
(x, y)
が
A ≤ x ≤ C
と
B ≤ y ≤ D
を満たすとき，またその場合に限りキャラクターはダメージを受けない．
3 行目はあなたが操作するキャラクターが最初にいるマスの座標
(X
0
, Y
0
)
を表す整数であり
1 ≤ X
0
, Y
0
≤ 100
を満たす．4 行目から続く
N
行には
N
箇所の目的地の座標が与えられる．
3+i
行目は
i
番目の目的地のマスの座標
(X
i
, Y
i
)
を表す整数であり
1 ≤ X
i
, Y
i
≤ 100
を満たす．キャラクターが最初にいるマスおよび目的地のマスの座標はそれぞれ異なる，すなわち
(X
j
, Y
j
) ≠ (X
k
, Y
k
)
(0 ≤ j < k ≤ N)
を満たす．
入力の終わりは，1 個のゼロだけからなる行で表される．
Output
各データセットについて，あなたの操作するキャラクターがダメージを受ける回数を 1 行で出力せよ．
Sample Input
2
3 3 5 7
3 3
7 3
7 7
5
1 10 100 10
1 1
100 1
50 20
50 80
51 21
51 1
0
Output for the Sample Input
5
174
入力例を以下の図に示す．
(3, 3)
から
(5, 3)
の間は毒のない土地であるが
(6, 3)
と
(7, 3)
は毒のある沼地であるため，1 番目の目的地に移動するまでにダメージを 2 回受ける．1 番目の目的地から 2 番目の目的地まで下方向に 4 回移動して最短距離で移動した場合は，すべてのマスが毒のある沼地であるためダメージを 4 回受ける．遠回りして毒のない土地を通った場合は，
(6, 3)
，
(6, 7)
，
(7, 7)
の毒のある沼地に入るためダメージを 3 回受ける．ダメージを受ける回数を最小化するような移動方法を選んだとき，ダメージを受ける回数は 5 回である．

Submitted solutions:

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define ALL(x) (x).begin(),(x).end()
#define REP(i, n) for(ll i=0; i<(ll)(n); i++)
#define PER(i, n) for(ll i=(ll)(n)-1; i>=0; i--)

template<typename T> int LB(const vector<T>& v, T x) { return lower_bound(ALL(v),x)-v.begin(); }
template<typename T> int UQ(T& v) { sort(ALL(v)); v.erase(unique(ALL(v)),v.end()); return v.size(); }
template<typename T> bool chmax(T &a, T b) { return a<b ? a=b, true : false; }
template<typename T> bool chmin(T &a, T b) { return a>b ? a=b, true : false; }
template<typename T> using rpriority_queue = priority_queue<T,vector<T>,greater<T>>;
using ll=long long; const int INF=1e9+10; const ll INFL=4e18;
using ld=long double; using lll=__int128_t; using ull=unsigned long long;
using VI=vector<int>; using VVI=vector<VI>; using VL=vector<ll>; using VVL=vector<VL>;
using PL=pair<ll,ll>; using VP=vector<PL>; using WG=vector<vector<pair<int,ll>>>;


#ifdef LOCAL
#include "./debug.hpp"
#else
#define debug(...)
#define print_line
#endif


//----------------------------------------------------------


bool solve() {
    ll N;
    cin>>N;
    if(N==0) return false;
    ll A,B,C,D; cin>>A>>B>>C>>D; A--; B--; C--; D--;

    VL X(N+1),Y(N+1);
    REP(i,N+1) cin>>X[i]>>Y[i], X[i]--, Y[i]--;

    ll ans=0;
    REP(i,N) {
        ll sx=X[i], sy=Y[i];
        ll gx=X[i+1], gy=Y[i+1];

        deque<pair<int,int>> dq; dq.push_back({sx,sy});

        VVL dist(100,VL(100,INFL)); dist[sx][sy]=0;

        while(!dq.empty()) {
            auto [x,y]=dq.front(); dq.pop_front();

            for(auto[dx,dy]:{pair{0,1},{1,0},{-1,0},{0,-1}}) {
                ll nx=x+dx, ny=y+dy;
                if(nx<0||ny<0||nx>=100||ny>=100) continue;
                ll c=A<=nx&&nx<=C&&B<=ny&&ny<=D;
                c=1-c;
                ll ncost=dist[x][y]+c;

                if(c==0 && chmin(dist[nx][ny],ncost)) dq.push_front({nx,ny});
                if(c==1 && chmin(dist[nx][ny],ncost)) dq.push_back({nx,ny});
            }
        }

        ans+=dist[gx][gy];
    }

    cout<<ans<<'\n';
    return true;
}


int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout << fixed << setprecision(15);
    cerr << fixed << setprecision(15);
    while (true) {
        if (!solve()) {
            break;
        }
    }
}
accuracy: 1
time_ms: 310
memory_kb: 3496
final_rank: 5

code_snippet: #include <bits/extc++.h>

using namespace std;
using ll = long long;
#define rep(i, n) for (ll i = 0; i < ll(n); i++)

bool solve() {
  ll m = 100;
  ll n;
  cin >> n;
  if (n == 0) return false;
  ll a, b, c, d;
  cin >> a >> b >> c >> d;
  a--;
  b--;
  vector<pair<ll, ll>> xys(n + 1);
  rep(i, n + 1) {
    cin >> xys[i].first >> xys[i].second;
    xys[i].first--;
    xys[i].second--;
  }
  vector<vector<pair<ll, ll>>> es(m * m);
  rep(i, m) {
    rep(j, m) {
      ll cost = 1;
      if (a <= i && i < c && b <= j && j < d) {
        cost = 0;
      }
      if (i != 0) {
        es[i - 1 + j * m].emplace_back(i + j * m, cost);
      }
      if (i != m - 1) {
        es[i + 1 + j * m].emplace_back(i + j * m, cost);
      }
      if (j != 0) {
        es[i + (j - 1) * m].emplace_back(i + j * m, cost);
      }
      if (j != m - 1) {
        es[i + (j + 1) * m].emplace_back(i + j * m, cost);
      }
    }
  }
  ll ans = 0;
  rep(i, n) {
    ll from = xys[i].first + xys[i].second * m;
    ll to = xys[i + 1].first + xys[i + 1].second * m;
    priority_queue<pair<ll, ll>, vector<pair<ll, ll>>, greater<pair<ll, ll>>>
        pq;
    vector<bool> visited(m * m, false);
    pq.push({0, from});
    visited[from] = true;
    while (pq.size()) {
      auto [cnow, node] = pq.top();
      if (node == to) {
        ans += cnow;
        break;
      }
      pq.pop();
      for (auto e : es[node]) {
        auto [nx, cost] = e;
        if (!visited[nx]) {
          pq.push({cnow + cost, nx});
          visited[nx] = true;
        }
      }
    }
  }
  cout << ans << endl;
  return true;
}

int main() {
  while (solve());
}
accuracy: 1
time_ms: 520
memory_kb: 4360
final_rank: 17

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

#include <atcoder/all>
using namespace atcoder;

using ll = long long;
using mint = modint998244353;

bool solve() {
    int N;
    cin >> N;
    if(N == 0) return false;
    int A, B, C, D;
    cin >> A >> B >> C >> D;
    const int M = 102;
    const int INF = M * M;
    vector<int> X(N + 1), Y(N + 1);
    for(int i = 0; i <= N; i++) {
        cin >> X[i] >> Y[i];
    }
    int ans = 0;
    for(int i = 0; i < N; i++) {
        deque<pair<int, int>> que;
        vector dp(M, vector<int>(M, INF));
        dp[X[i]][Y[i]] = 0;
        que.push_back(make_pair(X[i], Y[i]));
        auto PUSH = [&](int x0, int y0, int x1, int y1) -> void {
            int x = x1, y = y1;
            if(x < 1 || x >= M || y < 1 || y >= M) return;
            if(A <= x && x <= C && B <= y && y <= D) {
                if(dp[x1][y1] > dp[x0][y0]) {
                    dp[x1][y1] = dp[x0][y0];
                    que.push_front(make_pair(x1, y1));
                }
            }else {
                if(dp[x1][y1] > dp[x0][y0] + 1) {
                    dp[x1][y1] = dp[x0][y0] + 1;
                    que.push_back(make_pair(x1, y1));
                }
            }
        };
        while(!que.empty()) {
            auto [x, y] = que.front();
            // if(x == X[i + 1] && y == Y[i + 1]) break;
            que.pop_front();
            PUSH(x, y, x, y - 1); PUSH(x, y, x, y + 1);
            PUSH(x, y, x - 1, y); PUSH(x, y, x + 1, y);
        }
        ans += dp[X[i + 1]][Y[i + 1]];
    }
    cout << ans << endl;
    return true;
}

int main() {
    while(solve());
}
accuracy: 1
time_ms: 210
memory_kb: 3712
final_rank: 13

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

#include <atcoder/all>
using namespace atcoder;

using ll = long long;
using mint = modint998244353;

bool solve() {
    int N;
    cin >> N;
    if(N == 0) return false;
    int A, B, C, D;
    cin >> A >> B >> C >> D;
    vector<int> X(N + 1), Y(N + 1);
    for(int i = 0; i <= N; i++) {
        cin >> X[i] >> Y[i];
    }
    int ans = 0;
    const int M = 101;
    const int INF = 2 * M;
    for(int i = 0; i < N; i++) {
        deque<pair<int, int>> que;
        vector dp(M, vector<int>(M, INF));
        dp[X[i]][Y[i]] = 0;
        que.push_back(make_pair(X[i], Y[i]));
        auto PUSH = [&](int x0, int y0, int x1, int y1) {
            if(min(x1, y1) < 0 || max(x1, y1) >= M) return;
            if(A <= x1 && x1 <= C && B <= y1 && y1 <= D) {
                if(dp[x1][y1] > dp[x0][y0]) {
                    dp[x1][y1] = dp[x0][y0];
                    que.push_front(make_pair(x1, y1));
                }
            }else {
                if(dp[x1][y1] > dp[x0][y0] + 1) {
                    dp[x1][y1] = dp[x0][y0] + 1;
                    que.push_back(make_pair(x1, y1));
                }
            }
        };
        while(!que.empty()) {
            auto [x, y]= que.front();
            que.pop_front();
            if(x == X[i + 1] && y == Y[i + 1]) break;
            PUSH(x, y, x + 1, y); PUSH(x, y, x - 1, y);
            PUSH(x, y, x, y + 1); PUSH(x, y, x, y - 1);
        }
        ans += dp[X[i + 1]][Y[i + 1]];
    }
    cout << ans << endl;
    return true;
}

int main() {
    while(solve());
}
accuracy: 1
time_ms: 170
memory_kb: 3712
final_rank: 12

code_snippet: #include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <climits>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <deque>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <limits>
#include <map>
#include <numeric>
#include <queue>
#include <ranges>
#include <regex>
#include <set>
#include <span>
#include <sstream>
#include <stack>
#include <string>
#include <string_view>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
// #include <atcoder/dsu>

#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define rep1(i, n) for (int i = 1; i <= (int)(n); i++)
#define all(a) a.begin(), a.end()
using namespace std;

template <class T>
inline bool chmin(T &a, T b) {
	if (a > b) {
		a = b;
		return true;
	}
	return false;
}
template <class T>
inline bool chmax(T &a, T b) {
	if (a < b) {
		a = b;
		return true;
	}
	return false;
}

template <class T1, class T2>
std::ostream &operator<<(std::ostream &out, const pair<T1, T2> &A) {
	cout << "{" << A.first << "," << A.second << "}";
	return out;
}

template <class T1, class T2>
std::ostream &operator<<(std::ostream &out, const map<T1, T2> &M) {
	for (const auto &A : M) {
		cout << "{" << A.first << "," << A.second << "}";
	}
	return out;
}

template <class T1>
std::ostream &operator<<(std::ostream &out, const set<T1> &M) {
	cout << "{";
	for (const auto &A : M) {
		cout << A << ", ";
	}
	cout << "}" << endl;
	return out;
}

template <class T1>
std::ostream &operator<<(std::ostream &out, const multiset<T1> &M) {
	cout << "{";
	for (const auto &A : M) {
		cout << A << ", ";
	}
	cout << "}" << endl;
	return out;
}

template <class T>
std::ostream &operator<<(std::ostream &out, const vector<T> &A) {
	for (const T &a : A) {
		cout << a << " ";
	}
	return out;
}

void print() { cout << endl; }

template <typename Head, typename... Tail>
void print(Head H, Tail... T) {
	cout << H << " ";
	print(T...);
}

template <class T>
std::istream &operator>>(std::istream &in, vector<T> &A) {
	for (T &a : A) {
		std::cin >> a;
	}
	return in;
}

using ll = long long;
// using mint = modint1000000007;
// using PII = pair<int, int>;
// using PLL = pair<ll, ll>;
// using Graph = vector<vector<int>>;
constexpr int INF = numeric_limits<int>::max() / 2;
constexpr ll LINF = numeric_limits<ll>::max() / 2;

// ランレングス圧縮
// イテレータを受け取る
// verify: https://atcoder.jp/contests/abc380/submissions/60002447
template <typename T, typename Iterator>
vector<pair<T, int>> RLE(Iterator begin, Iterator end) {
	vector<pair<T, int>> res;
	for (auto itr = begin; itr != end; ++itr) {
		if (res.empty() || res.back().first != *itr) {
			res.emplace_back(*itr, 1);
		} else {
			res.back().second++;
		}
	}
	return res;
}

// 座標圧縮
// unordered_mapが使えない場合はmapに変更しよう
// https://atcoder.jp/contests/abc213/submissions/60002695
template <typename T>
unordered_map<T, int> compress(vector<T> &X) {
	auto tmp = X;
	ranges::sort(tmp);
	tmp.erase(unique(tmp.begin(), tmp.end()), tmp.end());
	unordered_map<T, int> res;
	for (int i = 0; i < (int)tmp.size(); i++) {
		res[tmp[i]] = i;
	}
	return res;
}

struct Edge {
	int to;
	ll cost;
};

using Graph = vector<vector<Edge>>;
using Pll = pair<ll, ll>;

// ダイクストラ
void dijkstra(const Graph &G, int s, vector<ll> &dist) {
	int N = G.size();
	dist.assign(N, -1);
	dist[s] = 0;
	priority_queue<Pll, vector<Pll>, greater<Pll>> que;
	que.push({0, s});
	while (!que.empty()) {
		Pll p = que.top();
		que.pop();
		int v = p.second;
		if (dist[v] < p.first) continue;
		for (auto e : G[v]) {
			if (dist[e.to] == -1 || dist[e.to] > dist[v] + e.cost) {
				dist[e.to] = dist[v] + e.cost;
				que.push({dist[e.to], e.to});
			}
		}
	}
}

bool solve() {
	// ここからスタート
	int N;
	cin >> N;
	if (N == 0) return false;
	int M = 101;
	Graph G(M * M);
	auto id = [M](int x, int y) { return y * M + x; };
	int A, B, C, D;
	cin >> A >> B >> C >> D;
	auto isPoison = [&](int x, int y) {
		return not(A <= x && x <= C && B <= y && y <= D);
	};
	vector<pair<int, int>> dir = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
	rep1(i, 100) rep1(j, 100) {
		for (auto [dy, dx] : dir) {
			int nx = i + dx;
			int ny = j + dy;
			if (ny <= 0 || nx <= 0 || nx >= M || ny >= M) continue;
			if (isPoison(nx, ny)) {
				G[id(i, j)].emplace_back(id(nx, ny), 1);
			} else {
				G[id(i, j)].emplace_back(id(nx, ny), 0);
			}
		}
	}
	vector<pair<int, int>> pos(N + 1);
	rep(i, N + 1) {
		int x, y;
		cin >> x >> y;
		pos[i] = {x, y};
	}
	int cnt = 0;
	rep(i, N) {
		auto [fx, fy] = pos[i];
		auto [tx, ty] = pos[i + 1];
		vector<ll> dist;
		dijkstra(G, id(fx, fy), dist);
		cnt += dist[id(tx, ty)];
	}
	cout << cnt << endl;

	return true;
}

int main(void) {
	std::cin.tie(0)->sync_with_stdio(0);
	while (solve());
}
accuracy: 1
time_ms: 970
memory_kb: 4676
final_rank: 18

code_snippet: # include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
const double pi = acos(-1);
template<class T>constexpr T inf() { return ::std::numeric_limits<T>::max(); }
template<class T>constexpr T hinf() { return inf<T>() / 2; }
template <typename T_char>T_char TL(T_char cX) { return tolower(cX); }
template <typename T_char>T_char TU(T_char cX) { return toupper(cX); }
template<class T> bool chmin(T& a,T b) { if(a > b){a = b; return true;} return false; }
template<class T> bool chmax(T& a,T b) { if(a < b){a = b; return true;} return false; }
int popcnt(unsigned long long n) { int cnt = 0; for (int i = 0; i < 64; i++)if ((n >> i) & 1)cnt++; return cnt; }
int d_sum(ll n) { int ret = 0; while (n > 0) { ret += n % 10; n /= 10; }return ret; }
int d_cnt(ll n) { int ret = 0; while (n > 0) { ret++; n /= 10; }return ret; }
ll gcd(ll a, ll b) { if (b == 0)return a; return gcd(b, a%b); };
ll lcm(ll a, ll b) { ll g = gcd(a, b); return a / g*b; };
ll MOD(ll x, ll m){return (x%m+m)%m; }
ll FLOOR(ll x, ll m) {ll r = (x%m+m)%m; return (x-r)/m; }
template<class T> using dijk = priority_queue<T, vector<T>, greater<T>>;
# define all(qpqpq)           (qpqpq).begin(),(qpqpq).end()
# define UNIQUE(wpwpw)        (wpwpw).erase(unique(all((wpwpw))),(wpwpw).end())
# define LOWER(epepe)         transform(all((epepe)),(epepe).begin(),TL<char>)
# define UPPER(rprpr)         transform(all((rprpr)),(rprpr).begin(),TU<char>)
# define rep(i,upupu)         for(ll i = 0, i##_len = (upupu);(i) < (i##_len);(i)++)
# define reps(i,opopo)        for(ll i = 1, i##_len = (opopo);(i) <= (i##_len);(i)++)
# define len(x)                ((ll)(x).size())
# define bit(n)               (1LL << (n))
# define pb push_back
# define eb emplace_back
# define exists(c, e)         ((c).find(e) != (c).end())

struct INIT{
	INIT(){
		std::ios::sync_with_stdio(false);
		std::cin.tie(0);
		cout << fixed << setprecision(20);
	}
}INIT;

namespace mmrz {
	void solve();
}

int main(){
	mmrz::solve();
}
#define debug(...) (static_cast<void>(0))

using namespace mmrz;

using vll=vector<ll>;
using vvll = vector<vector<ll>>;
using ull = unsigned long long;
using lll = __int128;
#define per(i,n) for(ll i=n-1;i>=0;--i)
#define rep2(i,a,n) for (ll i=a;i<n;++i)
#define per2(i,a,n) for (ll i=a;i>=n;--i)

// [BEGIN] template の include
int di[] = {1, 0, -1, 0};
int dj[] = {0, 1, 0, -1};
const int M = 100;
int SOLVE(){
	int n;
	cin >> n;
	if(n==0) return 1;

	int a, b, c, d; cin >> a >> b >> c >> d;
	a--;
	b--;
	c--;
	d--;
	vvll cost(M, vll(M,1));
	rep2(i,a,c+1) {
		rep2(j,b,d+1) {
			cost[i][j] = 0;
		}
	}

	ll ans = 0;
	int cx, cy; cin >> cx >> cy;
	cx--;
	cy--;
	int targx, targy;
	rep(_,n) {
		cin >> targx >> targy;
		targx--;
		targy--;
		vvll seen(M, vll(M, -1));
		
		deque<tuple<int,int, ll>> que;
		que.push_front({cx,cy, 0ll});

		while(!que.empty()) {
			auto [px, py, cs] = que.front();
			que.pop_front();
			if(seen[px][py] != -1) continue;
			seen[px][py] = cs;
			rep(r,4) {
				int nx = px + di[r];
				int ny = py + dj[r];
				if(nx >= 0 && ny >= 0 && nx < M && ny < M && seen[nx][ny] == -1) {
					if(cost[nx][ny]==0) {
						que.push_front({nx,ny,cs});
					} else {
						que.push_back({nx,ny,cs+1});
					}
				}
			}
		} 
		ans += seen[targx][targy];
		cx = targx;
		cy = targy;
		debug(seen[targx][targy]);
	}
	cout << ans << '\n';
	return 0;
}

void mmrz::solve(){
	while(!SOLVE());
}
accuracy: 1
time_ms: 250
memory_kb: 3840
final_rank: 15

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define all(a) (a).begin(), (a).end()
#define rep(i, n) for (int i = 0; i < (int)(n); ++i)
#define rrep(i, n) for (int i = (int)(n) - 1; 0 <= i; --i)
template <typename T> bool chmax(T& a, T b) {
  if (a < b) {
    a = b;
    return true;
  }
  return false;
}
template <typename T> bool chmin(T& a, T b) {
  if (a > b) {
    a = b;
    return true;
  }
  return false;
}
void solve();
int N,A,B,C,D,X[1<<10],Y[1<<10];
signed main() {
  cin.tie(nullptr)->sync_with_stdio(false);
  cout << fixed << setprecision(20);
  int TESTCASES = 1<<30;
  //cin >> TESTCASES;
  while (TESTCASES--) {
    cin>>N;
    if(N==0)break;
    cin>>A>>B>>C>>D,--A,--B;
    rep(i,N+1)cin>>X[i]>>Y[i],--X[i],--Y[i];
    solve();
  }
}
void solve() {
  int ans=0;
  rep(i,N){
    constexpr int M=100;
    vector dist(M,vector<int>(M,1<<30));
    dist[X[i]][Y[i]]=0;
    deque<pair<int,int>>que;
    que.push_back({X[i],Y[i]});
    while(!que.empty()){
      auto[x,y]=que.front();
      que.pop_front();
      int dx[]={1,0,-1,0};
      rep(dir,4){
        int xx=x+dx[dir],yy=y+dx[(dir+1)%4];
        if(0<=xx&&xx<M&&0<=yy&&yy<M){
          if(A<=xx&&xx<C&&B<=yy&&yy<D){
            if(chmin(dist[xx][yy],dist[x][y])){
              que.push_front({xx,yy});
            }
          }else{
            if(chmin(dist[xx][yy],dist[x][y]+1)){
              que.push_back({xx,yy});
            }
          }
        }
      }
    }
    ans+=dist[X[i+1]][Y[i+1]];
  }
  cout<<ans<<'\n';
}
accuracy: 1
time_ms: 250
memory_kb: 3712
final_rank: 14

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define all(a) (a).begin(), (a).end()
#define rep(i, n) for (int i = 0; i < (int)(n); ++i)
#define rrep(i, n) for (int i = (int)(n) - 1; 0 <= i; --i)
template <typename T> bool chmax(T& a, T b) {
  if (a < b) {
    a = b;
    return true;
  }
  return false;
}
template <typename T> bool chmin(T& a, T b) {
  if (a > b) {
    a = b;
    return true;
  }
  return false;
}
void solve();
int N,A,B,C,D;
vector<int>X,Y;
signed main(){
  cin.tie(nullptr)->sync_with_stdio(false);
  cout << fixed << setprecision(20);
  int TESTCASES = 1<<30;
  //cin >> TESTCASES;
  while (TESTCASES--) {
    cin>>N;
    if(N==0)break;
    cin>>A>>B>>C>>D;
    --A,--B;
    X.clear();
    Y.clear();
    X.assign(N+1,0);
    Y.assign(N+1,0);
    rep(i,N+1)cin>>X[i]>>Y[i],--X[i],--Y[i];
    solve();
  }
}
void solve() {
  int px=X[0],py=Y[0];
  int ans=0;
  for(int i=1;i<=N;++i){
    vector<vector<int>>dist(100,vector<int>(100,1<<30));
    dist[px][py]=0;
    deque<pair<int,int>>que;
    que.push_back({px,py});
    while(!que.empty()){
      auto[x,y]=que.front();
      que.pop_front();
      int dx[]={1,0,-1,0},dy[]={0,1,0,-1};
      rep(dir,4){
        int xx=x+dx[dir],yy=y+dy[dir];
        if(0<=xx&&xx<100&&0<=yy&&yy<100){
          if(A<=xx&&xx<C&&B<=yy&&yy<D){
            if(chmin(dist[xx][yy],dist[x][y]))que.push_front({xx,yy});
          }else{
            if(chmin(dist[xx][yy],dist[x][y]+1))que.push_back({xx,yy});
          }
        }
      }
    }
    ans+=dist[X[i]][Y[i]];
    px=X[i],py=Y[i];
  }
  cout<<ans<<'\n';
}
accuracy: 1
time_ms: 250
memory_kb: 3584
final_rank: 8

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define all(...) std::begin(__VA_ARGS__), std::end(__VA_ARGS__)
#define rall(...) std::rbegin(__VA_ARGS__), std::rend(__VA_ARGS__)
#define OVERLOAD_REP(_1, _2, _3, _4, 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, n) for (ll i=a;i<n;i++)
#define REP4(i, a, b, n) for(ll i=a;i<n;i+=b)
#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP4, REP3, REP2, REP1)(__VA_ARGS__)
#define OVERLOAD_RREP(_1, _2, _3, _4, name, ...) name
#define RREP1(n) for(ll i=n;i>=0;i--)
#define RREP2(i, n) for(ll i=n;i>=0;i--)
#define RREP3(i, a, n) for(ll i=n;i>=a;i--)
#define RREP4(i, a, b, n) for(ll i=n;i>=a;i-=b)
#define rrep(...) OVERLOAD_RREP(__VA_ARGS__, RREP4, RREP3, RREP2, RREP1)(__VA_ARGS__)
#define foa(a,v)  (auto& a : (v))
#define uniq(a) sort(all(a));a.erase(unique(all(a)),end(a))
#define len(n) (long long)(n).size()
#define pb push_back
using ll = long long;
using ld = long double;
using ull = unsigned long long;
using vi = vector<int>;
using vvi = vector<vi>;
using vvvi = vector<vvi>;
using vll = vector<ll>;
using vvll = vector<vll>;
using vvvll = vector<vvll>;
using vs = vector<string>;
using vvs = vector<vs>;
using vvvs = vector<vvs>;
using vld = vector<ld>;
using vvld = vector<vld>;
using vvvld = vector<vvld>;
using vc = vector<char>;
using vvc = vector<vc>;
using vvvc = vector<vvc>;
using pll = pair<ll,ll>;
using vpll = vector<pll>;
using vvpll = vector<vpll>;
template<class... T>
constexpr auto min(T... a){
    return min(initializer_list<common_type_t<T...>>{a...});
}
template<class... T>
constexpr auto max(T... a){
    return max(initializer_list<common_type_t<T...>>{a...});
}
template<class... T>
void input(T&... a){
    (cin >> ... >> a);
}
ll modpow(ll a,ll b,ll c){
    ll ans = 1;
    while (b){
        if (b & 1){
            ans *= a;
            ans %= c;
        }
        a *= a;
        a %= c;
        b /= 2;
    }
    return ans;
}
#define INT(...) int __VA_ARGS__; input(__VA_ARGS__)
#define LL(...) ll __VA_ARGS__; input(__VA_ARGS__)
#define ULL(...) ull __VA_ARGS__; input(__VA_ARGS__)
#define LD(...) ld __VA_ARGS__; input(__VA_ARGS__)
#define STR(...) string __VA_ARGS__; input(__VA_ARGS__)
#define CHA(...) char __VA_ARGS__; input(__VA_ARGS__)
#define VLL(name,length) vll name(length);rep(i,length){cin >> name[i];}
#define VVLL(name,h,w) vvll name(h,vll(w));rep(i,h)rep(j,w){cin >> name[i][j];}
#define VVVLL(name,a,b,c) vvvll name(a,vvll(b,vll(c)));rep(i,a)rep(j,b)rep(k,c){cin >> name[i][j][k];}
#define VI(name,length) vi name(length);rep(i,length){cin >> name[i];}
#define VVI(name,h,w) vvi name(h,vi(w));rep(i,h)rep(j,w){cin >> name[i][j];}
#define VVVI(name,a,b,c) vvvi name(a,vvll(b,vi(c)));rep(i,a)rep(j,b)rep(k,c){cin >> name[i][j][k];}
#define VLD(name,length) vld name(length);rep(i,length){cin >> name[i];}
#define VVLD(name,h,w) vvld name(h,vld(w));rep(i,h)rep(j,w){cin >> name[i][j];}
#define VVVLD(name,a,b,c) vvvld name(a,vvld(b,vld(c)));rep(i,a)rep(j,b)rep(k,c){cin >> name[i][j][k];}
#define VC(name,length) vc name(length);rep(i,length){cin >> name[i];}
#define VVC(name,h,w) vvc name(h,vc(w));rep(i,h)rep(j,w){cin >> name[i][j];}
#define VVVC(name,a,b,c) vvvc name(a,vvc(b,vc(c)));rep(i,a)rep(j,b)rep(k,c){cin >> name[i][j][k];}
#define VS(name,length) vs name(length);rep(i,length){cin >> name[i];}
#define VVS(name,h,w) vvs name(h,vs(w));rep(i,h)rep(j,w){cin >> name[i][j];}
#define VVVS(name,a,b,c) vvvs name(a,vvs(b,vs(c)));rep(i,a)rep(j,b)rep(k,c){cin >> name[i][j][k];}
#define PLL(name) pll name;cin>>name.first>>name.second;
#define VPLL(name,length) vpll name(length);rep(i,length){cin>>name[i].first>>name[i].second;}

void print(){cout << "\n";}
template<class T, class... Ts>
void print(const T& a, const Ts&... b){cout << a;(cout << ... << (cout << ' ', b));cout << '\n';}
void print(vll x){rep(i,len(x)){cout << x[i];if(i!=len(x)-1){cout << " ";}else{cout << '\n';}}}
void print(vvll x){rep(i,len(x))rep(j,len(x[i])){cout << x[i][j];if(j!=len(x[i])-1){cout << " ";}else{cout << '\n';}}}


void solve(ll n, ll a, ll b, ll c, ll d, vpll z){
    auto bfs = [&](ll sx,ll sy,ll gx,ll gy){
        ll h = 110;
        ll w = 110;
        vvll dist(h,vll(w,1LL<<60));
        dist[sx][sy] = 0;
        deque<pll> q;
        q.push_back({sx,sy});
        vpll dxy = {{-1,0},{1,0},{0,-1},{0,1}};
        while(!q.empty()){
            auto [x,y] = q.front();
            q.pop_front();
            for(auto [dx,dy]:dxy){
                ll tx = x+dx;
                ll ty = y+dy;
                if(0 <= tx && tx < h && 0 <= ty && ty < w){
                    if(a <= tx && tx <= c && b <= ty && ty <= d){
                        if(dist[tx][ty] > dist[x][y] + 0){
                            dist[tx][ty] = dist[x][y] + 0;
                            q.push_front({tx,ty});
                        }
                    }
                    else{
                        if(dist[tx][ty] > dist[x][y] + 1){
                            dist[tx][ty] = dist[x][y] + 1;
                            q.push_back({tx,ty});
                        }
                    }
                    
                }
            }
        }
        return dist[gx][gy];
    };
    ll ans = 0;
    rep(i,n){
        ans += bfs(z[i].first,z[i].second,z[i+1].first,z[i+1].second);
    }
    print(ans);
}
  
int main(){
    while(1){
        LL(n);
        if(n == 0){break;}
        LL(a,b,c,d);
        VPLL(z,n+1);
        solve(n,a,b,c,d,z);
    }
}
accuracy: 1
time_ms: 320
memory_kb: 3840
final_rank: 16

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define ALL(x) x.begin(),x.end()
#define dbg(x) cerr << #x << ':' << (x) << endl;
using ll = long long;
using ld = long double;

int n;
int a,b,c,d;
int sx,sy;
vector<int> x,y;
int m = 100;
vector<vector<int>> dis(m, vector<int>(m));



void solve() {
    cin >> n;
    if (n == 0) exit(0);
    cin >> a >> b >> c >> d;
    --a; --b;

    cin >> sx >> sy;
    --sx; --sy;
    x.resize(n);
    y.resize(n);
    for (int i = 0; i < n; ++i) {
        cin >> x[i] >> y[i];
        --x[i]; --y[i];
    }


    deque<pair<int,int>> q;
    int ans = 0;
    int dx[] = {-1, 0, 1, 0, -1};
    for (int i = 0; i < n; ++i) {
        // init
        for (int j = 0; j < m; ++j) {
            fill(ALL(dis[j]), 1000);
        }
        dis[sy][sx] = 0;
        q.emplace_back(sx, sy);

        // 01-bfs
        while (q.size()) {
            auto [X,Y] = q.front();
            if (X == x[i] && Y == y[i]) {
                ans += dis[Y][X];
                break;
            }
            q.pop_front();
            for (int k = 0; k < 4; ++k) {
                int nx = X + dx[k];
                int ny = Y + dx[k+1];
                if (!(0 <= nx && nx < m && 0 <= ny && ny < m)) continue;

                if (a <= nx && nx < c && b <= ny && ny < d) {
                    if (dis[ny][nx] > dis[Y][X]) {
                        dis[ny][nx] = dis[Y][X];
                        q.emplace_front(nx, ny);
                    }
                }
                else {
                    if (dis[ny][nx] > dis[Y][X] + 1) {
                        dis[ny][nx] = dis[Y][X] + 1;
                        q.emplace_back(nx, ny);
                    }
                }
            }
        }
        q.clear();
        sx = x[i];
        sy = y[i];
    }
    cout << ans << '\n';
}

int main()
{   
    while (true) solve();
}
accuracy: 1
time_ms: 220
memory_kb: 3440
final_rank: 2

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

#define all(v) v.begin(), v.end()
#define ll long
#define ld long double
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<vvl> vvvl;

struct edge
{
	int x, y;
	int cost;
};

int main()
{
	while (true)
	{
		int N;
		cin >> N;
		if (N == 0)
		{
			break;
		}
		int A, B, C, D;
		cin >> A >> B >> C >> D;
		A--, B--, C--, D--;
		vector<pair<int, int>> XY(N + 1);
		for (int i = 0; i <= N; i++)
		{
			cin >> XY[i].first >> XY[i].second;
			XY[i].first--, XY[i].second--;
		}

		// グラフの構築
		map<pair<int, int>, vector<edge>> graph;
		int dx[4] = {0, 1, 0, -1};
		int dy[4] = {1, 0, -1, 0};
		for (int i = 0; i < 100; i++)
		{
			for (int j = 0; j < 100; j++)
			{
				for (int d = 0; d < 4; d++)
				{
					int nx = i + dx[d];
					int ny = j + dy[d];
					if (!(0 <= nx && nx < 100 && 0 <= ny && ny < 100))
					{
						continue;
					}
					int cost = 1;
					if (A <= nx && nx <= C && B <= ny && ny <= D)
					{
						cost = 0;
					}
					graph[{i, j}].push_back({nx, ny, cost});
				}
			}
		}

		// ダイクストラ
		// i -> i+1に遷移
		int ans = 0;
		for (int i = 0; i < N; i++)
		{
			priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, greater<tuple<int, int, int>>> pq;
			pq.push({0, XY[i].first, XY[i].second});
			vector<vector<int>> dist(100, vector<int>(100, 1e9));
			dist[XY[i].first][XY[i].second] = 0;
			while (!pq.empty())
			{
				auto [now_cost, now_x, now_y] = pq.top();
				pq.pop();
				if (now_x == XY[i + 1].first && now_y == XY[i + 1].second)
				{
					ans += now_cost;
					break;
				}
				for (auto [next_x, next_y, plus_cost] : graph[{now_x, now_y}])
				{
					if (dist[next_x][next_y] > now_cost + plus_cost)
					{
						dist[next_x][next_y] = now_cost + plus_cost;
						pq.push({now_cost + plus_cost, next_x, next_y});
					}
				}
			}
		}
		cout << ans << endl;
	}
}
accuracy: 1
time_ms: 2010
memory_kb: 4836
final_rank: 20

code_snippet: #include <iostream>
#include <cmath>
#include <queue>
#include <utility>
using namespace std;
using P = pair<int, int>;
const int dx[4] = {0, 0, 1, -1}, dy[4] = {1, -1, 0, 0};
int main() {
    while(1) {
        int n; cin >> n;
        if(!n) break;
        int a, b, c, d; cin >> a >> b >> c >> d;
        int sx, sy, gx, gy;
        cin >> gx >> gy;
        int ans = 0;
        for(int i = 0; i < n; i++) {
            sx = gx; sy = gy;
            cin >> gx >> gy;
            deque<P> q;
            q.push_front(P(sx, sy));
            vector<vector<int>> dist(101, vector<int>(101, -1));
            dist[sx][sy] = 0;
            while(!q.empty()) {
                int x = q.front().first, y = q.front().second;
                q.pop_front();
                if(x == gx && y == gy) break;
                for(int dir = 0; dir < 4; dir++) {
                    int nx = x + dx[dir], ny = y + dy[dir];
                    if(!(0 <= nx && nx <= 100 && 0 <= ny && ny <= 100 && dist[nx][ny] == -1)) continue;
                    if(a <= nx && nx <= c && b <= ny && ny <= d) {
                        q.push_front(P(nx, ny));
                        dist[nx][ny] = dist[x][y];
                    } else {
                        q.push_back(P(nx, ny));
                        dist[nx][ny] = dist[x][y] + 1;
                    }
                }
            }
            ans += dist[gx][gy];
        }
        cout << ans << endl;
    }
}
accuracy: 1
time_ms: 130
memory_kb: 3540
final_rank: 6

code_snippet: #include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define all(x) (x).begin(),(x).end()
#define eb emplace_back
using namespace std;
using ll = long long;
using ld = long double;
using vl = vector<long long>;
using vvl = vector<vector<long long>>; using vs = vector<string>;
using pl = pair<long long, long long>;
template <typename T> inline bool chmin(T& a, const T& b) {bool compare = a > b; if (a > b) a = b; return compare;}
template <typename T> inline bool chmax(T& a, const T& b) {bool compare = a < b; if (a < b) a = b; return compare;}
template<class T>using rp_queue=priority_queue<T,vector<T>,greater<T>>;
template <typename T> T gcd(T a, T b) {if (b == 0)return a; else return gcd(b, a % b);}
template <typename T> inline T lcm(T a, T b) {return a /gcd(a, b)*b;}
const ll INF = 1LL << 60;
const ld PI = acos(-1);
template <class OStream, class T> OStream &operator<<(OStream &os, const std::vector<T> &vec);
template <class OStream, class T, size_t sz> OStream &operator<<(OStream &os, const std::array<T, sz> &arr);
template <class OStream, class T, class TH> OStream &operator<<(OStream &os, const std::unordered_set<T, TH> &vec);
template <class OStream, class T, class U> OStream &operator<<(OStream &os, const pair<T, U> &pa);
template <class OStream, class T> OStream &operator<<(OStream &os, const std::deque<T> &vec);
template <class OStream, class T> OStream &operator<<(OStream &os, const std::set<T> &vec);
template <class OStream, class T> OStream &operator<<(OStream &os, const std::multiset<T> &vec);
template <class OStream, class T> OStream &operator<<(OStream &os, const std::unordered_multiset<T> &vec);
template <class OStream, class T, class U> OStream &operator<<(OStream &os, const std::pair<T, U> &pa);
template <class OStream, class TK, class TV> OStream &operator<<(OStream &os, const std::map<TK, TV> &mp);
template <class OStream, class TK, class TV, class TH> OStream &operator<<(OStream &os, const std::unordered_map<TK, TV, TH> &mp);
template <class OStream, class... T> OStream &operator<<(OStream &os, const std::tuple<T...> &tpl);
 
template <class OStream, class T> OStream &operator<<(OStream &os, const std::vector<T> &vec) { os << '['; for (auto v : vec) os << v << ','; os << ']'; return os; }
template <class OStream, class T, size_t sz> OStream &operator<<(OStream &os, const std::array<T, sz> &arr) { os << '['; for (auto v : arr) os << v << ','; os << ']'; return os; }
template <class... T> std::istream &operator>>(std::istream &is, std::tuple<T...> &tpl) { std::apply([&is](auto &&... args) { ((is >> args), ...);}, tpl); return is; }
template <class OStream, class... T> OStream &operator<<(OStream &os, const std::tuple<T...> &tpl) { os << '('; std::apply([&os](auto &&... args) { ((os << args << ','), ...);}, tpl); return os << ')'; }
template <class OStream, class T, class TH> OStream &operator<<(OStream &os, const std::unordered_set<T, TH> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <class OStream, class T> OStream &operator<<(OStream &os, const std::deque<T> &vec) { os << "deq["; for (auto v : vec) os << v << ','; os << ']'; return os; }
template <class OStream, class T> OStream &operator<<(OStream &os, const std::set<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <class OStream, class T> OStream &operator<<(OStream &os, const std::multiset<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <class OStream, class T> OStream &operator<<(OStream &os, const std::unordered_multiset<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <class OStream, class T, class U> OStream &operator<<(OStream &os, const std::pair<T, U> &pa) { return os << '(' << pa.first << ',' << pa.second << ')'; }
template <class OStream, class TK, class TV> OStream &operator<<(OStream &os, const std::map<TK, TV> &mp) { os << '{'; for (auto v : mp) os << v.first << "=>" << v.second << ','; os << '}'; return os; }
template <class OStream, class TK, class TV, class TH> OStream &operator<<(OStream &os, const std::unordered_map<TK, TV, TH> &mp) { os << '{'; for (auto v : mp) os << v.first << "=>" << v.second << ','; os << '}'; return os; }
#ifdef LOCAL
const string COLOR_RESET = "\033[0m", BRIGHT_GREEN = "\033[1;32m", BRIGHT_RED = "\033[1;31m", BRIGHT_CYAN = "\033[1;36m", NORMAL_CROSSED = "\033[0;9;37m", RED_BACKGROUND = "\033[1;41m", NORMAL_FAINT = "\033[0;2m";
#define dbg(x) std::cerr << BRIGHT_CYAN << #x << COLOR_RESET << " = " << (x) << NORMAL_FAINT << " (L" << __LINE__ << ") " << __FILE__ << COLOR_RESET << std::endl
#define dbgif(cond, x) ((cond) ? std::cerr << BRIGHT_CYAN << #x << COLOR_RESET << " = " << (x) << NORMAL_FAINT << " (L" << __LINE__ << ") " << __FILE__ << COLOR_RESET << std::endl : std::cerr)
#else
#define dbg(x) ((void)0)
#define dbgif(cond, x) ((void)0)
#endif
void solve();
int main(){
  cin.tie(nullptr);
  ios_base::sync_with_stdio(false);
  cout<<fixed<<setprecision(15);
  int num_tc = 1;
  //cin >> num_tc;
  rep(tc,num_tc){
    //cout << "Case #" << tc+1 << ": " ;// << endl;
    solve();
  }
}
//見切り発車で実装しては行けない．頭の中でコードが完全に出来上がるまで書き始めるな．
//オーバーフローしているか確認する
//小さいケースで動いているかを確認する。
int dx[] = {1,0,-1,0};
int dy[] = {0,1,0,-1};
void solve(){
  while(true){
    int N;cin>>N;
    if(N==0)return;
    //01BFSを用いれば良いですね。
    ll A,B,C,D;cin>>B>>A>>D>>C;
    A--;
    B--;
    //[A,C) x [B,D)ではコスト0で移動可能
    ll x0,y0;cin>>y0>>x0;x0--,y0--;
    ll ans = 0;
    rep(i,N){
      ll x,y;cin>>y>>x;
      x--;
      y--;
      deque<pl> que;
      que.push_back({x0,y0});
      vvl dist(110,vl(110,-1));
      dist[x0][y0] = 0;
      while(!que.empty()){
        auto[a,b] = que.front();
        que.pop_front();
        rep(d,4){
          int na = a+dx[d];
          int nb = b+dy[d];
          if(0<=na&&na<110&&0<=nb&&nb<=110){
            if(dist[na][nb]!=-1)continue;
            if(A<=na&&na<C&&B<=nb&&nb<D){
              que.push_front({na,nb});
              dist[na][nb] = dist[a][b];
            }else{
              que.push_back({na,nb});
              dist[na][nb] = dist[a][b]+1;
            }
          }
        }
      }
      ans+=dist[x][y];
      x0 = x;
      y0 = y;
    }
    cout<<ans<<endl;
  }

}
accuracy: 1
time_ms: 340
memory_kb: 3660
final_rank: 11

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (long long i = 0; i < (long long)(n); i++)
#define rrep(i,start,end) for (long long i = start;i >= (long long)(end);i--)
#define repn(i,end) for(long long i = 0; i <= (long long)(end); i++)
#define reps(i,start,end) for(long long i = start; i < (long long)(end); i++)
#define repsn(i,start,end) for(long long i = start; i <= (long long)(end); i++)
#define each(p,a) for(auto &p:a)
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef vector<long long> vll;
typedef vector<pair<long long ,long long>> vpll;
typedef vector<vector<long long>> vvll;
typedef set<ll> sll;
typedef map<long long , long long> mpll;
typedef pair<long long ,long long> pll;
typedef tuple<long long , long long , long long> tpl3;
#define LL(...) ll __VA_ARGS__; input(__VA_ARGS__)
#define LD(...) ld __VA_ARGS__; input(__VA_ARGS__)
#define Str(...) string __VA_ARGS__; input(__VA_ARGS__)
#define Ch(...) char __VA_ARGS__; input(__VA_ARGS__)
#define all(a)  (a).begin(),(a).end()
#define UNIQUE(v) v.erase( unique(v.begin(), v.end()), v.end() );
#define sz(x) (int)x.size()
// << std::fixed << std::setprecision(10)
const ll INF = 1LL << 60;
const ld EPS = 1e-9;
 
inline ll lfloor(ll x,ll m){return (x - ((x % m+ m)%m))/m;}
inline ll positive_mod(ll a,ll m){return (a % m + m)%m;}
inline ll popcnt(ull a){ return __builtin_popcountll(a);}
template<class T> bool chmin(T& a, T b){if(a > b){a = b;return true;}return false;}
template<class T> bool chmax(T& a, T b){if(a < b){a = b;return true;}return false;}
template<typename T> std::istream &operator>>(std::istream&is,std::vector<T>&v){for(T &in:v){is>>in;}return is;}
template<typename T> std::ostream &operator<<(std::ostream&os,const std::vector<T>&v){for(auto it=std::begin(v);it!=std::end(v);){os<<*it<<((++it)!=std::end(v)?" ":"");}return os;}
template<typename T1, typename T2>std::ostream &operator<< (std::ostream &os, std::pair<T1,T2> p){os << "{" << p.first << "," << p.second << "}";return os;}
template<class... T>void input(T&... a){(cin >> ... >> a);}
void print(){cout << endl;}
template<class T, class... Ts>void print(const T& a, const Ts&... b){cout << a;((cout << ' ' << b), ...);cout << endl;}
template<class T> void pspace(const T& a){ cout << a << ' ';}
void perr(){cerr << endl;}
template<class T, class... Ts>void perr(const T& a, const Ts&... b){cerr << a;((cerr << ' ' << b), ...);cerr << endl;}
void yes(bool i = true){ return print(i?"yes":"no"); }
void Yes(bool i = true){ return print(i?"Yes":"No"); }
void YES(bool i = true){ return print(i?"YES":"NO"); }
template <class T> vector<T> &operator++(vector<T> &v) {for(auto &e : v) e++;return v;}
template <class T> vector<T> operator++(vector<T> &v, signed) {auto res = v;for(auto &e : v) e++;return res;}
template <class T> vector<T> &operator--(vector<T> &v) {for(auto &e : v) e--;return v;}
template <class T> vector<T> operator--(vector<T> &v, signed) {auto res = v;for(auto &e : v) e--;return res;}
//grid探索用
vector<ll> _ta = {0,0,1,-1,1,1,-1,-1};
vector<ll> _yo = {1,-1,0,0,1,-1,1,-1};
bool isin(ll now_i,ll now_j,ll h,ll w){return (0<=now_i && now_i < h && 0 <= now_j && now_j < w);}
  
ll lpow(ll x,ll n){ll ans = 1;while(n >0){if(n & 1)ans *= x;x *= x;n >>= 1;}return ans;}
ll Modlpow(ll x,ll n,ll m){ll ans = 1;ll a = x%m;while(n >0){if(n & 1){ans *= a;ans%= m;}a *= a;a %= m;n >>= 1;}return ans;} 
const ll MOD9 = 998244353LL;
const ll MOD10 = 1000000007LL;

// for AOJ or ICPC or etc..
// 全部が0だったらtrueを返す
template<class Tp> bool zero (const Tp &x) {return x == 0;}
template<class Tp, class... Args> bool zero (const Tp &x, const Args& ...args) {return zero(x) and zero(args...);}


// 変数をちゃんと全部受け取る！
void solve(ll n){
  LL(lx,ly,rx,ry);
  lx--;ly--;rx--;ry--;
  vll x(n+1),y(n+1);
  rep(i,n+1){
    cin >> x[i] >> y[i];
    x[i]--;y[i]--;
  }

  auto insq = [&](ll ny,ll nx){
    return (ly <= ny && ny <= ry && lx <= nx && nx <= rx);
  };

  auto bfs = [&](ll id){
    deque<pll> deq;
    //0からの距離が入る
    vvll find(100,vll(100,INF));
    find[y[id]][x[id]] = 0;
    deq.push_back({y[id],x[id]});
    while(!deq.empty()){
     auto[ny,nx] = deq.front();
     deq.pop_front();
     rep(i,4){
      ll ty = ny + _ta[i];
      ll tx = nx + _yo[i];
      if(isin(ty,tx,100,100) && find[ty][tx] == INF){
        if(insq(ty,tx)){
          find[ty][tx] = find[ny][nx];
          deq.push_front({ty,tx});
        }else{
          find[ty][tx] = find[ny][nx] + 1;
          deq.push_back({ty,tx});
        }
      }
     }
    }
    // rep(i,10){
    //   rep(j,10){
    //     cerr << find[i][j] << " ";
    //   }
    //   cerr << endl;
    // }
    // cerr << endl;
    // cerr << y[id+1] << " " << x[id+1] << endl;
    return find[y[id+1]][x[id+1]];
  };

  auto dist = [&](ll id){
    if(insq(y[id],x[id])){
      return 0LL;
    }
    ll xcost = 0;
    if(x[id] < lx){
      xcost += lx - x[id];
    }else if(x[id] > rx){
      xcost += x[id] - rx;
    }
    ll ycost = 0;
    if(y[id] < ly){
      ycost += ly - y[id];
    }else if(y[id] > ry){
      ycost += y[id] -ry;
    }
    return xcost + ycost;
  };

  ll ans = 0;
  rep(i,n){
    ll basecost = bfs(i);
    ll mae = dist(i);
    if(mae != 0){
      mae--;
    }
    ll ushiro  = dist(i+1);
    ans += min(mae + ushiro,basecost);

    // cerr << ans << endl;
  }
  cout << ans << endl;
}
 
int main(){
  ios::sync_with_stdio(false);cin.tie(nullptr);
  while(true){
    LL(n);//変数数調整
    if(zero(n))break;
    solve(n);
  }
}
accuracy: 1
time_ms: 230
memory_kb: 3652
final_rank: 10

code_snippet: #include <iostream>
#include <vector>
#include <deque>
int calc(int A, int B, int C, int D, int X0, int Y0, int X1, int Y1) {
    std::deque<std::pair<int, int>> que;
    std::vector<std::vector<int>> dist(100, std::vector<int>(100, 1e9));
    dist[X0][Y0] = 0;
    que.push_front({ X0, Y0 });
    std::vector<int> deltas = { 1, 0, -1, 0 };
    while(!que.empty()) {
        auto [x, y] = que.front();
        que.pop_front();
        for(int d = 0; d < 4; d++) {
            int s = x + deltas[d];
            int t = y + deltas[d ^ 1];
            if(0 <= s && s < 100 && 0 <= t && t < 100) {
                if(A <= s && s < C && B <= t && t < D) {
                    if(dist[s][t] > dist[x][y]) {
                        dist[s][t] = dist[x][y];
                        que.push_front({ s, t });
                    }
                }
                else {
                    if(dist[s][t] > dist[x][y] + 1) {
                        dist[s][t] = dist[x][y] + 1;
                        que.push_back({ s, t });
                    }
                }
            }
        }
    }
    return dist[X1][Y1];
}

bool solve() {
    int N;
    std::cin >> N;
    if(N == 0) return false;
    int A, B, C, D;
    std::cin >> A >> B >> C >> D;
    A--;
    B--;
    std::vector<int> X(N + 1), Y(N + 1);
    for(int i = 0; i <= N; i++) {
        std::cin >> X[i] >> Y[i];
        X[i]--;
        Y[i]--;
    }
    int ans = 0;
    for(int i = 0; i < N; i++) {
        ans += calc(A, B, C, D, X[i], Y[i], X[i + 1], Y[i + 1]);
    }
    std::cout << ans << std::endl;
    return true;
}

int main() {
    while(solve());
}
accuracy: 1
time_ms: 290
memory_kb: 3544
final_rank: 7

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

using ll = long long;
using vll=vector<ll> ;
using ull= unsigned long long;
#define all(v) (v).begin(),(v).end()
#define rep(i,n) for(int i=0;i<n;i++)

using P =pair<ll,ll>;
using PP = pair<ll,P>;
vll dx={0,1,0,-1},dy={1,0,-1,0};
ll INF =1ll<<60;


bool solve(){
    ll N;cin>>N;
    if(N==0) return 0;
    ll a,b,c,d;cin>>a>>b>>c>>d;
    a--;b--;c--;d--;
    
    vll A(N+1),B(N+1);
    rep(i,N+1) cin>>B[i]>>A[i],A[i]--,B[i]--;

    ll ans=0;
    rep(i,N){
        ll nowi=A[i],nowj=B[i],toi=A[i+1],toj=B[i+1];
        
        vector dist(110,vll(100,INF));
        priority_queue<PP,vector<PP>,greater<PP>> pq;
       pq.push({0,{nowi,nowj}});
        while(pq.size()){
            auto [cost,now]=pq.top();pq.pop();
            auto [i2,j2]=now;
            if(dist[i2][j2]!=INF) continue;
        
            dist[i2][j2]=cost;
            rep(k,4){
                ull i3=i2+dx[k],j3=j2+dy[k];
                if(!(i3<100&&j3<100)) continue;
                if(b<=i3&&i3<=d&&a<=j3&&j3<=c) pq.push({cost,{i3,j3}});
                else pq.push({cost+1,{i3,j3}});
            }
        }
        ans+=dist[toi][toj];
 
    }
    cout << ans << endl;










    return 1;
}


int main(){
    while(solve());
}
accuracy: 1
time_ms: 6990
memory_kb: 3420
final_rank: 19

code_snippet: #include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for (int i = 0; i < (n); ++i)
using ll = long long;
int ctoi(char c){return c-'0';}
ll ctoll(char c){return c-'0';}

const int INF = 1001001001;

int bfs(vector<vector<int>>&field,int sx,int sy,int gx,int gy){
   int dx[4] = {1,0,-1,0};
   int dy[4] = {0,1,0,-1};
   vector<vector<int>>d((int)field.size(),vector<int>((int)field.at(0).size(),INF));
   deque<pair<int,int>>que;
   
   que.push_front(make_pair(sx,sy));
   d.at(sx).at(sy) = 0;

   while(que.size()){
      pair<int,int>p = que.front();
      que.pop_front();
      if(p.first == gx && p.second == gy)break;
      for(int i = 0;i < 4;i++){
         int nx = p.first + dx[i]; int ny = p.second + dy[i];

         if(0 <= nx && nx < field.size() && 0 <= ny && ny < field.at(0).size() && d.at(nx).at(ny) == INF){
            if(field[nx][ny] == 1){
               que.push_back({nx,ny});
               d.at(nx).at(ny) = d.at(p.first).at(p.second) + 1;

            }else{
               que.push_front({nx,ny});
               d.at(nx).at(ny) = d.at(p.first).at(p.second) + 0;
            } 
         }
      }
   }
   return d.at(gx).at(gy);
} 

void solve(int n){
     int a,b,c,d;
     cin >> a >> b >> c >> d;
     a--;b--;
     vector<vector<int>>field(100,vector<int>(100,1));
     for(int i = b;i < d;i++){
          for(int j = a;j < c;j++){
               field[i][j] = 0;
          }
     }

     vector<pair<int,int>>xy(n+1);
     rep(i,n+1){
          int x,y;
          cin >> y >> x;
          x--;y--;
          xy[i] = {x,y};
     }

     int ans = 0;
     rep(i,n){
          ans += bfs(field,xy[i].first,xy[i].second,xy[i+1].first,xy[i+1].second);
     }
     cout << ans << endl;
}

int main(){
     while(true){
          int n;
          cin >> n;
          if(n==0)break;
          solve(n);
     }
}
accuracy: 1
time_ms: 260
memory_kb: 3588
final_rank: 9

code_snippet: #include<bits/stdc++.h>
using namespace std;
const int MAX = 1000000005;

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

int main() {
    ios::sync_with_stdio(0);cin.tie();
    int N;
    while (cin >> N) {
        if (N == 0) break;
        int A, B, C, D;
        cin >> A >> B >> C >> D;
        A--; B--; C--; D--;
        vector<int> X(N+1), Y(N+1);
        for (int i = 0; i < N+1; i++) {
            cin >> X[i] >> Y[i];
            X[i]--; Y[i]--;
        }
        int ans = 0;
        for (int i = 0; i < N; i++) {
            vector<vector<int>> dist(100, vector<int>(100, MAX));
            deque<pair<int, int>> deq;
            dist[X[i]][Y[i]] = 0;
            deq.push_back({X[i], Y[i]});
            while (deq.size()) {
                auto [x, y] = deq.front();
                deq.pop_front();
                for (int k = 0; k < 4; k++) {
                    int nx = x + dx[k], ny = y + dy[k];
                    if (nx < 0 || nx >= 100 || ny < 0 || ny >= 100) continue;
                    if (nx >= A && nx <= C && ny >= B && ny <= D) {
                        if (dist[nx][ny] > dist[x][y]) {
                            dist[nx][ny] = dist[x][y];
                            deq.push_front({nx, ny});
                        }
                    } else {
                        if (dist[nx][ny] > dist[x][y] + 1) {
                            dist[nx][ny] = dist[x][y] + 1;
                            deq.push_back({nx, ny});
                        }
                    }
                }
            }
            ans += dist[X[i+1]][Y[i+1]];
        }
        cout << ans << endl;
    }
}
accuracy: 1
time_ms: 330
memory_kb: 3440
final_rank: 4

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

int main(){
    while(1){
        int N; cin >> N;
        if(N == 0) break;
        int A, B, C, D; cin >> A >> B >> C >> D;
        A--, B--, C--, D--;

        int x, y; cin >> x >> y;
        x--, y--;
        int ans = 0;
        const int INF = 1e9;
        const int dx[4] = {0, 1, 0, -1};
        const int dy[4] = {1, 0, -1, 0};

        for(int _ = 0; _ < N; _++){
            vector<vector<int>> dist(100, vector<int>(100, INF));

            deque<pair<int, int>> deq;
            deq.push_front(make_pair(x, y));
            dist[x][y] = 0;
            while(!deq.empty()){
                const auto [ux, uy] = deq.front();
                deq.pop_front();
                for(int i = 0; i < 4; i++){
                    int nx = ux + dx[i], ny = uy + dy[i];
                    if(nx < 0 || 100 <= nx || ny < 0 || 100 <= ny) continue;
                    int cst = int(!(A <= nx && nx <= C && B <= ny && ny <= D));
                    if(dist[nx][ny] > dist[ux][uy] + cst){
                        dist[nx][ny] = dist[ux][uy] + cst;
                        if(cst == 0) deq.push_front(make_pair(nx, ny));
                        else deq.push_back(make_pair(nx, ny));
                    }
                }
            }

            int xxx, yyy; cin >> xxx >> yyy;
            xxx--, yyy--;
            ans += dist[xxx][yyy];
            x = xxx, y = yyy;
        }

        cout << ans << endl;
    }
}
accuracy: 1
time_ms: 290
memory_kb: 3384
final_rank: 1

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

int main(){
    while(1){
        int N; cin >> N;
        if(N == 0) break;
        int A, B, C, D; cin >> A >> B >> C >> D;
        A--, B--, C--, D--;

        int x, y; cin >> x >> y;
        x--, y--;
        int ans = 0;
        const int INF = 1e9;
        const int dx[4] = {0, 1, 0, -1};
        const int dy[4] = {1, 0, -1, 0};

        for(int _ = 0; _ < N; _++){
            vector<vector<int>> dist(100, vector<int>(100, INF));

            deque<pair<int, int>> deq;
            deq.push_front(make_pair(x, y));
            dist[x][y] = 0;
            while(!deq.empty()){
                const auto [ux, uy] = deq.front();
                deq.pop_front();
                for(int i = 0; i < 4; i++){
                    int nx = ux + dx[i], ny = uy + dy[i];
                    if(nx < 0 || 100 <= nx || ny < 0 || 100 <= ny) continue;
                    int cst = int(!(A <= nx && nx <= C && B <= ny && ny <= D));
                    if(dist[nx][ny] > dist[ux][uy] + cst){
                        dist[nx][ny] = dist[ux][uy] + cst;
                        if(cst == 0) deq.push_front(make_pair(nx, ny));
                        else deq.push_back(make_pair(nx, ny));
                    }
                }
            }

            int xxx, yyy; cin >> xxx >> yyy;
            xxx--, yyy--;
            ans += dist[xxx][yyy];
            x = xxx, y = yyy;
        }

        cout << ans << endl;
    }
}
accuracy: 1
time_ms: 290
memory_kb: 3444
final_rank: 3