CodeTON Round 5 c ( dp

cpp 复制代码
#include<bits/stdc++.h>
using namespace std ;
using ll = long long;
using PII = pair<int,int>;
//using = pair<int,int>;
using VI = vector<int>;
const int mod = 10007;
const int limit = 30000;
int n,m,s;
int x;

int count_1(ll x){
    int res=0;
    while(x){
        res += x&1;
        x = x>>1;
    }
    return res;
}


void solve(){
    cin>>n;
    VI a(n+2);
    VI l(n+2,-0x3f3f3f3f);
    VI dp(n+2,0);
    for(int i=1;i<=n;i++) cin>>a[i];

    for(int i=1;i<=n;i++){
        dp[i] = dp[i-1];
        dp[i] = max(dp[i],i + l[a[i]]);
        l[a[i]] = max(l[a[i]] , dp[i-1]-i+1);
    }
    cout<<dp[n]<<"\n";
}

int main(){
    int t;
    cin>>t;
    while(t--){
        solve();

    }
}

先考虑构建一个朴素的做法

dpi = max(dpi-1 , dpj-1 + i - j +1) j <= i && aj == ai

很明显这是一个二重循环,但对于在一次 j 的循环中,dpj-1 + i - j +1 其中i是不变的,

所以只需要记录下每个数字的最大的 dpj-1 - j + 1 就可以在O(1) 时间内实现转移

相关推荐
可靠的仙人掌13 小时前
SAC(Soft Actor-Critic)算法底座
开发语言·算法·php
海石14 小时前
单调栈复健,顺便,牺牲一下吧,空间复杂度!一切献给AC
算法·leetcode
海石14 小时前
JS击败94%,Hard题想不到动态规划,那就用数组和栈试试
算法·leetcode
码少女14 小时前
数据结构——希尔排序
数据结构·排序算法
星子yu15 小时前
【学习】怎么学好数据结构
数据结构·学习
alphaTao16 小时前
LeetCode 每日一题 2026/7/6-2026/7/12
算法·leetcode
想吃火锅100516 小时前
【leetcode】56.合并区间js
算法·leetcode·职场和发展
imuliuliang16 小时前
可合并堆在多任务调度中的优势与实现技巧7
算法
学究天人16 小时前
数学公理体系大全:Comprehensive Collection of Mathematical Axiom Systems(卷6)
网络·算法·数学建模·动态规划·几何学·图论·拓扑学
wabs66616 小时前
关于动态规划【力扣72.编辑距离的思考】
算法·leetcode·动态规划