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.
* 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
* 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
5 1 3 2 1 1
1
题解:
理解了题意就很水的一题,从前往后一次dp求最长不下降子序列,从后往前再来一次,然后总数减去最长的那个就是答案
代码:
#include<iostream>
#include<stdio.h>
#include<map>
#include<algorithm>
#include<math.h>
#include<queue>
#include<stack>
#include<string>
#include<cstring>
using namespace std;
int a[30005];
int d1[5];//记录结尾是i的长度最长的子序列长度
int d2[5];
int main()
{
int i,j,k,n,m;
scanf("%d",&n);
memset(d1,0,sizeof(d1));
memset(d2,0,sizeof(d2));
int maxx=0;
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
int t=1;
for(j=a[i];j>=1;j--)//从前往后求一次
{
if(d1[j]>d1[t])
t=j;
}
d1[a[i]]=d1[t]+1;
maxx=max(maxx,d1[a[i]]);//取最大
}
for(i=n-1;i>=0;i--)//从后往前求一次
{
int t=1;
for(j=a[i];j>=1;j--)
{
if(d2[j]>d2[t])
t=j;
}
d2[a[i]]=d2[t]+1;
maxx=max(maxx,d2[a[i]]);//取最大
}
printf("%d\n",n-maxx);
return 0;
}