Problem:
Lucky Dip
Time Limit: 8 sec / Memory Limit: 64 MB
C: 福袋
福袋，それは年始を祝う商習慣の一つである．
人気の福袋には多くの人が開店前から行列を作り，ターゲットの福袋へダッシュする．
この風物詩に魅了されたあなたは，今年もお目当ての福袋を狙い，計画を立てていた．
しかし，お客を呼び寄せる側の某百貨店の店長は頭を悩ませていた．
どうやらフロアの準備が開店に間に合いそうにない．
そこで店長はある一つのアイディアを思いついた．
それは開店後，店内を徐々に開放すればなんとか営業できるのではないかというものである．
あなたは刻一刻と変化する店内の情報を元に，お目当ての福袋がどの時間帯から入手できるのかを調べたい．
Input
入力は単一のデータセットで与えられ，EOFで終了する．
店内の様子は各行が
W
文字からなる
H
行の文字列で表される．
1 行目
W H
2 <
W
,
H
<= 1000
続く
H
行
店内の様子
.: 床
#: 壁
t
: 目的の福袋
目的の福袋は店内に必ず1つだけ存在する．
H
+ 2 行目
営業時間
N
(0 <=
N
<= 1000)
続く
N
行
x
1
y
1
x
2
x
2
...
x
i
y
i
...
x
n
y
n
(
x
i
,
y
i
)は，
i
時間目に開放される壁の座標を表す．(0 <=
x
i
<
W
, 0 <=
y
i
<
H
)
x
i
が列，
y
i
が行である．
開放される壁の座標の位置が "#" なら "." に置き換え，"." なら何もしない．
目的の福袋が開放されることはない．
(0, 0) が壁になることはない．
またあるマスからの移動は，上下左右の4方向のマスへのみが可能であり，壁の上へ移動することはできないものとする．
Output
左上(0, 0) から
t
の座標へ辿りつけるようになる時間
s
(-1 <=
s
<=
N
)を1行で出力せよ．
壁を開放せずに辿りつける場合，0 を出力せよ．
営業時間が終了しても到達できなければ -1 を出力すること．
Sample Input 1
10 10
.....#....
.....#....
.....#....
######....
..........
####......
....###...
t..#..####
...##.....
....#...##
3
0 3
0 5
4 6
Sample Output 1
2
Sample Input 2
10 10
.....#....
.....#....
.....#....
##########
##########
##########
##########
t..#..####
...##.....
....#...##
3
0 3
0 5
4 6
Sample Output 2
-1

Submitted solutions:

code_snippet: #pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;

mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
ll myRand(ll B) {
    return (ull)rng() % B;
}
inline double time() {
    return static_cast<long double>(chrono::duration_cast<chrono::nanoseconds>(chrono::steady_clock::now().time_since_epoch()).count()) * 1e-9;
}

struct UnionFind{
    vector<int> par,num;
    vector<bool> done;
    UnionFind(int n):par(n),num(n,1),done(n,false){
        iota(par.begin(),par.end(),0);  //include<numeric>
    }
    int find(int v){
        return (par[v]==v)?v:(par[v]=find(par[v]));
    }
    void unite(int u,int v){
        u=find(u),v=find(v);
        if(u==v)return;
        if(num[u]<num[v])swap(u,v);
        num[u]+=num[v];
        par[v]=u;
        done[u]=done[u]|done[v];
    }
    bool same(int u,int v){
        return find(u) == find(v);
    }
    bool ispar(int v){
        return v=find(v);
    }
    int size(int v){
        return num[find(v)];
    }
};

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

int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    int w,h; cin >> w >> h;
    vector<string> s(h);
    int S = 0, T = 0;
    for (size_t i = 0; i < h; i++) {
        cin >> s[i];
        for (size_t j = 0; j < w; j++) {
            if (s[i][j] == 't') {
                s[i][j] = '.';
                T = i*w+j;
            }
        }
    }
    UnionFind uf(h*w);
    for (size_t i = 0; i < h; i++) {
        for (size_t j = 0; j < w; j++) {
            if (s[i][j] == '.') {
                for (size_t k = 0; k < 4; k++) {
                    int ni = i+dx[k];
                    int nj = j+dy[k];
                    if (0 <= ni and ni < h and 0 <= nj and nj < w and s[ni][nj] == '.') {
                        uf.unite(i*w+j, ni*w+nj);
                    }   
                }
            }   
        }
    }
    if (uf.same(S,T)) {
        cout << 0 << endl;
        return 0;
    }
    int n; cin >> n;
    for (size_t i = 0; i < n; i++) {
        int y,x; cin >> y >> x;
        s[x][y] = '.';
        for (size_t k = 0; k < 4; k++) {
            int ni = x+dx[k];
            int nj = y+dy[k];
            if (0 <= ni and ni < h and 0 <= nj and nj < w and s[ni][nj] == '.') {
                uf.unite(x*w+y, ni*w+nj);
            }   
        }
        if (uf.same(S,T)) {
            cout << i+1 << endl;
            return 0;
        }
    }
    cout << -1 << endl;
    
}
accuracy: 1
time_ms: 20
memory_kb: 12276
final_rank: 7

code_snippet: #line 2 "/home/yuruhiya/programming/library/template/template_no_Ruby.cpp"
#include <bits/stdc++.h>
#line 4 "/home/yuruhiya/programming/library/template/constants.cpp"
#include <string_view>
#line 7 "/home/yuruhiya/programming/library/template/constants.cpp"

#define rep(i, n) for (int i = 0; i < (n); ++i)
#define FOR(i, m, n) for (int i = (m); i < (n); ++i)
#define rrep(i, n) for (int i = (n)-1; i >= 0; --i)
#define rfor(i, m, n) for (int i = (m); i >= (n); --i)
#define unless(c) if (!(c))
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define range_it(a, l, r) (a).begin() + (l), (a).begin() + (r)

using namespace std;
using ll = long long;
using LD = long double;
using VB = vector<bool>;
using VVB = vector<VB>;
using VI = vector<int>;
using VVI = vector<VI>;
using VL = vector<ll>;
using VVL = vector<VL>;
using VS = vector<string>;
using VD = vector<LD>;
using PII = pair<int, int>;
using VP = vector<PII>;
using PLL = pair<ll, ll>;
using VPL = vector<PLL>;
template <class T> using PQ = priority_queue<T>;
template <class T> using PQS = priority_queue<T, vector<T>, greater<T>>;
constexpr int inf = 1000000000;
constexpr long long inf_ll = 1000000000000000000ll, MOD = 1000000007;
constexpr long double PI = 3.14159265358979323846, EPS = 1e-12;
namespace CharacterClass {
	constexpr string_view
	    digit = "0123456789",
	    xdigit = "0123456789ABCDEFabcdef", lower = "abcdefghijklmnopqrstuvwxyz",
	    upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
	    alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
	    alnum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
	    word = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",
	    punct = R"(!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~)",
	    graph =
	        R"(!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~)",
	    print =
	        R"( !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~)",
	    blank = " \t", space = " \t\n\r\f\v";
}  // namespace CharacterClass
#line 7 "/home/yuruhiya/programming/library/template/Input.cpp"
using namespace std;

