博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
HDU 1394 Minimum Inversion Number (数据结构-线段树)
阅读量:4675 次
发布时间:2019-06-09

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

Minimum Inversion Number

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 9514    Accepted Submission(s): 5860

Problem Description
The inversion number of a given number sequence a1, a2, ..., an is the number of pairs (ai, aj) that satisfy i < j and ai > aj.
For a given sequence of numbers a1, a2, ..., an, if we move the first m >= 0 numbers to the end of the seqence, we will obtain another sequence. There are totally n such sequences as the following:
a1, a2, ..., an-1, an (where m = 0 - the initial seqence)
a2, a3, ..., an, a1 (where m = 1)
a3, a4, ..., an, a1, a2 (where m = 2)
...
an, a1, a2, ..., an-1 (where m = n-1)
You are asked to write a program to find the minimum inversion number out of the above sequences.
 

Input
The input consists of a number of test cases. Each case consists of two lines: the first line contains a positive integer n (n <= 5000); the next line contains a permutation of the n integers from 0 to n-1.
 

Output
For each case, output the minimum inversion number on a single line.
 

Sample Input
 
10 1 3 6 9 0 8 5 7 4 2
 

Sample Output
 
16
 

Author
CHEN, Gaoli
 

Source
 

Recommend
Ignatius.L
 

题目大意:

求逆序数。也就是给你一个序列,每次求逆序数,然再把第一个数放到这个序列的末尾,构成新的序列。问你这n个序列的最小的逆序数。

解题思路:

1、对于每个序列,其原来的逆序数记为 pre , 如果当前把该序列 第一个数 a[0] 移动到尾部,那么新序列的逆序数为 pre-a[i]+(n-a[i]-1)

因为序列中比a[i]大的数有 n-a[i]-1 个,比a[i]小的有 a[i]个。

因此只需求出第一个序列的逆序数,依次可以递推出这n个序列的逆序数,求出最小的即可

2、求第一个序列的逆序数的方法

(1)暴力算法,据说不会超时

(2)线段树,建 [0,n]这段树,对于数据 a[i] ,先查询 (a[i]+1,n) 这段的值也就是比a[i]大的数的个数也就是 逆序数,然后插入 (a[i],a[i]) 值为1

代码:

#include 
#include
#include
#include
#include
using namespace std;const int maxn=5100;struct tree{ int l,r,sum;}a[maxn*4];int data[maxn],n,m;void build(int l,int r,int k){ a[k].l=l; a[k].r=r; a[k].sum=0; if(l
=mid+1) insert(l,r,2*k+1,c); else{ insert(l,mid,2*k,c); insert(mid+1,r,2*k+1,c); } a[k].sum=a[2*k].sum+a[2*k+1].sum; }}int query(int l,int r,int k){ if(l<=a[k].l && a[k].r<=r){ return a[k].sum; }else{ int mid=(a[k].l+a[k].r)/2; if(r<=mid) return query(l,r,2*k); else if(l>=mid+1) return query(l,r,2*k+1); else{ return query(l,mid,2*k) + query(mid+1,r,2*k+1) ; } }}void solve(){ int ans=0; build(1,n,1); for(int i=1;i<=n;i++){ ans+=query(data[i]+1,n,1); insert(data[i]+1,data[i]+1,1,1); //cout<
<<" "<
<



转载于:https://www.cnblogs.com/toyking/p/3797409.html

你可能感兴趣的文章
宏定义详解
查看>>
PHP 开启报错机制
查看>>
hdu 1016 Prime Ring Problem
查看>>
VC++6.0在Win7以上系统上Open或Add to Project files崩溃问题 解决新办法
查看>>
vue之双绑实现
查看>>
thymeleaf自定义标签方言处理
查看>>
js两数字相除 保留两位小数
查看>>
Objective-C之成魔之路【5-选择结构】
查看>>
【HDU 2586】LCA模板
查看>>
SAP PA 共享 免费下载
查看>>
文件管理器
查看>>
登录之后更新导航
查看>>
文字图形组合技巧2[摘]
查看>>
ssh注解basedao简单的实现
查看>>
RGB配色表
查看>>
Dance GAN 迁移不同视频中人物动作的方法
查看>>
artDialog组件与iframe
查看>>
xBIM 实战02 在浏览器中加载IFC模型文件并设置特效
查看>>
【中国剩余定理】【容斥原理】【快速乘法】【数论】HDU 5768 Lucky7
查看>>
Session变量不能传送到下一页.解决: session.use_trans_sid = 1
查看>>