hdu 5273 Dylans loves sequence 逆序数 区间dp
生活随笔
收集整理的這篇文章主要介紹了
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
總結
以上是生活随笔為你收集整理的hdu 5273 Dylans loves sequence 逆序数 区间dp的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 浦发信用卡签约分期可以撤销吗?怎么撤销?
- 下一篇: weui-switch开关控件,表单提交