#ifdef _WIN32
#define getchar_unlocked _getchar_nolock
#define putchar_unlocked _putchar_nolock
#define fwrite_unlocked fwrite
#define fflush_unlocked fflush
#endif
class Scanner {
	static int gc() {
		return getchar_unlocked();
	}
	static char next_char() {
		char c;
		read(c);
		return c;
	}
	template <class T> static void read(T& v) {
		cin >> v;
	}
	static void read(char& v) {
		while (isspace(v = gc()))
			;
	}
	static void read(bool& v) {
		v = next_char() != '0';
	}
	static void read(string& v) {
		v.clear();
		for (char c = next_char(); !isspace(c); c = gc()) v += c;
	}
	static void read(int& v) {
		v = 0;
		bool neg = false;
		char c = next_char();
		if (c == '-') {
			neg = true;
			c = gc();
		}
		for (; isdigit(c); c = gc()) v = v * 10 + (c - '0');
		if (neg) v = -v;
	}
	static void read(long long& v) {
		v = 0;
		bool neg = false;
		char c = next_char();
		if (c == '-') {
			neg = true;
			c = gc();
		}
		for (; isdigit(c); c = gc()) v = v * 10 + (c - '0');
		if (neg) v = -v;
	}
	static void read(double& v) {
		v = 0;
		double dp = 1;
		bool neg = false, after_dp = false;
		char c = next_char();
		if (c == '-') {
			neg = true;
			c = gc();
		}
		for (; isdigit(c) || c == '.'; c = gc()) {
			if (c == '.') {
				after_dp = true;
			} else if (after_dp) {
				v += (c - '0') * (dp *= 0.1);
			} else {
				v = v * 10 + (c - '0');
			}
		}
		if (neg) v = -v;
	}
	static void read(long double& v) {
		v = 0;
		long double dp = 1;
		bool neg = false, after_dp = false;
		char c = next_char();
		if (c == '-') {
			neg = true;
			c = gc();
		}
		for (; isdigit(c) || c == '.'; c = gc()) {
			if (c == '.') {
				after_dp = true;
			} else if (after_dp) {
				v += (c - '0') * (dp *= 0.1);
			} else {
				v = v * 10 + (c - '0');
			}
		}
		if (neg) v = -v;
	}
	template <class T, class U> static void read(pair<T, U>& v) {
		read(v.first);
		read(v.second);
	}
	template <class T> static void read(vector<T>& v) {
		for (auto& e : v) read(e);
	}
	template <size_t N = 0, class T> static void read_tuple_impl(T& v) {
		if constexpr (N < tuple_size_v<T>) {
			read(get<N>(v));
			read_tuple_impl<N + 1>(v);
		}
	}
	template <class... T> static void read(tuple<T...>& v) {
		read_tuple_impl(v);
	}
	struct ReadVectorHelper {
		size_t n;
		ReadVectorHelper(size_t _n) : n(_n) {}
		template <class T> operator vector<T>() {
			vector<T> v(n);
			read(v);
			return v;
		}
	};
	struct Read2DVectorHelper {
		size_t n, m;
		Read2DVectorHelper(const pair<size_t, size_t>& nm) : n(nm.first), m(nm.second) {}
		template <class T> operator vector<vector<T>>() {
			vector<vector<T>> v(n, vector<T>(m));
			read(v);
			return v;
		}
	};

public:
	string read_line() const {
		string v;
		for (char c = gc(); c != '\n' && c != '\0'; c = gc()) v += c;
		return v;
	}
	template <class T> T read() const {
		T v;
		read(v);
		return v;
	}
	template <class T> vector<T> read_vector(size_t n) const {
		vector<T> a(n);
		read(a);
		return a;
	}
	template <class T> operator T() const {
		return read<T>();
	}
	int operator--(int) const {
		return read<int>() - 1;
	}
	ReadVectorHelper operator[](size_t n) const {
		return ReadVectorHelper(n);
	}
	Read2DVectorHelper operator[](const pair<size_t, size_t>& nm) const {
		return Read2DVectorHelper(nm);
	}
	void operator()() const {}
	template <class H, class... T> void operator()(H&& h, T&&... t) const {
		read(h);
		operator()(forward<T>(t)...);
	}

private:
	template <template <class...> class, class...> struct Multiple;
	template <template <class...> class V, class Head, class... Tail>
	struct Multiple<V, Head, Tail...> {
		template <class... Args> using vec = V<vector<Head>, Args...>;
		using type = typename Multiple<vec, Tail...>::type;
	};
	template <template <class...> class V> struct Multiple<V> { using type = V<>; };
	template <class... T> using multiple_t = typename Multiple<tuple, T...>::type;
	template <size_t N = 0, class T> void multiple_impl(T& t) const {
		if constexpr (N < tuple_size_v<T>) {
			auto& vec = get<N>(t);
			using V = typename remove_reference_t<decltype(vec)>::value_type;
			vec.push_back(read<V>());
			multiple_impl<N + 1>(t);
		}
	}

public:
	template <class... T> auto multiple(size_t h) const {
		multiple_t<T...> result;
		while (h--) multiple_impl(result);
		return result;
	}
} in;
#define inputs(T, ...) \
	T __VA_ARGS__;     \
	in(__VA_ARGS__)
#define ini(...) inputs(int, __VA_ARGS__)
#define inl(...) inputs(long long, __VA_ARGS__)
#define ins(...) inputs(string, __VA_ARGS__)
#line 7 "/home/yuruhiya/programming/library/template/Output.cpp"
#include <charconv>
#line 10 "/home/yuruhiya/programming/library/template/Output.cpp"
using namespace std;

struct BoolStr {
	const char *t, *f;
	BoolStr(const char* _t, const char* _f) : t(_t), f(_f) {}
} Yes("Yes", "No"), yes("yes", "no"), YES("YES", "NO"), Int("1", "0");
struct DivStr {
	const char *d, *l;
	DivStr(const char* _d, const char* _l) : d(_d), l(_l) {}
} spc(" ", "\n"), no_spc("", "\n"), end_line("\n", "\n"), comma(",", "\n"),
    no_endl(" ", "");
class Output {
	BoolStr B{Yes};
	DivStr D{spc};

public:
	void put(int v) const {
		char buf[12]{};
		if (auto [ptr, e] = to_chars(begin(buf), end(buf), v); e == errc{}) {
			fwrite(buf, sizeof(char), ptr - buf, stdout);
		} else {
			assert(false);
		}
	}
	void put(long long v) const {
		char buf[21]{};
		if (auto [ptr, e] = to_chars(begin(buf), end(buf), v); e == errc{}) {
			fwrite(buf, sizeof(char), ptr - buf, stdout);
		} else {
			assert(false);
		}
	}
	void put(bool v) const {
		put(v ? B.t : B.f);
	}
	void put(vector<bool>::reference v) const {
		put(v ? B.t : B.f);
	}
	void put(char v) const {
		putchar_unlocked(v);
	}
	void put(const char* v) const {
		fwrite_unlocked(v, 1, strlen(v), stdout);
	}
	void put(double v) const {
		printf("%.20f", v);
	}
	void put(long double v) const {
		printf("%.20Lf", v);
	}
	template <class T> void put(const T& v) const {
		cout << v;
	}
	template <class T, class U> void put(const pair<T, U>& v) const {
		put(v.first);
		put(D.d);
		put(v.second);
	}
	template <class InputIterater>
	void put_range(const InputIterater& begin, const InputIterater& end) const {
		for (InputIterater i = begin; i != end; ++i) {
			if (i != begin) put(D.d);
			put(*i);
		}
	}
	template <class T> void put(const vector<T>& v) const {
		put_range(v.begin(), v.end());
	}
	template <class T, size_t N> void put(const array<T, N>& v) const {
		put_range(v.begin(), v.end());
	}
	template <class T> void put(const vector<vector<T>>& v) const {
		for (size_t i = 0; i < v.size(); ++i) {
			if (i) put(D.l);
			put(v[i]);
		}
	}

	Output() = default;
	Output(const BoolStr& _boolstr, const DivStr& _divstr) : B(_boolstr), D(_divstr) {}
	Output& operator()() {
		put(D.l);
		return *this;
	}
	template <class H> Output& operator()(H&& h) {
		put(h);
		put(D.l);
		return *this;
	}
	template <class H, class... T> Output& operator()(H&& h, T&&... t) {
		put(h);
		put(D.d);
		return operator()(forward<T>(t)...);
	}
	template <class InputIterator>
	Output& range(const InputIterator& begin, const InputIterator& end) {
		put_range(begin, end);
		put(D.l);
		return *this;
	}
	template <class T> Output& range(const T& a) {
		range(a.begin(), a.end());
		return *this;
	}
	template <class... T> void exit(T&&... t) {
		operator()(forward<T>(t)...);
		std::exit(EXIT_SUCCESS);
	}
	Output& flush() {
		fflush_unlocked(stdout);
		return *this;
	}
	Output& set(const BoolStr& b) {
		B = b;
		return *this;
	}
	Output& set(const DivStr& d) {
		D = d;
		return *this;
	}
	Output& set(const char* t, const char* f) {
		B = BoolStr(t, f);
		return *this;
	}
} out;
#line 6 "/home/yuruhiya/programming/library/template/functions.cpp"
using namespace std;

template <class T> int sz(const T& v) {
	return v.size();
}
template <class T, class U> int lower_index(const T& a, const U& v) {
	return lower_bound(all(a), v) - a.begin();
}
template <class T, class U> int upper_index(const T& a, const U& v) {
	return upper_bound(all(a), v) - a.begin();
}
template <class T> auto Slice(const T& v, size_t i, size_t len) {
	return i < v.size() ? T(v.begin() + i, v.begin() + min(i + len, v.size())) : T();
}
template <class T> T div_ceil(T n, T m) {
	return (n + m - 1) / m;
}
template <class T> T div_ceil2(T n, T m) {
	return div_ceil(n, m) * m;
}
template <class T> T triangle(T n) {
	return (n & 1) ? (n + 1) / 2 * n : n / 2 * (n + 1);
}
template <class T> T nC2(T n) {
	return (n & 1) ? (n - 1) / 2 * n : n / 2 * (n - 1);
}
template <class T> T middle(const T& l, const T& r) {
	return l + (r - l) / 2;
}
template <class T> bool chmax(T& a, const T& b) {
	if (a < b) {
		a = b;
		return true;
	}
	return false;
}
template <class T> bool chmin(T& a, const T& b) {
	if (a > b) {
		a = b;
		return true;
	}
	return false;
}
template <class T> bool in_range(const T& v, const T& min, const T& max) {
	return min <= v && v < max;
}
template <class T> bool in_square(T n) {
	T s = sqrt(n);
	return s * s == n || (s + 1) * (s + 1) == n;
}
template <class T = long long> T BIT(int b) {
	return T(1) << b;
}
template <class T, class U = typename T::value_type> U Gcdv(const T& v) {
	return accumulate(next(v.begin()), v.end(), U(*v.begin()), gcd<U, U>);
}
template <class T, class U = typename T::value_type> U Lcmv(const T& v) {
	return accumulate(next(v.begin()), v.end(), U(*v.begin()), lcm<U, U>);
}
template <class T, class U> T Pow(T a, U n) {
	T result = 1;
	while (n > 0) {
		if (n & 1) {
			result *= a;
			n--;
		} else {
			a *= a;
			n >>= 1;
		}
	}
	return result;
}
template <class T, class U> T Powmod(T a, U n, T mod) {
	T result = 1;
	while (n > 0) {
		if (n & 1) {
			result = result * a % mod;
			n--;
		} else {
			a = a * a % mod;
			n >>= 1;
		}
	}
	return result;
}
namespace internal {
	template <class T, size_t N> auto make_vector(vector<int>& sizes, const T& init) {
		if constexpr (N == 1) {
			return vector(sizes[0], init);
		} else {
			int size = sizes[N - 1];
			sizes.pop_back();
			return vector(size, make_vector<T, N - 1>(sizes, init));
		}
	}
}  // namespace internal
template <class T, size_t N>
auto make_vector(const int (&sizes)[N], const T& init = T()) {
	vector s(rbegin(sizes), rend(sizes));
	return internal::make_vector<T, N>(s, init);
}
#line 7 "/home/yuruhiya/programming/library/template/template_no_Ruby.cpp"
#if __has_include(<library/dump.hpp>)
#include <library/dump.hpp>
#define LOCAL
#else
#define dump(...) ((void)0)
#endif

