#include<bits/stdc++.h>
using namespace std;
const int MAXN = 8e3;
const int INF32 = 1e9;
///vector
#define SZ(x) (int)x.size()
///input
int N;
int P[MAXN+5];
namespace sub1 {
int Ans = INF32;
bool check(const vector<int>& P) {
for(int l = 0; l < N; l++)
{
for(int r = 0; r < N; r++)
{
bool cond1 = false, cond2 = false;
for(int i = l; i <= r; i++)
{
if(P[i] > P[l] && P[i] > P[r]) cond1 = true;
if(P[i] < P[l] && P[i] < P[r]) cond2 = true;
}
if(cond1 && cond2) return false;
}
}
return true;
}
void solution() {
vector<int> perm(N);
for(int i = 0; i < N; i++) {
perm[i] = i + 1;
}
do {
if(check(perm)) {
int cnt = 0;
for(int i = 1; i <= N; i++) {
if(P[i] != perm[i - 1]) cnt++;
}
Ans = min(Ans, cnt);
}
} while(next_permutation(perm.begin(), perm.end()));
cout << Ans;
}
bool check() {
return (N <= 7);
}
}
namespace sub2 {
int Ans = INF32;
int tmp[4];
void brute_force(int l, int r, int Min, int Max, int cnt) {
if(l > r) {
Ans = min(Ans, cnt);
return;
}
tmp[0] = cnt;
if(P[l] != Min) tmp[0]++;
brute_force(l + 1, r, Min + 1, Max, tmp[0]);
tmp[1] = cnt;
if(P[l] != Max) tmp[1]++;
brute_force(l + 1, r, Min, Max - 1, tmp[1]);
tmp[2] = cnt;
if(P[r] != Min) tmp[2]++;
brute_force(l, r - 1, Min + 1, Max, tmp[2]);
tmp[3] = cnt;
if(P[r] != Max) tmp[3]++;
brute_force(l, r - 1, Min, Max - 1, tmp[3]);
}
void solution() {
brute_force(1, N, 1, N, 0);
cout << Ans;
}
bool check() {
return (N <= 13);
}
}
void solution() {
cin >> N;
for(int i = 1; i <= N; i++) {
cin >> P[i];
}
if(sub1::check()) return sub1::solution();
if(sub2::check()) return sub2::solution();
}
#define FILE "task"
main() {
if(fopen(FILE".in","r")) {
freopen(FILE".in","r",stdin);
freopen(FILE".ans","w",stdout);
}
cin.tie(nullptr)->ios_base::sync_with_stdio(false);
solution();
cerr << "\n" << clock() << " ms";
return 0;
}
Compilation message (stderr)
giraffes.cpp:102:1: warning: ISO C++ forbids declaration of 'main' with no type [-Wreturn-type]
102 | main() {
| ^~~~
giraffes.cpp: In function 'int main()':
giraffes.cpp:104:16: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
104 | freopen(FILE".in","r",stdin);
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~
giraffes.cpp:105:16: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
105 | freopen(FILE".ans","w",stdout);
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |