E. Fixed Points
题目链接
看完题解挺简单的一道dp题目
题意:给你一个数组,每次可以删除一个数,让你求出删数的个数最少的次数,使得a[i]==i的个数大于等于k。
题解:设dp[i][j]为前i个数保留j个数,然后如果第i数保留的话那么就得a[i]==j才能使得dp[i][j]更新(dp[i][j]=max(dp[i-1][j-1]+1,dp[i][j]),如果第
i个数不保留的话,那么就是dp[i][j]=max(dp[i][j],max(dp[i-1][j-1],dp[i-1][j]),至于为什么有dp[i-1][j-1],那就得看最后一个样例了,仔细理解一下就知道了。
#include <algorithm>
#include <deque>
#include <iomanip>
#include <iostream>
#include <map>
#include <math.h>
#include <queue>
#include <set>
#include <stack>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <unordered_map>
#include <vector>
#define ll long long int
#define ms(a, b) memset(a, b, sizeof(a))
#define lowbit(x) x & -x
#define fi first
#define se second
#define ull unsigned long long
#define lson (rt << 1)
#define rson (rt << 1 | 1)
#define endl "\n"
#define bug cout << "----acac----" << endl;
#define IOS ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
using namespace std;
const int maxn = 1e6 + 10;
const int maxm = 2e3 + 50;
const double eps = 1e-8;
const ll inf = 0x3f3f3f3f;
const ll lnf = 0x3f3f3f3f3f3f3f3f;
const double pi = acos(-1);
const ll mod = 1e9 + 7;
int n, k;
int dp[maxm][maxm];
int a[maxm];
int main()
{
IOS;
int T;
cin >> T;
while (T--)
{
cin >> n >> k;
bool flage = true;
for (int i = 1; i <= n; i++)
{
cin >> a[i];
if(i!=a[i])
{
flage = false;
}
}
if(flage)
{
cout << "0" << endl;
continue;
}
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
dp[i][j] = 0;
}
}
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= i; j++)
{
dp[i][j] = max(dp[i][j], max(dp[i - 1][j],dp[i-1][j-1]));
if(a[i]==j)
{
dp[i][j] = max(dp[i - 1][j - 1] + 1, dp[i][j]);
}
}
}
int ans = inf;
for (int i = 1; i <= n;i++)
{
if(dp[n][i]>=k)
{
ans = min(ans, n - i);
}
}
if(ans==inf)
{
cout << "-1" << endl;
}
else
cout << ans << endl;
}
return 0;
}