template <class T> constexpr T oj_local(const T& oj, const T& local) {
#ifndef LOCAL
	return oj;
#else
	return local;
#endif
}
#line 5 "/home/yuruhiya/programming/library/Utility/Point.cpp"
#include <optional>
#line 9 "/home/yuruhiya/programming/library/Utility/Point.cpp"
using namespace std;

struct Point {
	static int H, W;
	static const vector<Point> direction;
	using direction_iterator = vector<Point>::const_iterator;
	static void set_range(int _H, int _W) {
		H = _H;
		W = _W;
	}
	static constexpr Point zero() {
		return {0, 0};
	}
	static constexpr Point one() {
		return {1, 1};
	}
	static constexpr Point L() {
		return {-1, 0};
	}
	static constexpr Point R() {
		return {1, 0};
	}
	static constexpr Point U() {
		return {0, -1};
	}
	static constexpr Point D() {
		return {0, 1};
	}
	static constexpr Point LU() {
		return {-1, -1};
	}
	static constexpr Point LD() {
		return {-1, 1};
	}
	static constexpr Point RU() {
		return {1, -1};
	}
	static constexpr Point RD() {
		return {1, 1};
	}

	int x, y;
	constexpr Point() : x(0), y(0) {}
	constexpr Point(int _x, int _y) : x(_x), y(_y) {}
	constexpr Point(const pair<int, int>& xy) : x(xy.first), y(xy.second) {}
	Point(int n) : x(n % W), y(n / W) {}
	constexpr Point operator+() const {
		return *this;
	}
	constexpr Point operator-() const {
		return {-x, -y};
	}
	constexpr Point operator+(const Point& p) const {
		return Point(*this) += p;
	}
	constexpr Point operator-(const Point& p) const {
		return Point(*this) -= p;
	}
	constexpr Point operator*(const Point& p) const {
		return Point(*this) *= p;
	}
	constexpr Point operator/(const Point& p) const {
		return Point(*this) /= p;
	}
	constexpr Point operator%(const Point& p) const {
		return Point(*this) %= p;
	}
	constexpr Point operator+(int n) const {
		return Point(*this) += n;
	}
	constexpr Point operator-(int n) const {
		return Point(*this) -= n;
	}
	constexpr Point operator*(int n) const {
		return Point(*this) *= n;
	}
	constexpr Point operator/(int n) const {
		return Point(*this) /= n;
	}
	constexpr Point operator%(int n) const {
		return Point(*this) %= n;
	}
	constexpr Point& operator+=(const Point& p) {
		x += p.x;
		y += p.y;
		return *this;
	}
	constexpr Point& operator-=(const Point& p) {
		x -= p.x;
		y -= p.y;
		return *this;
	}
	constexpr Point& operator*=(const Point& p) {
		x *= p.x;
		y *= p.y;
		return *this;
	}
	constexpr Point& operator/=(const Point& p) {
		x /= p.x;
		y /= p.y;
		return *this;
	}
	constexpr Point& operator%=(const Point& p) {
		x %= p.x;
		y %= p.y;
		return *this;
	}
	constexpr Point& operator+=(int n) {
		x += n;
		y += n;
		return *this;
	}
	constexpr Point& operator-=(int n) {
		x -= n;
		y -= n;
		return *this;
	}
	constexpr Point& operator*=(int n) {
		x *= n;
		y *= n;
		return *this;
	}
	constexpr Point& operator/=(int n) {
		x /= n;
		y /= n;
		return *this;
	}
	constexpr Point& operator%=(int n) {
		x %= n;
		y %= n;
		return *this;
	}
	constexpr bool operator==(const Point& p) const {
		return x == p.x && y == p.y;
	}
	constexpr bool operator!=(const Point& p) const {
		return x != p.x || y != p.y;
	}
	bool operator<(const Point& p) const {
		return to_i() < p.to_i();
	}
	bool operator<=(const Point& p) const {
		return to_i() <= p.to_i();
	}
	bool operator>(const Point& p) const {
		return to_i() > p.to_i();
	}
	bool operator>=(const Point& p) const {
		return to_i() >= p.to_i();
	}
	constexpr int operator[](int i) const {
		return i == 0 ? x : i == 1 ? y : 0;
	}
	constexpr bool in_range(int height, int width) const {
		return 0 <= x && x < width && 0 <= y && y < height;
	}
	bool in_range() const {
		return in_range(H, W);
	}
	int to_i() const {
		return x + y * W;
	}
	constexpr pair<int, int> to_pair() const {
		return {x, y};
	}
	constexpr int manhattan_distance(const Point& p) const {
		return std::abs(x - p.x) + std::abs(y - p.y);
	}
	constexpr int distance_square(const Point& p) const {
		return (x - p.x) * (x - p.x) + (y - p.y) * (y - p.y);
	}
	template <class Real> constexpr Real distance(const Point& p) const {
		return sqrt(static_cast<Real>(distance_square(p)));
	}
	constexpr Point abs(const Point& p) const {
		return {std::abs(x - p.x), std::abs(y - p.y)};
	}
	constexpr Point abs() const {
		return {std::abs(x), std::abs(y)};
	}
	Point& swap() {
		std::swap(x, y);
		return *this;
	}

	class enumrate_adjacent_helper {
		shared_ptr<Point> p;
		direction_iterator first, last;

		class iterator {
			shared_ptr<Point> p;
			direction_iterator it;

		public:
			iterator(shared_ptr<Point> _p, direction_iterator _it) : p(_p), it(_it) {}
			Point operator*() const {
				return *p + *it;
			}
			iterator& operator++() {
				++it;
				return *this;
			}
			bool operator!=(iterator other) const {
				return it != other.it;
			}
		};

	public:
		enumrate_adjacent_helper(shared_ptr<Point> _p, direction_iterator _first,
		                         direction_iterator _last)
		    : p(_p), first(_first), last(_last) {}
		iterator begin() const {
			return iterator(p, first);
		}
		iterator end() const {
			return iterator(p, last);
		}
	};
	auto enumrate_adjacent(direction_iterator first, direction_iterator last) const {
		return enumrate_adjacent_helper(make_shared<Point>(*this), first, last);
	}
	auto adjacent4() const {
		return enumrate_adjacent(direction.begin(), direction.begin() + 4);
	}
	auto adjacent8() const {
		return enumrate_adjacent(direction.begin(), direction.begin() + 8);
	}

	class enumrate_adj_in_range_helper {
		shared_ptr<Point> p;
		direction_iterator first, last;

		class sentinel {};
		class iterator {
			shared_ptr<Point> p;
			direction_iterator first, last;

			void increment_until_in_range() {
				for (; first != last; ++first) {
					if ((*p + *first).in_range()) return;
				}
			}

		public:
			iterator(shared_ptr<Point> _p, direction_iterator _first,
			         direction_iterator _last)
			    : p(_p), first(_first), last(_last) {
				increment_until_in_range();
			}
			Point operator*() const {
				return *p + *first;
			}
			iterator& operator++() {
				++first;
				increment_until_in_range();
				return *this;
			}
			bool operator!=(sentinel other) const {
				return first != last;
			}
		};

	public:
		enumrate_adj_in_range_helper(shared_ptr<Point> _p, direction_iterator _first,
		                             direction_iterator _last)
		    : p(_p), first(_first), last(_last) {}
		iterator begin() const {
			return iterator(p, first, last);
		}
		sentinel end() const {
			return sentinel();
		}
	};
	template <class InputIterator>
	auto enumrate_adj_in_range(InputIterator first, InputIterator last) const {
		return enumrate_adj_in_range_helper(make_shared<Point>(*this), first, last);
	}
	auto adj4_in_range() const {
		return enumrate_adj_in_range(direction.begin(), direction.begin() + 4);
	}
	auto adj8_in_range() const {
		return enumrate_adj_in_range(direction.begin(), direction.end());
	}

	constexpr Point left() const {
		return {x - 1, y};
	}
	constexpr Point right() const {
		return {x + 1, y};
	}
	constexpr Point up() const {
		return {x, y - 1};
	}
	constexpr Point down() const {
		return {x, y + 1};
	}
	Point succ() const {
		if (x != W - 1) {
			return {x + 1, y};
		} else {
			return {0, y + 1};
		}
	}
	Point pred() const {
		if (x != 0) {
			return {x - 1, y};
		} else {
			return {W - 1, y - 1};
		}
	}
	constexpr Point moved(char c) const {
		return Point(*this).move(c);
	}
	constexpr Point& move(char c) {
		switch (c) {
			case 'L':
			case 'l':
			case 'W':
			case '>':
				x--;
				break;
			case 'R':
			case 'r':
			case 'E':
			case '<':
				x++;
				break;
			case 'U':
			case 'u':
			case 'N':
			case '^':
				y--;
				break;
			case 'D':
			case 'd':
			case 'S':
			case 'v':
				y++;
				break;
		}
		return *this;
	}
	constexpr Point rotate90() const {
		return {y, -x};
	}
	constexpr Point rotate180() const {
		return {-x, -y};
	}
	constexpr Point rotate270() const {
		return {-y, x};
	}
	char to_direction_char(string_view lrud = "LRUD") const {
		assert(4 <= lrud.size() && lrud.size() <= 5);
		if (y == 0 && x < 0) {
			return lrud[0];
		} else if (y == 0 && x > 0) {
			return lrud[1];
		} else if (x == 0 && y < 0) {
			return lrud[2];
		} else if (x == 0 && y > 0) {
			return lrud[3];
		} else if (lrud.size() == 5) {
			return lrud[4];
		} else {
			assert(false);
		}
	}

