hdu5273(区间逆序对的个数)

  题目的大致意思是有一个数组,然后有Q个询问,对于每次询问给出L和R,然后要给出每次L和R区间内的逆序对个数。

  解答方法就是先算出ans[0][1...N-1]的结果,然后根据再来算ans[i][i+1...N-1](0

#include "stdio.h"
#include "string.h"
#include "math.h"
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

#define MAXM 1
#define MAXN 1
#define max(a,b) a > b ? a : b
#define min(a,b) a < b ? a : b
#define Mem(a,b) memset(a,b,sizeof(a))
int Mod = 1000000007;
double pi = acos(-1.0);
double eps = 1e-6;

typedef struct{
	int f,t,w,next;
}Edge;
Edge edge[MAXM];
int head[MAXN];
int kNum;
typedef long long LL;

void addEdge(int f, int t, int w)
{
	edge[kNum].f = f;
	edge[kNum].t = t;
	edge[kNum].w = w;
	edge[kNum].next = head[f];
	head[f] = kNum ++;
}

int dp[1005][1005];
int cnt[1005];
int num[1005];
int N, Q;

void solve(){
	cin>>Q;
	Mem(cnt, 0);
	Mem(dp, 0);
	for(int i = 0; i < N; i ++){
		scanf("%d",&num[i]);
	}

	for(int i = 1; i < N; i ++){
		dp[0][i] = dp[0][i-1];
		for(int j = 0; j < i; j ++){
			if(num[i] < num[j])
				dp[0][i] ++;
		}
	}
	
	int jichu; //累加器
	for(int i = 1; i < N; i ++){
		if( num[i] < num[i-1] ) jichu = 1;
		else jichu = 0;
		for(int j = i + 1;j < N; j ++){
			if( num[j] < num[i-1] ) jichu ++;
			dp[i][j] = dp[i-1][j] - jichu;
		}
	}


	/*for(int i = 1; i < N; i ++){
		cnt[i] = cnt[i-1];
		for(int j = 0; j < i; j ++){
			if( num[i] < num[j] )
				cnt[i] ++;
		}
	}*/

	int L, R;
	for(int i = 0; i < Q; i ++){
		scanf("%d %d", &L, &R);
		printf("%d\n",dp[L-1][R-1]);
	}

}


int main()
{
//	freopen("d:\\test.txt", "r", stdin);
	while(cin>>N){
		solve();
	}

	return 0;
}


你可能感兴趣的:(Algorithm)