【POJ 3670】Eating Together

Eating Together
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 5617   Accepted: 2739

Description

The cows are so very silly about their dinner partners. They have organized themselves into three groups (conveniently numbered 1, 2, and 3) that insist upon dining together. The trouble starts when they line up at the barn to enter the feeding area.

Each cow i carries with her a small card upon which is engraved Di (1 ≤ Di ≤ 3) indicating her dining group membership. The entire set of N (1 ≤ N ≤ 30,000) cows has lined up for dinner but it's easy for anyone to see that they are not grouped by their dinner-partner cards.

FJ's job is not so difficult. He just walks down the line of cows changing their dinner partner assignment by marking out the old number and writing in a new one. By doing so, he creates groups of cows like 111222333 or 333222111 where the cows' dining groups are sorted in either ascending or descending order by their dinner cards.

FJ is just as lazy as the next fellow. He's curious: what is the absolute mminimum number of cards he must change to create a proper grouping of dining partners? He must only change card numbers and must not rearrange the cows standing in line.

Input

* Line 1: A single integer: N
* Lines 2..N+1: Line i describes the i-th cow's current dining group with a single integer: Di

Output

* Line 1: A single integer representing the minimum number of changes that must be made so that the final sequence of cows is sorted in either ascending or descending order

Sample Input

5
1
3
2
1
1

Sample Output

1

Source

 
有点水啊。
看到题目很容易想到是最长不下降/不上升序列。
没错,就是比较哪个最长。
然而用普通的算法很难在规定的时间内出答案。然后呢?我们要用线段树????
不!
不用那么复杂,仔细看题,卡片的编号只是在1~3之间。
然而我看见有人连3都要优化成log23。。。我无语了。
好吧,讲讲怎么优化。
开个数组记录以这个编号结尾的最长序列的长度。
然而之后的每一次枚举你都只是从比当前编号小于等于/大于等于的编号结尾的序列连接过来。
那么忽略常数3,时间就是O(N)
#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;

const int MAXN = 30005;

int record[2][3];
int f[2][MAXN];
int n;
int id;

int main()
{
    memset(record, 0, sizeof(record));
    scanf("%d", &n);
    f[0][0] = f[1][0] = 1;
    scanf("%d", &id);
    record[0][id - 1] = record[1][id - 1] = 1;
    for (int i = 1; i < n; ++i)
    {
        scanf("%d", &id);
        f[0][i] = f[1][i] = 1;
        for (int j = 0; j < id; ++j) f[0][i] = max(f[0][i], record[0][j] + 1);
        for (int j = id - 1; j < 3; ++j) f[1][i] = max(f[1][i], record[1][j] + 1);
        record[0][id - 1] = max(record[0][id - 1], f[0][i]);
        record[1][id - 1] = max(record[1][id - 1], f[1][i]);
    }
    int maxt1 = 0;
    int maxt2 = 0;
    for (int i = 0; i < n; ++i)
    {
        maxt1 = max(maxt1, f[0][i]);
        maxt2 = max(maxt2, f[1][i]);
    }
    printf("%d
", n - max(maxt1, maxt2));
    return 0;
}
原文地址:https://www.cnblogs.com/albert7xie/p/4757060.html