Sequence in the Pocket

Sequence in the Pocket

题目大意

给定一个序列,每次可以把一个元素移到列首(最左边),求最少移几次使其有序(非降序)。

题目分析:

我们将输入的数组复制一份进行排序,然后从后往前寻找有多少元素在原数组保持有序,用总的元素个数减去有序的个数就是我们需要移动的次数。

为什么要从后往前寻找?
因为我们只能将元素移动到最左边。

从后往前寻找的方法:

int ans = n;
for (int i = n; i >= 1; i--) 
if (a[i] == b[ans]) ans--; 
printf("%d\n", ans);

如果a[i] == b[ans],那么ans--继续寻找。
如果a[i] != b[ans],那么i--直到找到或循环结束。

代码:

#include "bits/stdc++.h"
using namespace std;
const int MAXN = 1e5 + 5;
int a[MAXN], b[MAXN];
int main() {
    int t, n;
    scanf("%d", &t);
    while (t--) {
        scanf("%d", &n);
        for (int i = 1; i <= n; i++) {
            scanf("%d", &a[i]);
            b[i] = a[i];
        }
        sort(b + 1, b + 1 + n);
        int ans = n;
        for (int i = n; i >= 1; i--) 
            if (a[i] == b[ans]) ans--; 
        printf("%d\n", ans);
    }
    return 0;
}
posted @ 2020-09-04 12:51  Treasure_lee  阅读(170)  评论(0)    收藏  举报