树状数组求逆序对
(2019-06-26 16:36:32)| 分类: 数据结构,指针 | 
树状数组求逆序对,是其中的重要应用方式之一:
求逆序对
给定一个序列a1,a2,a3,……,an,如果存在iaj,那么我们称之为逆序对,求给定序列中逆序对的数目。
输入
第一行为n,表示序列的长度,接下来的n行,第i+1行表示序列的第i个数。
输出
所有逆序对的总数
样例输入
4
3 2 3 2
样例输出
3
一)直接树状数组,相当于桶排序,数组要开得很大,或者超限;
#include "bits/stdc++.h"
#define lowbit(x) (x&-x)
#define LL long long
using namespace std;
const int maxn = 1e6+10;
int t[maxn];
void add(int x){   
while(x<=maxn) t[x]++, x+= lowbit(x);}  
int query(int x)
{   int ans=0;  
}
int main(){
}
单选题:A)    C)  
二)离散化处理,用序号开数组,数组可以比较小:
#include "bits/stdc++.h"
#define lowbit(x) (x&-x)
using namespace std;
const int maxn= 500005;
int c[maxn]; //树状数组
int n;
struct node
{
bool operator < (const node x) const{
}
} a[maxn];
void update(int t, int value){ 
}
int getsum(int t){
}
int main(){
}
单选:1)D   2)A  
多选:1)B,C
三)Swaps and Inversions HDU6318
Long long ago, there was an integer sequence a.
Tonyfang think this sequence is messy, so he will count the
number of inversions in this sequence. Because he is angry, you
will have to pay x yuan for every inversion in the sequence.
You don't want to pay too much, so you can try to play some
tricks before he sees this sequence. You can pay y yuan to swap any
two adjacent elements.
What is the minimum amount of money you need to spend?
The definition of inversion in this problem is pair (i,j)
which 1≤iaj.
Input
There are multiple test cases, please read till the end of
input file.
For each test, in the first line, three integers, n,x,y, n
represents the length of the sequence.
In the second line, n integers separated by spaces,
representing the orginal sequence a.1≤n,x,y≤100000, numbers in the
sequence are in [?109,109]. There're 10 test cases.
Output
For every test case, a single integer representing minimum
money to pay.
Sample Input
3 233 666
1 2 3
3 1 666
3 2 1
Sample Output
0
3
题目意思:
给你一个长度为n的数列
开始检查,如果某两个数不是从小大大顺序的,有一个就罚x元,
或者也可以直接在检查之前对不符合要求的调换位置(相邻的)
花费y元
然后要你求最小的花费
所以就是直接求这个序列的逆序数然后乘以x和y花费中较小的一个
逆序数可以归并或者数状数组求解
参考程序一,使用归并排序:
#define max_v 100005
using namespace std;
typedef long long LL;
LL a[max_v];
LL temp[max_v];
LL ans;
void mer(int s,int m,int t)
{
}
void megsort(int s,int t)
{
}
int main()
{
}
参考程序二,树状数组:
#include
using namespace std;
#define max_v 500005
int n;
struct node
{
} p[max_v];
int c[max_v];
int re[max_v];
int maxx;
int lowbit(int x)
{
}
void update(int x,int d)
{
}
int getsum(int x)//返回1到x中小与等于x的数量
{
}
bool cmp(node a,node b)
{
}
int main()
{
}
前一篇:树状数组:第k个数
										后一篇:道路铺设--货币系统--赛道建设
					
 加载中…
加载中…