Bzoj1584 usaco 2009 Mar gold 2. Cleaning up

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.