array array array HDU - 6197 (最长上升子序列)

本文介绍了一个有趣的问题:如何判断一个数组是否可以通过删除指定数量的元素变为非递增或非递减序列。通过求解最长上升子序列和最长下降子序列,文章提供了一种高效的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

array array array HDU - 6197

One day, Kaitou Kiddo had stolen a priceless diamond ring. But detective Conan blocked Kiddo’s path to escape from the museum. But Kiddo didn’t want to give it back. So, Kiddo asked Conan a question. If Conan could give a right answer, Kiddo would return the ring to the museum.
Kiddo: “I have an array A and a number k, if you can choose exactly k elements from A and erase them, then the remaining array is in non-increasing order or non-decreasing order, we say A is a magic array. Now I want you to tell me whether A
is a magic array. ” Conan: “emmmmm…” Now, Conan seems to be in trouble, can you help him?
Input
The first line contains an integer T indicating the total number of test cases. Each test case starts with two integers n and k in one line, then one line with n integers: A1,A2…An.
1≤T≤20
1≤n≤105
0≤k≤n
1≤Ai≤105

Output
For each test case, please output “A is a magic array.” if it is a magic array. Otherwise, output “A is not a magic array.” (without quotes).
Sample Input

3
4 1
1 4 3 7
5 2
4 1 3 1 2
6 1
1 4 3 5 4 6

Sample Output

A is a magic array.
A is a magic array.
A is not a magic array.
题意:

给你一个长度为n的序列,问能否删除k个元素使得剩下的元素是非递增序列或者非递减序列

分析:

可以分别求一下最长上升子序列和最长下降子序列

为什么要求这两个东西呢

以最长上升子序列为例,加入我们求出了这个序列的最长上升子序列了,那么原来序列长度减去最长上升子序列长度剩下的个数就是我们必须要删去的元素,我们拿这个数和k比较,如果必须要删去的元素个数大于k,那么我们一定不能得到要求的非递减(或非递增)序列,而如果k大于等于要删去的元素,这样我们一定可以得到,因为如果k恰好等于那一定可以,如果大于我们删去几个非递减序列中的数这个序列一定还是非递减的不会影响其性质。

所以对于求最长上升子序列套用nlogn的模板直接求就可以,那么最长下降子序列怎么求呢,可以把数组倒着存一遍,继续求最长上升子序列,得到的长度就是原的序列的最长下降子序列了

code:

#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = 1e5+10;
int dp1[maxn],dp2[maxn];
int a[maxn],b[maxn];
int n,k;
int main(){
    int T;
    scanf("%d",&T);
    while(T--){
        scanf("%d%d",&n,&k);
        for(int i = 0; i < n; i++){
            scanf("%d",&a[i]);
        }
        int l = 0;
        for(int i = n-1; i >= 0; i--){
            b[l++] = a[i];//倒着存一遍求最长上升子序列即最长递减子序列
        }
        memset(dp1,INF,sizeof(dp1));
        for(int i = 0; i < n; i++){
            *lower_bound(dp1,dp1 + n,a[i]) = a[i];
        }
        int max1 = lower_bound(dp1,dp1 + n,INF) - dp1;
        memset(dp2,INF,sizeof(dp2));
        for(int i = 0; i < n; i++){
            *lower_bound(dp2,dp2 + n,b[i]) = b[i];
        }
        int max2 = lower_bound(dp2,dp2 + n,INF) - dp2;
        if(n - max1 <= k || n - max2 <= k)
            printf("A is a magic array.\n");
        else
            printf("A is not a magic array.\n");
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值