Problem:
現代的な屋敷(Modern Mansion)
あなたは，ある大きな屋敷に迷い込んでしまった．この屋敷は正方形の部屋が東西南北に格子状に，東西方向に
M
列，南北方向に
N
行の合計
M × N
個並んだ構造をしている．西から
x
列目(1 ≤
x
≤
M
)，南から
y
行目(1 ≤
y
≤
N
) にある部屋を(
x
,
y
) で表す．
東西南北に隣り合う 2 部屋の間は，壁の中央にある扉により結ばれている．それぞれの扉は，閉じていて通行不可能な状態か，開いていて通行可能な状態のいずれかにある．扉が開いているとき，それらの部屋の中央間を移動するのに 1 分間かかる．また，いくつかの部屋の中央にはスイッチがあり，スイッチを 1 分間押し続けると，屋敷内のすべての扉の開閉の状態が切り替わる．
今，東西に隣り合う 2 部屋を結ぶすべての扉は閉じていて，南北に隣り合う 2 部屋を結ぶすべての扉は開いている．あなたは今部屋 (1, 1) の中央にいて，部屋 (
M
,
N
) の中央まで最短時間で移動したい．
課題
屋敷の大きさ
M
,
N
および，スイッチのある
K
個の部屋の位置 (
X
1
,
Y
1
), (
X
2
,
Y
2
),..., (
X
K
,
Y
K
) が与えられる．東西に隣り合う 2 部屋を結ぶすべての扉は閉じていて，南北に隣り合う 2 部屋を結ぶすべての扉は開いている状態から始めて，部屋 (1, 1) の中央から部屋 (
M
,
N
) の中央まで移動するのに最短で何分かかるかを求めるプログラムを作成せよ．ただし，部屋 (
M
,
N
) に辿り着くことができないときはそれを指摘せよ．
制限
2 ≤
M
≤ 100 000      屋敷の東西方向の部屋の個数
2 ≤
N
≤ 100 000     屋敷の南北方向の部屋の個数
1 ≤
K
≤ 200 000     スイッチのある部屋の個数
1 ≤
X
i
≤
M
スイッチのある部屋の東西方向の位置
1 ≤
Y
i
≤
N
スイッチのある部屋の南北方向の位置
入力
標準入力から以下のデータを読み込め．
1 行目には，整数
M, N, K
が空白を区切りとして書かれている．
M
は屋敷の東西方向の部屋の個数，
N
は屋敷の南北方向の部屋の個数，
K
はスイッチのある部屋の個数を表す．
続く
K
行のうちの
i
行目(1 ≤
i
≤
K
) には，整数
X
i
,
Y
i
が空白を区切りとして書かれている．これは，部屋(
X
i
,
Y
i
) の中央にスイッチがあることを表す．
K
個の組(
X
1
,
Y
1
), (
X
2
,
Y
2
),..., (
X
K
,
Y
K
) は互いに異なる．
出力
標準出力に，移動に最短で何分かかるかを表す整数を 1 行で出力せよ．ただし，部屋(
M
,
N
) に辿り着くことができないときは代わりに整数 -1 を出力せよ．
採点基準
採点用データのうち，配点の20%分については，
M
≤ 1 000,
N
≤ 1 000 を満たす．
採点用データのうち，配点の30%分については，
K
≤ 2 000 を満たす．
採点用データのうち，配点の50%分については，これら 2 つの条件の少なくとも一方を満たす．また，これら 2 つの条件の両方を満たすような採点用データはない．
入出力例
入力例 1
3 2 1
1 2
出力例 1
4
この例では，以下の行動によって 4 分間で部屋(1, 1) の中央から部屋(3, 2) の中央へ移動することができ，これが最短である．
部屋(1, 2) の中央へ移動する．
部屋(1, 2) の中央のスイッチを押す．
部屋(2, 2) の中央へ移動する．
部屋(3, 2) の中央へ移動する．
このときの屋敷の様子が以下の図に表されている．図では右方向が東，上方向が北であり，×印はあなたの位置，○印はスイッチを表す．
入力例 2
3 2 1
2 1
出力例 2
-1
この例では，あなたは部屋(3, 2) に辿り着くことができない．
入力例 3
8 9 15
3 1
3 2
3 7
3 8
1 1
4 5
4 3
5 6
5 8
6 3
6 2
7 5
8 9
8 6
8 5
出力例 3
25
この例では，最初の屋敷の様子は以下の図のようになっている．部屋(1, 1) や部屋(
M
,
N
) の中央にスイッチがある可能性もあることに注意せよ．
問題文と自動審判に使われるデータは、
情報オリンピック日本委員会
が作成し公開している問題文と採点用テストデータです。

Submitted solutions:

code_snippet: #include<iostream>
#include<functional>
#include<algorithm>
#include<queue>
#include<tuple>
using namespace std;
#pragma warning(disable:4996)
long long a[240000], b[240000], dist[240000][2], H, W, K;
vector<pair<int, int>>X[120000], Y[120000];
vector<tuple<long long, long long, long long>>x[240000][2];
priority_queue<tuple<long long, long long, long long>, vector<tuple<long long, long long, long long>>, greater<tuple<long long, long long, long long>>>Q;
void dijkstra() {
	for (int i = 0; i < 240000; i++) { dist[i][0] = 999999999999999999LL; dist[i][1] = 999999999999999999LL; }
	dist[0][0] = 0; Q.push(make_tuple(0, 0, 0));
	while (!Q.empty()) {
		long long a1 = get<0>(Q.top()), a2 = get<1>(Q.top()), a3 = get<2>(Q.top()); Q.pop();
		for (int i = 0; i < x[a2][a3].size(); i++) {
			long long to1 = get<0>(x[a2][a3][i]), to2 = get<1>(x[a2][a3][i]), cost = get<2>(x[a2][a3][i]);
			if (dist[to1][to2] > a1 + cost) {
				dist[to1][to2] = a1 + cost; Q.push(make_tuple(dist[to1][to2], to1, to2));
			}
		}
	}
}
int main() {
	cin >> H >> W >> K; X[1].push_back(make_pair(1, 0)); Y[1].push_back(make_pair(1, 0));
	X[H].push_back(make_pair(W, K + 1)); Y[W].push_back(make_pair(H, K + 1));
	for (int i = 1; i <= K; i++) { scanf("%d%d", &a[i], &b[i]); X[a[i]].push_back(make_pair(b[i], i)); Y[b[i]].push_back(make_pair(a[i], i)); }
	for (int i = 1; i <= H; i++) { sort(X[i].begin(), X[i].end()); }
	for (int i = 1; i <= W; i++) { sort(Y[i].begin(), Y[i].end()); }
	for (int i = 1; i <= H; i++) {
		for (int j = 0; j < X[i].size(); j++) {
			int G1 = X[i][j].first, G2 = X[i][j].second;
			if (G2 != 0 && G2 != K + 1) { x[G2][0].push_back(make_tuple(G2, 1, 1)); x[G2][1].push_back(make_tuple(G2, 0, 1)); }
			if (j != X[i].size() - 1) {
				int G3 = X[i][j + 1].first, G4 = X[i][j + 1].second;
				x[G2][0].push_back(make_tuple(G4, 0, abs(G1 - G3))); x[G4][0].push_back(make_tuple(G2, 0, abs(G1 - G3)));
			}
		}
	}
	for (int i = 1; i <= W; i++) {
		for (int j = 0; j < Y[i].size(); j++) {
			int G1 = Y[i][j].first, G2 = Y[i][j].second;
			if (G2 != 0 && G2 != K + 1) { x[G2][0].push_back(make_tuple(G2, 1, 1)); x[G2][1].push_back(make_tuple(G2, 0, 1)); }
			if (j != Y[i].size() - 1) {
				int G3 = Y[i][j + 1].first, G4 = Y[i][j + 1].second;
				x[G2][1].push_back(make_tuple(G4, 1, abs(G1 - G3))); x[G4][1].push_back(make_tuple(G2, 1, abs(G1 - G3)));
			}
		}
	}
	dijkstra();
	long long ans = min(dist[K + 1][0], dist[K + 1][1]);
	if (ans >= 999999999999999LL)ans = -1;
	cout << ans << endl;
	return 0;
}
accuracy: 1
time_ms: 300
memory_kb: 84432
final_rank: 10

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

const int MX_SIZE= 2e6 + 10;

struct node {
    int u;
    long long cost;
};

struct edge {
    int u;
    long long cost;
};

struct cmp {
    bool operator()(node &l, node &r) {
        return l.cost > r.cost;
    }
};

vector< edge > adj[MX_SIZE];
long long dist[MX_SIZE];

void dijkstra( int src) {
    for(int i = 0; i < MX_SIZE; i++)
        dist[i] = 1e18;
    dist[src] = 0;

    priority_queue<node, vector<node>, cmp> pq;
    pq.push({src, 0});

    while (!pq.empty()) {
        long long u = pq.top().u;
        long long cost = pq.top().cost;
        pq.pop();

        if (dist[u] < cost) continue;

        for (auto [v, w]: adj[u]) {
            if (dist[v] > dist[u] + w) {
                dist[v] = dist[u] + w;
                pq.push({v, dist[v]});
            }
        }
    }
}

