导弹防御系统
本题就是拦截导弹的dfs
版
- 能覆盖整个序列的最少的不上升子序列的个数等价于该序列的最长上升子序列长度
- 能覆盖整个序列的最少的不下降子序列的个数等价于该序列的最长下降子序列长度
#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0);
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define ull unsigned long long
#define pb push_back
#define PII pair<int, int>
#define VIT vector<int>
#define x first
#define y second
#define inf 0x3f3f3f3f
const int N = 55;
int down[N], up[N];
int ans;
int a[N];
int n;
void dfs(int u, int n1, int n2) {
if (n1 + n2 >= ans) return;
if (u == n + 1) {
ans = min(ans, n1 + n2);
return;
}
int k = 0;
while (k < n1 && a[down[k]] > a[u]) ++k;
if (k >= n1) {
down[k] = u;
dfs(u + 1, n1 + 1, n2);
} else {
int t = down[k];
down[k] = u;
dfs(u + 1, n1, n2);
down[k] = t;
}
k = 0;
while (k < n2 && a[up[k]] < a[u]) ++k;
if (k >= n2) {
up[k] = u;
dfs(u + 1, n1, n2 + 1);
} else {
int t = up[k];
up[k] = u;
dfs(u + 1, n1, n2);
up[k] = t;
}
}
int main() {
//freopen("in.txt", "r", stdin);
IO;
while (cin >> n) {
if (!n) break;
ans = inf;
for (int i = 1; i <= n; ++i) cin >> a[i];
dfs(1, 0, 0);
cout << ans << '\n';
}
return 0;
}