POJ 2029 Get Many Persimmon Trees(二維樹狀數組)

超級傳送門:http://poj.org/problem?id=2029


題意:一塊W*H的矩形區域,每一小塊可能有柿子樹,讓你用一個S*T的矩形選擇,問最多能選中幾棵柿子樹。(注意S和T不能倒置,題目給你3 5和5 3是不一樣的做法)。


分析:典型的二維樹狀數組,枚舉矩形起點,求和,取最大值,注意邊界。


代碼:

#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 505;
int n,w,h;
int c[maxn][maxn];
int lowbit(int t) {
    return t & -t;
}
int getsum(int x,int y) {
    int ret = 0;
    for (int i=x;i>=1;i-=lowbit(i)) {
        for (int j=y;j>=1;j-=lowbit(j)) {
            ret += c[i][j];
        }
    }
    return ret;
}
void update(int x,int y,int val) {
    for (int i=x;i<=w;i+=lowbit(i)) {
        for (int j=y;j<=h;j+=lowbit(j)) {
            c[i][j] += val;
        }
    }
}
int main () {
    #ifndef ONLINE_JUDGE
        freopen("1.txt","r",stdin);
    #endif
    int s,t,x,y;
    while (scanf("%d",&n)>0 && n) {
        memset(c,0,sizeof(c));
        scanf("%d%d",&w,&h);
        for (int i=1;i<=n;i++) {
            scanf("%d%d",&x,&y);
            update(x,y,1);
        }
        scanf("%d%d",&s,&t);
        int max = 0;
        for (int i=s;i<=w;i++) {
            for (int j=t;j<=h;j++) {
                int ans = getsum(i,j)-getsum(i-s,j)-getsum(i,j-t)+getsum(i-s,j-t);
                max = max>ans?max:ans;
           }
        }
        printf("%d\n",max);
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章