1. 程式人生 > >poj 3670Eating Together(最長不上升最長不下降子序列)

poj 3670Eating Together(最長不上升最長不下降子序列)

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

先求一遍最長不下降子序列,再求一遍最長不上升子序列,分別用n減去這兩個長度,求最小值即為結果,求不上升子序列時採用二分方法提高效率

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

int a[30005];
int d[30005];
int n,len,ans,l,r,k;
int main()
{scanf("%d",&n);
memset(d,0,sizeof(d));
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
 len=1;
d[1]=a[1];
for(int i=2;i<=n;i++)
{
    if(a[i]>=d[len])
    d[++len]=a[i];
    else
    {
       l=1;
       r=len;
       while(l<r)
       {
           k=(l+r)/2;
           if(d[k]>a[i])
           {
               r=k;
           }
           else
           {
               l=k+1;
           }
       }
    d[l]=a[i];
    }
}
   ans=len;
   len=0;
  memset(d,0,sizeof(0));
  d[1]=a[1];
  len=1;
k=0;
  for(int i=2;i<=n;i++)
  {
      if(a[i]<=d[len])
      d[++len]=a[i];
    else
    {

    l=1;
    r=len;
    while(l<r)
    {
        k=(l+r)/2;
        if(d[k]<a[i])
        {
            r=k;

        }
        else
        {
            l=k+1;
        }
    }
    d[l]=a[i];
  }
  }
  printf("%d\n",min(n-ans,n-len));
  return 0;
}