int main() {
    int n, m, k;
    cin >> m >> n >> k;
    
    pair<pair<int, int>, int> key[k+2];
    for(int i = 1; i <= k; i++){
		cin >> key[i].first.first >> key[i].first.second;
		key[i].second = i;
	}
    
    // key in position (1, 1)
    key[0].first.first = 1;
    key[0].first.second = 1;
    key[0].second = 0;
    
    // key in position (m, n)
    key[k + 1].first.first = m;
    key[k + 1].first.second = n;
    key[k + 1].second = k + 1;
    
    for(int i = 1; i <= k; i++){
		edge e;
		e.cost = 1;
		e.u = i + k + 2;
		adj[i].push_back(e);
		e.u = i;
		adj[i + k + 2].push_back(e);
	}
    
    sort(key, key + k + 2);

    for(int i = 0; i <= k; i++){
		if(key[i].first.first == key[i + 1].first.first){
			edge e;
			e.cost = abs(key[i + 1].first.second - key[i].first.second);
			e.u = key[i + 1].second;
			adj[key[i].second].push_back(e);
			e.u = key[i].second;
			adj[key[i + 1].second].push_back(e);
		}
	}
    
    for(int i = 0; i <= k + 1; i++){
		swap(key[i].first.first, key[i].first.second);
		key[i].second += k + 2; 
	}
	
	sort(key, key + k + 2);
	
    for(int i = 0; i <= k; i++){
		if(key[i].first.first == key[i + 1].first.first){
			edge e;
			e.cost = abs(key[i + 1].first.second - key[i].first.second);
			e.u = key[i + 1].second;
			adj[key[i].second].push_back(e);
			e.u = key[i].second;
			adj[key[i + 1].second].push_back(e);
		}
	}
    
    dijkstra(0);
    long long ans = min(dist[k+1], dist[2 * k + 3]);
    
    if(ans == 1e18)
        cout << -1 << "\n";
    else
        cout << ans << "\n";
    return 0;
}
accuracy: 1
time_ms: 260
memory_kb: 102304
final_rank: 11

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

const int MX_SIZE= 2e6 + 10;

struct node {
    int u;
    long long cost;
};

struct edge {
    int u;
    int cost;
};

struct cmp {
    bool operator()(node &l, node &r) {
        return l.cost > r.cost;
    }
};

vector< edge > adj[MX_SIZE];
long long dist[MX_SIZE];

void dijkstra( int src) {
    for(int i = 0; i < MX_SIZE; i++)
        dist[i] = 1e18;
    dist[src] = 0;

    priority_queue<node, vector<node>, cmp> pq;
    pq.push({src, 0});

    while (!pq.empty()) {
        long long u = pq.top().u;
        long long cost = pq.top().cost;
        pq.pop();

        if (dist[u] < cost) continue;

        for (auto [v, w]: adj[u]) {
            if (dist[v] > dist[u] + w) {
                dist[v] = dist[u] + w;
                pq.push({v, dist[v]});
            }
        }
    }
}

int main() {
    int n, m, k;
    cin >> m >> n >> k;

    pair<pair<int, int>, int> key[k+2];
    for(int i = 1; i <= k; i++){
        cin >> key[i].first.first >> key[i].first.second;
        key[i].second = i;
    }

    // key in position (1, 1)
    key[0].first.first = 1;
    key[0].first.second = 1;
    key[0].second = 0;

    // key in position (m, n)
    key[k + 1].first.first = m;
    key[k + 1].first.second = n;
    key[k + 1].second = k + 1;

    for(int i = 1; i <= k; i++){
        edge e;
        e.cost = 1;
        e.u = i + k + 2;
        adj[i].push_back(e);
        e.u = i;
        adj[i + k + 2].push_back(e);
    }

    sort(key, key + k + 2);

    for(int i = 0; i <= k; i++){
        if(key[i].first.first == key[i + 1].first.first){
            edge e;
            e.cost = abs(key[i + 1].first.second - key[i].first.second);
            e.u = key[i + 1].second;
            adj[key[i].second].push_back(e);
            e.u = key[i].second;
            adj[key[i + 1].second].push_back(e);
        }
    }

    for(int i = 0; i <= k + 1; i++){
        swap(key[i].first.first, key[i].first.second);
        key[i].second += k + 2;
    }

    sort(key, key + k + 2);

    for(int i = 0; i <= k; i++){
        if(key[i].first.first == key[i + 1].first.first){
            edge e;
            e.cost = abs(key[i + 1].first.second - key[i].first.second);
            e.u = key[i + 1].second;
            adj[key[i].second].push_back(e);
            e.u = key[i].second;
            adj[key[i + 1].second].push_back(e);
        }
    }

    dijkstra(0);
    int ans = min(dist[k+1], dist[2 * k + 3]);

    if(ans >= 1e18)
        cout << -1 << "\n";
    else
        cout << ans << "\n";
    return 0;
}
accuracy: 0.03225806451612903
time_ms: 190
memory_kb: 90252
final_rank: 20

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

const int MX_SIZE= 2e6 + 10;

struct node {
    int u;
    long long cost;
};

struct edge {
    int u;
    int cost;
};

struct cmp {
    bool operator()(node &l, node &r) {
        return l.cost > r.cost;
    }
};

vector< edge > adj[MX_SIZE];
long long dist[MX_SIZE];

void dijkstra( int src) {
    for(int i = 0; i < MX_SIZE; i++)
        dist[i] = 1e18;
    dist[src] = 0;

    priority_queue<node, vector<node>, cmp> pq;
    pq.push({src, 0});

    while (!pq.empty()) {
        long long u = pq.top().u;
        long long cost = pq.top().cost;
        pq.pop();

        if (dist[u] < cost) continue;

        for (auto [v, w]: adj[u]) {
            if (dist[v] > dist[u] + w) {
                dist[v] = dist[u] + w;
                pq.push({v, dist[v]});
            }
        }
    }
}

int main() {
    int n, m, k;
    cin >> m >> n >> k;

    pair<pair<int, int>, int> key[k+2];
    for(int i = 1; i <= k; i++){
        cin >> key[i].first.first >> key[i].first.second;
        key[i].second = i;
    }

    // key in position (1, 1)
    key[0].first.first = 1;
    key[0].first.second = 1;
    key[0].second = 0;

    // key in position (m, n)
    key[k + 1].first.first = m;
    key[k + 1].first.second = n;
    key[k + 1].second = k + 1;

    for(int i = 1; i <= k; i++){
        edge e;
        e.cost = 1;
        e.u = i + k + 2;
        adj[i].push_back(e);
        e.u = i;
        adj[i + k + 2].push_back(e);
    }

    sort(key, key + k + 2);

    for(int i = 0; i <= k; i++){
        if(key[i].first.first == key[i + 1].first.first){
            edge e;
            e.cost = abs(key[i + 1].first.second - key[i].first.second);
            e.u = key[i + 1].second;
            adj[key[i].second].push_back(e);
            e.u = key[i].second;
            adj[key[i + 1].second].push_back(e);
        }
    }

    for(int i = 0; i <= k + 1; i++){
        swap(key[i].first.first, key[i].first.second);
        key[i].second += k + 2;
    }

    sort(key, key + k + 2);

    for(int i = 0; i <= k; i++){
        if(key[i].first.first == key[i + 1].first.first){
            edge e;
            e.cost = abs(key[i + 1].first.second - key[i].first.second);
            e.u = key[i + 1].second;
            adj[key[i].second].push_back(e);
            e.u = key[i].second;
            adj[key[i + 1].second].push_back(e);
        }
    }

    dijkstra(0);
    int ans = min(dist[k+1], dist[2 * k + 3]);

    if(ans == 1e18)
        cout << -1 << "\n";
    else
        cout << ans << "\n";
    return 0;
}
accuracy: 0.03225806451612903
time_ms: 190
memory_kb: 90140
final_rank: 19

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

const int MX_SIZE= 2e6 + 10;

struct node {
    int u;
    long long cost;
};

struct edge {
    int u;
    int cost;
};

struct cmp {
    bool operator()(node &l, node &r) {
        return l.cost > r.cost;
    }
};

vector< edge > adj[MX_SIZE];
long long dist[MX_SIZE];

void dijkstra( int src) {
    for(int i = 0; i < MX_SIZE; i++)
        dist[i] = 1e9;
    dist[src] = 0;

    priority_queue<node, vector<node>, cmp> pq;
    pq.push({src, 0});

    while (!pq.empty()) {
        long long u = pq.top().u;
        long long cost = pq.top().cost;
        pq.pop();

        if (dist[u] < cost) continue;

        for (auto [v, w]: adj[u]) {
            if (dist[v] > dist[u] + w) {
                dist[v] = dist[u] + w;
                pq.push({v, dist[v]});
            }
        }
    }
}

int main() {
    int n, m, k;
    cin >> m >> n >> k;

    pair<pair<int, int>, int> key[k+2];
    for(int i = 1; i <= k; i++){
        cin >> key[i].first.first >> key[i].first.second;
        key[i].second = i;
    }

    // key in position (1, 1)
    key[0].first.first = 1;
    key[0].first.second = 1;
    key[0].second = 0;

    // key in position (m, n)
    key[k + 1].first.first = m;
    key[k + 1].first.second = n;
    key[k + 1].second = k + 1;

    for(int i = 1; i <= k; i++){
        edge e;
        e.cost = 1;
        e.u = i + k + 2;
        adj[i].push_back(e);
        e.u = i;
        adj[i + k + 2].push_back(e);
    }

    sort(key, key + k + 2);

    for(int i = 0; i <= k; i++){
        if(key[i].first.first == key[i + 1].first.first){
            edge e;
            e.cost = abs(key[i + 1].first.second - key[i].first.second);
            e.u = key[i + 1].second;
            adj[key[i].second].push_back(e);
            e.u = key[i].second;
            adj[key[i + 1].second].push_back(e);
        }
    }

    for(int i = 0; i <= k + 1; i++){
        swap(key[i].first.first, key[i].first.second);
        key[i].second += k + 2;
    }

    sort(key, key + k + 2);

    for(int i = 0; i <= k; i++){
        if(key[i].first.first == key[i + 1].first.first){
            edge e;
            e.cost = abs(key[i + 1].first.second - key[i].first.second);
            e.u = key[i + 1].second;
            adj[key[i].second].push_back(e);
            e.u = key[i].second;
            adj[key[i + 1].second].push_back(e);
        }
    }

    dijkstra(0);
    int ans = min(dist[k+1], dist[2 * k + 3]);

    if(ans == 1e9)
        cout << -1 << "\n";
    else
        cout << ans << "\n";
    return 0;
}
accuracy: 0.7419354838709677
time_ms: 230
memory_kb: 90180
final_rank: 17

