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();

    }
}

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

dp[i] = max(dp[i-1] , dp[j-1] + i - j +1) j <= i && a[j] == a[i]

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

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

相关推荐
知识浅谈6 小时前
DeepSeek V4 和 GPT-5.5 在同一天发布了??我也很懵,但对比完我悟了
算法
DeepModel6 小时前
通俗易懂讲透 Q-Learning:从零学会强化学习核心算法
人工智能·学习·算法·机器学习
田梓燊6 小时前
力扣:19.删除链表的倒数第 N 个结点
算法·leetcode·链表
简简单单做算法8 小时前
基于GA遗传优化双BP神经网络的时间序列预测算法matlab仿真
神经网络·算法·matlab·时间序列预测·双bp神经网络
阿豪学编程8 小时前
面试题map/unordered相关
数据结构
guygg888 小时前
利用遗传算法解决列车优化运行问题的MATLAB实现
开发语言·算法·matlab
武藤一雄8 小时前
19个核心算法(C#版)
数据结构·windows·算法·c#·排序算法·.net·.netcore
sali-tec8 小时前
C# 基于OpenCv的视觉工作流-章52-交点查找
图像处理·人工智能·opencv·算法·计算机视觉
梦想的颜色9 小时前
mongoTemplate + Java 增删改查基础介绍
数据结构·数据库·mysql
yu85939589 小时前
MATLAB连续线性化模型预测控制(SL-MPC)
算法·机器学习·matlab