题意:给n个数,q次询问,(L,R)区间内的逆序数。
思路: 区间dp
代码一:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e3+10;
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
inline ll read(){
ll x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
//
int a[maxn],dp[maxn][maxn];
int main(){
int n,q; n = read(), q = read();
for(int i=1; i<=n; i++)
a[i] = read();
for(int len=1; len<n; len++)
for(int i=1; i+len<=n; i++){
int j = i+len;
dp[i][j] = dp[i+1][j] + dp[i][j-1] - dp[i+1][j-1];
if(a[i] > a[j])
dp[i][j]++;
}
for(int i=0; i<q; i++){
int l,r; l=read(),r=read();
cout << dp[l][r] << endl;
}
return 0;
}
dp[i][j], 先求出每个i为起始位置的逆序数, dp[i][j] = dp[i][j-1];
再移动i,求出任意(L,R)区间内的逆序数。 dp[i][j] = dp[i+1][j];
代码二:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e3+10;
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
inline ll read(){
ll x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
//
int a[maxn],dp[maxn][maxn];
int main(){
int n,q; n=read(),q=read();
for(int i=1; i<=n; i++)
a[i] = read();
for(int i=1; i<=n; i++){ //dp[i][j]是[i,j]区间里i为起始位置的倒置数对
for(int j=i+1; j<=n; j++)
if(a[i] > a[j]){
dp[i][j]++;
// cout << "111dp[" << i << "][" << j << "] = " << dp[i][j] << endl;
}
for(int j=i+1; j<=n; j++){
dp[i][j] += dp[i][j-1];
// cout << "222dp[" << i << "][" << j << "] = " << dp[i][j] << endl;
}
}
for(int i=n-1; i>=1; i--) //再枚举[i,j]这个区间里面任意一个数为起始位置,含有的倒置数对
for(int j=i+1; j<=n; j++){
dp[i][j] += dp[i+1][j];
// cout << "333dp[" << i << "][" << j << "] = " << dp[i][j] << endl;
}
while(q--){
int l,r; l=read(),r=read();
cout << dp[l][r] << endl;
}
return 0;
}