code_snippet: #include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <climits>
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <utility>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <deque>
#include <functional>

using namespace std;

#define int long long
#define MP make_pair
#define PB push_back
#define FI first
#define SE second
#define MAX_K 200000
typedef pair<int, pair<int, int> > PPII;
typedef pair<int, int> PII;
static const int INF = 1ll << 60;
static const int dx[] = { 1, -1, 0, 0 };
static const int dy[] = { 0, 0, 1, -1 };

int M, N, K;
vector<PII> fld, X, Y;
int D[MAX_K + 5];
bool flg = false;

// ダイクストラアルゴリズムによる最短距離計算
void dijkstra() {
    priority_queue<PPII, vector<PPII>, greater<PPII> > que;
    fill(D, D + MAX_K + 5, INF);
    D[0] = 0;
    que.push(PPII(0, PII(0, 0)));
    
    while (!que.empty()) {
        PPII p = que.top();
        que.pop();
        int v = p.SE.FI;
        int On = p.SE.SE;
        
        if (D[v] < p.FI) continue;
        if (fld[v].FI == M && fld[v].SE == N) break;

        int p1 = lower_bound(X.begin(), X.end(), PII(fld[v].FI, fld[v].SE)) - X.begin();
        int p2 = lower_bound(Y.begin(), Y.end(), PII(fld[v].SE, fld[v].FI)) - Y.begin();
        
        for (int i = p1 - 1; i <= p1 + 1; i++) {
            if (p1 == X.size()) break;
            if (i < 0 || i >= X.size()) continue;
            int t = lower_bound(fld.begin(), fld.end(), PII(X[i].FI, X[i].SE)) - fld.begin();
            PII e = fld[t];
            if (fld[v].FI != e.FI) continue;
            if ((!flg) && e.FI == 1 && e.SE == 1) continue;
            if (fld[v].FI != e.FI && fld[v].SE != e.SE) continue;
            int cost = abs(e.FI - fld[v].FI) + abs(e.SE - fld[v].SE);
            if (On == 1) cost++;
            if (D[t] > D[v] + cost) {
                D[t] = D[v] + cost;
                que.push(PPII(D[t], MP(t, 0)));
            }
        }
        
        for (int i = p2 - 1; i <= p2 + 1; i++) {
            if (flg == false && fld[v].FI == 1 && fld[v].SE == 1) break;
            if (p2 == Y.size()) break;
            if (i < 0 || i >= Y.size()) continue;
            int t = lower_bound(fld.begin(), fld.end(), PII(Y[i].SE, Y[i].FI)) - fld.begin();
            PII e = fld[t];
            if (fld[v].SE != e.SE) continue;
            if ((!flg) && e.FI == 1 && e.SE == 1) continue;
            if (fld[v].FI != e.FI && fld[v].SE != e.SE) continue;
            int cost = abs(e.FI - fld[v].FI) + abs(e.SE - fld[v].SE);
            if (On == 0) cost++;
            if (D[t] > D[v] + cost) {
                D[t] = D[v] + cost;
                que.push(PPII(D[t], MP(t, 1)));
            }
        }
    }
}

signed main() {
    cin >> M >> N >> K;
    fld.PB(PII(1, 1));
    fld.PB(PII(M, N));
    X.PB(PII(1, 1));
    Y.PB(PII(1, 1));
    X.PB(PII(M, N));
    Y.PB(PII(N, M));
    
    for (int i = 0; i < K; ++i) {
        int x, y;
        cin >> x >> y;
        if (x == 1 && y == 1) {
            flg = true;
            continue;
        }
        if (x == M && y == N) continue;
        fld.PB(PII(x, y));
        X.PB(PII(x, y));
        Y.PB(PII(y, x));
    }
    
    sort(fld.begin(), fld.end());
    sort(X.begin(), X.end());
    sort(Y.begin(), Y.end());
    
    dijkstra();
    
    int ans = lower_bound(fld.begin(), fld.end(), MP(M, N)) - fld.begin();
    if (D[ans] >= INF) cout << -1 << endl;
    else cout << D[ans] << endl;
    
    return 0;
}
accuracy: 1
time_ms: 280
memory_kb: 19008
final_rank: 1

code_snippet: #include <bits/stdc++.h>
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(), v.rend()
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define drep(i,j,n) for(int i=0;i<(int)(n-1);i++)for(int j=i+1;j<(int)(n);j++)
#define trep(i,j,k,n) for(int i=0;i<(int)(n-2);i++)for(int j=i+1;j<(int)(n-1);j++)for(int k=j+1;k<(int)(n);k++)
#define codefor int test;scanf("%d",&test);while(test--)
#define INT(...) int __VA_ARGS__;in(__VA_ARGS__)
#define LL(...) ll __VA_ARGS__;in(__VA_ARGS__)
#define yes(ans) if(ans)printf("yes\n");else printf("no\n")
#define Yes(ans) if(ans)printf("Yes\n");else printf("No\n")
#define YES(ans) if(ans)printf("YES\n");else printf("NO\n")
#define popcount(v) __builtin_popcountll(v)
#define vector2d(type,name,h,...) vector<vector<type>>name(h,vector<type>(__VA_ARGS__))
#define vector3d(type,name,h,w,...) vector<vector<vector<type>>>name(h,vector<vector<type>>(w,vector<type>(__VA_ARGS__)))
#define vector4d(type,name,h,w,d,...) vector<vector<vector<vector<type>>>>name(h,vector<vector<vector<type>>>(w,vector<vector<type>>(d,vector<type>(__VA_ARGS__))))
using namespace std;
using ll = long long;
template<class T> using rpriority_queue = priority_queue<T, vector<T>, greater<T>>;
const int MOD=1000000007;
const int MOD2=998244353;
const int INF=1<<30;
const ll INF2=1LL<<60;
void scan(int& a){scanf("%d",&a);}
void scan(long long& a){scanf("%lld",&a);}
template<class T,class L>void scan(pair<T, L>& p){scan(p.first);scan(p.second);}
template<class T,class U,class V>void scan(tuple<T,U,V>& p){scan(get<0>(p));scan(get<1>(p));scan(get<2>(p));}
template<class T, size_t size> void scan(array<T, size>& a){ for(auto&& i : a) scan(i);}
template<class T> void scan(T& a){cin>>a;}
template<class T> void scan(vector<T>& vec){for(auto&& it:vec)scan(it);}
void in(){}
template <class Head, class... Tail> void in(Head& head, Tail&... tail){scan(head);in(tail...);}
void print(const int& a){printf("%d",a);}
void print(const long long& a){printf("%lld",a);}
void print(const double& a){printf("%.15lf",a);}
template<class T,class L>void print(const pair<T, L>& p){print(p.first);putchar(' ');print(p.second);}
template<class T> void print(const T& a){cout<<a;}
template<class T> void print(const vector<T>& vec){if(vec.empty())return;print(vec[0]);for(auto it=vec.begin();++it!= vec.end();){putchar(' ');print(*it);}}
void out(){putchar('\n');}
template<class T> void out(const T& t){print(t);putchar('\n');}
template <class Head, class... Tail> void out(const Head& head,const Tail&... tail){print(head);putchar(' ');out(tail...);}
template<class T> void dprint(const T& a){cerr<<a;}
template<class T> void dprint(const vector<T>& vec){if(vec.empty())return;cerr<<vec[0];for(auto it=vec.begin();++it!= vec.end();){cerr<<" "<<*it;}}
void debug(){cerr<<endl;}
template<class T> void debug(const T& t){dprint(t);cerr<<endl;}
template <class Head, class... Tail> void debug(const Head& head, const Tail&... tail){dprint(head);cerr<<" ";debug(tail...);}
ll intpow(ll a, ll b){ ll ans = 1; while(b){ if(b & 1) ans *= a; a *= a; b /= 2; } return ans; }
ll modpow(ll a, ll b, ll p){ ll ans = 1; while(b){ if(b & 1) (ans *= a) %= p; (a *= a) %= p; b /= 2; } return ans; }
ll modinv(ll a, ll m) {ll b = m, u = 1, v = 0;while (b) {ll t = a / b;a -= t * b; swap(a, b);u -= t * v; swap(u, v);}u %= m;if (u < 0) u += m;return u;}
ll updivide(ll a,ll b){return (a+b-1)/b;}
int msb(ll v){return 63-__builtin_clzll(v);}
template<class T> void chmax(T &a,const T b){if(b>a)a=b;}
template<class T> void chmin(T &a,const T b){if(b<a)a=b;}

int main(){
    INT(h,w,k);
    vector<vector<pair<int,int>>> Y(h),X(w);
    vector<vector<pair<int,int>>> g(2*k+2);
    Y[0].emplace_back(0,2*k);
    //X[0].emplace_back(0,2*k);
    Y[h-1].emplace_back(w-1,2*k+1);
    X[w-1].emplace_back(h-1,2*k+1);
    int y,x,x1,x2,y1,y2;
    rep(i,k){
        in(y,x);
        y--,x--;
        Y[y].emplace_back(x,i);
        X[x].emplace_back(y,k+i);
        g[i].emplace_back(k+i,1);
        g[k+i].emplace_back(i,1);
    }
    rep(y,h){
        sort(all(Y[y]));
        for(int i=0;i+1<Y[y].size();i++){
            tie(x1,y1)=Y[y][i];
            tie(x2,y2)=Y[y][i+1];
            g[y1].emplace_back(y2,x2-x1);
            g[y2].emplace_back(y1,x2-x1);
        }
    }
    rep(x,w){
        sort(all(X[x]));
        for(int i=0;i+1<X[x].size();i++){
            tie(x1,y1)=X[x][i];
            tie(x2,y2)=X[x][i+1];
            g[y1].emplace_back(y2,x2-x1);
            g[y2].emplace_back(y1,x2-x1);
        }
    }
    vector<ll> dist(2*k+2,INF2);
    ll d;
    int v;
    rpriority_queue<pair<ll,int>> pq;
    dist[2*k]=0;
    pq.push({0,2*k});
    while(!pq.empty()){
        tie(d,v)=pq.top();
        pq.pop();
        if(d>dist[v])continue;
        for(auto p:g[v]){
            if(d+p.second>=dist[p.first])continue;
            dist[p.first]=d+p.second;
            pq.push({dist[p.first],p.first});
        }
    }
    out(dist.back()==INF2?-1:dist.back());
}
accuracy: 1
time_ms: 230
memory_kb: 46940
final_rank: 2

code_snippet: #include <bits/stdc++.h>
using namespace std;
const long long MOD1 = 1000000007;
const long long MOD2 = 998244353;
typedef long long ll;
//typedef int ll;
typedef pair<ll, ll> P;
const long long INF = 1e10;
template <typename T>
void input_arr(vector<T>& A, ll N) {
	for (ll i = 0; i < N; i++) {
		cin >> A[i];
	}
}
template <typename T, typename Q>
void input_arr(vector<pair<T, Q>>& A, ll N) {
	for (ll i = 0; i < N; i++) {
		cin >> A[i].first >> A[i].second;
	}
}
template <typename T>
void input_arr(vector<vector<T>>& A, ll H, ll W) {
	for (ll i = 0; i < H; i++) {
		for (ll j = 0; j < W; j++) {
			cin >> A[i][j];
		}
	}
}
template<typename T = ll>
struct Edge {
    ll from, to; T cost;
    Edge (ll from, ll to, T cost = 1) : from(from), to(to), cost(cost) {}
};
template<typename T = ll>
struct Graph {
    vector<vector<Edge<T>>> G;
    Graph() = default;
    explicit Graph(ll N) : G(N) {}
    size_t size() const {
        return G.size();
    }
    void add_edge(ll from, ll to, T cost = 1, bool direct = false) {
        G[from].emplace_back(from, to, cost);
        if (!direct) G[to].emplace_back(to, from, cost);
    }
    void read(ll M, ll padding = -1, bool weight = false, bool direct = false) {
        for (ll i = 0; i < M; i++) {
            ll a, b; cin >> a >> b;
            a += padding;
            b += padding;
            T c = T(1);
            if (weight) cin >> c;
            add_edge(a, b, c, direct);
        }
    }
    vector<Edge<T>> &operator[](const int &k) {
        return G[k];
    }
};
void dijkstra(const Graph<long long>& G, int s, vector<long long>& dis) {
    int N = G.size();
    dis.resize(N, INF);
    priority_queue<P, vector<P>, greater<P>> pq;
    dis[s] = 0;
    pq.emplace(dis[s], s);
    while (!pq.empty()) {
        P p = pq.top();
        pq.pop();
        int v = p.second;
        if (dis[v] < p.first) {
            continue;
        }
        for (auto& e : G.G[v]) {
            if (dis[e.to] > dis[v] + e.cost) {
                dis[e.to] = dis[v] + e.cost;
                pq.emplace(dis[e.to], e.to);
            }
        }
    }
}
void solve() {
    ll M, N, K; cin >> M >> N >> K;
    Graph<ll>G(2 * K + 2);
    vector<P>X(K); input_arr(X, K);
    vector<pair<P, ll>>A(K);
    for (ll i = 0; i < K; i++) {
        A[i] = {X[i], i + 1};
        G.add_edge(i + 1, K + i + 1, 1);
        if (X[i].first == 1) G.add_edge(0, i + 1, abs(X[i].second - 1));
        if (X[i].first == M) G.add_edge(i + 1, 2 * K + 1, abs(X[i].second - N));
        if (X[i].second == N) G.add_edge(K + i + 1, 2 * K + 1, abs(X[i].first - M));
    }
    sort(A.begin(), A.end());
    for (ll i = 0; i < K - 1; i++) {
        if (A[i].first.first == A[i + 1].first.first) G.add_edge(A[i].second, A[i + 1].second, abs(A[i].first.second - A[i + 1].first.second));
    }
    for (ll i = 0; i < K; i++) {
        swap(A[i].first.first, A[i].first.second);
    }
    sort(A.begin(), A.end());
    for (ll i = 0; i < K - 1; i++) {
        if (A[i].first.first == A[i + 1].first.first) G.add_edge(A[i].second + K, A[i + 1].second + K, abs(A[i].first.second - A[i + 1].first.second));
    }
    vector<ll>dist(2 * K + 2, INF);
    dijkstra(G, 0, dist);
    if (dist[2 * K + 1] == INF) cout << -1 << endl;
    else cout << dist[2 * K + 1] << endl;
}
int main() {
    ll T=1; //cin >> T;
    while (T--) solve();
}
accuracy: 1
time_ms: 290
memory_kb: 70084
final_rank: 7

code_snippet: #include<bits/stdc++.h>
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#define rep(i, x) for(ll i = 0; i < x; i++)
#define rep2(i, x) for(ll i = 1; i <= x; i++)
#define all(a) (a).begin(),(a).end()
#define puts(x) cout << (x) << "\n"
using ll = long long;
using ld = long double;
using namespace std;
const ll INF = 10000000000000000;

typedef pair <ll, ll> P;
struct status {
	bool ok;
	ll x;
	ll y;
	ll cost;

	bool operator<(const status& rhs) const { return cost < rhs.cost; };
	bool operator>(const status& rhs) const { return cost > rhs.cost; };
};

signed main() {
	ios::sync_with_stdio(false);
	std::cin.tie(nullptr);
	//cout << fixed << setprecision(15);

	//問題と縦横が逆ぎゃっぶぶぶぶぶっくしでゅ
	//input
	ll m, n, k; cin >> m >> n >> k;
	vector<ll> x(k), y(k); vector<vector<P>> tate(m + 2), yoko(n + 2);
	bool first = false;
	rep(i, k) {
		cin >> x[i] >> y[i]; tate[x[i]].push_back(P(y[i], i)); yoko[y[i]].push_back(P(x[i], i));
		if (x[i] == 1 && y[i] == 1) { first = true; }
	}
	if (!first) { tate[1].push_back(P(1, k)); yoko[1].push_back(P(1, k)); }

	ll ans = INF;
	vector<ll> d(k + 1, INF);
	priority_queue<status, vector<status>, greater<status> >que;
	que.push({ true, m, n, 0 }); que.push({ false, m, n, 0 });
	while (que.size()) {
		bool flag = que.top().ok;
		ll px = que.top().x, py = que.top().y, c = que.top().cost; que.pop();
		if (px == 1 && py == 1) {
			if (flag) { ans = min(ans, c - 1); }
			if (!flag && first) { ans = min(ans, c); }
			continue;
		}
		if (!flag) {//yoko->tate
			rep(i, tate[px].size()) {
				ll cnt = c + abs(py - tate[px][i].first) + 1;
				if (py != tate[px][i].first && cnt < d[tate[px][i].second]) {
					d[tate[px][i].second] = cnt;
					que.push({ true, px, tate[px][i].first, cnt });
					//cout << px << ' ' << py << ' ' << px << ' ' << tate[px][i].first << endl;
				}
			}
		}
		else {//tate->yoko
			rep(i, yoko[py].size()) {
				ll cnt = c + abs(px - yoko[py][i].first) + 1;
				if (px != yoko[py][i].first && cnt < d[yoko[py][i].second]) {
					d[yoko[py][i].second] = cnt;
					que.push({ false, yoko[py][i].first, py, cnt });
					//cout << ' ' << px << ' ' << py << ' ' << yoko[py][i].first << ' ' << py << endl;
				}
			}
		}
	}
	if (ans == INF) { cout << "-1\n"; return 0; }
	cout << ans << endl;
	return 0;
}
accuracy: 1
time_ms: 350
memory_kb: 38008
final_rank: 5

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

vector<pair<int,int>> g[400100];