	static Point to_direction(char c, string_view lrud = "LRUD") {
		assert(lrud.size() == 4);
		if (c == lrud[0]) {
			return L();
		} else if (c == lrud[1]) {
			return R();
		} else if (c == lrud[2]) {
			return U();
		} else if (c == lrud[3]) {
			return D();
		} else {
			return zero();
		}
	}

	template <class T, class value_type = typename T::value_type::value_type>
	static optional<Point> find(const T& grid, const value_type& val) {
		assert(static_cast<int>(grid.size()) == H);
		for (int i = 0; i < H; ++i) {
			assert(static_cast<int>(grid[i].size()) == W);
			for (int j = 0; j < W; ++j) {
				if (grid[i][j] == val) {
					return Point(j, i);
				}
			}
		}
		return nullopt;
	}
	template <class T, class Predicate>
	static optional<Point> find_if(const T& grid, Predicate pred) {
		assert(static_cast<int>(grid.size()) == H);
		for (int i = 0; i < H; ++i) {
			assert(static_cast<int>(grid[i].size()) == W);
			for (int j = 0; j < W; ++j) {
				if (pred(grid[i][j])) {
					return Point(j, i);
				}
			}
		}
		return nullopt;
	}
	template <class T, class value_type = typename T::value_type::value_type>
	static optional<Point> find_one(const T& grid, const value_type& val) {
		assert(static_cast<int>(grid.size()) == H);
		optional<Point> result;
		for (int i = 0; i < H; ++i) {
			assert(static_cast<int>(grid[i].size()) == W);
			for (int j = 0; j < W; ++j) {
				if (grid[i][j] == val) {
					assert(!result);
					result = Point(j, i);
				}
			}
		}
		return result;
	}

	static auto enumrate_2D_points() {
		class enumrate_2D_points_helper {
		public:
			class iterator {
				Point p;

			public:
				iterator(const Point& _p) : p(_p) {}
				Point operator*() const {
					return p;
				}
				iterator& operator++() {
					p = p.succ();
					return *this;
				}
				iterator& operator--() {
					p = p.pred();
					return *this;
				}
				bool operator!=(iterator other) const {
					return p != other.p;
				}
			};
			iterator begin() const {
				return iterator(Point(0, 0));
			}
			iterator end() const {
				return iterator(Point(0, H));
			}
		};
		return enumrate_2D_points_helper();
	}

	friend ostream& operator<<(ostream& os, const Point& p) {
		return os << '(' << p.x << ", " << p.y << ')';
	}
	friend istream& operator>>(istream& is, Point& p) {
		return is >> p.y >> p.x;
	}
};
int Point::H, Point::W;
const vector<Point> Point::direction{Point::R(),  Point::D(),  Point::U(),  Point::L(),
                                     Point::RD(), Point::LU(), Point::RU(), Point::LD()};
#line 9 "/home/yuruhiya/programming/library/Serch/GridBFS.cpp"
using namespace std;

vector<vector<int>> GridBFS(const vector<string>& grid, Point start, char wall) {
	constexpr int INF = numeric_limits<int>::max();
	int h = grid.size(), w = grid.front().size();
	Point::set_range(h, w);
	vector<vector<int>> result(h, vector<int>(w, INF));
	if (grid[start.y][start.x] == wall) {
		return result;
	}
	result[start.y][start.x] = 0;
	queue<Point> q;
	q.push(start);
	while (!q.empty()) {
		auto now = q.front();
		q.pop();
		for (auto adj : now.adj4_in_range()) {
			if (grid[adj.y][adj.x] != wall && result[adj.y][adj.x] == INF) {
				q.push(adj);
				result[adj.y][adj.x] = result[now.y][now.x] + 1;
			}
		}
	}
	return result;
}
vector<vector<int>> GridBFS(const vector<string>& grid, char start, char wall) {
	Point::set_range(grid.size(), grid.front().size());
	auto s = Point::find_one(grid, start);
	assert(s);
	return GridBFS(grid, *s, wall);
}
int GridBFS(const vector<string>& grid, Point start, Point goal, char wall) {
	return GridBFS(grid, start, wall)[goal.y][goal.x];
}
int GridBFS(const vector<string>& grid, char start, char goal, char wall) {
	assert(start != goal);
	Point::set_range(grid.size(), grid.front().size());
	auto s = Point::find_one(grid, start), g = Point::find_one(grid, goal);
	assert(s && g);
	return GridBFS(grid, *s, *g, wall);
}
#line 3 "a.cpp"

int main() {
	for (int w, h; cin >> w >> h;) {
		Point::set_range(h, w);
		VS s = in[h];
		ini(n);
		vector<Point> points = in[n];
		for (auto& p : points) p.swap();
		Point goal = *Point::find(s, 't');

		auto check = [&](int x) {
			VS grid = s;
			rep(i, x) {
				Point p = points[i];
				if (grid[p.y][p.x] == '#') {
					grid[p.y][p.x] = '.';
				}
			}
			return GridBFS(grid, Point(0, 0), goal, '#') < INT_MAX;
		};

		if (check(0)) {
			out(0);
		} else if (!check(n)) {
			out(-1);
		} else {
			int ng = 0, ok = n;
			while (abs(ng - ok) > 1) {
				int mid = (ng + ok) / 2;
				(check(mid) ? ok : ng) = mid;
			}
			out(ok);
		}
	}
}
accuracy: 1
time_ms: 370
memory_kb: 10224
final_rank: 14

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

int di[4] = {0,1,0,-1};
int dj[4] = {1,0,-1,0};
#define inRange(x,a,b) (a <= x && x < b)

struct UF{
    vector<int> p;
    int n;

    UF(int siz){
        n = siz;
        p.resize(n, 0);
        for(int i = 0; i < n; i++)  p[i] = i;
    }

    int parent(int x){
        if(p[x] != x)   p[x] = parent(p[x]);
        return p[x];
    }

    bool same(int x, int y){
        return parent(x) == parent(y);
    }
    
    void unite(int x, int y){
        x = parent(x), y = parent(y);
        p[x] = y;
    }
};

int main(){
    int w, h;
    cin >> w >> h;
    int ti, tj;
    char mat[h][w];
    for(int i = 0; i < h; i++){
        for(int j = 0; j < w; j++){
            cin >> mat[i][j];
            if(mat[i][j] == 't')    ti = i, tj = j;
        }
    }
    UF uf(w*h);
    for(int i = 0; i < h; i++){
        for(int j = 0; j < w; j++){
            if(mat[i][j] == '#')    continue;
            for(int k = 0; k < 2; k++){
                int ni = i+di[k], nj = j+dj[k];
                if(inRange(ni,0,h)&&inRange(nj,0,w)&&mat[ni][nj]!='#'){
                    uf.unite(i*w+j, ni*w+nj);
                }
            }
        }
    }
    int n;
    cin >> n;
    for(int i = 0; i <= n; i++){
        if(uf.same(0, ti*w+tj)){
            cout << i << endl;
            return 0;
        }
        if(i == n)  break;
        int si, sj;
        cin >> sj >> si;
        mat[si][sj] = '.';
        for(int k = 0; k < 4; k++){
            int ni = si+di[k], nj = sj+dj[k];
            if(inRange(ni,0,h)&&inRange(nj,0,w)&&mat[ni][nj]!='#'){
                uf.unite(si*w+sj, ni*w+nj);
            }
        }
    }
    cout << -1 << endl;
    return 0;
}
accuracy: 1
time_ms: 60
memory_kb: 7736
final_rank: 5

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

#define int long long

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

struct UnionFind{
  int n;
  vector<int> r,p;
  UnionFind(){}
  UnionFind(int sz):n(sz),r(sz,1),p(sz,0){iota(p.begin(),p.end(),0);}
  int find(int x){
    return (x==p[x]?x:p[x]=find(p[x]));
  }
  bool same(int x,int y){
    return find(x)==find(y);
  }
  void unite(int x,int y){
    x=find(x);y=find(y);
    if(x==y) return;
    if(r[x]<r[y]) swap(x,y);
    r[x]+=r[y];
    p[y]=x;
  }
  int size(int x){
    return r[find(x)];
  }
};

