Magical Subsequence(线性dp)

Magical Subsequence

[Link](Problem - B - Codeforces)

题意

给你一个序列,让你选择一个子序列,使得子序列中任意奇数项和后一个偶数项的和都相同,问你子序列最长为多少。

题解

​ 对于前i个数来说它的选法是存在最优解的,因此考虑DP,设 f [ i , j ] : 从 前 i 个 数 里 选 且 两 两 相 加 和 为 j 的 最 长 子 序 列 的 长 度 f[i,j]:从前i个数里选且两两相加和为j的最长子序列的长度 f[i,j]:ij,考虑划分集合为第i个数选与不选,因此状态转移即 f [ i , j ] = m a x ( f [ i − 1 , j ] , f [ l a s t [ i , j − a [ i ] ] − 1 , j ] + 2 ) 当 l a s t [ i , j − a [ i ] ] 存 在 时 转 移 f[i,j]=max(f[i-1,j],f[last[i,j-a[i]]-1,j]+2){当last[i,j-a[i]]存在时转移} f[i,j]=max(f[i1,j],f[last[i,ja[i]]1,j]+2)last[i,ja[i]], l a s t [ i , j ] : 第 i 个 数 前 面 第 一 个 值 为 j 的 位 置 last[i,j]:第i个数前面第一个值为j的位置 last[i,j]:ij

Code

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <set>
#include <queue>
#include <vector>
#include <map>
#include <bitset>
#include <unordered_map>
#include <cmath> 
#include <stack>
#include <iomanip>
#include <deque> 
#include <sstream>
#define x first
#define y second
#define debug(x) cout<<#x<<":"<<x<<endl;
using namespace std;
typedef long double ld;
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<double, double> PDD;
typedef unsigned long long ULL;
const int N = 1e5 + 10, M = 2 * N, INF = 0x3f3f3f3f, mod = 1e9 + 7;
const double eps = 1e-8, pi = acos(-1), inf = 1e20;
#define tpyeinput int
inline char nc() {static char buf[1000000],*p1=buf,*p2=buf;return p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++;}
inline void read(tpyeinput &sum) {char ch=nc();sum=0;while(!(ch>='0'&&ch<='9')) ch=nc();while(ch>='0'&&ch<='9') sum=(sum<<3)+(sum<<1)+(ch-48),ch=nc();}
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
int h[N], e[M], ne[M], w[M], idx;
void add(int a, int b, int v = 0) {
    e[idx] = b, w[idx] = v, ne[idx] = h[a], h[a] = idx ++;
}
int n, m, k;
int f[N][201], last[N][201], a[N];
int main() {
    ios::sync_with_stdio(false), cin.tie(0);
    cin >> n;
    for (int i = 1; i <= n; i ++ ) {
        cin >> a[i];
        for (int j = 1; j <= 100; j ++ ) 
            if (j == a[i]) last[i + 1][j] = i;
            else last[i + 1][j] = last[i][j];
    }
    for (int i = 1; i <= n; i ++ ) 
        for (int j = 1; j <= 200; j ++ ) {
            f[i][j] = f[i - 1][j];
            if (j <= a[i]) continue ;
            if (last[i][j - a[i]]) f[i][j] = max(f[i][j], f[last[i][j - a[i]] - 1][j] + 2);
           }
    int res = 0;
    for (int i = 1; i <= 200; i ++ ) res = max(res, f[n][i]);
    cout << res << endl;
    return 0;
}
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值