Backfront AtCoder - 3959 (最长连续上升序列)

本文介绍了一种通过特定操作对整数序列进行排序的方法,并提供了一个C++实现示例。该算法利用最长递增子序列的概念来确定将序列排序所需的最小操作次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

You are given a sequence (P1,P2,…,PN) which is a permutation of the integers from 1 through N. You would like to sort this sequence in ascending order by repeating the following operation:

  • Choose an element in the sequence and move it to the beginning or the end of the sequence.

Find the minimum number of operations required. It can be proved that it is actually possible to sort the sequence using this operation.

Constraints

  • 1N2×105
  • (P1,P2,…,PN) is a permutation of (1,2,…,N).
  • All values in input are integers.
Input

Input is given from Standard Input in the following format:

N
P1
:
PN
Output

Print the minimum number of operations required.

Sample Input 1

4
1
3
2
4
Sample Output 1

2

For example, the sequence can be sorted in ascending order as follows:

  • Move 2 to the beginning. The sequence is now (2,1,3,4).
  • Move 1 to the beginning. The sequence is now (1,2,3,4).
Sample Input 2

6
3
2
5
1
4
6
Sample Output 2

4
Sample Input 3

8
6
3
1
2
7
4
8
5
Sample Output 3

5

这个题是可以 既往后放,又可以往前放。

我一开始就想的是逆序对,结果逆序对只可以只往一个方向放,不能既往前放,又往后放。4 2 3  1,是个反例

所以用最长上升序列。找到最长的一个,其他的不往后放,就往前放。  n-len 就行,找最小的一个。




#include <cstdio>
#include<cstring>
#include <algorithm>
using  namespace std;
#define mem(v,x) memset(v,x,sizeof(v))
#define low(x) (x & (-x))
int pos[500010],n,m;

int main() {
    scanf("%d",&n);
    for (int i = 1; i <= n; i++){
       scanf("%d",&m);
       pos[m] = i;
    }
    int len = 1,ans = 5000000;
    for (int i = 1; i < n; i++){
        if (pos[i+1] > pos[i]) len++; else{
            ans = min(ans,n-len);
            len = 1;
        }
    }
    ans = min(ans,n-len);
    printf("%d\n",ans);

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值