signed main() {
  cin.tie(0);
  ios_base::sync_with_stdio(0);
  cout << fixed << setprecision(12);

  int W, H;
  cin >> W >> H;  

  vector<string> s(H);
  for ( int i = 0; i < H; i++ ) {
    cin >> s[i];    
  }
  
  UnionFind uf((W+1)*(H+1));

  int g;
  for ( int i = 0; i < H; i++ ) {
    for ( int j = 0; j < W; j++ ) {
      // cout << i << " " << j << endl;
      if ( s[i][j] == '.' ) {
	for ( int k = 0; k < 4; k++ ) {
	  int ny = i+dy[k], nx = j+dx[k];
	  if ( ny < 0 || ny >= H || nx < 0 || nx >= W ) continue;	  
	  if ( s[ny][nx] == '.' || s[ny][nx] == 't' ) uf.unite(i*W+j, ny*W+nx);	  
	}
      }
      if ( s[i][j] == 't' ) {
	g = i*W+j;	
	for ( int k = 0; k < 4; k++ ) {
	  int ny = i+dy[k], nx = j+dx[k];
	  if ( ny < 0 || ny >= H || nx < 0 || nx >= W ) continue;	  
	  if ( s[ny][nx] == '.' || s[ny][nx] == 't' ) uf.unite(i*W+j, ny*W+nx);	  
	}
      }
    }
  }

  int N;
  cin >> N;
 
  int ans = -1;

  if ( uf.same(0, g) ) ans = 0;  
  
  for ( int i = 0; i < N; i++ ) {
    int x, y;
    cin >> x >> y;
    s[y][x] = '.';    
    if ( ans >= 0 ) continue;
    for ( int k = 0; k < 4; k++ ) {
      int ny = y+dy[k], nx = x+dx[k];
      if ( ny < 0 || ny >= H || nx < 0 || nx >= W ) continue;	  
      if ( s[ny][nx] == '.' || s[ny][nx] == 't' ) uf.unite(y*W+x, ny*W+nx);      
    }

    if ( uf.same(0, g) ) ans = i+1;    
  }

  cout << ans << endl;

  return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 19416
final_rank: 11

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

#define int long long

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

struct UnionFind{
  int n;
  vector<int> r,p;
  UnionFind(){}
  UnionFind(int sz):n(sz),r(sz,1),p(sz,0){iota(p.begin(),p.end(),0);}
  int find(int x){
    return (x==p[x]?x:p[x]=find(p[x]));
  }
  bool same(int x,int y){
    return find(x)==find(y);
  }
  void unite(int x,int y){
    x=find(x);y=find(y);
    if(x==y) return;
    if(r[x]<r[y]) swap(x,y);
    r[x]+=r[y];
    p[y]=x;
  }
  int size(int x){
    return r[find(x)];
  }
};

signed main() {
  cin.tie(0);
  ios_base::sync_with_stdio(0);
  cout << fixed << setprecision(12);

  int W, H;
  cin >> W >> H;  

  vector<string> s(H);
  for ( int i = 0; i < H; i++ ) {
    cin >> s[i];    
  }
  
  UnionFind uf((W+1)*(H+1));

  int g;
  for ( int i = 0; i < H; i++ ) {
    for ( int j = 0; j < W; j++ ) {
      // cout << i << " " << j << endl;
      if ( s[i][j] == '.' ) {
	for ( int k = 0; k < 4; k++ ) {
	  int ny = i+dy[k], nx = j+dx[k];
	  if ( ny < 0 || ny >= H || nx < 0 || nx >= W ) continue;	  
	  if ( s[ny][nx] == '.' || s[ny][nx] == 't' ) uf.unite(i*W+j, ny*W+nx);	  
	}
      }
      if ( s[i][j] == 't' ) {
	g = i*W+j;	
	for ( int k = 0; k < 4; k++ ) {
	  int ny = i+dy[k], nx = j+dx[k];
	  if ( ny < 0 || ny >= H || nx < 0 || nx >= W ) continue;	  
	  if ( s[ny][nx] == '.' || s[ny][nx] == 't' ) uf.unite(i*W+j, ny*W+nx);	  
	}
      }
    }
  }

  int N;
  cin >> N;
 
  int ans = -1;  
  for ( int i = 0; i < N; i++ ) {
    int x, y;
    cin >> x >> y;
    s[y][x] = '.';    
    if ( ans >= 0 ) continue;
    for ( int k = 0; k < 4; k++ ) {
      int ny = y+dy[k], nx = x+dx[k];
      if ( ny < 0 || ny >= H || nx < 0 || nx >= W ) continue;	  
      if ( s[ny][nx] == '.' || s[ny][nx] == 't' ) uf.unite(y*W+x, ny*W+nx);      
    }

    if ( uf.same(0, g) ) ans = i+1;    
  }

  cout << ans << endl;

  return 0;
}
accuracy: 0.16666666666666666
time_ms: 20
memory_kb: 19428
final_rank: 16

code_snippet: #include<iomanip>
#include<limits>
#include<thread>
#include<utility>
#include<iostream>
#include<string>
#include<algorithm>
#include<set>
#include<map>
#include<vector>
#include<stack>
#include<queue>
#include<cmath>
#include<numeric>
#include<cassert>
#include<random>
#include<chrono>
#include<unordered_set>
#include<unordered_map>
#include<fstream>
#include<list>
#include<functional>
#include<bitset>
#include<complex>
#include<tuple>
using namespace std;
typedef unsigned long long int ull;
typedef long long int ll;
typedef pair<ll,ll> pll;
typedef long double D;
#define F first
#define S second
const ll E=1e18+7;
const ll MOD=1000000007;

vector<ll> dx={1,0,-1,0};
vector<ll> dy={0,1,0,-1};


int main(){
    ll w,h;
    cin>>w>>h;
    vector<string> A(h);
    for(auto &I:A){cin>>I;}
    vector<vector<bool>> can(h,vector<bool>(w,false));
    pll G;
    for(int i=0;i<h;i++){
        for(int t=0;t<w;t++){
            if(A[i][t]=='t'){G={i,t};}
        }
    }
    queue<pll> Q;
    Q.push({0,0});
    can[0][0]=true;
    while(!Q.empty()){
        pll W=Q.front(); Q.pop();
        for(int i=0;i<4;i++){
            ll X=W.F+dx[i];
            ll Y=W.S+dy[i];
            if(X<0 || Y<0 || X>=h || Y>=w || can[X][Y] || A[X][Y]=='#'){continue;}
            can[X][Y]=true;
            Q.push({X,Y});
        }
    }
    if(can[G.F][G.S]){cout<<0<<endl; return 0;}
    ll n;
    cin>>n;
    for(int T=1;T<=n;T++){
        ll x,y;
        cin>>x>>y;
        swap(x,y);
        if(A[x][y]=='#'){
            A[x][y]='.';
            for(int i=0;i<4;i++){
                ll X=x+dx[i];
                ll Y=y+dy[i];
                if(X<0 || Y<0 || X>=h || Y>=w || !can[X][Y] || A[X][Y]=='#'){continue;}
                Q.push({x,y});
                can[x][y]=true;
                break;
            }
            while(!Q.empty()){
                pll W=Q.front(); Q.pop();
                for(int i=0;i<4;i++){
                    ll X=W.F+dx[i];
                    ll Y=W.S+dy[i];
                    if(X<0 || Y<0 || X>=h || Y>=w || can[X][Y] || A[X][Y]=='#'){continue;}
                    can[X][Y]=true;
                    Q.push({X,Y});
                }
            }
        }
        if(can[G.F][G.S]){cout<<T<<endl; return 0;}
    }
    cout<<-1<<endl;
    
    
    return 0;
}
accuracy: 1
time_ms: 30
memory_kb: 4212
final_rank: 1

code_snippet: #include<bits/stdc++.h>
using namespace std;
using Int = long long;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}


struct UnionFind{
  Int n;
  vector<Int> r,p;
  UnionFind(){}
  UnionFind(Int sz):n(sz),r(sz,1),p(sz,0){iota(p.begin(),p.end(),0);}
  Int find(Int x){
    return (x==p[x]?x:p[x]=find(p[x]));
  }
  bool same(Int x,Int y){
    return find(x)==find(y);
  }
  void unite(Int x,Int y){
    x=find(x);y=find(y);
    if(x==y) return;
    if(r[x]<r[y]) swap(x,y);
    r[x]+=r[y];
    p[y]=x;
  }
  Int size(Int x){
    return r[find(x)];
  }
};

//INSERT ABOVE HERE
signed main(){
  Int w,h;
  cin>>w>>h;

  vector<string> st(h);
  for(Int i=0;i<h;i++) cin>>st[i];

  auto idx=[&](Int y,Int x){return y*w+x;};  
  UnionFind uf(h*w);
  
  auto in=[&](Int y,Int x){return 0<=y&&y<h&&0<=x&&x<w;};
  Int dy[]={0,0,1,-1};
  Int dx[]={1,-1,0,0};

  auto check=
    [&](Int y,Int x)->void{
      if(!in(y,x)||st[y][x]=='#') return;
      for(Int k=0;k<4;k++){
        Int ny=y+dy[k],nx=x+dx[k];
        if(in(ny,nx)&&st[ny][nx]!='#')
          uf.unite(idx(y,x),idx(ny,nx));        
      }
    };

  for(Int i=0;i<h;i++)
    for(Int j=0;j<w;j++)
      check(i,j);
  
  Int ty=0,tx=0;
  for(Int i=0;i<h;i++)
    for(Int j=0;j<w;j++)
      if(st[i][j]=='t')
        ty=i,tx=j;  
  
  if(uf.same(idx(0,0),idx(ty,tx))){
    cout<<0<<endl;
    return 0;
  }

  Int n;
  cin>>n;
  
  Int x,y,cnt=0;
  while(cin>>x>>y){
    cnt++;
    if(st[y][x]!='#') continue;
    st[y][x]='.';
    check(y,x);
    if(uf.same(idx(0,0),idx(ty,tx))){
      cout<<cnt<<endl;
      return 0;
    }
  }
 
  cout<<-1<<endl;
  return 0;
}
accuracy: 1
time_ms: 30
memory_kb: 19500
final_rank: 12

