1. 程式人生 > >線段樹之

線段樹之

求逆序數的方法: 1.直接暴力求解 2.線段樹求解 需要知道HASH(離散化)。//192和132逆序數是一樣的,所以可以對映到一樣的情況。 求逆序數的思路:遍歷每一個數字,如果這個數字前面有比它大的數字,那麼比它大的數字的個數即比他大的區間的sum值,例如a=5,它的逆序數即6-10的sum值。 例題:

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 本題思路:因為這個序列的數字是從0~n-1並且是沒有重複的數字,所以也就不需要離散化了,就遍歷輸入的序列即可,因為後面的序列的逆序數是ans-a[0]+n-a[n]-1;因為最前面的數字到了最後面,那麼假如n=10,a[0]=3,那麼在後面比它小的數字只有0、1、2,所以它到了最後面逆序數-3,而比它大的有3、4、5、6、7、8、9所以又多了6,之後以此類推。

//有問題。。。。
#include <cstdio>
#include <iostream>
#include <string.h>
#define MAXSIZE 5005
using namespace std;
int N;
int number[MAXSIZE];
int mini[MAXSIZE];
int C;
struct node{
	int l,r;
	int sum;
}tr[MAXSIZE<<2];
void build(int m,int l,int r);
void pushup(int m);
void update(int m,int index,int val);//單點更新
int query(int m,int l,int r);//區間查詢

int main(){
	int cnt;
	while(~scanf("%d",&N)){
		memset(tr,0,sizeof(tr));
		C=0;
		cnt=0;//求這個點的逆序數
		build(1,0,N-1);//建樹過程
		for(int i=0;i<N;i++){
			scanf("%d",&number[i]);
			update(1,number[i],1);
			if(number[i]+1<=N-1){//需要考慮是否越界
				cnt+=query(1,number[i]+1,N-1);
			}
		}
		mini[C++]=cnt;//計算每個序列的逆序數
		for(int i=0;i<N-1;i++){//意思是把number[i]移到序列最後面
			mini[C]=mini[C-1]-number[i]+N-number[i]-1;
			C++;
		}
		int Min =100000000;
		for(int i=0;i<C;i++){
			if(mini[i]<Min)Min = mini[i];
		}
		printf("%d\n",Min);
	}
	return 0;
}
void pushup(int m){
	tr[m].sum = tr[m<<1].sum+ tr[m<<1|1].sum;
}
void build(int m,int l,int r){	
	tr[m].l=l;
	tr[m].r=r;
	if(l==r){
		tr[m].sum=0;
		return;
	}
	int mid = (l+r)>>1;
	build(m<<1,l,mid);
	build(m<<1|1,mid+1,r);
	pushup(m);
}
void update(int m,int index,int val){
	if(tr[m].l==index&&tr[m].r==index){
		tr[m].sum+=val;
		return;
	}
	int mid = (tr[m].r+tr[m].l)>>1;
	if(index>mid)update(m<<1|1,index,val);
	else if(index<=mid)update(m<<1,index,val);
	pushup(m);
}
int query(int m,int l, int r){	
	if(tr[m],l==l&&tr[m].r==r){
		return tr[m].sum;
	}
	int mid =(tr[m].r+tr[m].l)>>1;
	int temp;
	if(r<=mid)temp = query(m<<1,l,r);
	else if(l>mid)temp = query(m<<1|1,l,r);
	else temp = query(m<<1,l,mid)+query(m<<1|1,mid+1,r);
	return temp;
}