2299
来源:互联网 发布:linux网络应用项目开发 编辑:程序博客网 时间:2024/06/05 14:26
这道题目的大意 是求 冒泡排序的交换次数
但是 若这道题目 用冒泡排序做的话,肯定会超时 。O(n^2);
但这道题目可以转换为求 逆序数 的大小。(线性代数里面学过的)
9 1 0 5 4
逆序数=4+1+0+1=6 这正是 答案。
我们可以使用 merge_sort() 来求 逆序数 。O(nlogn)
要注意 用int 型的话 ,会wa 的,要用long long
如果用的是cpp 的话 , 不要用cin 要用 scanf 。 后者比前者快了 1000ms 左右
memory time7266k 391ms#include <iostream>#include <stdio.h>#include <algorithm>using namespace std;long long a[500010];long long c[500010];long long ans,cnt;void merge(int s1,int e1,int s2,int e2){ int p=0,p1=s1,p2=s2; while(p1<=e1&&p2<=e2) { if(a[p1]<a[p2]) { c[p++]=a[p1++]; } else { c[p++]=a[p2++]; ans+=e1-p1+1; } } while(p1<=e1) c[p++]=a[p1++]; while(p2<=e2) c[p++]=a[p2++]; for(int i=s1;i<=e2;i++) a[i]=c[i-s1];}void merge_sort(int s,int e){ if(s<e) { int m=(s+e)/2; merge_sort(s,m); merge_sort(m+1,e); merge(s,m,m+1,e); }}int main(){ int n; while(scanf("%d",&n)==1&&n) { for(int i=0;i<n;i++) scanf("%d",&a[i] ); ans=0; merge_sort(0,n-1); cout<<ans<<endl; }}
0 0
- 2299
- POJ-2299-POJ 2299
- POJ 2299
- Poj 2299
- POJ 2299
- hdu 2299
- poj 2299
- poj 2299
- poj 2299
- poj.2299
- POJ 2299
- poj 2299
- poj-2299
- poj 2299
- poj-2299
- poj 2299
- POJ 2299
- poj 2299
- 可运行的JAR文件,如何在系统中运行
- CSS定位
- JAVA 并发机制--生产者消费者问题
- Windows下Oracle11g手动建库
- HDU1024 Max Sum Plus Plus
- 2299
- 数学之路-sas备忘(4)
- HTTP协议之multipart/form-data请求分析
- uva 125(floyd变式)
- iOS XMPP Framework 07 - 收发消息 下
- C# WPF 设置窗口无边框
- Leetcode--Merge k Sorted Lists
- 在sql*plus中怎么查看一些命令的用法
- 【UOJ Goodbye Jiawu】