Problem:
尾根 (Ridge)
問題
JOI カルデラは景観の良さが多くの登山家に愛される美しい地形である．
特に，尾根と呼ばれる場所からの景観は絶景である．
JOI カルデラの土地は南北 H キロメートル，東西 W キロメートルの長方形である．
南北，東西に 1 キロメートルごとに JOI カルデラの土地を分け，これら H×W 個の領域を区域と呼ぶ．
すべての区域において，その中では標高は等しい．また，異なる区域の標高は異なる．
ある区域に雨が降ると，雨水はその区域に東西南北に隣り合う最大で 4 つの区域のうち，
標高がその区域より低いような区域のすべてに流れる．そのような区域がない場合，雨水はその区域に溜まる．
他の区域から流れてきた雨水についても同様である．
JOI カルデラの外側は，外輪山の急峻な崖に囲まれているため，雨水が JOI カルデラの外に流れ出すことはない．
ある区域について，その区域のみに雨が降った場合，最終的に複数の区域に雨水が溜まるとき，その区域を尾根と呼ぶ．
絶景をこよなく愛する登山家たちのために，尾根の区域がいくつあるかを求めるプログラムを作成せよ．
入力
入力は 1 + H 行からなる．
1 行目には 2 個の整数 H, W (1 ≦ H ≦ 1000, 1 ≦ W ≦ 1000) が空白を区切りとして書かれており，JOI カルデラが南北に H キロメートル，東西に W キロメートルにわたることを表す．
続く H 行にはそれぞれ W 個の整数が空白を区切りとして書かれており，標高の情報を表す．
H 行のうちの i 行目の j 番目 (1 ≦ i ≦ H, 1 ≦ j ≦ W) の整数 M
i,j
(1 ≦ M
i,j
≦ H×W) は，JOI カルデラの北から i 行目，西から j 列目の区域の標高を表す．
(i,j) ≠ (k,l) なら，M
i,j
≠ M
k,l
を満たす．
出力
尾根の区域の個数を 1 行で出力せよ．
入出力例
入力例 1
3 3
2 9 4
7 5 3
6 1 8
出力例 1
4
入力例 2
3 5
5 3 8 2 14
9 10 4 1 13
12 7 11 6 15
出力例 2
4
入力例 1 において，標高が 5, 7, 8, 9 の 4 個の区域が尾根である．例えば，標高 9 の区域に雨が降った場合，最終的に雨水は標高 1, 2, 3 の 3 個の区域に溜まる．したがって，標高 9 の区域は尾根である．また，標高 6 の区域に雨が降った場合，最終的に雨水は標高 1 の区域にしか溜まらない．したがって，標高 6 の区域は尾根ではない．
入力例 2 において，標高が 8, 10, 11, 12 の 4 個の区域が尾根である．
情報オリンピック日本委員会作 『第 16 回日本情報オリンピック JOI 2016/2017 予選競技課題』

Submitted solutions:

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define INF 1LL<<60
int main(void){
    // Your code here!
    ll h,w,ans=0;cin>>h>>w;
    vector<vector<ll>> ma(h+2,vector<ll>(w+2,INF));
    vector<vector<pair<ll,bool>>> maf(h+2,vector<pair<ll,bool>>(w+2,{-1,0}));
    vector<ll> d={-1,0,1,0,-1};
    for(ll i=0;i<h;i++)for(ll j=0;j<w;j++)cin>>ma[i+1][j+1];
    queue<pair<ll,pair<ll,ll>>> q;
    for(ll i=1;i<=h;i++)for(ll j=1;j<=w;j++){
        bool ok=1;
        for(ll k=0;k<4;k++){
            ll ni=i+d[k],nj=j+d[k+1];
            if(ma[ni][nj]<ma[i][j])ok=0;
        }
        if(ok)q.push({ma[i][j],{i,j}});
    }
    while(q.size()){
        auto [f,jf]=q.front();q.pop();
        auto [x,y]=jf;
        for(ll i=0;i<4;i++){
            ll nx=x+d[i],ny=y+d[i+1];
            if(ma[nx][ny]==INF||(maf[nx][ny].first!=-1&&maf[nx][ny].second)||ma[nx][ny]<ma[x][y])continue;
            if(maf[nx][ny].first==-1){
                maf[nx][ny].first=f;
                q.push({f,{nx,ny}});
            }else{
                if(maf[nx][ny].first!=f){
                    maf[nx][ny].second=1;
                    q.push({f,{nx,ny}});
                }
            }
        }
    }
    for(ll i=0;i<h;i++)for(ll j=0;j<w;j++)if(maf[i+1][j+1].first!=-1&&maf[i+1][j+1].second)ans++;
    cout<<ans<<endl;
}
accuracy: 1
time_ms: 210
memory_kb: 27104
final_rank: 7

code_snippet: #include<bits/stdc++.h>
#include<unordered_set>
using namespace std;
#define ALL(a)  a.begin(),a.end()
#define SZ(a) int((a).size())
#define SORT(c) sort(ALL((c)))
#define UNIQ(c) (c).erase(unique(ALL((c))), end((c)))
#define FOR(i, s, e) for (int(i) = (s); (i) < (e); (i)++)
#define debug(x) cerr << #x << ": " << x << endl

using LL = long long; template<class T> using V = vector<T>;


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

	int H, W;
	cin >> H >> W;
	V<V<int>>vs(H, V<int>(W));
	using PII = pair<int, int>;
	V<pair<int, PII>>q;
	FOR(i, 0, H) {
		FOR(j, 0, W) {
			cin >> vs[i][j];
			q.push_back({ vs[i][j] ,{i,j} });
		}
	}
	const int DY[] = { 0,0,1,-1 };
	const int DX[] = { 1,-1,0,0 };
	SORT(q);
	// unordered_set
	V<V<V<int>>>RootFlow(H, V<V<int>>(W));
	FOR(i, 0, SZ(q)) {
		int m = q[i].first;
		int y = q[i].second.first, x = q[i].second.second;
		if (!SZ(RootFlow[y][x])) {
			RootFlow[y][x].push_back(m); // s
		}
		SORT(RootFlow[y][x]);
		UNIQ(RootFlow[y][x]);
		FOR(k, 0, 4) {
			int ny = y + DY[k], nx = x + DX[k];
#define IN(a,b,c) a<=b&&b<c
			if (IN(0, ny, H) && IN(0, nx, W)) {
				if (vs[ny][nx] > vs[y][x]) {
					for (const auto&it : RootFlow[y][x]) {
						RootFlow[ny][nx].push_back(it);
					}
				}
			}
		}
	}

	int ans = 0;
	FOR(i, 0, H) {
		FOR(j, 0, W) {
			SORT(RootFlow[i][j]);
			UNIQ(RootFlow[i][j]);
			ans += (SZ(RootFlow[i][j]) > 1);
		}
	}
	cout << ans << endl;
	return 0;
}
accuracy: 1
time_ms: 340
memory_kb: 110640
final_rank: 15

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

