POJ3671 Dining Cows

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 8126   Accepted: 3441

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

 
问最少变换几次可以使原数列变成只有一串连续的1和一串连续的2的形式。
 
DP,枚举断点i,将i位置之前全变成1,之后全变成2,记录最优解即可。
 
 1 /**/
 2 #include<iostream>
 3 #include<cstdio>
 4 #include<cmath>
 5 #include<cstring>
 6 #include<algorithm>
 7 using namespace std;
 8 const int mxn=50000;
 9 int a[mxn],b[mxn];
10 int n;
11 int main(){
12     scanf("%d",&n);
13     int i,j;
14     int d;
15     for(i=1;i<=n;i++){
16         scanf("%d",&d);
17         if(d==1){
18             a[i]=a[i-1]+1;//前缀和 
19             b[i]=b[i-1];
20         }
21         else{
22             a[i]=a[i-1];
23             b[i]=b[i-1]+1;
24         }
25     }
26     int ans=mxn;
27     for(i=1;i<=n;i++){
28         ans=min(ans,a[n]-a[i]+b[i]);//枚举断点,将i及之前所有的2替换成1,将i后面所有的1替换成2 
29     }
30     ans=min(ans,min(a[n],b[n]));//全部替换成1或2 
31     printf("%d
",ans);
32     return 0;
33 }
原文地址:https://www.cnblogs.com/SilverNebula/p/5837732.html