int main(){
	cin.tie(nullptr);
	ios::sync_with_stdio(false);
	int m,n; cin >> m >> n;
	int k; cin >> k;
	vector<vector<pair<int,int>>> tate(m,vector<pair<int,int>>());
	vector<vector<pair<int,int>>> yoko(n,vector<pair<int,int>>());
	for(int i=0;i<k;i++){
		int x,y; cin >> x >> y;
		x--; y--;
		tate[x].push_back({y,i});
		yoko[y].push_back({x,i});
	}
	tate[m-1].push_back({n-1,k});
	yoko[n-1].push_back({m-1,k});
	k++;
	for(int i=0;i<m;i++){
		sort(tate[i].begin(), tate[i].end());
		for(int j=1;j<tate[i].size();j++){
			auto p=tate[i][j-1],pp=tate[i][j];
			g[p.second*2].push_back({pp.second*2,pp.first-p.first});
			g[pp.second*2].push_back({p.second*2,pp.first-p.first});
		}
	}
	for(int i=0;i<n;i++){
		sort(yoko[i].begin(), yoko[i].end());
		for(int j=1;j<yoko[i].size();j++){
			auto p=yoko[i][j-1],pp=yoko[i][j];
			g[p.second*2+1].push_back({pp.second*2+1,pp.first-p.first});
			g[pp.second*2+1].push_back({p.second*2+1,pp.first-p.first});
		}
	}
	for(int i=0;i<k;i++){
		g[i*2].push_back({i*2+1,1});
		g[i*2+1].push_back({i*2,1});
	}
	vector<ll> dp(2*k,1e18);
	priority_queue<pair<ll,int>> pq;
	for(auto p:tate[0]){
		dp[p.second*2]=p.first;
		pq.push({-dp[p.second*2],p.second*2});
	}
	while(pq.size()){
		auto p=pq.top(); pq.pop();
		if(-p.first!=dp[p.second])continue;
		for(auto to:g[p.second]){
			if(dp[to.first]>dp[p.second]+to.second){
				dp[to.first]=dp[p.second]+to.second;
				pq.push({-dp[to.first],to.first});
			}
		}
	}
	ll res=min(dp[2*k-1],dp[2*k-2]);
	if(res==1e18)res=-1;
	cout << res << endl;
}
accuracy: 1
time_ms: 260
memory_kb: 46440
final_rank: 3

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

vector<pair<int,int>> g[400100];

int main(){
	cin.tie(nullptr);
	ios::sync_with_stdio(false);
	int m,n; cin >> m >> n;
	int k; cin >> k;
	vector<vector<pair<int,int>>> tate(m,vector<pair<int,int>>());
	vector<vector<pair<int,int>>> yoko(n,vector<pair<int,int>>());
	for(int i=0;i<k;i++){
		int x,y; cin >> x >> y;
		x--; y--;
		tate[x].push_back({y,i});
		yoko[y].push_back({x,i});
	}
	tate[m-1].push_back({n-1,k});
	yoko[n-1].push_back({m-1,k});
	k++;
	for(int i=0;i<m;i++){
		sort(tate[i].begin(), tate[i].end());
		for(int j=1;j<tate[i].size();j++){
			auto p=tate[i][j-1],pp=tate[i][j];
			g[p.second*2].push_back({pp.second*2,pp.first-p.first});
			g[pp.second*2].push_back({p.second*2,pp.first-p.first});
		}
	}
	for(int i=0;i<n;i++){
		sort(yoko[i].begin(), yoko[i].end());
		for(int j=1;j<yoko[i].size();j++){
			auto p=yoko[i][j-1],pp=yoko[i][j];
			g[p.second*2+1].push_back({pp.second*2+1,pp.first-p.first});
			g[pp.second*2+1].push_back({p.second*2+1,pp.first-p.first});
		}
	}
	for(int i=0;i<k;i++){
		g[i*2].push_back({i*2+1,1});
		g[i*2+1].push_back({i*2,1});
	}
	vector<int> dp(2*k,1e9);
	priority_queue<pair<int,int>> pq;
	for(auto p:tate[0]){
		dp[p.second*2]=p.first;
		pq.push({-dp[p.second*2],p.second*2});
	}
	while(pq.size()){
		auto p=pq.top(); pq.pop();
		if(-p.first!=dp[p.second])continue;
		for(auto to:g[p.second]){
			if(dp[to.first]>dp[p.second]+to.second){
				dp[to.first]=dp[p.second]+to.second;
				pq.push({-dp[to.first],to.first});
			}
		}
	}
	int res=min(dp[2*k-1],dp[2*k-2]);
	if(res==1e9)res=-1;
	cout << res << endl;
}
accuracy: 0.7419354838709677
time_ms: 240
memory_kb: 44544
final_rank: 15

code_snippet: #include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <numeric>
#include <iomanip>
#include <stack>
#include <tuple>

using namespace std;

using ll = long long;

template<class T>bool chmax(T& a, const T& b) { if (a < b) { a = b; return 1; } return 0; }
template<class T>bool chmin(T& a, const T& b) { if (b < a) { a = b; return 1; } return 0; }

const int inf = (1 << 30) - 1;
const ll infll = 1LL << 60;

struct Edge {
    ll from; // 移動前のノード
    ll to; // 移動先のノード
    ll cost; // 辺のコスト
    ll hoge; // 任意変更 いらないかも

    Edge() = default;
    Edge(ll _to) : from(-1), to(_to), cost(1), hoge(-1) {};
    Edge(ll _to, ll _cost) : from(-1), to(_to), cost(_cost), hoge(-1) {};
    Edge(ll _from, ll _to, ll _cost) : from(_from), to(_to), cost(_cost), hoge(-1) {};
    Edge(ll _from, ll _to, ll _cost, ll _hoge) : from(_from), to(_to), cost(_cost), hoge(_hoge) {};
    bool operator< (const Edge& rhs) const {
        return cost < rhs.cost;
    }
    bool operator> (const Edge& rhs) const {
        return cost > rhs.cost;
    }
    bool operator==(const Edge& rhs) const {
        if (from != rhs.from) return false;
        if (to != rhs.to) return false;
        if (cost != rhs.cost) return false;
        if (hoge != rhs.hoge) return false;
        return true;
    }
    bool operator!=(const Edge& rhs) const {
        if (from != rhs.from) return true;
        if (to != rhs.to) return true;
        if (cost != rhs.cost) return true;
        if (hoge != rhs.hoge) return true;
        return false;
    }
};

using Graph = vector<vector<Edge>>;


// ダイクストラ法 O(ElogV)
vector<ll> dijkstra(ll start, const Graph& G) {
    vector<ll> dist(G.size(), infll);
    // 辺のコストが小さい順に取り出す　場合に応じて変更
    priority_queue<Edge, vector<Edge>, greater<Edge>> que;
    //queue<Edge> que; // コストがすべて1の場合は普通のbfsにする コメントアウトしよう

    dist[start] = 0; // dist[i] := start->iまでの最短距離
    que.push(Edge(start, 0));

    while (!que.empty()) {
        ll cost, u; // 今までにかかった時間　現在の頂点
        cost = que.top().cost, u = que.top().to;
        //cost = que.front().cost, u = que.front().to;
        que.pop();
        if (dist[u] < cost) continue;
        for (auto& e : G[u]) {
            ll v = e.to;
            ll new_cost = cost + e.cost;

            if (dist[v] <= new_cost) continue;

            dist[v] = new_cost;
            que.push(Edge(v, new_cost));
        }
    }
    return dist;
}


int main() {

    int m, n, k;
    cin >> m >> n >> k;
    vector<set<int>> vx(100001, set<int>());
    vector<set<int>> vy(100001, set<int>());


    Graph G((2 + k) * 2); // スタート，ゴール，スイッチ * 2
    const int geta = 2 + k;

    // 前半が縦に開いている 後半が横に開いている

    vector<pair<int, int>> xy(k);
    map<pair<int, int>, int> mp;

    for (int i = 0; i < k; ++i) {
        int x, y;
        cin >> x >> y;
        vx[x].emplace(y);
        vy[y].emplace(x);
        xy[i] = { x, y };
        mp[{x, y}] = i;
    }

    if (m == 1) {
        cout << n << endl;
        return 0;
    }

    // エッジを貼る

    for (int i = 0; i < k; ++i) {
        // このスイッチから行ける場所
        int x = xy[i].first;
        int y = xy[i].second;
        // 同じ階層
        {
            auto itr = vx[x].lower_bound(y);
            if (next(itr) != vx[x].end()) {
                int ty = *next(itr);
                int id = mp[{x, ty}];
                if (i != id) {
                    G[i].emplace_back(id, abs(xy[id].second - y));
                    G[id].emplace_back(i, abs(xy[id].second - y));
                }
            }
            if (itr != vx[x].begin()) {
                int ty = *prev(itr);
                int id = mp[{x, ty}];
                if (i != id) {
                    G[i].emplace_back(id, abs(xy[id].second - y));
                    G[id].emplace_back(i, abs(xy[id].second - y));
                }
            }
        }

        // 同じ階層
        {
            auto itr = vy[y].lower_bound(x);
            if (next(itr) != vy[y].end()) {
                int tx = *next(itr);
                int id = mp[{tx, y}];
                if (i != id) {
                    G[i + geta].emplace_back(id + geta, abs(xy[id].first - x));
                    G[id + geta].emplace_back(i + geta, abs(xy[id].first - x));
                }
            }
            if (itr != vy[y].begin()) {
                int tx = *prev(itr);
                int id = mp[{tx, y}];
                if (i != id) {
                    G[i + geta].emplace_back(id + geta, abs(xy[id].first - x));
                    G[id + geta].emplace_back(i + geta, abs(xy[id].first - x));
                }
            }
        }

        G[i].emplace_back(i + geta, 1);
        G[i + geta].emplace_back(i, 1);
    }

    // スタート
    {
        int x = 1;
        int y = 1;

        int i = k;

        if (vx[x].size()) {
            int ty = *vx[x].begin();
            int id = mp[{x, ty}];

            if (i != id) {
                G[i].emplace_back(id, abs(xy[id].second - y));
                G[id].emplace_back(i, abs(xy[id].second - y));
            }
        }

        if (vy[y].size()) {
            int tx = *vy[y].begin();
            int id = mp[{tx, y}];
            if (i != id) {
                G[i + geta].emplace_back(id + geta, abs(xy[id].first - x));
                G[id + geta].emplace_back(i + geta, abs(xy[id].first - x));
            }
        }
    }

    // ゴール
    {
        int x = m;
        int y = n;

        int i = k + 1;

        if (vx[x].size()) {
            int ty = *prev(vx[x].end());
            int id = mp[{x, ty}];
            if (i != id) {
                G[i].emplace_back(id, abs(xy[id].second - y));
                G[id].emplace_back(i, abs(xy[id].second - y));
            }
        }
        if (vy[y].size()) {
            int tx = *prev(vy[y].end());
            int id = mp[{tx, y}];
            if (i != id) {
                G[i + geta].emplace_back(id + geta, abs(xy[id].first - x));
                G[id + geta].emplace_back(i + geta, abs(xy[id].first - x));
            }
        }
    }

    auto dist = dijkstra(k, G);

    ll ans = min(dist[k + 1], dist[k + 1 + geta]);
    if (ans == infll) ans = -1;
    cout << ans << endl;

    return 0;
}
accuracy: 1
time_ms: 940
memory_kb: 172204
final_rank: 14