vector<int> dx={-1,0,1,0},dy={0,-1,0,1};
int main() {
    int H,W;
    cin>>H>>W;
    vector<pair<int,int>> P(H*W);
    vector<vector<int>> Q(H,vector<int>(W));
    vector<vector<set<int>>> S(H,vector<set<int>>(W));
    for(int h=0;h<H;h++){
        for(int w=0;w<W;w++){
            cin>>Q[h][w];
            Q[h][w]--;
            P[Q[h][w]]={h,w};
        }
    }
    int an=0;
    for(int p=0;p<H*W;p++){
        auto [y,x]=P[p];
        for(int d=0;d<4;d++){
            int ny=y+dy[d];
            int nx=x+dx[d];
            if(ny>=0&&nx>=0&&ny<H&&nx<W&&Q[ny][nx]<Q[y][x]){
                for(auto s:S[ny][nx])S[y][x].insert(s);
            }
        }
        if(S[y][x].size()==0)S[y][x].insert(p);
        while(S[y][x].size()>2){
            S[y][x].erase(S[y][x].begin());
        }
        if(S[y][x].size()==2)an++;
    }
    cout<<an<<endl;
    
}
accuracy: 1
time_ms: 440
memory_kb: 145952
final_rank: 18

code_snippet: #line 1 "a.cpp"
#define PROBLEM ""
#line 1 "/home/kuhaku/home/github/algo/lib/algorithm/in_field.hpp"
#include <cstdint>
#include <utility>

namespace internal {

template <int Idx>
struct in_field_impl {
    template <class Head, class... Tail>
    constexpr in_field_impl(Head &&head, Tail &&...tail)
        : limit(head), impl(std::forward<Tail>(tail)...) {}

    template <class Head, class... Tail>
    constexpr bool is_internal(Head x, Tail &&...tail) const {
        return 0 <= x && x < limit && impl.is_internal(std::forward<Tail>(tail)...);
    }

  private:
    std::int64_t limit;
    in_field_impl<Idx - 1> impl;
};

template <>
struct in_field_impl<0> {
    constexpr in_field_impl() {}

    constexpr bool is_internal() const {
        return true;
    }
};

}  // namespace internal

template <int Idx>
struct InField {
    template <class... Args, std::enable_if_t<(sizeof...(Args) == Idx)> * = nullptr>
    constexpr InField(Args &&...args) : entity(std::forward<Args>(args)...) {}

    template <class... Args>
    constexpr bool operator()(Args &&...args) const {
        return entity.is_internal(std::forward<Args>(args)...);
    }

  private:
    internal::in_field_impl<Idx> entity;
};
#line 2 "/home/kuhaku/home/github/algo/lib/template/template.hpp"
#pragma GCC target("sse4.2,avx2,bmi2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
template <class T, class U>
constexpr bool chmax(T &a, const U &b) {
    return a < (T)b ? a = (T)b, true : false;
}
template <class T, class U>
constexpr bool chmin(T &a, const U &b) {
    return (T)b < a ? a = (T)b, true : false;
}
constexpr std::int64_t INF = 1000000000000000003;
constexpr int Inf = 1000000003;
constexpr double EPS = 1e-7;
constexpr double PI = M_PI;
#line 3 "/home/kuhaku/home/github/algo/lib/template/macro.hpp"
#define FOR(i, m, n) for (int i = (m); i < int(n); ++i)
#define FORR(i, m, n) for (int i = (m)-1; i >= int(n); --i)
#define FORL(i, m, n) for (int64_t i = (m); i < int64_t(n); ++i)
#define rep(i, n) FOR (i, 0, n)
#define repn(i, n) FOR (i, 1, n + 1)
#define repr(i, n) FORR (i, n, 0)
#define repnr(i, n) FORR (i, n + 1, 1)
#define all(s) (s).begin(), (s).end()
#line 3 "/home/kuhaku/home/github/algo/lib/template/sonic.hpp"
struct Sonic {
    Sonic() {
        std::ios::sync_with_stdio(false);
        std::cin.tie(nullptr);
        std::cout << std::fixed << std::setprecision(20);
    }

    constexpr void operator()() const {}
} sonic;
#line 5 "/home/kuhaku/home/github/algo/lib/template/atcoder.hpp"
using namespace std;
using ll = std::int64_t;
using ld = long double;
template <class T, class U>
std::istream &operator>>(std::istream &is, std::pair<T, U> &p) {
    return is >> p.first >> p.second;
}
template <class T>
std::istream &operator>>(std::istream &is, std::vector<T> &v) {
    for (T &i : v) is >> i;
    return is;
}
template <class T, class U>
std::ostream &operator<<(std::ostream &os, const std::pair<T, U> &p) {
    return os << '(' << p.first << ',' << p.second << ')';
}
template <class T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {
    for (auto it = v.begin(); it != v.end(); ++it) {
        os << (it == v.begin() ? "" : " ") << *it;
    }
    return os;
}
template <class Head, class... Tail>
void co(Head &&head, Tail &&...tail) {
    if constexpr (sizeof...(tail) == 0) std::cout << head << '\n';
    else std::cout << head << ' ', co(std::forward<Tail>(tail)...);
}
template <class Head, class... Tail>
void ce(Head &&head, Tail &&...tail) {
    if constexpr (sizeof...(tail) == 0) std::cerr << head << '\n';
    else std::cerr << head << ' ', ce(std::forward<Tail>(tail)...);
}
template <typename T, typename... Args>
auto make_vector(T x, int arg, Args... args) {
    if constexpr (sizeof...(args) == 0) return std::vector<T>(arg, x);
    else return std::vector(arg, make_vector<T>(x, args...));
}
void Yes(bool is_correct = true) {
    std::cout << (is_correct ? "Yes" : "No") << '\n';
}
void No(bool is_not_correct = true) {
    Yes(!is_not_correct);
}
void YES(bool is_correct = true) {
    std::cout << (is_correct ? "YES" : "NO") << '\n';
}
void NO(bool is_not_correct = true) {
    YES(!is_not_correct);
}
void Takahashi(bool is_correct = true) {
    std::cout << (is_correct ? "Takahashi" : "Aoki") << '\n';
}
void Aoki(bool is_not_correct = true) {
    Takahashi(!is_not_correct);
}
#line 4 "a.cpp"

int main(void) {
    int h, w;
    cin >> h >> w;
    vector a(h, vector(w, 0));
    cin >> a;

    InField<2> in_field(h, w);

    auto flatten = [&](int x, int y) {
        return x * w + y;
    };

    vector<tuple<int, int, int>> v;
    rep (i, h) {
        rep (j, w) v.emplace_back(a[i][j], i, j);
    }
    sort(all(v));
    vector b(h, vector(w, -1));
    vector<int> dx = {1, -1, 0, 0}, dy = {0, 0, 1, -1};
    for (auto [t, x, y] : v) {
        rep (k, 4) {
            int nx = x + dx[k], ny = y + dy[k];
            if (!in_field(nx, ny))
                continue;
            if (b[x][y] == -2)
                continue;
            if (b[nx][ny] == -1)
                continue;
            if (b[nx][ny] == -2)
                b[x][y] = -2;
            else if (b[nx][ny] == -3 && b[x][y] == -1)
                b[x][y] = flatten(nx, ny);
            else if (b[nx][ny] == -3 && b[x][y] != flatten(nx, ny))
                b[x][y] = -2;
            else if (b[nx][ny] == -3)
                continue;
            else if (b[x][y] == -1)
                b[x][y] = b[nx][ny];
            else if (b[x][y] != b[nx][ny])
                b[x][y] = -2;
        }
        if (b[x][y] == -1)
            b[x][y] = -3;
    }

    int ans = 0;
    rep (i, h) {
        rep (j, w) ans += b[i][j] == -2;
    }
    co(ans);

    return 0;
}
accuracy: 1
time_ms: 110
memory_kb: 23016
final_rank: 3

