警示后人

· · 个人记录

合唱队形

其实这道题的判断条件 T_1 < T_2 < ⋯ < T_i > T_{i + 1} > ⋯ > T_K 表示为在一个队形里面的身高是先递增后递减的。但是根据样例发现刚好最大的高度在正中间,如果你用二分的方式思考,处理最高值的左右两边,分别求出最长上升子序列和最长下降子序列,最终就只过了样例,喜提5分。QWQ

主要是因为T_i不可能一直都是中点,思想没错,代码不能就这么写。

样例输入:

8

186 186 150 200 160 130 197 220

错误代码

#include <bits/stdc++.h>
using namespace std;
const int maxn = 5e4 + 5;
int n;
int a[maxn];
void Read(){
    scanf("%d", &n);
    for(int i = 1; i <= n; ++i){
        scanf("%d", &a[i]);
    }
}

bool cmp(const int x, const int y){
    return x > y;
}

int max1 = 0;
int lis1[maxn];
int cnt = 0;
void LDS(){
    for(int i = 1; i <= n / 2; ++i){
        cnt++;
        if(max1 == 0){
            lis1[1] = a[1];
            max1 = 1;
        }else{
            int len = lower_bound(lis1 + 1, lis1 + max1 + 1, a[i], cmp) - lis1;
            lis1[len] = a[i];
            max1 = max(max1, len);
        }
    }
}

int max2 = 0;
int lis2[maxn];
void LIS(){
    for(int i = 1; i <= n - cnt; ++i){
        if(max2 == 0){
            lis2[1] = a[cnt];
            max2 = 1;
        }else{
            int len = lower_bound(lis2 + 1, lis2 + max2 + 1, a[i]) - lis2;
            lis2[len] = a[i];
            max2 = max(max2, len);
        }
    }
}

int main(){
    Read();
    LDS();
    LIS();
    printf("%d", max1 + max2);
    return 0;
}

正确的做法在这里 ,时间复杂度是 O(n^2), 如果你比较强,可以试试O(nlogn)的做法。

然后维护最长上升子序列和最长下降子序列的时候,记得清空数组和用过的变量,但我始终没明白为什么不能正序维护最长下降子序列,输出的数据就只有第一位,逻辑应该没有问题才对,只有40分。有没有大佬帮我解释一下,谢谢!

#include <bits/stdc++.h>
using namespace std;
const int maxn = 5e4 + 5;
int n;
int a[maxn];
void Read(){
    scanf("%d", &n);
    for(int i = 1; i <= n; ++i){
        scanf("%d", &a[i]);
    }
}

bool cmp(const int x, const int y){
    return x > y;
}

int maxx = 0;
int lis[maxn];
int l[maxn], r[maxn];
void LIS_LDS(){
    for(int i = 1; i <= n; ++i){
        int len = lower_bound(lis + 1, lis + maxx + 1, a[i]) - lis;
        lis[len] = a[i];
        l[i] = len;
        maxx = max(maxx, len);
    }
    maxx = 1;
    memset(lis, 0, sizeof(lis));
    for(int i = 1; i <= n; ++i){
        int len = lower_bound(lis + 1, lis + maxx + 1, a[i], cmp) - lis;
        lis[len] = a[i];
        r[i] = len;
        maxx = max(maxx, len);
    }
}

int ans = 0;
int main(){
    Read();
    LIS_LDS();
    for(int i = 1; i <= n; ++i){
        ans = max(ans, l[i] + r[i] - 1);
    }
    printf("%d", n - ans);
    return 0;
}

最后推荐一篇题解 ,感谢您的观看!