code_snippet: #include <iostream>
#include <queue>
#include <stack>
#include <vector>
#include <utility>
#include <algorithm>
#include <map>
#include <set>
#include <cassert>

using namespace std;

using lint = long long int;
const lint INF = 1e16;

template<typename T>
vector<pair<T, int>> dijkstra(vector<vector<pair<int, T>>> &g, int s) {
  int n = g.size();

  const auto inf = INF;
  vector<pair<T, int>> dist(n, {inf, -1});

  using P = pair<T, int>;

  priority_queue<P, vector<P>, greater<P>> que;
  dist[s] = {0, -1};
  que.emplace(dist[s].first, s);
  while (!que.empty()) {
    T cost;
    int node;
    tie(cost, node) = que.top();
    que.pop();
    if (dist[node].first < cost) continue;
    for (auto &e : g[node]) {
      auto next_cost = cost + e.second;
      int next_node = e.first;
      if (dist[next_node].first <= next_cost) continue;
      dist[next_node] = {next_cost, node};
      que.emplace(next_cost, next_node);
    }
  }

  return dist;
}

int main() {

  int m, n, k; cin >> m >> n >> k;
  vector<set<int>> x(m);
  vector<set<int>> y(n);
  vector<int> X(k);
  vector<int> Y(k);
  map<pair<int, int>, int> mp;
  for (int i = 0; i < k; i++) {
    cin >> X[i] >> Y[i];
    X[i]--;
    Y[i]--;
    x[X[i]].insert(Y[i]);
    y[Y[i]].insert(X[i]);
    mp[{X[i], Y[i]}] = i;
  }

  vector<vector<int>> toNode(k, vector<int>(2));
  int node = 0;
  for (int i = 0; i < k; i++) {
    for (int j = 0; j < 2; j++) {
      toNode[i][j] = node;
      node++;
    }
  }

  vector<vector<pair<int, lint>>> g(node + 1);
  for (int i = 0; i < k; i++) {
    for (int f = 0; f < 2; f++) {

      {
        // スイッチを切り替える
        int cur_node = toNode[i][f];
        int next_node = toNode[i][1 - f];
        lint cost = 1;
        g[cur_node].push_back({next_node, cost});
      }

      if (f == 0) {
        // 上下に移動できる
        int cx = X[i];
        int cy = Y[i];
        assert((mp[{cx, cy}] == i));
        int cur_node = toNode[mp[{cx, cy}]][f];
        auto itr = x[cx].lower_bound(cy);
        
        auto nxt = itr;
        nxt++;
        if (nxt != x[cx].end()) {
          int nx = cx;
          int ny = *nxt;
          int next_node = toNode[mp[{nx, ny}]][f];
          lint cost = (lint)abs(ny - cy);
          g[cur_node].push_back({next_node, cost});
        }

        auto prev = itr;
        if (prev != x[cx].begin()) {
          prev--;
          int nx = cx;
          int ny = *prev;
          int next_node = toNode[mp[{nx, ny}]][f];
          lint cost = (lint)abs(ny - cy);
          g[cur_node].push_back({next_node, cost});
        }

      } else {
        int cx = X[i];
        int cy = Y[i];
        assert((mp[{cx, cy}] == i));
        int cur_node = toNode[mp[{cx, cy}]][f];
        auto itr = y[cy].lower_bound(cx);

        auto nxt = itr;
        nxt++;
        if (nxt != y[cy].end()) {
          int nx = *nxt;
          int ny = cy;
          int next_node = toNode[mp[{nx, ny}]][f];
          lint cost = (lint)abs(nx - cx);
          g[cur_node].push_back({next_node, cost});
        }

        auto prev = itr;
        if (prev != y[cy].begin()) {
          prev--;
          int nx = *prev;
          int ny = cy;
          int next_node = toNode[mp[{nx, ny}]][f];
          lint cost = (lint)abs(nx - cx);
          g[cur_node].push_back({next_node, cost});
        }
      }
    }
  }

  // スーパーノード node
  for (int i = 0; i < k; i++) {
    if (X[i] != 0) continue;
    lint cost = Y[i];
    int next_node = toNode[mp[{X[i], Y[i]}]][0];
    g[node].push_back({next_node, cost});
  }

  auto dist = dijkstra(g, node);
  lint ans = INF;
  for (int i = 0; i < k; i++) {
    for (int f = 0; f < 2; f++) {
      if (X[i] == m - 1 and f == 0) {
        lint next_node = toNode[mp[{X[i], Y[i]}]][f];
        if (dist[next_node].first != INF) {
          lint cost = dist[next_node].first + n - 1 - Y[i];
          // cerr << "cost = " << cost << endl;
          ans = min(ans, cost);
        }
      }
      if (Y[i] == n - 1 and f == 1) {
        lint next_node = toNode[mp[{X[i], Y[i]}]][f];
        if (dist[next_node].first != INF) {
          lint cost = dist[next_node].first + m - 1 - X[i];
          // cerr << "cost = " << cost << endl;
          ans = min(ans, cost);
        }
      }
    }
  }

  if (ans >= INF) {
    cout << -1 << endl;
  } else {
    cout << ans << endl;
  }

  return 0;
}
accuracy: 1
time_ms: 830
memory_kb: 102708
final_rank: 13

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define pp pair<int,int>
#define rep(i,n) for(int (i)=0;(i)<(n);(i)++)
#define ll long long
#define ld long double
#define all(a) (a).begin(),(a).end()
#define mk make_pair
ll MOD=1000000007;
ll mod=998244353;
int inf=1000001000;
ll INF=1e18+5;


int main() {
    int n,m,k;
    cin >> m >> n >> k;
    int d[m][n][2];
    rep(i,m){
        rep(j,n){
            rep(ii,2) d[i][j][ii]=inf;
        }
    }
    d[0][0][0]=0;
    vector<vector<int>> a(m,vector<int>(n,0));
    rep(i,k){
        int f,g;
        cin >> f >> g;
        a[f-1][g-1]=1;
    }
    queue<pair<pair<int,int>,int>> q;
    q.push(mk(mk(0,0),0));
    while(!q.empty()){
    // cout << "aaaaaa" << endl;
        int f=q.front().first.first,g=q.front().first.second,h=q.front().second;
        // cout << f << " " << g << " " << h << endl;
        q.pop();
        if (h==0){
            if (g!=0){
                if (d[f][g-1][0]>d[f][g][0]+1){
                    d[f][g-1][0]=d[f][g][0]+1;
                    q.push(mk(mk(f,g-1),0));
                }
            }
            if (g!=n-1){
                if (d[f][g+1][0]>d[f][g][0]+1){
                    d[f][g+1][0]=d[f][g][0]+1;
                    q.push(mk(mk(f,g+1),0));
                }
            }
        }
        if (h==1){
            if (f!=0){
                if (d[f-1][g][1]>d[f][g][1]+1){
                    d[f-1][g-1][1]=d[f][g][1]+1;
                    q.push(mk(mk(f-1,g),1));
                }
            }
            if (f!=m-1){
                if (d[f+1][g][1]>d[f][g][1]+1){
                    d[f+1][g][1]=d[f][g][1]+1;
                    q.push(mk(mk(f+1,g),1));
                }
            }
        }
        if (a[f][g]==1){
        if (d[f][g][1-h]>d[f][g][h]+1){
            d[f][g][1-h]=d[f][g][h]+1;
            q.push(mk(mk(f,g),1-h));
        }}
    }
    // rep(i,n){
    //     rep(j,m){
    //         cout << d[j][i][1] << " ";
    //     }
    //     cout << endl;
    // }
    int ans=min(d[m-1][n-1][0],d[m-1][n-1][1]);
    if (ans==inf) cout << -1 << endl;
    else cout << ans << endl;
}
accuracy: 0.0967741935483871
time_ms: 40
memory_kb: 15148
final_rank: 18

