#include <map>
#include <set>
#include <cmath>
#include <queue>
#include <cstdio>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define PB push_back
#define MP make_pair
typedef double DB;
typedef long long LL;
typedef pair<int, int> PI;
typedef pair<string, string> PS;
const DB eps = 1e-8;
const int N = 5e4 + 7;
const int INF = 1e9 + 7;
const int MOD = 1e9 + 7;
map <int, int> S;
int last[N], next[N], a[N], now[N], f[N];
int main(){
int n;
while (scanf("%d", &n) == 1){
S.clear();
for (int i = 1; i <= n; i++){
scanf("%d", &a[i]);
if (S[a[i]]) last[i] = S[a[i]]; else last[i] = 0;
S[a[i]] = i;
}
S.clear();
for (int i = n; i >= 1; i--){
if (S[a[i]]) next[i] = S[a[i]]; else next[i] = n + 1;
S[a[i]] = i;
}
f[0] = 0;
memset(now, 0, sizeof(now));
for (int i = 1; i <= n; i++){
f[i] = i;
for (int j = 1; j * j <= i; j++){
if (!now[j]){
S.clear();
int cnt = 0;
for (int k = i; k >= 1; k--){
if (!S[a[k]]) cnt++;
if (cnt > j){
now[j] = k + 1;
break;
}
S[a[k]]++;
}
if (!now[j]) now[j] = 1;
f[i] = min(f[i], f[now[j] - 1] + j * j);
continue;
}
if (last[i] < now[j]){
while (next[now[j]] < i) now[j]++;
now[j]++;
}
f[i] = min(f[i], f[now[j] - 1] + j * j);
}
}
printf("%d\n", f[n]);
}
}
HDU5009西安网赛2014
最新推荐文章于 2024-01-17 18:47:28 发布