First Last Sorting(简单dp)

Arup has just created a data structure that makes the two following list transformations in constant O(1) time:

a. Take any element in the list and move it to the front.
b. Take any element in the list and move it to the back.

You’ve realized that sorting speed can be improved using these transformations. For example, consider the input list:
8, 3, 6, 7, 4, 1, 5, 2
We can do the following sequence of transformations to sort this list:
8, 3, 7, 4, 1, 5, 2, 6 (move 6 to end)
8, 3, 4, 1, 5, 2, 6, 7 (move 7 to end)
2, 8, 3, 4, 1, 5, 6, 7 (move 2 to front)
1, 2, 8, 3, 4, 5, 6, 7 (move 1 to front)
1, 2, 3, 4, 5, 6, 7, 8 (move 8 to end).

You are now curious. Given an input array of distinct values, what is the fewest number of these first/last operations necessary to sort the array?

The Problem:Given an initial permutation of the integers 1, 2, …, n, determine the fewest number of first/last operations necessary to get the list of values sorted in increasing order.

The Input:The first line of input will contain a single positive integer, n (n ≤ 1e5), representing the number of values to be sorted. The next n lines contain one integer each. All of these integers will be distinct values in between 1 and n (inclusive), representing the original order of the data to sort for the input case.

The Output:On a line by itself, output the fewest number of first/last operations necessary to sort the input list.
输出时每行末尾的多余空格,不影响答案正确性
样例输入1:
8
8
3
6
7
4
1
5
2
样例输出1: 5
样例输入2:
5
1
2
5
3
4
样例输出2: 1

简单的dp 求最长的递增序列,由于题意上说是连续的n个数字。所以要是求最长的连续的子序列可以获得。dp[m]:以m结尾的最长连续递增子序列长度。所以o(n)的dp就可以 即:dp[m]=dp[m]+1;
条件:所求的最长递增连续子序列:ep: 3,4,5

#include<math.h>
#include<stdlib.h>
#include<stack>
#include<stdio.h>
#include<queue>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<vector>
#include<map>
#include<string.h>
#define ll long long
#define db double
#define F(n) for(int i=1;i<=n;i++)
using namespace std; 
const int mx=1e5+10,inf=1000;
int num,dp[mx];
int main(){
 int n,ans=0;
 scanf("%d",&n);
 for(int i=1;i<=n;i++){
  cin>>num;
  dp[num]=dp[num-1]+1;
  ans=max(ans,dp[num]);
 }
 printf("%d\n",n-ans); 
 return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值