[ACM]Ultra-QuickSort
Time Limit: 7000MS Memory Limit: 65536KB
Total Submissions: 20 Accepted: 7
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
Hint:
Source:
Waterloo local 2005.02.05
这题没有什么可说的,直接调用系统的排序函数进行排序就行了,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | #include <iostream> #include <algorithm> using namespace std; #define MAXN 500001 int a[MAXN],t[MAXN],n; __int64 ans; void Merge( int l, int m, int r){ int i=0,j=l,k=m+1; while (j<=m && k<=r){ if (a[j]>a[k]){ t[i++]=a[k++]; ans+=m-j+1; } else t[i++]=a[j++]; } while (j<=m) t[i++]=a[j++]; while (k<=r) t[i++]=a[k++]; for (j=0;j<i;j++){ a[l+j]=t[j]; } } void Mergesort( int l, int r){ if (l<r){ int m=(l+r)/2; Mergesort(l,m); Mergesort(m+1,r); Merge(l,m,r); } } int main(){ int i; while ( scanf ( "%d" ,&n) && n){ ans=0; for (i=0;i<n;i++) scanf ( "%d" ,a+i); Mergesort(0,n-1); printf ("%I64d ",ans); } return 0; } |

本文基于署名 2.5 中国大陆许可协议发布,欢迎转载,演绎或用于商业目的,但是必须保留本文的署名小橋流水(包含链接)。如您有任何疑问或者授权方面的协商,请给我发邮件。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述