zoukankan      html  css  js  c++  java
  • H

    Description

    During Frosh Week, students play various fun games to get to know each other and compete against other teams. In one such game, all the frosh on a team stand in a line, and are then asked to arrange themselves according to some criterion, such as their height, their birth date, or their student number. This rearrangement of the line must be accomplished only by successively swapping pairs of consecutive students. The team that finishes fastest wins. Thus, in order to win, you would like to minimize the number of swaps required.
     

    Input

    The first line of input contains one positive integer n, the number of students on the team, which will be no more than one million. The following n lines each contain one integer, the student number of each student on the team. No student number will appear more than once. 
     

    Output

    Output a line containing the minimum number of swaps required to arrange the students in increasing order by student number. 
     

    Sample Input

    3
    3
    1
    2
     

    Sample Output

    2
     
    AC代码:
    #include<iostream>//归并排序
    #include<cstdio>
    #include<algorithm>
    #include<cstring>
    # define M 1000010
    using namespace std;
    long long int cnt;
    int A[M],T[M];
    int y,m;
    void merge_sort(int*A,int x,int y,int *T)
    {
      if(y-x>1)
      {
       int m=x+(y-x)/2;//划分
       int p=x,q=m,i=x;
       merge_sort(A,x,m,T);//递归求解
       merge_sort(A,m,y,T);//递归求解
       while(p<m||q<y)
       {
         if(q>=y||(p<m&&A[p]<=A[q]) )T[i++]=A[p++];//从左半数组复制到临时空间
    	 else
    	 {
    		 T[i++]=A[q++];//从右半数组复制到临时空间
    		 cnt+=m-p;
    	 }
       }
    	 for(i=x;i<y;i++)
    		 A[i]=T[i];//从辅助空间复制回A数组
      }
    }
    
    int main()
    {
    	int n;
    
    	while(scanf("%d",&n)!=EOF)
    	{
    	    cnt=0;
    		memset(A,0,sizeof(A));
    		memset(T,0,sizeof(T));
    		int i=0;
    		while(n--)
    		{
    	scanf("%d",&A[i++]);
    		}
        merge_sort(A,0,i,T);
    		printf("%lld
    ",cnt);//注意cnt一定要是long long int型
    
    	}
    
    return 0;
    
    }
     
    题意:逆序对,就是将编号按从小到大的顺序排列需要调换几次
    分析:本题一开始我用的是简单的冒泡法去做,但提交会超时,于是我想用打表解决,尴尬的是知道概念不会操作;然后又换了一种新知识解决,即归并排序。新知识不熟练是参照书上的核心代码写的。
    心得:归并排序可以用解决一些数据大的问题,而不会超时
     
  • 相关阅读:
    《Codeforces Round #696 (Div. 2)》
    从Java源码角度聊设计模式之工厂模式
    HashMap死循环【基于JDK1.7】情景重现与分析(带示意图)
    Java应用级别的线程中断—interrupt&isInterrupted&interrupted的区别
    Java队列学习笔记(2)---DelayQueue
    Java队列学习笔记(1)---AbstractQueue&PriorityQueue
    junit测试用例从src/test/resources下的txt文件读取多行数据并随机选择一行
    (Ant编程) Ienumerable类型、枚举器 和自定义的 linq
    如何 给select 下拉框 设定默认值
    分页sql
  • 原文地址:https://www.cnblogs.com/lbyj/p/5682599.html
Copyright © 2011-2022 走看看