이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
using namespace std;
const int NMAX = 5000;
const long long INF = 1e18;
priority_queue <pair<long long, pair<int, int>>> pq;
long long modul( long long x ) {return x < 0 ? -x : x;}
bool between( int a, int b, int c ) {return ( a <= b && b <= c ) || ( a >= b && b >= c );}
long long dist[NMAX + 1][NMAX + 1];
bool viz[NMAX + 1][NMAX + 1];
void update( int i, int j, long long d ) {
if ( d < dist[i][j] ) {
dist[i][j] = d;
pq.push( { -d, { i, j } } );
}
}
int main() {
int n;
cin >> n;
vector <int> v;
for ( int i = 1, x; i <= n; i ++ ) {
cin >> x;
v.push_back( x ) ;
while ( v.size() >= 3 && between( v[v.size() - 3], v[v.size() - 2], v[v.size() - 1] ) ) v.pop_back();
}
n = v.size();
for ( int i = 0; i < n; i ++ ) {
for ( int j = 0; j < n - 1; j ++ ) {
dist[i][j] = INF;
}
}
dist[0][n - 2] = 0;
pq.push( { 0, {0, n - 2} } );
while ( !pq.empty() ) {
auto p = pq.top();
pq.pop();
int i = p.second.first, j = p.second.second, d = dist[i][j];
if ( i == j || i == j + 1 ) {
cout << dist[i][j] << '\n';
return 0;
}
if ( viz[i][j] ) continue;
viz[i][j] = true;
if ( j > 0 && v[i] == v[j] ) update( i, j - 1, d );
if ( j < n - 1 && v[i] == v[j + 1] ) update( i, j + 1, d );
if ( i - 1 >= 0 && ( between( v[i], v[i - 1], v[j] ) || between( v[i], v[i - 1], v[j + 1] ) ) ) {
update( i - 1, j, d + modul( v[i] - v[i - 1] ) );
}
if ( i + 1 < n && ( ( between( v[i], v[i + 1], v[j] ) || between( v[i], v[i + 1], v[j + 1] ) ) ) ) {
update( i + 1, j, d + modul( v[i] - v[i + 1] ) );
}
if ( i + 1 < n && between( v[i], v[j], v[i + 1] ) ) {
update( j, i, d + modul( v[i] - v[j] ) );
}
if ( i - 1 >= 0 && between( v[i], v[j], v[i - 1] ) ) {
update( j, i - 1, d + modul( v[i] - v[j] ) );
}
if ( i + 1 < n && between( v[i], v[j + 1], v[i + 1] ) ) {
update( j + 1, i, d + modul( v[i] - v[j + 1] ) );
}
if ( i - 1 >= 0 && between( v[i], v[j + 1], v[i - 1] ) ) {
update( j + 1, i - 1, d + modul( v[i] - v[j + 1] ) );
}
}
cout << "NO\n";
return 0;
}
/**
I
/\ _ /\ _
/ \ / \/ \ / \
/ \/ \_/ \
/ \
**/
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |