hdu 5273 Dylans loves sequence 逆序数 区间dp

点击打开链接

题意:给n个数,q次询问,(L,R)区间内的逆序数。


思路: 区间dp

代码一:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 const int maxn = 1e3+10;
 5 const int INF = 0x3f3f3f3f;
 6 const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
 7 inline ll read(){
 8     ll x=0,f=1;char ch=getchar();
 9     while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
10     while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
11     return x*f;
12 }
13 //////////////////////////////////////////////////////////////////////////
14 
15 int a[maxn],dp[maxn][maxn];
16 
17 int main(){
18     int n,q; n = read(), q = read();
19     for(int i=1; i<=n; i++)
20         a[i] = read();
21     for(int len=1; len<n; len++)
22         for(int i=1; i+len<=n; i++){
23             int j = i+len;
24             dp[i][j] = dp[i+1][j] + dp[i][j-1] - dp[i+1][j-1];
25             if(a[i] > a[j])
26                 dp[i][j]++;
27         }
28     for(int i=0; i<q; i++){
29         int l,r; l=read(),r=read();
30         cout << dp[l][r] << endl;
31     }
32 
33     return 0;
34 }

思路二:

dp[i][j], 先求出每个i为起始位置的逆序数, dp[i][j] = dp[i][j-1];

再移动i,求出任意(L,R)区间内的逆序数。 dp[i][j] = dp[i+1][j];

代码二:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 const int maxn = 1e3+10;
 5 const int INF = 0x3f3f3f3f;
 6 const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
 7 inline ll read(){
 8     ll x=0,f=1;char ch=getchar();
 9     while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
10     while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
11     return x*f;
12 }
13 //////////////////////////////////////////////////////////////////////////
14 
15 int a[maxn],dp[maxn][maxn];
16 
17 int main(){
18     int n,q; n=read(),q=read();
19     for(int i=1; i<=n; i++)
20         a[i] = read();
21 
22     for(int i=1; i<=n; i++){ //dp[i][j]是[i,j]区间里i为起始位置的倒置数对
23         for(int j=i+1; j<=n; j++)
24             if(a[i] > a[j]){
25                 dp[i][j]++;
26                 // cout << "111dp[" << i << "][" << j << "] = " << dp[i][j] << endl;
27             }
28         for(int j=i+1; j<=n; j++){
29             dp[i][j] += dp[i][j-1];
30             // cout << "222dp[" << i << "][" << j << "] = " << dp[i][j] << endl;
31         }
32     }
33 
34     for(int i=n-1; i>=1; i--) //再枚举[i,j]这个区间里面任意一个数为起始位置,含有的倒置数对
35         for(int j=i+1; j<=n; j++){
36             dp[i][j] += dp[i+1][j];
37             // cout << "333dp[" << i << "][" << j << "] = " << dp[i][j] << endl;
38         }
39     while(q--){
40         int l,r; l=read(),r=read();
41         cout << dp[l][r] << endl;
42     }
43 
44     return 0;
45 }
原文地址:https://www.cnblogs.com/yxg123123/p/6827720.html