CF1699D. Almost Triple Deletions (DP)
作者:互联网
https://codeforces.com/contest/1699/problem/D
题意: 每次操作删除相邻且不同的两个数,问最后留下的最长等元素数组的长度。数组长度 1 <= n <= 1000.
思路:
- 假设最终数组留下的数字是x, 那么所有x的位置pos之间和pos的到边界的数都应该删完。
- 一段区间[l, r]的数要删完,区间中出现最多的数字的出现次数mx * 2 <= 区间长度len, 并且len必须是偶数
- 枚举最后的数字x,看x之间的数能否删完。这样想比较麻烦,思考可以发现这个问题有阶段性,不妨借助dp方程转移
- dp[i]表示以第i个位置上的数做最终序列的结尾的最长长度
#include<bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(false) ,cin.tie(0), cout.tie(0);
//#pragma GCC optimize(3,"Ofast","inline")
#define ll long long
#define PII pair<int, char>
//#define int long long
const int N = 5e3 + 5;
const int M = 1e5 + 5;
const int INF = 0x3f3f3f3f;
const ll LNF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1e9 + 7;
const double PI = acos(-1.0);
int f[N][N], a[N], dp[N];
bool check( int l, int r ) {
if( r - l < 0 ) return true;
if( f[l][r] <= (r - l + 1) / 2 && (r - l + 1) % 2 == 0 ) return true;
return false;
}
void solve() {
int n; cin >> n;
for ( int i = 1; i <= n; ++ i ) cin >> a[i];
for ( int i = 1; i <= n; ++ i ) {
vector<int> c(n + 1, 0);
for ( int j = i; j <= n; ++ j ) {
f[i][j] = max( f[i][j - 1], ++ c[a[j]]);
}
}
for ( int i = 1; i <= n; ++ i ) {
if( check( 1, i - 1 ) ) {
dp[i] = 1;
}
}
for ( int i = 1; i <= n; ++ i) {
for ( int j = 1; j <= i - 1; ++ j ) {
if( a[i] == a[j] && check( j + 1, i - 1) ) dp[i] = max(dp[i], dp[j] + 1);
}
}
int ans = 0;
for ( int i = 1; i <= n; ++ i) {
if( check( i + 1, n) ) ans = max( ans , dp[i]);
}
cout << ans << '\n';
for ( int i = 1; i <= n; ++ i ) {
dp[i] = -0x3f3f3f3f;
for ( int j = i; j <= n; ++ j ) {
f[i][j] = 0;
}
}
}
int main () {
memset(dp, -0x3f, sizeof dp);
int t; cin >> t;
while ( t -- ) solve();
return 0;
}
标签:Deletions,const,Almost,long,int,dp,数组,DP,define 来源: https://www.cnblogs.com/muscletear/p/16445633.html