code_snippet: #include "bits/stdc++.h"

#define REP(i,num) for(ll i=0;i<(num);++i)
#define FOR(i,c,num) for(ll (i)=(c);(i)<(num);++(i))
#define LOOP(i) while(i--)
#define ALL(c) c.begin(),c.end()
#define PRINTALL(c) for(auto pitr=c.begin();pitr!=c.end();++pitr){cout<<*pitr;if(next(pitr,1)!=c.end())cout<<' ';}cout<<endl;
#define PAIRCOMP(c,comp) [](const pair<ll,ll>& lhs,const pair<ll,ll>& rhs){return lhs.c comp rhs.c;}

using namespace std;
using ll = long long;
using ull = unsigned long long;
using vll = vector<ll>;
using vvll = vector<vector<ll>>;

constexpr ll atcoder_mod = 1e9+7;

template<typename T=ll>
T in(){ T x; cin >> x; return (x); }
template<typename T=ll,typename C=vector<T>>
C vecin(int N){ C x(N);REP(i,N){ x[i]=in<T>(); }return x; }
template<typename T=ll,size_t N>
array<T,N> arrin(){array<T,N> x;REP(i,N){ x[i]=in<T>(); }return x;}

void vout(){ cout << endl; }
template<typename Head,typename... Tail>
void vout(Head&& h,Tail&&... t){ cout << ' ' << h;vout(forward<Tail>(t)...); }
void out(){ cout << endl; }
template<typename Head,typename... Tail>
void out(Head&& h,Tail&&... t){ cout << h;vout(forward<Tail>(t)...); }

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

int main(){
	cin.tie(0);
	ios::sync_with_stdio(false);
	cout<<fixed<<setprecision(10);
	
	auto H=in(),W=in();
	vll P(H*W);
	vvll M(H,vll(W));
	vvll D(H,vll(W,-1)),O(H,vll(W,0));
	REP(i,H){
		REP(j,W){
			auto V=in();
			P[V-1] = j+i*W;
			M[i][j]=V;
		}
	}
	ll A=0;
	REP(i,H*W){
		auto C=P[i];
		auto X=C%W,Y=C/W;
		set<ll> L;
		if(X>0 && M[Y][X-1]<M[Y][X]){
			if(O[Y][X-1]){
				O[Y][X]=1;
				A++;
				continue;
			}
			L.insert(D[Y][X-1]);
		}
		if(X<W-1 && M[Y][X+1]<M[Y][X]){
			if(O[Y][X+1]){
				O[Y][X]=1;
				A++;
				continue;
			}
			L.insert(D[Y][X+1]);
		}
		if(Y>0 && M[Y-1][X]<M[Y][X]){
			if(O[Y-1][X]){
				O[Y][X]=1;
				A++;
				continue;
			}
			L.insert(D[Y-1][X]);
		}
		if(Y<H-1 && M[Y+1][X]<M[Y][X]){
			if(O[Y+1][X]){
				O[Y][X]=1;
				A++;
				continue;
			}
			L.insert(D[Y+1][X]);
		}
		if(L.empty()) D[Y][X]=M[Y][X];
		else if(L.size()==1) D[Y][X]=*L.begin();
		else{
			O[Y][X]=1;
			A++;
		}
	}
	out(A);
	return 0;
}
accuracy: 1
time_ms: 140
memory_kb: 34504
final_rank: 6

code_snippet: #include <bits/stdc++.h>
#include <iostream>
#include <limits>
#include <numeric>
#include <type_traits>
#include <bitset>
#include <map>
#include <unordered_map>
#include <set>
#include <random>

using namespace std;

#define rep(i,n,m) for(ll (i)=(n);(i)<(m);(i)++)
#define rrep(i,n,m) for(ll (i)=(n);(i)>(m);(i)--)
using ll = long long;
const ll mod = 1000000007;
const ll inf = 1e9;
const ll INF = 1e17;

void pline(vector<ll> lis){
    rep(i,0,lis.size()){
        printf ("%lld",lis[i]);
        if (i != lis.size()-1) printf(" ");
        else printf("\n");
    }
}

void pline(vector<pair<ll,ll>> lis){
    rep(i,0,lis.size()){
        printf ("/%lld,%lld/",lis[i].first,lis[i].second);
        if (i != lis.size()-1) printf(" ");
        else printf("\n");
    }
}

/*
void pmap(map<ll,mint>& lis){
    for (auto p : lis){
        printf ("%lld:%lld ,",p.first,p.second.val());
    }
    printf ("\n");
}*/


int main(){

    //ios::sync_with_stdio(false);
    //std::cin.tie(nullptr);

    std::random_device rnd;    
    std::mt19937 mt(rnd());           
    

    ll H,W;
    cin >> H >> W;

    vector<vector<ll>> A(H,vector<ll> (W,0));
    vector<vector<ll>> state(H,vector<ll> (W,0));

    rep(i,0,H){
        rep(j,0,W){
            cin >> A[i][j];
        }
    }

    vector<pair<ll,ll>> rev(H*W);

    rep(i,0,H){
        rep(j,0,W){
            rev[A[i][j]-1] = make_pair(i,j);
        }
    }

    /*
    rep(i,0,H){
        rep(j,0,W){
            state[i][j] = i*W+j+1;
        }
    }*/

    //rep(i,0,H) pline(state[i]);

    for (auto idx : rev){

        ll i = idx.first;
        ll j = idx.second;

        if (state[i][j] == 0) state[i][j] = mt();

        rep(d,0,4){
            ll nexi = i;
            ll nexj = j;
            if (d == 0) nexi -= 1;
            else if (d == 1) nexi += 1;
            else if (d == 2) nexj += 1;
            else nexj -= 1;

            if (nexi < 0 || nexi >= H || nexj < 0 || nexj >= W) continue;

            if (A[nexi][nexj] > A[i][j]){
                state[nexi][nexj] |= state[i][j];
                if (state[nexi][nexj] != state[i][j]){
                    state[nexi][nexj] |= INF;
                }
            }
        }
    }

    ll ans = 0;

    //rep(i,0,H) pline(state[i]);

    rep(i,0,H){
        rep(j,0,W){
            if (state[i][j] >= INF) ans++;
        }
    }

    cout << ans << endl;

}

/*

dagだよな…
最終地点が複数あるような…


*/
accuracy: 1
time_ms: 200
memory_kb: 34368
final_rank: 8

code_snippet: //#define _GLIBCXX_DEBUG

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