code_snippet: #include<bits/stdc++.h>
using namespace std;
#define lp(i,n) for(int i=0;i<n;i++)
#define lps(i,j,n) for(int i=j;i<n;i++)
#define fordebug int hoge;cin>>hoge;
#define DEKAI 1000000007;
#define INF (1<<28)
#define int long long
#define double long double
#define floot10 cout<<fixed<<setprecision(10)
bool dp[1100][1100];

signed main(){
  int w,h;
  cin>>w>>h;
  char a[1100][1100];
  lp(i,1100)lp(j,1100){
    dp[i][j]=false;
    a[i][j]='#';
  }
  int gx,gy;
  lp(i,h){
    lp(j,w){
      cin>>a[i+1][j+1];
      if(a[i+1][j+1]=='t'){
	gx=i+1;
	gy=j+1;
      }
    }
  }
  queue<pair<int,int>> q;
  q.push({1,1});
  dp[1][1]=true;
  int ax[4]={0,0,-1,1};
  int ay[4]={-1,1,0,0};
  int n;
  cin>>n;
  int hox[1010],hoy[1010];
  lp(i,n){
    cin>>hox[i]>>hoy[i];
  }
  lp(z,n+1){
    while(!q.empty()){
      int x,y;
      x=q.front().first;
      y=q.front().second;
      //cout<<x<<y<<endl;
      q.pop();
      lp(i,4){
	int nex=x+ax[i];
	int ney=y+ay[i];
	if(nex==gx&&ney==gy){
	  cout<<z<<endl;
	  return 0;
	}
	if(dp[nex][ney]==false){
	  dp[nex][ney]=true;
	  if(a[nex][ney]=='.'){
	    q.push({nex,ney});
	  }
	}
      }
    }
    if(z==n) break;/*
    lp(i,10){
      lp(j,10){
	if(dp[i+1][j+1]==false){
	  cout<<0;
	}
	else cout<<1;
      }
      cout<<endl;
    }
    lp(i,10){
      lp(j,10){
	cout<<a[i+1][j+1]
      }
      cout<<endl;
      }*/
    int bx,by;
    bx=hoy[z];
    by=hox[z];
    bx++;
    by++;
    if(a[bx][by]=='#'){
      a[bx][by]='.';
      if(dp[bx][by]==true){
	q.push({bx,by});
      }
    }
  }
  cout<<-1<<endl;
  return 0;
}
accuracy: 1
time_ms: 40
memory_kb: 5532
final_rank: 4

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

#define int long long
#define MAX 1100
int _rank[MAX*MAX], per[MAX*MAX];

void init(){
  for(int i = 0; i < MAX*MAX; i++){
    _rank[i] = 1;
    per[i] = i;
  }
}

int find(int x){
  return x == per[x]? x : per[x] = find(per[x]);
}

void unite(int x, int y){
  y = find(y);
  x = find(x);

  if(x == y) return;

  if(_rank[y] > _rank[x]){
    per[x] = y;
  } else {
    per[y] = x;
    if(_rank[y] == _rank[x]) _rank[x]++;
  }
}

bool same(int y, int x){
  return find(y) == find(x);
}


signed main(){
  int W, H, N;
  int tx, ty;
  int x, y;
  static string T[MAX];

  int dxy[4] = {0,0,1,-1};

  cin>>W>>H;

  for(int i = 0; i < H; i++){
    cin>>T[i];
  }

  init();
  
  for(int i = 0; i < H; i++){
    for(int j = 0; j < W; j++){

      if(T[i][j] == 't'){
	ty = i;
	tx = j;
      }
	if(T[i][j] == '#') continue;
	
      for(int k = 0; k < 4; k++){
	int nx = j + dxy[k], ny = i + dxy[3 - k];

	if(nx < 0 || nx >= W || ny < 0 || ny >= H) continue;

	if(T[ny][nx] == '#') continue;

	unite(i*MAX + j, ny*MAX + nx);
      }
    }
  }
  cin>>N;

  if(same(0,ty*MAX + tx)){
    cout<<0<<endl;
    return 0;
  }

  for(int i = 0; i < N; i++){
    cin>>x>>y;
    
    if(T[y][x] == '.') continue;
    T[y][x] = '.';
    
    for(int k = 0; k < 4; k++){
      int nx = x + dxy[k], ny = y + dxy[3 - k];
      
      if(nx < 0 || nx >= W || ny < 0 || ny >= H) continue;
      
      if(T[ny][nx] == '#') continue;

      unite(y*MAX + x, ny*MAX + nx);
    }


    if(same(0, ty*MAX + tx)){
      cout<<i+1<<endl;
      return 0;
    }
  }


  cout<<-1<<endl;
  return 0;
}
accuracy: 1
time_ms: 40
memory_kb: 22972
final_rank: 13

code_snippet: #include "bits/stdc++.h"
#include<unordered_map>
#include<unordered_set>
#pragma warning(disable:4996)
using namespace std;


struct UnionFind {
	vector<int> data;
	UnionFind(int size) : data(size, -1) { }
	bool unionSet(int x, int y) {
		x = root(x); y = root(y);
		if (x != y) {
			if (data[y] < data[x]) swap(x, y);
			data[x] += data[y]; data[y] = x;
		}
		return x != y;
	}
	int root(int x) {
		return data[x] < 0 ? x : data[x] = root(data[x]);
	}
	int size(int x) {
		return -data[root(x)];
	}
};

int main() {
	int W,H;cin>>W>>H;
	vector<vector<int>>field(H+2,vector<int>(W+2,1));
	int gx,gy;
	for (int i = 0; i < H; ++i) {
		string st;cin>>st;
		for (int j = 0; j < W; ++j) {
			if (st[j] == '#') {
				
			}
			else if (st[j] == '.') {
				field[i+1][j+1]=0;
			}
			else if (st[j] == 't') {
				field[i+1][j+1]=0;
				gx=j+1;
				gy=i+1;
			}
		}
	}

	int start_id=W+3;
	int goal_id(gy*(W+2)+gx);
	UnionFind uf((H+2)*(W+2));
	int dx[] = { -1,0,1,0 };
	int dy[] = { 0,1,0,-1 };
	for (int y = 1; y <= H; ++y) {
		for (int x = 1; x <= W; ++x) {
			const int now_y=y;
			const int now_x=x;
			const int now_id=((W+2)*now_y+now_x);
			for (int way = 0; way < 4; ++way) {
				const int next_y=now_y+dy[way];
				const int next_x=now_x+dx[way];
				const int next_id=((W+2)*next_y+next_x);

				if (!field[next_y][next_x] && !field[now_y][now_x]) {
					uf.unionSet(now_id,next_id);
				}
			}
		}
	}

	int ans=-1;
	{
		if (uf.root(start_id) == uf.root(goal_id)) {
			ans=0;
		}
		else {
			int N; cin >> N;
			for (int i = 0; i < N; ++i) {
				int x, y; cin >> x >> y;
				int now_y(y + 1);
				int now_x(x + 1);
				const int now_id = ((W + 2)*now_y + now_x);
				field[now_y][now_x] = 0;
				for (int way = 0; way < 4; ++way) {
					const int next_y = now_y + dy[way];
					const int next_x = now_x + dx[way];
					const int next_id = ((W + 2)*next_y + next_x);

					if (!field[next_y][next_x] && !field[now_y][now_x]) {
						uf.unionSet(next_id,now_id);
					}
				}
				if (uf.root(start_id) == uf.root(goal_id)) {
					ans=i+1;
					break;
				}
			}
		}
	}
	cout<<ans<<endl;
	return 0;
}
accuracy: 1
time_ms: 40
memory_kb: 10840
final_rank: 6

code_snippet: #include <stdio.h>
#include <cmath>
#include <algorithm>
#include <cfloat>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <iostream>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;

struct Info{
	Info(){
		row = col = 0;
	}
	Info(int arg_row,int arg_col){
		row = arg_row;
		col = arg_col;
	}
	int row,col;
};

int diff_row[4] = {-1,0,0,1},diff_col[4] = {0,-1,1,0};

int N,W,H;
int* boss,*height;
bool* check;
char** map;

int translate(int row,int col){
	return row*W+col;
}

bool rangeCheck(int row,int col){
	if(row >= 0 && row <= H-1 && col >= 0 && col <= W-1)return true;
	else{
		return false;
	}
}

int get_boss(int id){
	if(boss[id] == id)return id;
	else{
		return boss[id] = get_boss(boss[id]);
	}
}

int is_Same(int x,int y){
	return get_boss(x) == get_boss(y);
}

void unite(int x,int y){
	int boss_x = get_boss(x);
	int boss_y = get_boss(y);

	if(boss_x == boss_y)return;

	if(height[x] > height[y]){

		boss[boss_y] = boss_x;

	}else if(height[x] < height[y]){

		boss[boss_x] = boss_y;

	}else{ //height[x] == height[y]

		boss[boss_y] = boss_x;
		height[x]++;
	}
}