code_snippet: #include <bits/stdc++.h>
#define err(args...) {}
#ifdef DEBUG
#include "_debug.cpp"
#endif
using namespace std;
using ll = long long;
using ld = long double;
template <typename T> using lim = numeric_limits<T>;
template <typename T> istream& operator>>(istream& is, vector<T>& a) { for(T& x : a) { is >> x; } return is; }
template <typename X, typename Y> istream& operator>>(istream& is, pair<X, Y>& p) { return is >> p.first >> p.second; }
template <typename T> struct wedge {
    int u, v; T w;
    wedge reverse() const { return {v, u, w}; }
    friend ostream& operator<<(ostream& os, const wedge& e) {
        return os << "{u: " << e.u << ", v: " << e.v << ", w: " << e.w << "}";
    }
};
template <bool Directed, typename TEdge, bool Index> struct graph {
    using EType = TEdge;
    vector<TEdge> edges;
    vector<vector<int>> adj;
    graph(int n) : adj(n + Index) {}
    graph(int n, int m) : graph(n) { edges.reserve(m << not Directed); }
    TEdge& operator()(int e) { return edges[e]; }
    vector<int>& operator[](int u) { return adj[u]; }
    int size() { return adj.size() - Index; }
    void append(int u, const TEdge& e) {
        adj[u].push_back(edges.size());
        edges.push_back(e);
    }
    void add_edge(const TEdge& e) {
        append(e.u, e);
        if(not Directed) append(e.v, e.reverse());
    }
};
template <bool Directed, typename T, bool Index>
pair<vector<T>, vector<int>> sssp(graph<Directed, wedge<T>, Index>& g, const vector<int>& s) {
    vector<int> vis(g.adj.size()), p(g.adj.size(), -1);
    vector<T> d(g.adj.size(), lim<T>::max());
    priority_queue<pair<T, int>> pq;
    for(int u : s) {
        pq.push({d[u] = 0, u});
    }
    while(not pq.empty()) {
        int u = pq.top().second; pq.pop();
        if(not vis[u]) {
            vis[u] = true;
            for(int e : g[u]) {
                if(not vis[g(e).v] and d[g(e).v] > d[u] + g(e).w) {
                    pq.push({-(d[g(e).v] = d[u] + g(e).w), g(p[g(e).v] = e).v});
                }
            }
        }
    }
    return {d, p};
}
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    int m, n, k;
    cin >> m >> n >> k;
    vector<vector<vector<pair<int, int>>>> important_nodes_at_axis = {
        vector<vector<pair<int, int>>>(m + 1),
        vector<vector<pair<int, int>>>(n + 1)
    };
    int index = 0;
    auto insert_node = [&](int x, int y) {
        important_nodes_at_axis[0][x].push_back({y, index});
        important_nodes_at_axis[1][y].push_back({x, index});
        index += 2;
    };
    insert_node(1, 1);
    insert_node(m, n);
    for(int i = 0; i < k; i++) {
        int x, y;
        cin >> x >> y;
        insert_node(x, y);
    }
    graph<0, wedge<ll>, 0> g(index);
    for(int i = 4; i < index; i += 2) {
        g.add_edge({i, i ^ 1, 1});
    }
    for(int axis : {0, 1}) {
        for(auto& nodes : important_nodes_at_axis[axis]) {
            sort(nodes.begin(), nodes.end());
            for(int i = 0; i + 1 < nodes.size(); i++) {
                int ucoord, u;
                int vcoord, v;
                tie(ucoord, u) = nodes[i];
                tie(vcoord, v) = nodes[i + 1];
                g.add_edge({u ^ axis, v ^ axis, abs(ucoord - vcoord)});
            }
        }
    }
    auto d = sssp(g, {0}).first;
    ll ans = min(d[2], d[3]);
    cout << (ans == lim<ll>::max() ? -1 : ans) << endl;
    return 0;
}
accuracy: 1
time_ms: 330
memory_kb: 67600
final_rank: 8

code_snippet: #include<iostream>
#include<cstdio>
#include<cstring>
#include <cstdlib>  
#include <math.h>
#include <cmath>
#include<complex>
#include<cctype>
#include<string>
#include<set>
#include<iomanip>
#include <map>
#include<algorithm>
#include <functional>
#include<vector>
#include<climits>
#include<stack>
#include<queue>
#include<bitset>
#include <deque>
#include <climits>
#include <typeinfo>
#include <utility> 
using namespace std;
using Complex = complex<double>;
using ll = long long;
template<typename T>using min_priority_queue = priority_queue<T, vector<T>, greater<T>>;
const ll inf = 1145141919810364364LL;
double PI = acos(-1.0);
#define all(x) (x).begin(),(x).end()
#define puts(x) cout << x << endl
#define rep(i,m,n) for(ll i = m;i < n;++i)
#define pb push_back
#define fore(i,a) for(auto &i:a)
#define rrep(i,m,n) for(ll i = m;i >= n;--i)

int N,M,K;
vector<int>Ex[101010],Ey[101010];
ll dist[1000000];
map<vector<int>,int>mp;
vector<pair<int, int>>Enew[1000000];

void dijkstra() {
	for (int i = 0; i < 1000000;i++)dist[i] = inf;
	min_priority_queue<pair<ll,int>>q;
	int idx = mp[{0, 0, 0}];
	q.push({0,idx});
	while (q.size()) {
		auto p = q.top();
		q.pop();
		ll d = p.first;
		int v = p.second;
		fore(x, Enew[v]) {
			int to = x.first;
			ll cost = x.second;

			if (dist[to] > d + cost) {
				q.push({d+cost,to});
				dist[to] = d + cost;
			}
		}
	}
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);

	cin >> M >> N >> K;
	int fl0 = 0;
	int fl1 = 0;
	for (int i = 0; i < K; i++) {
		int x, y;
		cin >> x >> y;
		x--, y--;
		Ex[x].pb(y);
		Ey[y].pb(x);
		if (x == 0 && y == 0)fl0 = 1;
		if (x == M - 1 && y == N - 1)fl1 = 1;
	}
	if (!fl0) { Ex[0].pb(0); }
	if (!fl1) { 
		Ex[M - 1].pb(N - 1); 
		Ey[N - 1].pb(M - 1);
	}

	for (int i = 0; i < 101010; i++)sort(all(Ex[i]));
	for (int i = 0; i < 101010; i++)sort(all(Ey[i]));

	int cnt = 0;
	for (int i = 0; i < 101010; i++) {
		fore(x, Ex[i]) {
			if (fl0 == 0 && i == 0 && x == 0) {
				mp[{0,0,0}] = cnt;
				cnt++;
			}
			else {
				mp[{i,x,0}] = cnt;
				cnt++;
				mp[{i,x,1}] = cnt;
				cnt++;
			}
		}
	}

	for (int i = 0; i < 101010; i++) {
		for (int j = 0; j + 1 < Ex[i].size(); j++) {
			int num1 = mp[{i,Ex[i][j],0}];
			int num2 = mp[{i,Ex[i][j+1],0}];
			int diff = Ex[i][j + 1] - Ex[i][j];
			Enew[num1].pb({num2,diff});
			Enew[num2].pb({num1,diff});
		}
	}
	for (int i = 0; i < 101010; i++) {
		for (int j = 0; j + 1 < Ey[i].size(); j++) {
			int num1 = mp[{Ey[i][j],i, 1}];
			int num2 = mp[{Ey[i][j+1], i, 1}];
			int diff = Ey[i][j + 1] - Ey[i][j];
			Enew[num1].pb({ num2,diff });
			Enew[num2].pb({ num1,diff });
		}
	}

	for (int i = 0; i < 101010; i++) {
		fore(x, Ex[i]) {
			if (fl0 == 0 && i == 0 && x == 0)continue;
			if (fl1 == 0 && i == M - 1 && x == N - 1)continue;
			int num1 = mp[{i, x, 0}];
			int num2 = mp[{i, x, 1}];
			Enew[num1].pb({ num2,1 });
			Enew[num2].pb({ num1,1 });
		}
	}
	dijkstra();

	ll ans = min(dist[mp[{M - 1, N - 1, 0}]], dist[mp[{M - 1, N - 1, 1}]]);
	if (ans > 1e16)puts(-1);
	else puts(ans);

	return 0;
}
accuracy: 1
time_ms: 610
memory_kb: 105676
final_rank: 12

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

using ll = long long int;
using P = pair<ll, ll>;
using P3 = pair<int,P>;
using PP = pair<P, P>;
constexpr ll INF = 1LL<<60;
constexpr ll MOD = ll(1e9)+7;
constexpr int di[] = {0,1,0,-1};
constexpr int dj[] = {1,0,-1,0};


bool solve(){
    int m, n, k;
    cin >> m >> n >> k;
    vector<vector<P> > row(n), col(m), g((k+2)*2);
    for(int i=0;i<k;i++){
        int x, y;
        cin >> x >> y;
        x--; y--;
        row[y].emplace_back(P(x,i*2));
        col[x].emplace_back(P(y,i*2+1));
        g[i*2].emplace_back(P(i*2+1,1));
        g[i*2+1].emplace_back(P(i*2,1));
    }
    int S = k, G = k+1;
    col[0].emplace_back(P(0,S*2));
    row[n-1].emplace_back(P(m-1,G*2));
    col[m-1].emplace_back(P(n-1,G*2+1));
    for(int i=0;i<n;i++){
        sort(row[i].begin(), row[i].end());
        int t = row[i].size();
        for(int j=0;j<t-1;j++){
            int l = row[i][j].first, u = row[i][j].second;
            int r = row[i][j+1].first, v = row[i][j+1].second;
            g[u].emplace_back(P(v,r-l));
            g[v].emplace_back(P(u,r-l));
        }
    }
    for(int i=0;i<m;i++){
        sort(col[i].begin(),col[i].end());
        int t = col[i].size();
        for(int j=0;j<t-1;j++){
            int l = col[i][j].first, u = col[i][j].second;
            int r = col[i][j+1].first, v = col[i][j+1].second;
            g[u].emplace_back(P(v,r-l));
            g[v].emplace_back(P(u,r-l));
        }
    }
    vector<ll> d((k+2)*2, INF);
    priority_queue<P, vector<P>, greater<P> > que;
    d[S*2] = 0;
    que.push(P(0,S*2));
    while(!que.empty()){
        auto p = que.top();
        que.pop();
        int v = p.second;
        if(p.first > d[v]) continue;
        for(auto e : g[v]){
            ll u = e.first, cost = e.second;
            if(d[u] > d[v]+cost){
                d[u] = d[v]+cost;
                que.push(P(d[u],u));
            }
        }
    }
    ll ans = min(d[G*2], d[G*2+1]);
    cout << (ans < INF ? ans : -1) << endl;
    return true;
}

