codeforces 831D Two Melodies dp具有启发意义

来源:互联网 发布:caffe cn 编辑:程序博客网 时间:2024/06/01 14:48

D. Two Melodies
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Alice is a beginner composer and now she is ready to create another masterpiece. And not even the single one but two at the same time!

Alice has a sheet with n notes written on it. She wants to take two such non-empty non-intersecting subsequences that both of them form a melody and sum of their lengths is maximal.

Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.

Subsequence forms a melody when each two adjacent notes either differs by 1 or are congruent modulo 7.

You should write a program which will calculate maximum sum of lengths of such two non-empty non-intersecting subsequences that both of them form a melody.

Input

The first line contains one integer number n (2 ≤ n ≤ 5000).

The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — notes written on a sheet.

Output

Print maximum sum of lengths of such two non-empty non-intersecting subsequences that both of them form a melody.


题解:

这道题可以用费用流来做,详情见我的上一篇博文。

这里采用新的方法dp。

如果用dp[i][j]表示一条序列以ai结尾,一条序列以aj结尾的最值,那么很显然的dp[i][j]=dp[j][i]

我们采用的递推方程就是dp[i][j] = max(dp[i][t]+1)其中a[t]与a[j]之间有边相连,并且t<j

但这里出现了一个问题,就是递推方向的问题,试设想枚举i遍历j进行更新,j是从1开始的话,那就难免有j<i 的情况发生,这样的话,我们无法保证a[j]的值没被以ai结尾的序列用过(从而与题意不符)

所以我们在遍历j的时候,只能从i+1开始。这样就不用担心a[j]被前一个序列用过了。

现在又出现了一个问题,那就是dp[i][j](j<i)的值似乎没求出来啊,实际上dp[i][j] = dp[j][i],而j<i,dp[j][i]我们在前面已经求出来了,所以直接用就好啦。

代码:

#include <bits/stdc++.h>using namespace std;int n,ans;const int maxn = 5005;int a[maxn];int dp[maxn][maxn];int mx0[100007],mx1[10];int main(){cin>>n;for(int i = 1;i <= n;++i) scanf("%d",&a[i]);for(int i = 0;i <= n;++i){memset(mx0,0,sizeof(mx0));memset(mx1,0,sizeof(mx1));for(int j = 1;j < i;++j){mx0[a[j]] = max(mx0[a[j]],dp[i][j]);mx1[a[j]%7] = max(mx1[a[j]%7],dp[i][j]);}for(int j = i+1;j <= n;++j){dp[i][j] = dp[i][0]+1;int tmp = max(mx0[a[j]-1],mx0[a[j]+1])+1;dp[i][j] = max(dp[i][j],tmp);dp[i][j] = max(dp[i][j],mx1[a[j]%7]+1);mx0[a[j]] = max(mx0[a[j]],dp[i][j]);mx1[a[j]%7] = max(mx1[a[j]%7],dp[i][j]);ans = max(ans,dp[i][j]);dp[j][i] = dp[i][j];}}cout<<ans;return 0;}



原创粉丝点击