博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
求逆序对
阅读量:7213 次
发布时间:2019-06-29

本文共 1865 字,大约阅读时间需要 6 分钟。

逆序对是交换最少相邻元素交换次数

逆序数

 

在一个排列中,如果一对数的前后位置与大小顺序相反,即前面的数大于后面的数,那么它们就称为一个逆序。一个排列中逆序的总数就称为这个排列的逆序数。

 
如2 4 3 1中,2 1,4 3,4 1,3 1是逆序,逆序数是4。给出一个整数序列,求该序列的逆序数。

Input第1行:N,N为序列的长度(n <= 50000) 

第2 - N + 1行:序列中的元素(0 <= Aii <= 10^9)Output输出逆序数Sample Input

42431

Sample Output

4

归并排序

#include 
#include
using namespace std;const int N=100005;int w[N],sum[N],n;struct T{ int x,num;} a[N],T[N];void la(int l,int r){ if(r-l==1)return; int m=l+r>>1,tm=l+r>>1,tl=l,i=l; la(l,m),la(m,r); while(tl
=r||(tl
<=a[tm].x)) T[i++]=a[tl++],T[i-1].num+=tm-m; else T[i++]=a[tm++]; } for(int i=l; i

sort+查找的

#include 
#include
using namespace std;const int N=100005;int w[N],n;long long la(int l,int r){ if(r-l==1)return 0; int m=l+r>>1,s=la(l,m)+la(m,r),t; for(int i=l; i

树状数组

#include 
#include
using namespace std;const int N = 500005;struct Node{ int val; int pos; friend bool operator <(Node a,Node b) { return a.val < b.val; }};Node node[N];int c[N], hash[N], n;int lowbit(int x){ return x & (-x);}void update(int x){ while (x <= n) { c[x] += 1; x += lowbit(x); }}int getsum(int x){ int sum = 0; while (x > 0) { sum += c[x]; x -= lowbit(x); } return sum;}int main(){ scanf("%d", &n); for (int i = 1; i <= n; ++i) { scanf("%d", &node[i].val); node[i].pos = i; } sort(node + 1, node + n + 1); for (int i = 1; i <= n; ++i) hash[node[i].pos] = i; int ans = 0; for (int i = 1; i <= n; ++i) { update(hash[i]); ans += i - getsum(hash[i]); } printf("%d\n", ans); return 0;}

 

转载于:https://www.cnblogs.com/BobHuang/p/8979955.html

你可能感兴趣的文章
golang ide 升级
查看>>
SNMP详解
查看>>
mysql 主从同步,双主同步,如果服务器意外挂机,不同步怎么办
查看>>
在linux中配置安装telnet服务
查看>>
基于HAProxy的网站架构
查看>>
使用ext3grep恢复Linux下误删除的文件[原创]
查看>>
【cocos2d-x从c++到js】13:回调函数2——JSCallbackWrapper
查看>>
PHP操作Memcache实例介绍
查看>>
H5Plus实用代码片段
查看>>
3月第四周全球域名解析商:万网DNSPod排名均上升1名
查看>>
8月全球搜索引擎市场:百度位居第四 份额大涨
查看>>
Shell编程(逻辑判断、文件目录属性判断、if特殊用法、case判断)
查看>>
解决nginx下connect() to 127.0.0.1:3000 failed
查看>>
IPsec ***数据传输过程
查看>>
(总结)Linux下多行合并成一行,中间加分隔符
查看>>
专访阿里数据库备份专家 教你pick最有效的备份系统
查看>>
服务器主板点不亮排查
查看>>
Linux 用户组权限讲解
查看>>
18款开源Linux 管理系统
查看>>
国外值得关注的网站系列之二-社交化推荐网站GetGlue
查看>>