#define endl '\n'
#define lfs cout<<fixed<<setprecision(10)
#define ALL(a)  (a).begin(),(a).end()
#define ALLR(a)  (a).rbegin(),(a).rend()
#define UNIQUE(a) (a).erase(unique((a).begin(),(a).end()),(a).end())
#define spa << " " <<
#define fi first
#define se second
#define MP make_pair
#define MT make_tuple
#define PB push_back
#define EB emplace_back
#define rep(i,n,m) for(ll i = (n); i < (ll)(m); i++)
#define rrep(i,n,m) for(ll i = (ll)(m) - 1; i >= (ll)(n); i--)
using ll = long long;
using ld = long double;
const ll MOD1 = 1e9+7;
const ll MOD9 = 998244353;
const ll INF = 1e18;
using P = pair<ll, ll>;
template<typename T> using PQ = priority_queue<T>;
template<typename T> using QP = priority_queue<T,vector<T>,greater<T>>;
template<typename T1, typename T2>bool chmin(T1 &a,T2 b){if(a>b){a=b;return true;}else return false;}
template<typename T1, typename T2>bool chmax(T1 &a,T2 b){if(a<b){a=b;return true;}else return false;}
ll median(ll a,ll b, ll c){return a+b+c-max({a,b,c})-min({a,b,c});}
void ans1(bool x){if(x) cout<<"Yes"<<endl;else cout<<"No"<<endl;}
void ans2(bool x){if(x) cout<<"YES"<<endl;else cout<<"NO"<<endl;}
void ans3(bool x){if(x) cout<<"Yay!"<<endl;else cout<<":("<<endl;}
template<typename T1,typename T2>void ans(bool x,T1 y,T2 z){if(x)cout<<y<<endl;else cout<<z<<endl;}  
template<typename T1,typename T2,typename T3>void anss(T1 x,T2 y,T3 z){ans(x!=y,x,z);};  
template<typename T>void debug(const T &v,ll h,ll w,string sv=" "){for(ll i=0;i<h;i++){cout<<v[i][0];for(ll j=1;j<w;j++)cout<<sv<<v[i][j];cout<<endl;}};
template<typename T>void debug(const T &v,ll n,string sv=" "){if(n!=0)cout<<v[0];for(ll i=1;i<n;i++)cout<<sv<<v[i];cout<<endl;};
template<typename T>void debug(const vector<T>&v){debug(v,v.size());}
template<typename T>void debug(const vector<vector<T>>&v){for(auto &vv:v)debug(vv,vv.size());}
template<typename T>void debug(stack<T> st){while(!st.empty()){cout<<st.top()<<" ";st.pop();}cout<<endl;}
template<typename T>void debug(queue<T> st){while(!st.empty()){cout<<st.front()<<" ";st.pop();}cout<<endl;}
template<typename T>void debug(deque<T> st){while(!st.empty()){cout<<st.front()<<" ";st.pop_front();}cout<<endl;}
template<typename T>void debug(PQ<T> st){while(!st.empty()){cout<<st.top()<<" ";st.pop();}cout<<endl;}
template<typename T>void debug(QP<T> st){while(!st.empty()){cout<<st.top()<<" ";st.pop();}cout<<endl;}
template<typename T>void debug(const set<T>&v){for(auto z:v)cout<<z<<" ";cout<<endl;}
template<typename T>void debug(const multiset<T>&v){for(auto z:v)cout<<z<<" ";cout<<endl;}
template<typename T,size_t size>void debug(const array<T, size> &a){for(auto z:a)cout<<z<<" ";cout<<endl;}
template<typename T,typename V>void debug(const map<T,V>&v){for(auto z:v)cout<<"["<<z.first<<"]="<<z.second<<",";cout<<endl;}
template<typename T>vector<vector<T>>vec(ll x, ll y, T w){vector<vector<T>>v(x,vector<T>(y,w));return v;}
ll gcd(ll x,ll y){ll r;while(y!=0&&(r=x%y)!=0){x=y;y=r;}return y==0?x:y;}
vector<ll>dx={1,-1,0,0,1,1,-1,-1};vector<ll>dy={0,0,1,-1,1,-1,1,-1};
template<typename T>vector<T> make_v(size_t a,T b){return vector<T>(a,b);}
template<typename... Ts>auto make_v(size_t a,Ts... ts){return vector<decltype(make_v(ts...))>(a,make_v(ts...));}
template<typename T1, typename T2>ostream &operator<<(ostream &os, const pair<T1, T2>&p){return os << p.first << " " << p.second;}
template<typename T>ostream &operator<<(ostream &os, const vector<T> &v){for(auto &z:v)os << z << " ";cout<<"|"; return os;}
template<typename T>void rearrange(vector<int>&ord, vector<T>&v){
  auto tmp = v;
  for(int i=0;i<tmp.size();i++)v[i] = tmp[ord[i]];
}
template<typename Head, typename... Tail>void rearrange(vector<int>&ord,Head&& head, Tail&&... tail){
  rearrange(ord, head);
  rearrange(ord, tail...);
}
template<typename T> vector<int> ascend(const vector<T>&v){
  vector<int>ord(v.size());iota(ord.begin(),ord.end(),0);
  sort(ord.begin(),ord.end(),[&](int i,int j){return make_pair(v[i],i)<make_pair(v[j],j);});
  return ord;
}
template<typename T> vector<int> descend(const vector<T>&v){
  vector<int>ord(v.size());iota(ord.begin(),ord.end(),0);
  sort(ord.begin(),ord.end(),[&](int i,int j){return make_pair(v[i],-i)>make_pair(v[j],-j);});
  return ord;
}
template<typename T> vector<T> inv_perm(const vector<T>&ord){
  vector<T>inv(ord.size());
  for(int i=0;i<ord.size();i++)inv[ord[i]] = i;
  return inv;
}
ll FLOOR(ll n,ll div){assert(div>0);return n>=0?n/div:(n-div+1)/div;}
ll CEIL(ll n,ll div){assert(div>0);return n>=0?(n+div-1)/div:n/div;}
ll digitsum(ll n){ll ret=0;while(n){ret+=n%10;n/=10;}return ret;}
ll modulo(ll n,ll d){return (n%d+d)%d;};
template<typename T>T min(const vector<T>&v){return *min_element(v.begin(),v.end());}
template<typename T>T max(const vector<T>&v){return *max_element(v.begin(),v.end());}
template<typename T>T acc(const vector<T>&v){return accumulate(v.begin(),v.end(),T(0));};
template<typename T>T reverse(const T &v){return T(v.rbegin(),v.rend());};
//mt19937 mt(chrono::steady_clock::now().time_since_epoch().count());
int popcount(ll x){return __builtin_popcountll(x);};
int poplow(ll x){return __builtin_ctzll(x);};
int pophigh(ll x){return 63 - __builtin_clzll(x);};
template<typename T>T poll(queue<T> &q){auto ret=q.front();q.pop();return ret;};
template<typename T>T poll(priority_queue<T> &q){auto ret=q.top();q.pop();return ret;};
template<typename T>T poll(QP<T> &q){auto ret=q.top();q.pop();return ret;};
template<typename T>T poll(stack<T> &s){auto ret=s.top();s.pop();return ret;};
ll MULT(ll x,ll y){if(LLONG_MAX/x<=y)return LLONG_MAX;return x*y;}
ll POW2(ll x, ll k){ll ret=1,mul=x;while(k){if(mul==LLONG_MAX)return LLONG_MAX;if(k&1)ret=MULT(ret,mul);mul=MULT(mul,mul);k>>=1;}return ret;}
ll POW(ll x, ll k){ll ret=1;for(int i=0;i<k;i++){if(LLONG_MAX/x<=ret)return LLONG_MAX;ret*=x;}return ret;}
template< typename T = int >
struct edge {
  int to;
  T cost;
  int id;
  edge():id(-1){};
  edge(int to, T cost = 1, int id = -1):to(to), cost(cost), id(id){}
  operator int() const { return to; }
};

