牛客假日团队赛7:
链接:https://ac.nowcoder.com/acm/contest/997/G
来源:牛客网
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 32768K,其他语言65536K
64bit IO Format: %lld
题目描述
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
示例1
输入
复制
5
1
3
2
1
1
输出
复制
1
说明
We would need at least two changes to turn this into an increasing sequence (changing both non-1’s to a 1).
However, changing the first “1” to a “3” yields a decreasing sequence with just one change, which is optimal.
题意:
一个只由1,2,3组成的序列,改变最少的数使序列成为上升或下降序列。
很明显就是求一个最长上升子序列和最长下降子序列,需要修改的数量ans = N -两个子序列中长度的较大值。
N达到3e4,所以用基于贪心的O(NlogN)解法
AC_code:
#include <bits/stdc++.h>
using namespace std;
const int N = 3e4+4;
int a[N];
int st[N];
int main()
{
int n;
cin>>n;
int t = 0;
st[t] = 0;
for(int i = 1; i <= n; i++)
{
cin>>a[i];
if(a[i] >= st[t])
{
st[++t] = a[i];
}
else
{
int l = 1,r = t;
int res = 0;
while(l <= r)
{
int mid = (l+r)>>1;
if(st[mid] > a[i])
{
res = mid;
r = mid - 1;
}
else l = mid+1;
}
st[res] = a[i];
}
}
int maxx = t;
t = 0;
st[t] = 10;
for(int i = 1; i <= n; i++)
{
if(a[i] <= st[t])
{
st[++t] = a[i];
}
else
{
int l = 1,r = t;
int res = 0;
while(l <= r)
{
int mid = (l+r)>>1;
if(st[mid] < a[i])
{
res = mid;
r = mid - 1;
}
else l = mid+1;
}
st[res] = a[i];
}
}
maxx = max(maxx,t);
cout<<(n-maxx)<<endl;
return 0;
}