There is a color segment with a length of n. There are m colors in total. You need to divide it into several segments, and the cost of each segment is the square of the number of different colors in this segment. Calculate the minimum total cost.
SOL:
First, we noticed that the answer should not exceed n, because we can clearly divide each one into a segment and the answer is N.
Therefore, the total color of each segment cannot exceed SQRT (n ).
Therefore, we maintain the final position of the last appearance of SQRT (n) colors for transfer.
The total time complexity is O (n * SQRT (n )).
Code:
#include <cmath>#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>using namespace std; #define N 40010#define M 40010int col[N], dp[N], seq[210], now[210]; #define sqr(x) ((x)*(x)) int main() { int n, m; scanf("%d%d", &n, &m); register int i, j; for(i = 1; i <= n; ++i) scanf("%d", &col[i]); int lim = (int)sqrt(n); int nowlen = 0; int ins; for(i = 1; i <= n; ++i) { dp[i] = i; ins = 0; for(j = 1; j <= nowlen; ++j) if (seq[j] == col[i]) { ins = j; break; } if (!ins) { if (nowlen != lim) { seq[++nowlen] = col[i]; now[nowlen] = i; } else { for(j = 1; j < nowlen; ++j) seq[j] = seq[j + 1], now[j] = now[j + 1]; seq[nowlen] = col[i], now[nowlen] = i; } } else { for(j = ins; j < nowlen; ++j) seq[j] = seq[j + 1], now[j] = now[j + 1]; seq[nowlen] = col[i], now[nowlen] = i; } for(j = nowlen; j >= 2; --j) dp[i] = min(dp[i], dp[now[j - 1]] + sqr(nowlen + 1 - j)); } printf("%d", dp[n]); return 0;}
Bzoj1584 usaco 2009 Mar gold 2. Cleaning up