博客
关于我
2018HDU多校2-1010-Swaps and Inversions(hdu 6318)-逆序数,树状数组
阅读量:281 次
发布时间:2019-03-01

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

这里写图片描述

题意:

给出一个数列,其中每有一个逆序数就花费x元,也可以花费y元交换相邻两个数,求处理这个数列的最小花费

思路:

可分析出,交换一次最多只能减少一个逆序数,所以只可能全部交换或者一个都不交换,故此题只需求出逆序数个数即可

O(nlogn)时间下求逆序数个数,可用归并排序法或树状数组法
使用树状数组求解,先将数列从大到小排序,每次选取最大的数放入,树状数组中记录某位置出现数的个数(某位置是否有数),因选取的是最大的数,若最大数位置之前的位置有其他数的话,一定小于最大数,即有逆序数

代码:

#include 
#include
#include
using namespace std;const int N=100050;int n;long long c[N]; //c[n]表示a[1~n]的和,a数组省略struct node{ int val,pos;}a[100005];int lowbit(int x) //求2^k{ return x & -x;}long long getsum(int n) //区间查询,求a[1~n]的和{ long long res = 0; while(n>0) { res+=c[n]; n=n-lowbit(n); } return res;}int change(int x) //单点更新,将c[x]的值加1{ while(x<=n) { c[x]++; x+=lowbit(x); }}bool cmp(node a,node b) //包含相同数{ if(a.val!=b.val) return a.val>b.val; return a.pos>b.pos;}int main(){ std::ios::sync_with_stdio(false); int x,y; while(cin>>n>>x>>y) { memset(c,0,sizeof(c)); for(int i=1;i<=n;i++) { cin>>a[i].val; a[i].pos=i; } sort(a+1,a+n+1,cmp); long long cnt=0; for(int i=1;i<=n;i++) { change(a[i].pos); //修改最大数位置的值 cnt+=getsum(a[i].pos-1); //最大数位置之前的所有位置和,即区间求和,可知比当前数小的数有多少个 } long long ans1=cnt*x; long long ans2=cnt*y; cout<
<
你可能感兴趣的文章
NLP项目:维基百科文章爬虫和分类【02】 - 语料库转换管道
查看>>
NLP:使用 SciKit Learn 的文本矢量化方法
查看>>
nmap 使用方法详细介绍
查看>>
Nmap扫描教程之Nmap基础知识
查看>>
nmap指纹识别要点以及又快又准之方法
查看>>
Nmap渗透测试指南之指纹识别与探测、伺机而动
查看>>
Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NMF(非负矩阵分解)
查看>>
nmon_x86_64_centos7工具如何使用
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.7 Parameters vs Hyperparameters
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>