POJ 3670 Eating Together(LIS+nlogn算法)

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

 【题解】 题意是给你一个序列,要你把这个序列变成一个单调非递减或者单调非递增序列,最少需要改变几个数的数值,(如1,3,2,1,1,要把它变成单调非递增序列,只要把第一个数变成>=3即可,此操作次数为1,而如果要变成单调非递减序列,则要把后三个数都变成>=3,操作次数为3,所以总的最小操作数就为1)。

 

 很明显要正向逆向分别求一遍最长非递减子序列,取最大值,最后结果就是总个数m减去最大值。

 因为数据量比较大,所以要用到nlongn算法,详见http://http://blog.csdn.net/qq_38538733/article/details/75258177

 

 【AC代码】

#include
#include
#include
#include
using namespace std;
const int N=3e4+5;
int dp[N];
int a[N];
int m,maxn;

int main()
{
    scanf("%d",&m);
    for(int i=1;i<=m;i++)
        scanf("%d",&a[i]);
    dp[0]=0;
    int pos;
    int cnt=0;
    for(int i=1;i<=m;i++)
    {
        if(a[i]>=dp[cnt]) dp[++cnt]=a[i];
        else
        {
            pos=upper_bound(dp,dp+cnt+1,a[i])-dp;//此函数返回的是下标,所以减去数组首元素下标,即为整型
            dp[pos]=a[i];
        }
    }
    maxn=cnt;
    dp[0]=0;
    cnt=0;
    for(int i=m;i>0;i--)
    {
        if(a[i]>=dp[cnt]) dp[++cnt]=a[i];
        else
        {
            pos=upper_bound(dp,dp+cnt+1,a[i])-dp;
            dp[pos]=a[i];
        }
    }
    maxn=maxn>cnt?maxn:cnt;
    printf("%d\n",m-maxn);
    return 0;
}



你可能感兴趣的:(ACM__区间DP,ACM__算法收藏)