zoukankan      html  css  js  c++  java
  • Sort(归并)

    Sort

    时间限制:1000 ms  |  内存限制:65535 KB
    难度:4
     
    描述
    You want to processe a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. Then how many times it need. For example, 1 2 3 5 4, we only need one operation : swap 5 and 4.
     
    输入
    The input consists of T number of test cases.(<0T<1000) Each case consists of two lines: the first line contains a positive integer n (n <= 1000); the next line contains a permutation of the n integers from 1 to n.
    输出
    For each case, output the minimum times need to sort it in ascending order on a single line.
    样例输入
    2
    3
    1 2 3
    4
    4 3 2 1
    样例输出
    0
    6
    代码:
    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<cmath>
    #include<algorithm>
    using namespace std;
    const int MAXN = 1010;
    int num[MAXN], temp[MAXN]; 
    int ans;
    void mg(int l, int m, int r){
        int i = l, j = m + 1, cur = l;
        while(i <= m && j <= r){
            if(num[i] < num[j]){
                temp[cur++] = num[i++];
            }
            else{
                ans += j - cur;
                temp[cur++] = num[j++];
            }
        }
        for(int i = l; i <= r; i++)
            num[i] = temp[i];
    }
    void ms(int l, int r){
        int m;
        if(l < r){
            m = (l + r) >> 1;
            ms(l, m);
            ms(m + 1, r);
            mg(l, m, r);
        }
    }
    int main(){
        int T,n;
        scanf("%d", &T);
        while(T--){
            scanf("%d", &n);
            for(int i = 0; i < n; i++){
                scanf("%d", num + i);
            }
            ans = 0;
            ms(0, n - 1);
            printf("%d
    ", ans);
        }
        return 0;
    }
  • 相关阅读:
    spring揭秘读书笔记----spring的ioc容器之BeanFactory
    spring启动加载过程源码分析
    java线程数过高原因分析
    spring揭秘读书笔记----ioc的基本概念
    git merge rebase的区别及应用场景
    spring实现定时任务
    jetty.xml解析
    Hackthebox--------irked
    CTF之信息泄漏
    CTF web题型解题技巧
  • 原文地址:https://www.cnblogs.com/handsomecui/p/5602776.html
Copyright © 2011-2022 走看看