template<typename T>
using Graph = vector<vector<edge<T>>>;
template<typename T>
Graph<T>revgraph(const Graph<T> &g){
  Graph<T>ret(g.size());
  for(int i=0;i<g.size();i++){
    for(auto e:g[i]){
      int to = e.to;
      e.to = i;
      ret[to].push_back(e);
    }
  }
  return ret;
}
template<typename T>
Graph<T> readGraph(int n,int m,int indexed=1,bool directed=false,bool weighted=false){
  Graph<T> ret(n);
  for(int es = 0; es < m; es++){
    int u,v;
    T w=1;
    cin>>u>>v;u-=indexed,v-=indexed;
    if(weighted)cin>>w;
    ret[u].emplace_back(v,w,es);
    if(!directed)ret[v].emplace_back(u,w,es);
  }
  return ret;
}
template<typename T>
Graph<T> readParent(int n,int indexed=1,bool directed=true){
  Graph<T>ret(n);
  for(int i=1;i<n;i++){
    int p;cin>>p;
    p-=indexed;
    ret[p].emplace_back(i);
    if(!directed)ret[i].emplace_back(p);
  }
  return ret;
}

int main(){
  cin.tie(nullptr);
  ios_base::sync_with_stdio(false);
  ll res=0,buf=0;
  bool judge = true;
	ll h,w;cin>>h>>w;
	auto a=vec(h,w,0LL);
	rep(i,0,h)rep(j,0,w){
		cin>>a[i][j];
	}
	auto v=vec(h,w,-1LL);
	queue<P>que;
	rep(i,0,h){
		rep(j,0,w){
			v[i][j]=i*w+j;
			rep(o,0,4){
				ll ni=i+dx[o],nj=j+dy[o];
				if(ni>=0&&nj>=0&&ni<h&&nj<w&&a[i][j]>a[ni][nj])v[i][j]=-1;
			}
			if(v[i][j]!=-1){
				que.emplace(i,j);
			}
		}
	}
	//debug(v);
	while(!que.empty()){
		auto [x,y]=poll(que);
		rep(i,0,4){
			ll nx=x+dx[i],ny=y+dy[i];
			if(nx<0||ny<0||nx>=h||ny>=w||a[nx][ny]<a[x][y])continue;
			if(v[nx][ny]==-1){
				v[nx][ny]=v[x][y];
				que.emplace(nx,ny);
			}
			else if(v[nx][ny]!=INF&&v[nx][ny]!=v[x][y]){
				v[nx][ny]=INF;
				que.emplace(nx,ny);
			}
		}
	}
	//debug(v);
	rep(i,0,h)rep(j,0,w){
		if(v[i][j]==INF)res++;
	}
	cout<<res<<endl;
  return 0;
}
accuracy: 1
time_ms: 90
memory_kb: 19228
final_rank: 1

code_snippet: /* -*- coding: utf-8 -*-
 *
 * 0634.cc: 尾根 (Ridge)
 */

#include<cstdio>
#include<vector>
#include<queue>
#include<algorithm>
 
using namespace std;

/* constant */

const int MAX_H = 1000;
const int MAX_W = 1000;
const int MAX_N = MAX_H * MAX_W;

/* typedef */

typedef vector<int> vi;
typedef queue<int> qi;

/* global variables */

int ms[MAX_N], ds0[MAX_N], ds1[MAX_N], pns[MAX_N];
vi nbrs[MAX_N];
bool rs[MAX_N];

/* subroutines */

/* main */

int main() {
  int h, w;
  scanf("%d%d", &h, &w);
  int n = h * w;

  for (int i = 0; i < n; i++) scanf("%d", ms + i);

  for (int u = 0; u < n; u++) {
    int uy = u / w, ux = u % w;
    if (ux + 1 < w) {
      if (ms[u] < ms[u + 1])
	nbrs[u].push_back(u + 1), pns[u + 1]++;
      else
	nbrs[u + 1].push_back(u), pns[u]++;
    }
    if (uy + 1 < h) {
      if (ms[u] < ms[u + w])
	nbrs[u].push_back(u + w), pns[u + w]++;
      else
	nbrs[u + w].push_back(u), pns[u]++;
    }
  }
    
  fill(ds0, ds0 + n, -1);
  fill(ds1, ds1 + n, -1);
  qi q;
  for (int u = 0; u < n; u++)
    if (pns[u] == 0) ds0[u] = u, q.push(u);

  while (! q.empty()) {
    int u = q.front(); q.pop();
    for (auto v: nbrs[u]) {
      if (ds0[v] < 0)
	ds0[v] = ds0[u], ds1[v] = ds1[u];
      else if (ds1[v] < 0)
	ds1[v] = (ds0[v] != ds0[u]) ? ds0[u] : ds1[u];

      if (--pns[v] == 0) q.push(v);
    }
  }

  int cnt = 0;
  for (int i = 0; i < n; i++)
    if (ds1[i] >= 0) cnt++;

  printf("%d\n", cnt);
  return 0;
}
accuracy: 1
time_ms: 150
memory_kb: 73232
final_rank: 13

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__)))
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);
    vector2d(int,A,h,w);
    in(A);
    vector<int> dp(h*w,-1);
    function<int(int,int)> rec=[&](int y,int x){
        if(dp[y*w+x]!=-1)return dp[y*w+x];
        set<int> S;
        for(int i=0;i<4;i++){
            int dy=(i==0)-(i==1);
            int dx=(i==2)-(i==3);
            if(x+dx<0||y+dy<0||x+dx>=w||y+dy>=h)continue;
            if(A[y+dy][x+dx]<A[y][x])S.insert(rec(y+dy,x+dx));
        }
        if(S.size()==0)return dp[y*w+x]=y*w+x;
        return dp[y*w+x]=(S.size()>=2?-2:*S.begin());
    };
    int ans=0;
    rep(y,h){
        rep(x,w){
            ans+=(rec(y,x)==-2);
        }
    }
    out(ans);
}
accuracy: 1
time_ms: 110
memory_kb: 73120
final_rank: 12

code_snippet: // JOI2017年予選５　尾根
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0634
#include <bits/stdc++.h>
using namespace std;
int main(void) {
    int H,W;
    cin >> H >>W;
    int map[H+2][W+2];
    int onecheck[H+2][W+2];
    for(int i=0;i<H+2;i++){
        for(int j=0;j<W+2;j++){
            map[i][j]=H*W+1;
            onecheck[i][j]=0;
        }
    }
    for(int i=1;i<H+1;i++){
        for(int j=1;j<W+1;j++){
            cin >> map[i][j];
        }
    }
    // 水たまりを探す
    vector<pair<int,int> > mizutamari;
    for(int i=1;i<H+1;i++){
        for(int j=1;j<W+1;j++){
            if(map[i][j]<map[i+1][j] && map[i][j]<map[i-1][j] && map[i][j]<map[i][j+1] && map[i][j]<map[i][j-1])mizutamari.push_back(make_pair(i,j));
        }
    }
    
    for(int k=0;k<mizutamari.size();k++){
        queue<pair<int, int> >q;// キュー q を定義
        q.push(make_pair(mizutamari[k].first,mizutamari[k].second));//スタート地点をqにプッシュ
        int step[H+2][W+2];
        for(int i=0;i<H+2;i++){
            for(int j=0;j<W+2;j++){
                step[i][j]=0;
            }
        }
        while(q.empty()==false){// q が空になるまでループを回す
            pair<int, int> point=q.front();
            q.pop();
            int i=point.first;
            int j=point.second;
            if(map[i][j]<map[i+1][j] && step[i+1][j]==0 && onecheck[i+1][j]<2){step[i+1][j]=1;onecheck[i+1][j]++;q.push(make_pair(i+1,j));}
            if(map[i][j]<map[i-1][j] && step[i-1][j]==0 && onecheck[i-1][j]<2){step[i-1][j]=1;onecheck[i-1][j]++;q.push(make_pair(i-1,j));}
            if(map[i][j]<map[i][j+1] && step[i][j+1]==0 && onecheck[i][j+1]<2){step[i][j+1]=1;onecheck[i][j+1]++;q.push(make_pair(i,j+1));}
            if(map[i][j]<map[i][j-1] && step[i][j-1]==0 && onecheck[i][j-1]<2){step[i][j-1]=1;onecheck[i][j-1]++;q.push(make_pair(i,j-1));}
        }
    }
 
    int count=0;
    for(int i=1;i<H+1;i++){
        for(int j=1;j<W+1;j++){
            if(onecheck[i][j]>1)count++;
        }
    }
 
 
    cout << count << endl;
 
    return 0;
}
accuracy: 1
time_ms: 240
memory_kb: 14900
final_rank: 5

