【贪心】51Nod1241[特殊的排序]题解

来源:互联网 发布:php compact 编辑:程序博客网 时间:2024/06/05 08:37

题目概述

有一个 n 的排列,一次操作可以将一个位置上的数放到头或尾,求最少操作使得排列有序。

解题报告

贪心的策略是尽量少改变相对位置,所以我们刷一下”最长升“,这里的最长升指的是形如 i,i+1,i+2,,j 的最长子序列。假设最长升为 MAX ,那么 nMAX 就是答案。

严格证明?不会啊:P。

ps:题目里没说升序还是降序,我都写了,但好像只写升序也是对的???

示例程序

#include<cstdio>using namespace std;const int maxn=50000;int n,a[maxn+5],pos[maxn+5],MAX;int main(){    freopen("program.in","r",stdin);    freopen("program.out","w",stdout);    scanf("%d",&n);for (int i=1;i<=n;i++) scanf("%d",&a[i]),pos[a[i]]=i;    MAX=0;    for (int i=1,num=0,lst=0;i<=n;i++)    {        if (pos[i]>lst) lst=pos[i],num++; else num=1;        lst=pos[i];if (num>MAX) MAX=num;    }    for (int i=1,num=0,lst=0;i<=n;i++)    {        if (pos[i]<lst) lst=pos[i],num++; else num=1;        lst=pos[i];if (num>MAX) MAX=num;    }    return printf("%d\n",n-MAX),0;}