int main(){

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

	int limit = W*H;

	boss = new int[limit];
	height = new int[limit];
	check = new bool[limit];

	for(int i = 0; i < limit; i++){
		boss[i] = i;
		height[i] = 0;
		check[i] = false;
	}

	int dip;

	map = new char*[H];
	for(int i = 0; i < H; i++)map[i] = new char[W+1];

	for(int row = 0; row < H; row++){
		scanf("%s",map[row]);
		for(int col = 0; col < W; col++){
			if(map[row][col] == 't'){
				dip = translate(row,col);
			}
		}
	}

	int tmp,next_row,next_col,next;
	queue<Info> Q;

	for(int row = 0; row < H; row++){
		for(int col = 0; col < W; col++){
			if(map[row][col] != '#' && check[tmp=translate(row,col)] == false){
				check[tmp] = true;

				Q.push(Info(row,col));

				while(!Q.empty()){

					tmp = translate(Q.front().row,Q.front().col);

					for(int i = 0; i < 4; i++){
						next_row = Q.front().row + diff_row[i];
						next_col = Q.front().col + diff_col[i];
						next=translate(next_row,next_col);

						if(rangeCheck(next_row,next_col) == true && map[next_row][next_col] != '#' && check[next] == false){
							unite(tmp,next);
							check[next] = true;
							Q.push(Info(next_row,next_col));
						}
					}
					Q.pop();
				}

			}
		}
	}

	if(is_Same(0,dip)){
		printf("0\n");
		return 0;
	}

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

	int tmp_col,tmp_row;

	for(int loop = 1; loop <= N; loop++){
		scanf("%d %d",&tmp_col,&tmp_row);

		if(map[tmp_row][tmp_col] == '#'){
			map[tmp_row][tmp_col] = '.';

			if(rangeCheck(tmp_row-1,tmp_col) == true && map[tmp_row-1][tmp_col] != '#'){
				unite(translate(tmp_row-1,tmp_col),translate(tmp_row,tmp_col));
			}
			if(rangeCheck(tmp_row+1,tmp_col) == true && map[tmp_row+1][tmp_col] != '#'){
				unite(translate(tmp_row,tmp_col),translate(tmp_row+1,tmp_col));
				if(rangeCheck(tmp_row-1,tmp_col) == true){
					unite(translate(tmp_row-1,tmp_col),translate(tmp_row+1,tmp_col));
				}
			}

			if(rangeCheck(tmp_row,tmp_col-1) == true && map[tmp_row][tmp_col-1] != '#'){
				unite(translate(tmp_row,tmp_col-1),translate(tmp_row,tmp_col));
			}
			if(rangeCheck(tmp_row,tmp_col+1) == true && map[tmp_row][tmp_col+1] != '#'){
				unite(translate(tmp_row,tmp_col),translate(tmp_row,tmp_col+1));
				if(rangeCheck(tmp_row,tmp_col-1) == true){
					unite(translate(tmp_row,tmp_col-1),translate(tmp_row,tmp_col+1));
				}
			}

			if(is_Same(0,dip)){
				printf("%d\n",loop);
				return 0;
			}
		}
	}

	printf("-1\n");
	return 0;
}
accuracy: 1
time_ms: 40
memory_kb: 13092
final_rank: 8

code_snippet: #include<bits/stdc++.h>
#define r(i,n) for(int i=0;i<n;i++)
#define mk make_pair
using namespace std;
int n,m,h,w,x2,y2;
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
string s[1001];
bool b[1001][1001];
bool bfs(int y3,int x3){
  int y=0,x=0;
  b[0][0]=1;
  queue<pair<int,int> >q;
  q.push(mk(x3,y3));
  while(!q.empty()){
    pair<int,int>p=q.front();q.pop();
    int xx=p.first,yy=p.second;
    r(i,4){
      int x1=xx+dx[i],y1=yy+dy[i];
      if(x1<0||y1<0||x1>=w||y1>=h)continue;
      if(!b[y1][x1]&&s[y1][x1]!='#'){
	if(s[y1][x1]=='t')return 1;
	b[y1][x1]=1;
	q.push(mk(x1,y1));
      }
      else b[y1][x1]=1;
    }
  }
  return 0;
}
int main(){
  cin>>w>>h;
  r(i,h)cin>>s[i];
  cin>>m;
  if(bfs(0,0)){
    cout<<0<<endl;
    return 0;
  }
  r(i,m){
    cin>>x2>>y2;
    if(s[y2][x2]=='.')continue;
    s[y2][x2]='.';
    if(b[y2][x2])if(bfs(y2,x2)){
      cout<<i+1<<endl;
      return 0;
    }
  }
  cout<<-1<<endl;
}
accuracy: 1
time_ms: 30
memory_kb: 5092
final_rank: 3

code_snippet: #include<bits/stdc++.h>
#define r(i,n) for(int i=0;i<n;i++)
#define mk make_pair
using namespace std;
int n,m,h,w,x2,y2;
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
string s[1001];
bool b[1001][1001];
bool bfs(int y3,int x3){
  int y=0,x=0;
  b[0][0]=1;
  queue<pair<int,int> >q;
  q.push(mk(x3,y3));
  while(!q.empty()){
    pair<int,int>p=q.front();q.pop();
    int xx=p.first,yy=p.second;
    r(i,4){
      int x1=xx+dx[i],y1=yy+dy[i];
      if(x1<0||y1<0||x1>=w||y1>=h)continue;
      if(!b[y1][x1]&&s[y1][x1]!='#'){
	if(s[y1][x1]=='t')return 1;
	b[y1][x1]=1;
	q.push(mk(x1,y1));
      }
      else b[y1][x1]=1;
    }
  }
  return 0;
}
int main(){
  cin>>w>>h;
  r(i,h)cin>>s[i];
  cin>>m;
  bfs(0,0);
  r(i,m){
    cin>>x2>>y2;
    if(s[y2][x2]=='.')continue;
    s[y2][x2]='.';
    if(b[y2][x2])if(bfs(y2,x2)){
      cout<<i+1<<endl;
      return 0;
    }
  }
  cout<<-1<<endl;
}
accuracy: 0.16666666666666666
time_ms: 30
memory_kb: 5028
final_rank: 15

code_snippet: #include<bits/stdc++.h>
using namespace std;
int w , h;
vector <vector <char> > mp;
bool judge = false;
bool e = false;
vector <vector <int> > visited;
void dfs(int y , int x){
    if(y < 0 || h <= y || x < 0 || w <= x)
        return;
    if(visited[y][x] == 1)
        return;
    if(visited[y][x] == 2){
        judge = true;
        return;
    }
    visited[y][x] = 1;
    dfs(y + 1 , x);
    dfs(y - 1 , x);
    dfs(y , x + 1);
    dfs(y , x - 1);
}

int main(){
    //ifstream cin("2364-in7.txt");
    cin >> w >> h;
    mp = vector <vector <char> > (h , vector <char> (w));
    visited = vector <vector <int> > (h , vector <int> (w));
    for(int i = 0; i < h; i++)
        for(int j = 0; j < w; j++){
            cin >> mp[i][j];
            if(mp[i][j] == '#')
                visited[i][j] = 1;
            if(mp[i][j] == 't')
                visited[i][j] = 2;
        }
    dfs(0,0);
    if(judge){
        e = true;
        cout << 0 << endl;
    }
    int n;
    cin >> n;
    for(int t = 0; t < n; t++){
        int xx , yy;
        cin >> xx >> yy;
        mp[yy][xx] = '.';
        if(e)continue;
        for(int i = 0; i < h; i++)
            for(int j = 0; j < w; j++){
                if(mp[i][j] == '#')
                    visited[i][j] = 1;
                else if(mp[i][j] == 't')
                    visited[i][j] = 2;
                else
                    visited[i][j] = 0;
            }
        judge = false;
        dfs(0,0);
        if(judge){
            e = true;
            cout << t + 1 << endl;
        }
    }
    if(!e)
        cout << -1 << endl;
    return 0;
}
accuracy: 0.1111111111111111
time_ms: 50
memory_kb: 28128
final_rank: 20

code_snippet: #include<bits/stdc++.h>
using namespace std;
int w , h;
char mp[1010][1010];
bool judge = false;
bool e = false;
int visited[1010][1010];//0 == mada , 1 == visited || kabe, 2 == mokutekiti
void dfs(int y , int x){
    if(y < 0 || h <= y || x < 0 || w <= x)
        return;
    if(visited[y][x] == 1)
        return;
    if(visited[y][x] == 2){
        judge = true;
        return;
    }
    visited[y][x] = 1;
    dfs(y + 1 , x);
    dfs(y - 1 , x);
    dfs(y , x + 1);
    dfs(y , x - 1);
}

int main(){
    cin >> w >> h;
    for(int i = 0; i < h; i++)
        for(int j = 0; j < w; j++){
            cin >> mp[i][j];
            if(mp[i][j] == '#')
                visited[i][j] = 1;
            if(mp[i][j] == 't')
                visited[i][j] = 2;
        }
    dfs(0,0);
    if(judge){
        e = true;
        cout << 0 << endl;
    }
    int n;
    cin >> n;
    for(int t = 0; t < n; t++){
        int xx , yy;
        cin >> xx >> yy;
        mp[yy][xx] = '.';
        if(e)continue;
        for(int i = 0; i < h; i++)
            for(int j = 0; j < w; j++){
                if(mp[i][j] == '#')
                    visited[i][j] = 1;
                else if(mp[i][j] == 't')
                    visited[i][j] = 2;
                else
                    visited[i][j] = 0;
            }
        judge = false;
        dfs(0,0);
        if(judge){
            e = true;
            cout << t + 1 << endl;
        }
    }
    if(!e)
        cout << -1 << endl;
    return 0;
}
accuracy: 0.1111111111111111
time_ms: 50
memory_kb: 24180
final_rank: 19