code_snippet: #define _USE_MATH_DEFINES
#include <bits/stdc++.h>
using namespace std;
#define FOR(i,m,n) for(int i=(m);i<(n);++i)
#define REP(i,n) FOR(i,0,n)
#define ALL(v) (v).begin(),(v).end()
using ll = long long;
constexpr int INF = 0x3f3f3f3f;
constexpr long long LINF = 0x3f3f3f3f3f3f3f3fLL;
constexpr double EPS = 1e-8;
constexpr int MOD = 1000000007;
// constexpr int MOD = 998244353;
constexpr int dy[] = {1, 0, -1, 0}, dx[] = {0, -1, 0, 1};
constexpr int dy8[] = {1, 1, 0, -1, -1, -1, 0, 1}, dx8[] = {0, -1, -1, -1, 0, 1, 1, 1};
template <typename T, typename U> inline bool chmax(T &a, U b) { return a < b ? (a = b, true) : false; }
template <typename T, typename U> inline bool chmin(T &a, U b) { return a > b ? (a = b, true) : false; }
struct IOSetup {
  IOSetup() {
    std::cin.tie(nullptr);
    std::ios_base::sync_with_stdio(false);
    std::cout << fixed << setprecision(20);
  }
} iosetup;

int main() {
  int h, w; cin >> h >> w;
  vector m(h, vector(w, 0)); REP(i, h) REP(j, w) cin >> m[i][j], --m[i][j];
  vector<pair<int, int>> ord(h * w);
  REP(i, h) REP(j, w) ord[m[i][j]] = {i, j};
  vector ans(h, vector(w, vector<int>{}));
  REP(i, h * w) {
    auto [y, x] = ord[i];
    bool is_low = true;
    REP(k, 4) {
      int ny = y + dy[k], nx = x + dx[k];
      if (0 <= ny && ny < h && 0 <= nx && nx < w) is_low &= m[ny][nx] > m[y][x];
    }
    if (is_low) {
      ans[y][x].emplace_back(m[y][x]);
    } else {
      REP(k, 4) {
        int ny = y + dy[k], nx = x + dx[k];
        if (0 <= ny && ny < h && 0 <= nx && nx < w && m[ny][nx] < m[y][x]) {
          copy(ALL(ans[ny][nx]), back_inserter(ans[y][x]));
        }
      }
      sort(ALL(ans[y][x]));
      ans[y][x].erase(unique(ALL(ans[y][x])), ans[y][x].end());
      if (ans[y][x].size() > 2) ans[y][x].resize(2);
    }
  }
  int ridge = 0;
  REP(i, h) REP(j, w) ridge += ans[i][j].size() == 2;
  cout << ridge << '\n';
  return 0;
}
accuracy: 1
time_ms: 300
memory_kb: 69520
final_rank: 14

code_snippet: #include<bits/stdc++.h>
#define rep(i,n) for(int i=0; i< (n); i++)
using namespace std;
typedef long long ll;
const int mod = 1000000007;
const int inf = (1<<30);
int h,w;
int tebl[1005][1005]={};
int memo[1005][1005]={};//チェックしていない0　複数ある -1 一つしかない その場所

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


bool check(int y,int x){
	return (x>=0 && y>=0 && x<w && y<h);
}




int dp(int y,int x){
	if(memo[y][x]!=0) return memo[y][x];
	int k=0;//何も入っていないかどうか
	for(int i=0; i<4; i++){
		if(check(y+dy[i],x+dx[i])){
			if(tebl[y][x]>tebl[y+dy[i]][x+dx[i]]){//そこに水が流れるか
				int l=dp(y+dy[i],x+dx[i]);
				if(l==-1) return memo[y][x]=-1;
				if(k==0){
					k=l;
				}else if( k!=l){
					return memo[y][x]=-1;
				}
			}
		}
	}
	if(k==0){
		return memo[y][x]=tebl[y][x];
	}else{
		return memo[y][x]=k;
	}
	return 0;
}





int main(){
	cin>>h>>w;
	rep(i,h){
		rep(j,w){
			cin>>tebl[i][j];
		}
	}
	int ans=0;
	rep(i,h){
		rep(j,w){
			if(dp(i,j)==-1){
				ans++;
			}
		}
	}
	cout<<ans<<endl;
}
accuracy: 1
time_ms: 240
memory_kb: 49856
final_rank: 11

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()
using ll = long long;
using ld = long double;
using namespace std;
const ll INF = 1000000000000000000;
const ll mod = 1000000007;
const ll MOD = 998244353;
const ld pi = 3.141592653589793238;

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

ll in[1015][1015];
signed main() {
	ios::sync_with_stdio(false);
	std::cin.tie(nullptr);
	typedef pair<ll, ll> P;

	ll n, m; cin >> n >> m;
	vector<P> v(n * m + 5);
	rep(i, 1005) {
		rep(j, 1005) {
			in[i][j] = INF;
		}
	}
	rep2(i, n) {
		rep2(j, m) {
			cin >> in[i][j];
			v[in[i][j]] = P(i, j);
		}
	}
	vector<vector<vector<ll>>> one(n + 5, vector<vector<ll>>(m + 5));
	//map<ll, map<ll, map<ll, ll>>> used;
	ll ans = 0;
	rep2(i, n * m) {
		ll nx = v[i].first, ny = v[i].second, cnt = 0;
		//cout << nx << ' ' << ny << endl;
		rep(j, 4) {
			if (in[nx + dx[j]][ny + dy[j]] < i) {
				//cout << ' ' << j << endl;
				rep(k, one[nx + dx[j]][ny + dy[j]].size()) {
					//重複していないか
					bool flag = true;
					rep(l, one[nx][ny].size()) {
						if (one[nx][ny][l] == one[nx + dx[j]][ny + dy[j]][k]) {
							flag = false; break;
						}
					}
					if (flag) {
						one[nx][ny].push_back(one[nx + dx[j]][ny + dy[j]][k]);
						cnt++;
					}
				}
			}
		}
		if (cnt >= 2) { ans++; }
		if (cnt == 0) { one[nx][ny].push_back(i); }
	}
	cout << ans << endl;
	return 0;
}
accuracy: 1
time_ms: 310
memory_kb: 119064
final_rank: 16

