hdu5273(区间DP)

题意:

给出一个区间,问这个区间逆序对有几对;


思路:

[l, r]的逆序对就等于[l + 1, r] + [l, r- 1] - [l + 1, r - 1]如果l 和 r也构成逆序对,就再加一;


#include 
#include 

const int N = 1005;
int dp[N][N], num[N];

int main() {
	memset(dp, 0, sizeof(dp));
	int n, q;
	scanf("%d%d", &n, &q);
	for (int i = 1; i <= n; i++) {
		scanf("%d", &num[i]);
	}
	for (int len = 1; len < n; len++) {
		for (int l = 1; l + len <= n; l++) {
			int r = l + len;
			dp[l][r] = dp[l][r - 1] + dp[l + 1][r] - dp[l + 1][r - 1];
			if (num[l] > num[r])
				dp[l][r]++;
		}
	}
	int l, r;
	while (q--) {
		scanf("%d%d", &l, &r);
		printf("%d\n", dp[l][r]);
	}
	return 0;
}


你可能感兴趣的:(DP)