HDU - 5009 Paint Pearls(dp+思维优化)

Lee has a string of n pearls. In the beginning, all the pearls have no color. He plans to color the pearls to make it more fascinating. He drew his ideal pattern of the string on a paper and asks for your help. 

In each operation, he selects some continuous pearls and all these pearls will be painted to their target colors. When he paints a string which has k different target colors, Lee will cost k 2 points. 

Now, Lee wants to cost as few as possible to get his ideal string. You should tell him the minimal cost.

Input

There are multiple test cases. Please process till EOF. 

For each test case, the first line contains an integer n(1 ≤ n ≤ 5×10 4), indicating the number of pearls. The second line contains a 1,a 2,...,a n (1 ≤ a i≤ 10 9) indicating the target color of each pearl.

Output

For each test case, output the minimal cost in a line.

Sample Input

3
1 3 3
10
3 4 2 4 4 2 4 3 2 2

Sample Output

2
7

       遍历一段区间的价值是区间内不同数的数量的平方,求遍历(1-n)区间最小消耗是多少。

       我们记录加上包括第i个数的情况下,最多有cnt种数的位置j,于此dp[i] = min(dp[j]+cnt*cnt);还有就是当cnt*cnt>i的时候我们不如直接每个点都单独遍历一次还只需要i呢,所以跳出即可。期望复杂度为(n*sqrt(n))。

#include
using namespace std;
#define ll long long
const int N = 50010;
int n, col[N]; ll dp[N];
int pre[N], la[N];
int main() {
	ios::sync_with_stdio(0);
	cin.tie(0); cout.tie(0);
	while (cin >> n && n) {
		for (int i = 1; i <= n; i++)
			cin >> col[i];
		for (int i = 1; i <= n; i++) {
			dp[i] = 0x3f3f3f3f3f3f3f3f;
			pre[i] = i - 1; la[i] = i + 1;
		}
		pre[0] = -1; la[n] = -1;
		dp[0] = 0;
		mapid;
		for (int i = 1; i <= n; i++) {
			if (!id.count(col[i])) {
				id[col[i]] = i;
			}
			else {
				int idx = id[col[i]];
				pre[la[idx]] = pre[idx];
				la[pre[idx]] = la[idx];
				id[col[idx]] = i;
			}
			for (int k = pre[i], cnt = 1; k != -1; k = pre[k], cnt++) {
				dp[i] = min(dp[i], dp[k] + cnt * cnt);
				if (cnt*cnt > i) break;
			}
		}
		cout << dp[n] << "\n";
	}
	
	return 0;
}
/*
*/

 

你可能感兴趣的:(dp)