code_snippet: #include<bits/stdc++.h>
using namespace std;
int w , h;
char mp[1010][1010];
bool judge = false;
int visited[1010][1010];//0 == mada , 1 == visited || kabe, 2 == mokutekiti
void dfs(int y , int x){
    if(y < 0 || h <= y || x < 0 || w <= x)
        return;
    if(visited[y][x] == 1)
        return;
    if(visited[y][x] == 2){
        judge = true;
        return;
    }
    visited[y][x] = 1;
    dfs(y + 1 , x);
    dfs(y - 1 , x);
    dfs(y , x + 1);
    dfs(y , x - 1);
}

int main(){
    cin >> w >> h;
    for(int i = 0; i < h; i++)
        for(int j = 0; j < w; j++){
            cin >> mp[i][j];
            if(mp[i][j] == '#')
                visited[i][j] = 1;
            if(mp[i][j] == 't')
                visited[i][j] = 2;
        }
    dfs(0,0);
    if(judge){
        cout << 0 << endl;
        return 0; 
    }
    int n;
    cin >> n;
    for(int t = 0; t < n; t++){
        int xx , yy;
        cin >> xx >> yy;
        mp[yy][xx] = '.';
        for(int i = 0; i < h; i++)
            for(int j = 0; j < w; j++){
                if(mp[i][j] == '#')
                    visited[i][j] = 1;
                else if(mp[i][j] == 't')
                    visited[i][j] = 2;
                else
                    visited[i][j] = 0;
            }
        judge = false;
        dfs(0,0);
        if(judge){
            cout << t + 1 << endl;
            return 0; 
        }
    }
    cout << -1 << endl;
    return 0;
}
accuracy: 0.1111111111111111
time_ms: 50
memory_kb: 24124
final_rank: 17

code_snippet: #include<bits/stdc++.h>
using namespace std;
int w , h;
char mp[1010][1010];
bool judge = false;
int visited[1010][1010];//0 == mada , 1 == visited || kabe, 2 == mokutekiti
void dfs(int y , int x){
    if(y < 0 || h <= y || x < 0 || w <= x)
        return;
    if(visited[y][x] == 1)
        return;
    if(visited[y][x] == 2){
        judge = true;
        return;
    }
    visited[y][x] = 1;
    dfs(y + 1 , x);
    dfs(y - 1 , x);
    dfs(y , x + 1);
    dfs(y , x - 1);
}

int main(){
    cin >> w >> h;
    for(int i = 0; i < h; i++)
        for(int j = 0; j < w; j++){
            cin >> mp[i][j];
            if(mp[i][j] == '#')
                visited[i][j] = 1;
            if(mp[i][j] == 't')
                visited[i][j] = 2;
        }
    dfs(0,0);
    if(judge){
        cout << 0 << endl;
        return 0; 
    }
    int n;
    cin >> n;
    for(int t = 0; t < n; t++){
        int x , y;
        cin >> x >> y;
        mp[y][x] = '.';
        for(int i = 0; i < h; i++)
            for(int j = 0; j < w; j++){
                if(mp[i][j] == '#')
                    visited[i][j] = 1;
                else if(mp[i][j] == 't')
                    visited[i][j] = 2;
                else
                    visited[i][j] = 0;
            }
        judge = false;
        dfs(0,0);
        if(judge){
            cout << t + 1 << endl;
            return 0; 
        }
    }
    cout << -1 << endl;
    return 0;
}
accuracy: 0.1111111111111111
time_ms: 50
memory_kb: 24176
final_rank: 18

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

typedef long long ll;
#define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i))
#define each(itr,c) for(__typeof(c.begin()) itr=c.begin(); itr!=c.end(); ++itr)
#define all(x) (x).begin(),(x).end()
#define pb push_back
#define fi first
#define se second

typedef pair<int,int> pi;

int main()
{
    int dx[4]={1,-1,0,0},dy[4]={0,0,1,-1};
    int w,h;
    while(cin >>w >>h)
    {
        vector<string> s(h);
        rep(i,h) cin >>s[i];
        int n;
        scanf(" %d", &n);
        vector<int> x(n),y(n);
        rep(i,n) scanf(" %d %d", &x[i], &y[i]);

        pi g;
        rep(i,h)rep(j,w) if(s[i][j]=='t') g=pi(i,j);

        int ans=-1;
        #define IN(x,y) (0<=x && x<w && 0<=y && y<h)
        vector<vector<bool>> vis(h,vector<bool>(w,false));
        vis[0][0]=true;
        queue<pi> que;
        que.push(pi(0,0));
        rep(i,n+1)
        {
            while(!que.empty())
            {
                pi now=que.front();
                que.pop();
                if(now==g)
                {
                    ans=i;
                    break;
                }
                rep(j,4)
                {
                    int nx=now.se+dx[j],ny=now.fi+dy[j];
                    if(IN(nx,ny) && s[ny][nx]!='#' && !vis[ny][nx])
                    {
                        vis[ny][nx]=true;
                        que.push(pi(ny,nx));
                    }
                }
            }

            if(i==n || ans>=0) break;

            s[y[i]][x[i]]='.';
            rep(j,4)
            {
                int tx=x[i]+dx[j],ty=y[i]+dy[j];
                if(IN(tx,ty) && vis[ty][tx] && !vis[y[i]][x[i]])
                {
                    vis[y[i]][x[i]]=true;
                    que.push(pi(y[i],x[i]));
                }
            }
        }

        printf("%d\n", ans);
    }
    return 0;
}
accuracy: 1
time_ms: 40
memory_kb: 4384
final_rank: 2

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

typedef long long ll;
#define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i))
#define each(itr,c) for(__typeof(c.begin()) itr=c.begin(); itr!=c.end(); ++itr)
#define all(x) (x).begin(),(x).end()
#define pb push_back
#define fi first
#define se second

typedef pair<int,int> pi;

int w,h;
string s[1000];
int n;
int x[1000],y[1000];
bool wall[1000];

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

#define IN(x,y) (0<=x && x<w && 0<=y && y<h)
int vis[1000][1000];
bool check(int q)
{
    rep(i,q) s[y[i]][x[i]]='.';
    memset(vis,0,sizeof(vis));

    bool ret=false;

    queue<pi> que;
    que.push(pi(0,0));
    vis[0][0]=true;
    while(!que.empty())
    {
        pi now=que.front();
        que.pop();

        if(s[now.fi][now.se]=='t')
        {
            ret=true;
            break;
        }

        rep(i,4)
        {
            int nx=now.se+dx[i], ny=now.fi+dy[i];
            if(IN(nx,ny) && s[ny][nx]!='#' && !vis[ny][nx])
            {
                vis[ny][nx]=1;
                que.push(pi(ny,nx));
            }
        }
    }

    rep(i,q) if(wall[i]) s[y[i]][x[i]]='#';
    return ret;
}

int main()
{
    while(cin >>w >>h)
    {
        rep(i,h) cin >>s[i];
        cin >>n;
        rep(i,n)
        {
            cin >>x[i] >>y[i];
            wall[i]=(s[y[i]][x[i]]=='#');
        }

        if(check(0))
        {
            printf("0\n");
            continue;
        }

        int l=0, r=n+1;
        while(r-l>1)
        {
            int m=(l+r)/2;

            if(check(m)) r=m;
            else l=m;
        }

        if(r==n+1) r=-1;
        printf("%d\n", r);
    }
    return 0;
}
accuracy: 1
time_ms: 180
memory_kb: 8104
final_rank: 10

code_snippet: #include <bits/stdc++.h>
#define N 1000021
using namespace std;
int w,h;
int par[N],Rank[N];
char mp[1001][1001];

void init(){
  for(int i=0;i<N;i++) par[i]=i,Rank[i]=0;
}

int find(int x){
  if(par[x]==x)return x;
  return par[x]=find(par[x]);
}

void unite(int x,int y){
  x=find(x),y=find(y);
  if(x==y)return;
  if(Rank[x]<Rank[y])par[x]=y;
  else par[y]=x,Rank[x]+=(Rank[x]==Rank[y]);
}

bool same(int x,int y){return find(x)==find(y);}
int Pos(int x,int y){return w*y+x;}

int dx[]={0,0,-1,1};
int dy[]={1,-1,0,0};
void umeru(){
  for(int i=0;i<h;i++)
    for(int j=0;j<w;j++)
      for(int k=0;k<4;k++){
	int ni=i+dy[k],nj=j+dx[k];
	if(mp[i][j]=='#')continue;
	if(ni<0||nj<0||ni>=h||nj>=w||mp[ni][nj]=='#')continue;
	unite(Pos(j,i),Pos(nj,ni));
      }
}

void umeru2(int x,int y){
  for(int i=0;i<4;i++){
    int ny=y+dy[i],nx=x+dx[i];
    if(ny<0||nx<0||ny>=h||nx>=w||mp[ny][nx]=='#')continue;
    unite(Pos(x,y),Pos(nx,ny));
  }
}

int main(){
  init();
  cin>>w>>h;
  int t;
  for(int i=0;i<h;i++)
    for(int j=0;j<w;j++){
      cin>>mp[i][j];
      if(mp[i][j]=='t')t=Pos(j,i);
    }
  umeru();
 
  int n,ans=-1;
  if(same(0,t)) ans=0;
  cin>>n;
  for(int i=1,a,b;i<=n;i++){
    cin>>a>>b;
    umeru2(a,b);
    mp[b][a]='.';
    if(same(0,t)&&ans==-1)ans=i;
  }
  cout <<ans<<endl;
  return 0;
}
accuracy: 1
time_ms: 60
memory_kb: 11888
final_rank: 9