1. 程式人生 > >Two Melodies CodeForces - 813D

Two Melodies CodeForces - 813D

https://codeforces.com/problemset/problem/813/D  

DP好難啊.......

 

dp[i][j] = 一條鏈以i結尾, 另一條鏈以j結尾的最大值

關鍵要保證轉移時兩條鏈不能相交

 

 

#include <iostream>
#define REP(i,a,n) for(int i=a;i<=n;++i)
using namespace std;
const int N = 5e3+10, M = 1e7+10;
int n;
int a[N], dp[N][N], x[M], y[M];

int main() { cin>>n; REP(i,1,n) cin>>a[i]; int ans = 0; REP(i,0,n) { REP(j,0,7) x[j]=0; REP(j,1,n) y[a[j]]=0; REP(j,1,i) { x[a[j]%7]=max(x[a[j]%7],dp[i][j]); y[a[j]]=max(y[a[j]],dp[i][j]); } REP(j,i+1,n) { dp[i][j]
=max(dp[i][0],max(y[a[j]+1],y[a[j]-1])); dp[i][j]=max(dp[i][j],x[a[j]%7]); dp[j][i]=++dp[i][j]; x[a[j]%7]=max(x[a[j]%7],dp[i][j]); y[a[j]]=max(y[a[j]],dp[i][j]); ans = max(ans, dp[i][j]); } } printf("%d\n", ans); }