int main(){
    solve();
    return 0;
}
accuracy: 1
time_ms: 410
memory_kb: 62328
final_rank: 9

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

using namespace std;
typedef long long ll;
typedef pair<ll,ll> P;

ll M,N,K;
vector<P> G[500005];
vector<P> lis_x[100005];
vector<P> lis_y[100005];

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);

    cin >> M >> N >> K;

    lis_x[1].push_back(P(1,0));

    for (ll i = 0;i < K;i++){
        ll x,y; cin >> x >> y;
        lis_x[x].push_back(P(y,i+1));
        lis_y[y].push_back(P(x,i+1));
    }

    lis_x[M].push_back(P(N,K+1));
    lis_y[N].push_back(P(M,K+1));

    for (ll i = 0;i <= M;i++){
        if(!lis_x[i].size()) continue;
        sort(lis_x[i].begin(),lis_x[i].end());
        P p = lis_x[i][0];
        for (ll j = 1;j < lis_x[i].size();j++){
            //cout << i << " " <<  p.first << endl;
            G[p.second].push_back(P(lis_x[i][j].second,lis_x[i][j].first-p.first));
            G[lis_x[i][j].second].push_back(P(p.second,lis_x[i][j].first-p.first));
            p = lis_x[i][j];
        }
        //cout << endl;
    }

    for (ll i = 0;i <= N;i++){
        if(!lis_y[i].size()) continue;
        sort(lis_y[i].begin(),lis_y[i].end());
        P p = lis_y[i][0];
        for (ll j = 1;j < lis_y[i].size();j++){
            G[p.second+(K+2)].push_back(P(lis_y[i][j].second+(K+2),lis_y[i][j].first-p.first));
            G[lis_y[i][j].second+(K+2)].push_back(P(p.second+(K+2),lis_y[i][j].first-p.first));
            p = lis_y[i][j];
        }
    }

    for (ll i = 0;i <= K+2;i++){
        if(i%(K+2)){
            G[i].push_back(P(i+K+2,1));
            G[i+K+2].push_back(P(i,1));
        }
    }

    priority_queue<P,vector<P>, greater<P>> que;
    ll dist[500005];
    //fill(dist,dist+K*2+5,ll_MAX);
    for (ll i = 0;i < 500000;i++){
        dist[i] = LLONG_MAX;
    }
    dist[0] = 0;
    que.push(P(0,0));

    while(que.size()){
        P p = que.top(); que.pop();
        ll from = p.second;
        ll sum = p.first;
        if(dist[from] < sum) continue;
        //cout << from << " " << sum << endl;
        for (ll i = 0;i < G[from].size();i++){
            ll to = G[from][i].first;
            ll cost = G[from][i].second;
            if(dist[from]+cost < dist[to]){
                dist[to] = dist[from]+cost;
                que.push(P(dist[to],to));
            }
        }
    }

    ll ans = min(dist[K+1],dist[K+1+K+2]);
    if(ans == LLONG_MAX) ans = -1;

    cout << ans << endl;

    return 0;

}
accuracy: 1
time_ms: 290
memory_kb: 68280
final_rank: 6

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

using namespace std;
typedef long long ll;
typedef pair<int,int> P;

int M,N,K;
vector<P> G[500005];
vector<P> lis_x[100005];
vector<P> lis_y[100005];

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);

    cin >> M >> N >> K;

    lis_x[1].push_back(P(1,0));

    for (int i = 0;i < K;i++){
        int x,y; cin >> x >> y;
        lis_x[x].push_back(P(y,i+1));
        lis_y[y].push_back(P(x,i+1));
    }

    lis_x[M].push_back(P(N,K+1));
    lis_y[N].push_back(P(M,K+1));

    for (int i = 0;i <= M;i++){
        if(!lis_x[i].size()) continue;
        sort(lis_x[i].begin(),lis_x[i].end());
        P p = lis_x[i][0];
        for (int j = 1;j < lis_x[i].size();j++){
            //cout << i << " " <<  p.first << endl;
            G[p.second].push_back(P(lis_x[i][j].second,lis_x[i][j].first-p.first));
            G[lis_x[i][j].second].push_back(P(p.second,lis_x[i][j].first-p.first));
            p = lis_x[i][j];
        }
        //cout << endl;
    }

    for (int i = 0;i <= N;i++){
        if(!lis_y[i].size()) continue;
        sort(lis_y[i].begin(),lis_y[i].end());
        P p = lis_y[i][0];
        for (int j = 1;j < lis_y[i].size();j++){
            G[p.second+(K+2)].push_back(P(lis_y[i][j].second+(K+2),lis_y[i][j].first-p.first));
            G[lis_y[i][j].second+(K+2)].push_back(P(p.second+(K+2),lis_y[i][j].first-p.first));
            p = lis_y[i][j];
        }
    }

    for (int i = 0;i <= K+2;i++){
        if(i%(K+2)){
            G[i].push_back(P(i+K+2,1));
            G[i+K+2].push_back(P(i,1));
        }
    }

    priority_queue<P,vector<P>, greater<P>> que;
    int dist[500005];
    //fill(dist,dist+K*2+5,INT_MAX);
    for (int i = 0;i < 500000;i++){
        dist[i] = INT_MAX;
    }
    dist[0] = 0;
    que.push(P(0,0));

    while(que.size()){
        P p = que.top(); que.pop();
        int from = p.second;
        int sum = p.first;
        if(dist[from] < sum) continue;
        //cout << from << " " << sum << endl;
        for (int i = 0;i < G[from].size();i++){
            int to = G[from][i].first;
            int cost = G[from][i].second;
            if(dist[from]+cost < dist[to]){
                dist[to] = dist[from]+cost;
                que.push(P(dist[to],to));
            }
        }
    }

    int ans = min(dist[K+1],dist[K+1+K+2]);
    if(ans == INT_MAX) ans = -1;

    cout << ans << endl;

    return 0;

}
accuracy: 0.7419354838709677
time_ms: 250
memory_kb: 48376
final_rank: 16

code_snippet: #include<iostream>
#include<cstdlib>
#include<vector>
#include<queue>
#include<algorithm>

using namespace std;

typedef pair<int,int> PA;
typedef pair<long long,int> PAL;
typedef pair<PAL,int> PPA;

const long long INF = 1000010000100001;

int m,n,k;

vector<PA> vx[100010],vy[100010];
vector<PA> tate[200010],yoko[200010];
long long min_cost[2][200010];

void make_edge(){
    vx[n].push_back(PA(m,k+1));
    vy[1].push_back(PA(1,0));
    vy[m].push_back(PA(n,k+1));
    
    for(int i=1;i<=n;i++){
        if(vx[i].size() < 2) continue;
        sort(vx[i].begin(),vx[i].end());
        for(int j=0;j<vx[i].size()-1;j++){
            long long xcost = abs(vx[i][j].first-vx[i][j+1].first);
            yoko[ vx[i][j].second ].push_back( PAL(xcost,vx[i][j+1].second) );
            yoko[ vx[i][j+1].second ].push_back( PAL(xcost,vx[i][j].second) );
        }
    }
    
    for(int i=1;i<=m;i++){
        if(vy[i].size() < 2) continue;
        sort(vy[i].begin(),vy[i].end());
        for(int j=0;j<vy[i].size()-1;j++){
            long long ycost = abs(vy[i][j].first-vy[i][j+1].first);
            tate[ vy[i][j].second ].push_back( PAL(ycost,vy[i][j+1].second) );
            tate[ vy[i][j+1].second ].push_back( PAL(ycost,vy[i][j].second) );
        }
    }
    
}

int main(){
    
    int x,y;
    priority_queue<PPA,vector<PPA>,greater<PPA> > pq;
    
    cin >> m >> n >> k;
    for(int i=0;i<k;i++){
        cin >> x >> y;
        if(x==1 && y==1){
            vx[1].push_back(PA(1,0));
        }
        if(x==1 && y==1 || x==m && y==n) continue;
        vx[y].push_back(PA(x,i+1));
        vy[x].push_back(PA(y,i+1));
    }
    
    make_edge();
    
    for(int i=1;i<=k+1;i++){
        min_cost[0][i] = INF;
        min_cost[1][i] = INF;
    }
    min_cost[0][0] = 0;
    min_cost[1][0] = 0;
    
    pq.push( PPA(PA(0,0),0) );
    while(!pq.empty()){
        PPA pp = pq.top();
        pq.pop();
        PAL p = pp.first;
        
        for(int i=0;i<tate[p.second].size();i++){
            long long cost = p.first + tate[p.second][i].first;
            int to = tate[p.second][i].second;
            if(pp.second == 0 && min_cost[0][to] > cost){
                min_cost[0][to] = cost;
                pq.push( PPA(PAL(cost,to),0) );
            }
            if(pp.second == 1 && min_cost[0][to] > cost+1){
                min_cost[0][to] = cost+1;
                pq.push( PPA(PAL(cost+1,to),0) );
            }
        }
        
        for(int i=0;i<yoko[p.second].size();i++){
            long long cost = p.first + yoko[p.second][i].first;
            int to = yoko[p.second][i].second;
            if(pp.second == 0 && min_cost[1][to] > cost+1){
                min_cost[1][to] = cost+1;
                pq.push( PPA(PAL(cost+1,to),1) );
            }
            if(pp.second == 1 && min_cost[1][to] > cost){
                min_cost[1][to] = cost;
                pq.push( PPA(PAL(cost,to),1) );
            }
        }
        
    }
    
    long long ans = min(min_cost[0][k+1],min_cost[1][k+1]);
    cout << (ans==INF?-1:ans) << endl;
    
    return(0);
}
accuracy: 1
time_ms: 300
memory_kb: 40800
final_rank: 4