二维dp

题目:https://ac.nowcoder.com/acm/contest/332/E

分析:就是一个二维的dp,注意动态数组申请方法,vector<vector<int> >a(n,vector<int>(m,0))表示的是申请n*m的二维数组,但此时并未真正申请空间,还要a.resize(n), for(int i=0;i<n;i++) a[i].resize(m)才算申请了空间

本题需注意:边界,包不包含边界,对边界要分类讨论

Ac code:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e3+1;
int n,m;
vector<vector<ll> >a;
vector<vector<ll> >dp;
int main()
{
    int n,m;
    ll d,x;
    int q;
    scanf("%d%d%lld",&n,&m,&d);
    a.resize(n);
    for(int i=0; i<n; i++) a[i].resize(m);
    for(int i=0; i<n; i++)
        for(int j=0; j<m; j++)
            scanf("%lld",&a[i][j]);
    dp.resize(n);
    for(int i=0; i<n; i++) dp[i].resize(m);
    dp[0][0]=a[0][0]>=d?1:0;
    for(int i=0; i<n; i++)
    {
        for(int j=0; j<m; j++)
        {
            if(i==0&&j==0) continue;
            if(i==0&&j>0) dp[i][j]=dp[i][j-1]+(a[i][j]>=d);
            else if(i>0&&j==0) dp[i][j]=dp[i-1][j]+(a[i][j]>=d);
            else dp[i][j]=dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1]+(a[i][j]>=d?1:0);
        }
    }
    int x1,y1,x2,y2;
    scanf("%d",&q);
    while(q--)
    {
        ll ans=0;
        scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
        --x1,--y1,--x2,--y2;
        if(x1==0&&y1==0) ans=dp[x2][y2];
        else if(x1==0) ans=dp[x2][y2]-dp[x2][y1-1];
        else if(y1==0) ans=dp[x2][y2]-dp[x1-1][y2];
        else ans=dp[x2][y2]+dp[x1-1][y1-1]-dp[x2][y1-1]-dp[x1-1][y2];
        printf("%lld\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/shaohang_/article/details/86751607