栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

Magical Subsequence(线性dp)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Magical Subsequence(线性dp)

Magical Subsequence

[link](Problem - B - Codeforces)

题意

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

题解

​ 对于前i个数来说它的选法是存在最优解的,因此考虑DP,设 f [ i , j ] : 从 前 i 个 数 里 选 且 两 两 相 加 和 为 j 的 最 长 子 序 列 的 长 度 f[i,j]:从前i个数里选且两两相加和为j的最长子序列的长度 f[i,j]:从前i个数里选且两两相加和为j的最长子序列的长度,考虑划分集合为第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[i−1,j],f[last[i,j−a[i]]−1,j]+2)当last[i,j−a[i]]存在时转移, l a s t [ i , j ] : 第 i 个 数 前 面 第 一 个 值 为 j 的 位 置 last[i,j]:第i个数前面第一个值为j的位置 last[i,j]:第i个数前面第一个值为j的位置。

Code
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include  
#include 
#include 
#include  
#include 
#define x first
#define y second
#define debug(x) cout<<#x<<":"< PII;
typedef pair 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;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/676709.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号