code_snippet: #include <vector>
#include <iostream>
using namespace std;
const vector<int> dx = { 0, 1, 0, -1 };
const vector<int> dy = { 1, 0, -1, 0 };
int main() {
	int H, W;
	cin >> H >> W;
	vector<int> A(H * W), IA(H * W);
	for (int i = 0; i < H * W; ++i) {
		cin >> A[i]; --A[i];
		IA[A[i]] = i;
	}
	vector<int> dp(H * W, -1);
	int ans = 0;
	for (int i = 0; i < H * W; ++i) {
		int sx = IA[i] / W, sy = IA[i] % W;
		int reach = -1;
		bool several = false;
		for (int j = 0; j < 4; ++j) {
			int tx = sx + dx[j], ty = sy + dy[j], g = tx * W + ty;
			if (0 <= tx && tx < H && 0 <= ty && ty < W && A[g] < i) {
				if (dp[g] == -1) several = true;
				else if (reach == -1) reach = dp[g];
				else if (reach != dp[g]) several = true;
			}
		}
		if (several) dp[IA[i]] = -1;
		else if (reach != -1) dp[IA[i]] = reach;
		else dp[IA[i]] = IA[i];
		if (dp[IA[i]] == -1) ++ans;
	}
	cout << ans << endl;
	return 0;
}
accuracy: 1
time_ms: 240
memory_kb: 14480
final_rank: 4

code_snippet: #include <stdio.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <queue>
#include <cstdio>
#include <ctime>
#include <assert.h>
#include <chrono>
#include <random>
#include <numeric>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
using namespace std;
typedef long long int ll;
typedef unsigned long long ull;

mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
ll myRand(ll B) {
    return (ull)rng() % B;
}

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

int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    int h,w; cin >> h >> w;
    vector<vector<int>> a(h,vector<int>(w,0));
    map<int,pair<int,int>> mp;
    for(int i=0;i<h;i++){
        for(int j=0;j<w;j++){
            cin >> a[i][j];
            mp[a[i][j]]=make_pair(i,j);
        }
    }
    vector<int> v(h*w,0);
    for(int i=1;i<=h*w;i++){
        if(!v[i])v[i]=i;
        int x=mp[i].first,y=mp[i].second;
        for(int j=0;j<4;j++){
            int nx=x+dx[j],ny=y+dy[j];
            if(0<=nx&&nx<h&&0<=ny&&ny<w){
                if(a[nx][ny]<i)continue;
                int t=a[nx][ny];
                if(!v[t])v[t]=v[i];
                else if(v[t]!=v[i])v[t]=-1;
            }
        }
    }
    int res=0;
    for(int i=1;i<=h*w;i++){
        if(v[i]<0)res++;
    }
    cout << res << endl;
}
accuracy: 1
time_ms: 860
memory_kb: 73240
final_rank: 17

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

// → ↑ ← ↓
const int dy[4] = {0, 1, 0, -1};
const int dx[4] = {1, 0, -1, 0};

int main() {
    int H, W;
    cin >> H >> W;
    vector<vector<int>> M(H, vector<int>(W));
    vector<vector<int>> T(H, vector<int>(W));
    map<int, Pair> mp;
    rep(i, H) rep(j, W) {
        cin >> M[i][j];
        mp[M[i][j]] = make_pair(i, j);
        T[i][j] = M[i][j];
    }
    rep(h, H * W) {
        int y = mp[h + 1].first;
        int x = mp[h + 1].second;
        set<int> st;
        rep(i, 4) {
            int ny = y + dy[i], nx = x + dx[i];
            if(ny < 0 || ny >= H || nx < 0 || nx >= W) continue;
            if(M[y][x] > M[ny][nx]) {
                st.insert(T[ny][nx]);
            }
        }
        if(st.size() == 1) T[y][x] = *st.begin();
        else if(st.size() > 1) T[y][x] = 0;
    }
    int ans = 0;
    rep(i, H) rep(j, W) {
        if(T[i][j] == 0) ans++;
    }
    cout << ans << '\n';
    return 0;
}
accuracy: 1
time_ms: 1160
memory_kb: 73196
final_rank: 19

code_snippet: #include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize("Ofast")
#pragma GCC target("avx")
#define all(x) (x).begin(),(x).end()
#define rep(i,n) for(int (i)=0;i<(n);i++)
#define rrep(i,n) for(int (i)=1;i<=(n);i++)
#define REP(i,m,n) for(int (i)=(m);(i)<(n);(i)++)
#define MOD 1000000007
#define INF 1e18
#define int long long
#define endl "\n"
#define yorn(f) puts((f)?"Yes":"No")
#define YORN(f) puts((f)?"YES":"NO")
typedef long long ll;
typedef pair<int, int> P;
int gcd(int a,int b){return b?gcd(b,a%b):a;};
int lcm(int a,int b){return a/gcd(a,b)*b;};
int mod(int a,int b){return (a+b-1)/b;};
template<typename A, size_t N, typename T>
void Fill(A(&array)[N],const T &val){std::fill((T*)array,(T*)(array+N),val);}
template<class T>inline bool chmax(T& a,T b){if(a<b){a=b;return true;}return false;};
template<class T>inline bool chmin(T& a,T b){if(a>b){a=b;return true;}return false;};

int h, w;
const int dx[4] = {-1, 0, 1, 0};
const int dy[4] = {0, -1, 0, 1};
int fld[1001][1001];
int cnt[1001][1001];

bool isOK(int x, int y) {
	if(0 <= x && x < w && 0 <= y && y < h) return 1;
	return 0;
}

bool isvalley(int x, int y) {
	rep(i, 4) {
		int nx = x + dx[i];
		int ny = y + dy[i];
		if(isOK(nx, ny)) {
			if(fld[ny][nx] < fld[y][x]) return 0;
		}
	}
	return 1;
}

void bfs(int sx, int sy) {
	if(!isvalley(sx, sy)) return ;
	cnt[sy][sx]++;

	queue<P> que;
	vector<vector<int>> came(h, vector<int>(w, 0));
	que.push(P(sx, sy));
	while(!que.empty()) {
		P p = que.front();
		que.pop();
		rep(i, 4) {
			int nx = p.first + dx[i];
			int ny = p.second + dy[i];
			if(!isOK(nx, ny)) continue;
			if(!came[ny][nx] && fld[p.second][p.first] < fld[ny][nx]) {
				came[ny][nx] = 1;
				que.push(P(nx, ny));
				cnt[ny][nx]++;
			}
		}
	}
}

signed main() {
	cin.tie(0);
	cout.tie(0);
	ios::sync_with_stdio(false);
	//cout << fixed << setprecision(15);
	
	cin >> h >> w;
	rep(i, h) rep(j, w) cin >> fld[i][j];

	rep(i, h) {
		rep(j, w) {
			bfs(j, i);
		}
	}
	// rep(i, h) {
	// 	rep(j, w) cout << cnt[i][j] << " ";
	// 	cout << endl;
	// }
	int ans = 0;
	rep(i, h) {
		rep(j, w) {
			if(cnt[i][j] != 1) ans++;
		}
	}
	cout << ans << endl;
	return 0;
}
accuracy: 1
time_ms: 360
memory_kb: 26200
final_rank: 10

code_snippet: #include <iostream>
#include <vector>
#include <set>
#include <tuple>

template <class T>
std::vector<T> vec(int len, T elem) { return std::vector<T>(len, elem); }

const std::vector<int>
    dx{-1, 0, 1, 0},
    dy{0, -1, 0, 1};

