CF384 div2 E. Vladik and cards
题意
给你一个1−8的排列,求一个满足条件的最长子序列
每种数字的差小于等于1,并且每种数字之内是连续的
解法
首先单纯认为用dp肯定不行的
所以应该考虑二分答案(所求长度具有二分性)
再用dp判断是否可行,这个dp很简单就是dp[N][1<<8]
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
using namespace std;
const int N = 1005;
const int INF = 0x3f3f3f3f;
int n;
vector<int> in[10];
int dp[N][300];
int a[N];
int cur[10];
void gmax(int &a, int b) {
if(a < b) a = b;
}
int ok(int len) {
for(int i = 0; i < 10; ++i) cur[i] = 0;
memset(dp,-1,sizeof(dp));
dp[0][0] = 0;
for(int i = 0; i < n; ++i) {
for(int j = 0; j < 256; ++j) {
if(dp[i][j] == -1) continue;
for(int k = 0; k < 8; ++k) {
if(j>>k&1) continue;
int tt = cur[k]+len-1;
if(tt < in[k].size()) gmax(dp[in[k][tt]+1][j | (1<<k)], dp[i][j]);
if(tt+1 < in[k].size()) gmax(dp[in[k][tt+1]+1][j | (1<<k)], dp[i][j]+1);
}
}
cur[a[i]-1] ++;
}
int ans = -1;
for(int i = 0; i <= n; ++i) gmax(ans, dp[i][255]);
if(ans == -1) return 0;
else return ans*(len+1) + (8-ans)*len;
}
int main(){
while(~scanf("%d",&n)) {
for(int i = 0; i < 10; ++i) in[i].clear();
for(int i = 0; i < n; ++i) {
scanf("%d",&a[i]);
in[a[i]-1].push_back(i);
}
int l = 1, r = n/8;
while(l <= r) {
int mid = (l+r)>>1;
if(ok(mid)) l = mid+1;
else r = mid-1;
}
int ans = max(ok(l), ok(r));
if(ans == 0) {
for(int i = 0; i < 8; ++i) {
if(!in[i].empty())
ans ++;
}
}
printf("%d\n",ans);
}
return 0;
}