POJ 3670 Eating Together(dp)

女爷i 2022-06-12 13:10 218阅读 0赞

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

  1. 5
  2. 1
  3. 3
  4. 2
  5. 1
  6. 1

Sample Output

  1. 1

题解:

理解了题意就很水的一题,从前往后一次dp求最长不下降子序列,从后往前再来一次,然后总数减去最长的那个就是答案

代码:

  1. #include<iostream>
  2. #include<stdio.h>
  3. #include<map>
  4. #include<algorithm>
  5. #include<math.h>
  6. #include<queue>
  7. #include<stack>
  8. #include<string>
  9. #include<cstring>
  10. using namespace std;
  11. int a[30005];
  12. int d1[5];//记录结尾是i的长度最长的子序列长度
  13. int d2[5];
  14. int main()
  15. {
  16. int i,j,k,n,m;
  17. scanf("%d",&n);
  18. memset(d1,0,sizeof(d1));
  19. memset(d2,0,sizeof(d2));
  20. int maxx=0;
  21. for(i=0;i<n;i++)
  22. {
  23. scanf("%d",&a[i]);
  24. int t=1;
  25. for(j=a[i];j>=1;j--)//从前往后求一次
  26. {
  27. if(d1[j]>d1[t])
  28. t=j;
  29. }
  30. d1[a[i]]=d1[t]+1;
  31. maxx=max(maxx,d1[a[i]]);//取最大
  32. }
  33. for(i=n-1;i>=0;i--)//从后往前求一次
  34. {
  35. int t=1;
  36. for(j=a[i];j>=1;j--)
  37. {
  38. if(d2[j]>d2[t])
  39. t=j;
  40. }
  41. d2[a[i]]=d2[t]+1;
  42. maxx=max(maxx,d2[a[i]]);//取最大
  43. }
  44. printf("%d\n",n-maxx);
  45. return 0;
  46. }

发表评论

表情:
评论列表 (有 0 条评论,218人围观)

还没有评论,来说两句吧...

相关阅读

    相关 CF558 A. Eating Soup

      给出结点数n  结点两两相连成一个环     再给出m   求 在环中去掉m个点   使得联通块最大   输出最大联通块   比赛的时候我还在模拟。。。 其实可以找一