POJ(3671):Dining Cows

ime Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 9184   Accepted: 3750

Description

The cows are so very silly about their dinner partners. They have organized themselves into two groups (conveniently numbered 1 and 2) that insist upon dining together in order, with group 1 at the beginning of the line and group 2 at the end. 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 ≤ 2) 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 112222 or 111122 where the cows' dining groups are sorted in ascending order by their dinner cards. Rarely he might change cards so that only one group of cows is left (e.g., 1111 or 222).

FJ is just as lazy as the next fellow. He's curious: what is the absolute minimum 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+1 describes cow i's dining preference with a single integer: Di

Output

* Line 1: A single integer that is the minimum number of cards Farmer John must change to assign the cows to eating groups as described.

Sample Input

7
2
1
1
1
2
2
1

Sample Output

2

Source

USACO 2008 February Bronze

题目要求:

给定一串由1,2组成的数,求出至少改动几次,可以把数列变成递增的。

改动次数 = n(序列长度) - 最长递增序列

用在线算法做(在输入每个数的同时,进行操作)——如果第i个数输入的是 1,那么就把由前n-1个数中以1结尾的数列长度加1。(表示把这个1放在那个序列后,组成新的序列,序列长度增加了1);如果输入的数是2,此时就有多种选择了,可以放在由1结尾的最长序列后,也可以放在由二结尾的。此时就比较哪个序列更长,与长的组成新序列。

#include<iostream>
#include<cstdio>
using namespace std;
const int maxn = 30000+10;
int cows[maxn];
int dp[maxn]; //dp[i]表示前i个数中最长序列
int main()
{
    int n;
    int c1,c2;
    cin>>n;
    c1 = 0;
    c2 = 0;
    for(int i = 1;i <= n;i++){
        cin>>cows[i];
        if(cows[i] == 1){
            dp[i] = dp[c1]+1; c1=i;//c1记录前i位中由1结尾的最长序列所在位置
        }
        else{
            dp[i] = max(dp[c1],dp[c2])+1; c2=i;
        }
    }
    printf("%d\n",n-max(dp[c1],dp[c2]));

}

猜你喜欢

转载自blog.csdn.net/qq_42018521/article/details/81806326