• 排序---P1116 车厢重组


    P1116 车厢重组

    来自 <车厢重组 - 洛谷>

    其实这道题本质上就是求逆序对的过程:

    两种方法:一个是通过冒泡排序过程求逆序对;一个是通过归并排序过程求逆序对。

    法一:当通过冒泡排序进行正序排列时,相邻两个数需要进行交换时,则说明这是一个逆序对,逆序对++。

    1. import java.util.Scanner;
    2. /**
    3.  * 用冒泡思想算逆序对,每次进行交换时,逆序对++
    4.  */
    5. public class Main {
    6.     public static void main(String[] args) {
    7.         int n,ans=0;
    8.         Scanner scanner=new Scanner(System.in);
    9.         n = scanner.nextInt();
    10.         int[] a=new int[n];
    11.         for(int i=0;i
    12.             a[i]=scanner.nextInt();
    13.         }
    14.         for(int i=1;i<=n-1;i++){
    15.             for(int j=0;j<=n-1-i;j++){
    16.                 if(a[j]>a[j+1]){
    17.                     int t=a[j];
    18.                     a[j]=a[j+1];
    19.                     a[j+1]=t;
    20.                     ans++;
    21.                 }
    22.             }
    23.         }
    24.         System.out.println(ans);
    25.     }
    26. }

    法二:归并排序,逆序对=左边有序数列的逆序对+右边有序数列的逆序对+处于左右两边的逆序对

     

    1. import java.util.Scanner;
    2. /**
    3.  * 用归并的思路算逆序对
    4.  */
    5. public class Main {
    6.     public static int n;
    7.     public static int[] a=new int[100005];
    8.     public static int[] temp=new int[100005];
    9.     public static void main(String[] args) {
    10.         Scanner scanner=new Scanner(System.in);
    11.         n=scanner.nextInt();
    12.         for(int i=0;i
    13.             a[i]=scanner.nextInt();
    14.         }
    15.         System.out.println(merge_sort(0,n-1));
    16.     }
    17.     public static int merge_sort(int l,int r){
    18.         if(l>=r){
    19.             return 0;
    20.         }
    21.         int mid=(l+r)/2;
    22.         int res=merge_sort(l,mid)+merge_sort(mid+1,r);
    23.         int i=l,j=mid+1,k=0;
    24.         while(i<=mid&&j<=r){
    25.             if(a[i]<=a[j]){
    26.                 temp[k++]=a[i++];
    27.             }
    28.             else{
    29.                 res+=mid-i+1;
    30.                 temp[k++]=a[j++];
    31.             }
    32.         }
    33.         while(i<=mid){
    34.             temp[k++]=a[i++];
    35.         }
    36.         while (j<=r){
    37.             temp[k++]=a[j++];
    38.         }
    39.         for(i=l,j=0;i<=r;i++,j++){
    40.             a[i]=temp[j];
    41.         }
    42.         return res;
    43.     }
    44. }

  • 相关阅读:
    javax.net.ssl.SSLHandshakeException: No appropriate protocol
    144. 二叉树的前序遍历
    Mac下docker安装MySQL8.0.34
    HDMI 基于 4 层 PCB 的布线指南
    文字转语音怎么做?分享三种配音方法,真人语音很逼真
    2022/6/27 Quartz(定时任务)讲解+入门案例
    线性代数的艺术
    从 Google 离职,前Go 语言负责人跳槽小公司
    Springboot辅助功能(内嵌tomcat服务器)
    赋能工业数字化转型|辽宁七彩赛通受邀出席辽宁省工业互联网+安全可控先进制造业数字服务产业峰会
  • 原文地址:https://blog.csdn.net/m0_73866527/article/details/133492183