zoukankan      html  css  js  c++  java
  • poj 2299 归并排序求逆序数 (可做模板)

    Time Limit: 7000MS   Memory Limit: 65536K
    Total Submissions: 48077   Accepted: 17533

    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
    

    Source

     

    #include<string.h>
    #include<stdio.h>
    #include<iostream>
    #include<algorithm>
    using namespace std;
    
    long long  sum;
    int temp[500005];
    
    void sort2(int a[],int l,int mid,int r){
     // memset(temp,0,sizeof(temp));
       int i=l,j=mid+1,k=0;
       while(i<=mid&&j<=r){
          if(a[i]<a[j]){
            temp[k++]=a[i++];
          }
          else{
            temp[k++]=a[j++];
            sum+=mid-i+1;
          }
       }
       while(i<=mid)  temp[k++]=a[i++];
       while(j<=r)    temp[k++]=a[j++];
    
       for(int i=l,k=0;i<=r;k++,i++)
        a[i]=temp[k];
    
    }
    
    void sort1(int a[],int l,int r){
       int mid;
       if(l<r){
           mid=(l+r)/2;
           sort1(a,l,mid);
           sort1(a,mid+1,r);
           sort2(a,l,mid,r);
       }
    }
    int main(){
       int n;
    int a[500005];
       while(scanf("%d",&n)!=EOF){
    
          if(n==0)
            break;
           
            sum=0;
          for(int i=0;i<n;i++)
            scanf("%d",&a[i]);
          sort1(a,0,n-1);
          printf("%lld
    ",sum);
    
    
       }
       return 0;
    }

     

     

     

     

     

  • 相关阅读:
    java第四次作业
    JAVA第三次作业
    Java第二次作业
    Java第一次作业
    android studio下载
    Android面试常问到的知识点
    [Java基础]List,Map集合总结
    搞ACM的你伤不起[转自RoBa]------(看一次,笑一次)
    06.5.1.Functions
    05.virsh命令的常用操作(kvm)
  • 原文地址:https://www.cnblogs.com/13224ACMer/p/4698765.html
Copyright © 2011-2022 走看看