zoukankan      html  css  js  c++  java
  • 2015 HUAS Summer Trainning #4 A

    Description

    In this problem, you have to analyze a particular sorting algorithm. The algorithm processes a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. For the input sequence 
    9 1 0 5 4 ,
    Ultra-QuickSort produces the output 
    0 1 4 5 9 .
    Your task is to determine how many swap operations Ultra-QuickSort needs to perform in order to sort a given input sequence.

    Input

    The input contains several test cases. Every test case begins with a line that contains a single integer n < 500,000 -- the length of the input sequence. Each of the the following n lines contains a single integer 0 ≤ a[i] ≤ 999,999,999, the i-th input sequence element. Input is terminated by a sequence of length n = 0. This sequence must not be processed.

    Output

    For every input sequence, your program prints a single line containing an integer number op, the minimum number of swap operations necessary to sort the given input sequence.

    Sample Input

    5
    9
    1
    0
    5
    4
    3
    1
    2
    3
    0
    

    Sample Output

    6

    0

    题目大意:求逆序数的个数;

    解题思路:因为有时间限制,不能有2层循环来找。需要用到归并排序。

    代码:

     1 #include<iostream>
     2 #include<algorithm>
     3 using namespace std;
     4 const long long  maxn=500000+10;
     5 int a[maxn];
     6 long long  paisu(int x,int y)
     7 {
     8     if(x>=y) return 0;
     9     long long  cnt=0;
    10     int m=x+(y-x)/2;
    11     cnt+=paisu(x,m);
    12     cnt+=paisu(m+1,y);
    13     int p2=m+1;
    14     for(int p1=x;p1<=m;p1++)
    15     {
    16         for(int j=p2;j<=y;j++)
    17         {
    18             if(a[p1]<a[j])
    19                 break;
    20             else p2++;
    21         }
    22         cnt+=p2-m-1;
    23     }
    24     sort(a+x,a+y+1);
    25     return cnt;
    26 
    27 }
    28 int main()
    29 {
    30     int i;
    31     int n;
    32     while(cin>>n&&n)
    33     {
    34         for(i=0;i<n;i++)
    35             cin>>a[i];
    36         cout<<paisu(0,n-1)<<endl;
    37     }
    38     return 0;
    39 }
    View Code
  • 相关阅读:
    zabbix监控系统客户端安装
    可以学习的博客地址
    Linux下Nagios的安装与配置
    ShopNC多用户商城标题去版权 后台去版权方法2.0版本
    解析crontab php自动运行的方法
    暑假周报告(第五周)
    暑假周报告(第四周)
    暑假周报告(第三周)
    暑假周报告(第二周)
    《大道至简》读后感
  • 原文地址:https://www.cnblogs.com/huaxiangdehenji/p/4711884.html
Copyright © 2011-2022 走看看