dp(第一次尝试)

本文介绍了一种求解最长不下降子序列问题的高效算法,并通过代码详细展示了如何使用二分查找法优化动态规划过程,同时解释了upper_bound函数的作用。

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

题目:点击打开链接

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include <cmath>
#include<stack>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<algorithm>
using namespace std;

typedef long long LL;
const int INF = (1<<30)-1;
const int mod=1000000007;
const int maxn=1000005;

int a[maxn],f[maxn];
int main()
{
    int T;
    scanf("%d",&T);
    int kase=0;
    while(T--)
    {
        int n;
        scanf("%d",&n);
        for(int i=1; i<=n; i++)
        {
            scanf("%d",&a[i]);
            a[i]=a[i]-i;
        }

        int len=1;
        f[1]=a[1];
        for(int i=2; i<=n; i++)
        {
            if(a[i]>=f[len]) f[++len]=a[i];//这里也和求最长上升子序列不同,是大于等于
            else
            {
                int pos=upper_bound(f+1,f+len+1,a[i])-f;//upper_bound返回的是序列中严格大于key值的第一个数
                f[pos]=a[i];
            }
        }
        printf("Case #%d:\n",++kase);
        printf("%d\n",n-len);
    }
    return 0;
}
其实这个dp我并不是特别擅长,但是这个代码我看的有点懂,但不是特别的懂,只是能够推出来这是对的,反正就是感觉比较厉害,这里面还有一个函数,就是lower_bound返回的是第一个大于等于该值的位置,而upper_bound是返回第一个大于该值的

的值的位置,其实也不是 特别懂,反正是看了别人的代码,总体上思路也不是特别的明确。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值