Cod sursa(job #2078850)

Utilizator felixiPuscasu Felix felixi Data 30 noiembrie 2017 07:52:42
Problema A+B Scor 0
Compilator cpp Status done
Runda Lista lui wefgef Marime 2.49 kb
#include <bits/stdc++.h>

using namespace std;

#define pii pair<I64,I64>

ifstream in("input.txt");
ofstream out("output.txt");

typedef long long I64;

const I64 NMAX = 2000;

I64 v[NMAX+2][NMAX+2];
I64 N, M, d[NMAX+2][NMAX+2], walked = 0;
I64 dx[4] = {-1, 0, 1, 0};
I64 dy[4] = {0,1,0,-1};

void GO(I64 x, I64 y)
{
    if( d[x][y] ) {
        out << d[x][y] + walked - 1 << '\n';
        return ;
    }
    d[x][y] = ++walked;
    vector< pair<I64,pii> > pts;
    for( I64 i = 0;  i < 4;  ++i ) {
        I64 nx = x + dx[i];
        I64 ny = y + dy[i];
        if( nx < 1 || ny < 1 || nx> N || ny > M ) continue;
        if( d[nx][ny] + 1 == d[x][y] && d[nx][ny] > 0 ) continue;
        pts.push_back( make_pair( v[nx][ny], make_pair(nx,ny) ) );
    }
    sort( pts.begin(), pts.end() );
    I64 dist = (1 << 30), bx = 1, by = 1;
    for( auto pt : pts ) {
        if( abs(pt.first - v[x][y]) < dist ) {
            dist = abs(pt.first - v[x][y]);
            bx = pt.second.first;
            by = pt.second.second;
        }
    }
    GO(bx,by);
}

int main()
{
    cin.tie(0);
    cout.tie(0);
    ios_base::sync_with_stdio(0);
    in >> N >> M;
    for( I64 i = 1;  i <= N;  ++i ) {
        for( I64 j = 1;  j <= M;  ++j ) in>>v[i][j];
    }
    queue<pii> Q;
    Q.push(make_pair(1,1));
    while(!Q.empty())
    {
        pii nod = Q.front();
        Q.pop();
        I64 x = nod.first;
        I64 y = nod.second;
        if( d[x][y] ) {
            out << d[x][y] + walked - 1 << '\n';
            return 0;
        }
        d[x][y] = ++walked;
        vector< pair<I64,pii> > pts;
        for( I64 i = 0;  i < 4;  ++i ) {
            I64 nx = x + dx[i];
            I64 ny = y + dy[i];
            if( nx < 1 || ny < 1 || nx> N || ny > M ) continue;
            if( d[nx][ny] + 1 == d[x][y] && d[nx][ny] > 0 ) continue;
            pts.push_back( make_pair( v[nx][ny], make_pair(nx,ny) ) );
        }
        sort( pts.begin(), pts.end() );
        I64 dist = (1 << 30), bx = 1, by = 1;
        for( auto pt : pts ) {
            if( abs(pt.first - v[x][y]) < dist ) {
                dist = abs(pt.first - v[x][y]);
                bx = pt.second.first;
                by = pt.second.second;
            }
        }
        Q.push(make_pair(bx,by));
    }

    /*
    for( I64 i = 1;  i <= N;  ++i ) {
        for( I64 j = 1;  j <= M;  ++j ) {
            cout << d[i][j] << ' ';
        }
        cout << '\n';
    }*/
    return 0;
}