void solve() {
    int h, w;
    std::cin >> h >> w;

    auto xss = vec(h, vec(w, 0));
    std::vector<std::pair<int, int>> pos(h * w);
    for (int x = 0; x < h; ++x) {
        for (int y = 0; y < w; ++y) {
            auto& a = xss[x][y];
            std::cin >> a;
            pos[--a] = std::make_pair(x, y);
        }
    }

    auto to = vec(h, vec(w, 0));
    for (auto p : pos) {
        int x, y;
        std::tie(x, y) = p;

        std::set<int> tos;
        for (int i = 0; i < 4; ++i) {
            int nx = x + dx[i],
                ny = y + dy[i];
            if (nx < 0 || h <= nx || ny < 0 || w <= ny ||
                xss[nx][ny] > xss[x][y]) continue;

            if (to[nx][ny] < 0) to[x][y] = -1;
            tos.insert(to[nx][ny]);
        }

        if (to[x][y] < 0) continue;

        if (tos.empty()) tos.insert(xss[x][y]);
        if (tos.size() >= 2) tos.insert(-1);
        to[x][y] = *tos.begin();
    }

    int ans = 0;
    for (int x = 0; x < h; ++x) {
        for (int y = 0; y < w; ++y) {
            if (to[x][y] < 0) ++ans;
        }
    }

    std::cout << ans << std::endl;
}

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

    solve();

    return 0;
}
accuracy: 1
time_ms: 140
memory_kb: 18648
final_rank: 2

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

int h, w;
int m[1010][1010];
bool visited[1010][1010];
vector<int> dp[1010][1010];

void dfs(int y, int x) {
	if(visited[y][x]) return;
	// cerr << y << " " << x << '\n';
	visited[y][x] = true;
	const int dy[] = {0, 1, 0, -1};
	const int dx[] = {1, 0, -1, 0};
	for(int i = 0; i < 4; ++i) {
		int ny = y + dy[i];
		if(ny < 0 or h <= ny) continue;
		int nx = x + dx[i];
		if(nx < 0 or w <= nx) continue;
		if(m[y][x] > m[ny][nx]) {
			dfs(ny, nx);
			for(int d : dp[ny][nx]) {
				dp[y][x].push_back(d);
			}
		}
	}
	if(dp[y][x].size() == 0) dp[y][x].push_back(m[y][x]);
	sort(dp[y][x].begin(), dp[y][x].end());
	dp[y][x].erase(unique(dp[y][x].begin(), dp[y][x].end()), dp[y][x].end());
}

int main() {
	cin >> h >> w;
	for(int i = 0; i < h; ++i) {
		for(int j = 0; j < w; ++j) {
			cin >> m[i][j];
		}
	}
	int ans = 0;
	for(int i = 0; i < h; ++i) {
		for(int j = 0; j < w; ++j) {
			dfs(i, j);
			// cerr << i << " " << j << '\n';
			// for(int k : dp[i][j]) {
			// 	cerr << k << '\n';
			// }
			if(dp[i][j].size() > 1) {
				++ans;
			}
		}
	}
	cout << ans << '\n';
	return 0;
}
accuracy: 0.4
time_ms: 360
memory_kb: 101952
final_rank: 20

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

#define endl '\n'
#define ALL(a)  (a).begin(),(a).end()
#define ALLR(a)  (a).rbegin(),(a).rend()
#define spa << " " <<
#define test cout<<"test"<<endl;
#define fi first
#define se second
#define MP make_pair
#define PB push_back
#define EB emplace_back
#define rep(i,n,m) for(ll i = (n); i < (ll)(m); i++)
#define rrep(i,n,m) for(ll i = (m) - 1; i >= (ll)(n); i--)
using ll = long long;
using ld = long double;
const ll MOD = 1e9+7;
//const ll MOD = 998244353;
const ll INF = 1e18;
using P = pair<ll, ll>;
template<typename T>
void chmin(T &a,T b){if(a>b)a=b;}
template<typename T>
void chmax(T &a,T b){if(a<b)a=b;}
void pmod(ll &a,ll b){a=(a+b)%MOD;}
void pmod(ll &a,ll b,ll c){a=(b+c)%MOD;}
void qmod(ll &a,ll b){a=(a*b)%MOD;}
void qmod(ll &a,ll b,ll c){a=(b*c)%MOD;}
ll median(ll a,ll b, ll c){return a+b+c-max({a,b,c})-min({a,b,c});}
void ans1(bool x){if(x) cout<<"Yes"<<endl;else cout<<"No"<<endl;}
void ans2(bool x){if(x) cout<<"YES"<<endl;else cout<<"NO"<<endl;}
void ans3(bool x){if(x) cout<<"Yay!"<<endl;else cout<<":("<<endl;}
template<typename T1,typename T2>
void ans(bool x,T1 y,T2 z){if(x)cout<<y<<endl;else cout<<z<<endl;}  
template<typename T>
void debug(vector<vector<T>>&v,ll h,ll w){for(ll i=0;i<h;i++)
{cout<<v[i][0];for(ll j=1;j<w;j++)cout spa v[i][j];cout<<endl;}};
void debug(vector<string>&v,ll h,ll w){for(ll i=0;i<h;i++)
{for(ll j=0;j<w;j++)cout<<v[i][j];cout<<endl;}};
template<typename T>
void debug(vector<T>&v,ll n){if(n!=0)cout<<v[0];
for(ll i=1;i<n;i++)cout spa v[i];cout<<endl;};
template<typename T>
vector<vector<T>>vec(ll x, ll y, T w){
  vector<vector<T>>v(x,vector<T>(y,w));return v;}
ll gcd(ll x,ll y){ll r;while(y!=0&&(r=x%y)!=0){x=y;y=r;}return y==0?x:y;}
vector<ll>dx={1,0,-1,0,1,1,-1,-1};
vector<ll>dy={0,1,0,-1,1,-1,1,-1};
template<typename T>
vector<T> make_v(size_t a,T b){return vector<T>(a,b);}
template<typename... Ts>
auto make_v(size_t a,Ts... ts){
  return vector<decltype(make_v(ts...))>(a,make_v(ts...));
}
ostream &operator<<(ostream &os, pair<ll, ll>&p){
  return os << p.first << " " << p.second;
}  

int main(){
  cin.tie(nullptr);
  ios_base::sync_with_stdio(false);
  //cout<<fixed<<setprecision(10);
  ll res=0,buf=0;
  bool judge = true;
  ll h,w;cin>>h>>w;
  auto v=vec(h,w,0LL);
  rep(i,0,h)rep(j,0,w)cin>>v[i][j];
  vector<pair<ll,P>>idx;
  rep(i,0,h)rep(j,0,w){
    idx.EB(v[i][j],MP(i,j));
  }
  auto ret=vec(h,w,-1LL);
  auto t=vec(h,w,false);
  sort(ALL(idx));
  rep(i,0,h*w){
    set<ll>st;
    ll kx=idx[i].se.fi,ky=idx[i].se.se;
    rep(j,0,4){
      ll x=idx[i].se.fi+dx[j];
      ll y=idx[i].se.se+dy[j];
      if(x<0||y<0||x>=h||y>=w)continue;
      if(ret[x][y]>=0)st.insert(ret[x][y]);
      if(t[x][y])t[idx[i].se.fi][idx[i].se.se]=true;
    }
    if(st.size()>=2)t[idx[i].se.fi][idx[i].se.se]=true;
    if(st.size()==0)ret[kx][ky]=kx*h+ky;
    if(st.size()==1)ret[kx][ky]=*st.begin();
  }
  //debug(t,h,w);
  //debug(ret,h,w);
  rep(i,0,h)rep(j,0,w)if(t[i][j])res++;
  cout<<res<<endl;
  return 0;
}
accuracy: 1
time_ms: 220
memory_kb: 42228
final_rank: 9