H - Frosh Week

本文介绍了一种使用归并排序算法来解决逆序对计数问题的方法。通过将学生队伍按学号排序的过程,实现了逆序对的有效计数。文章详细解释了归并排序的实现过程,并给出了完整的AC代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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\n",cnt);

	}

return 0;

}
 
分析:问题的实质是一个逆序对,用归并排序的方法解决
分治三步法:1.划分问题:把序列分成元素个数尽量相等的两部分
               2.递归求解:把两半元素分别求解
               3.合并问题:把两个有序表合并成一个
 
 
 
 
 
 

转载于:https://www.cnblogs.com/lbyj/p/5696919.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值