zoukankan      html  css  js  c++  java
  • 1241 特殊的排序

    1241 特殊的排序

    题目来源: 摩根斯坦利的比赛题
    基准时间限制:1 秒 空间限制:131072 KB
    一个数组的元素为1至N的整数,现在要对这个数组进行排序,在排序时只能将元素放在数组的头部或尾部,问至少需要移动多少个数字,才能完成整个排序过程?
    例如:
    2 5 3 4 1 将1移到头部 => 
    1 2 5 3 4 将5移到尾部 =>
    1 2 3 4 5 这样就排好了,移动了2个元素。
     
    给出一个1-N的排列,输出完成排序所需的最少移动次数。
    Input
    第1行:1个数N(2 <= N <= 50000)。
    第2 - N + 1行:每行1个数,对应排列中的元素。
    Output
    输出1个数,对应所需的最少移动次数。
    Input示例
    5
    2
    5
    3
    4
    1
    Output示例
    2
    思路:就是找最长的符合原来的排列的长度,比如25341,符合的最长的为2 3 4,然后总长度减下就是需要移动的,那么问题就是则么去找这个序列,就是相差一的,因为要连续,所以看下比当前这个数小一的是否在前面在的话就是前一个输得长度加一。
    复杂度O(n);
     1 #include <stdio.h>
     2 #include <algorithm>
     3 #include <stdlib.h>
     4 #include <string.h>
     5 #include <iostream>
     6 #include <math.h>
     7 #include <queue>
     8 #include <set>
     9 #include <map>
    10 using namespace std;
    11 typedef long long LL;
    12 const LL mod = 1e9+7;
    13 int ans[60000];
    14 int id[60000];
    15 int t[60000];
    16 int main(void)
    17 {
    18         int n;
    19         int i,j;scanf("%d",&n);
    20         for(i = 1; i <= n; i++)
    21         {
    22                 scanf("%d",&ans[i]);
    23                 id[ans[i]] = i;
    24         }
    25         int maxx = 1;
    26         fill(t,t+60000,1);
    27         for(i = 2; i <= n; i ++)
    28         {
    29                 if(id[i-1] < id[i])
    30                 {
    31                      t[id[i]] = t[id[i-1]]+1;
    32                      maxx = max(t[id[i]],maxx);
    33                 }
    34         }
    35         printf("%d
    ",n-maxx);
    36         return 0;
    37 }
    
    
    油!油!you@
  • 相关阅读:
    条款14:在资源管理类中心copying行为(Think carefully about copying behavior in resource-manage classes)
    matlab ()的用法
    正式学习React(五) Reactjs 的 PropTypes 使用方法
    正式学习 react(三)
    webpack ------require,ensure
    转的git
    Session机制详解
    ES5 object的新函数
    HDU 4635 Strongly connected (强连通分量)
    HDU 4635 Strongly connected (强连通分量)
  • 原文地址:https://www.cnblogs.com/zzuli2sjy/p/5857832.html
Copyright © 2011-2022 走看看