Codeforces 628E Zbazi in Zeydabad 树状数组

题意:一个n*m的矩阵,要么是 . 要么是 z ,问可以形成几个大z

分析:(直接奉上官方题解,我感觉说的实在是太好了)

Let's precalculate the values zlij, zrij, zldij — the maximal number of letters 'z' to the left, to the right and to the left-down from the position (i, j). It's easy to do in O(nm) time. Let's fix some cell (i, j). Consider the value c = min(zlij, zldij).  It's the maximum size of the square with upper right ceil in (i, j). But the number of z-patterns can be less than c.  Consider some cell (x, y) diagonally down-left from (i, j) on the distance no more than c. The cells (i, j) and (x, y) forms z-pattern if y + zrxy > j.

Let's maintain some data structure for each antidiagonal (it can be described by formula x + y) that can increment in a point and take the sum on a segment (Fenwick tree will be the best choice for that). Let's iterate over columns j from the right to the left and process the events: we have some cell (x, y) for which y + zrxy - 1 = j. In that case we should increment the position y in the tree number x + y by one.  Now we should iterate over the cells (x, y) in the current column and add to the answer the value of the sum on the segment from j - c + 1 to j in the tree number i + j .

 

 补充:这样从右到左更新,当更新第j列的时候,每一条对角线上的 能够向右延伸到大于等于j的"z"都已经更新完毕,直接统计就行

时间复杂度O(nmlogm)

代码:

#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;
typedef long long LL;
const int N = 3e3+5;
char s[N][N];
short l[N][N],r[N][N],x[N][N];
int n,m;
short c[N*2][N];
void add(int x,int i)
{
    for(; i<=m; i+=(i&(-i)))
        c[x][i]++;
}
int sum(int x,int i)
{
    int res=0;
    for(; i>0; i-=(i&(-i)))
        res+=c[x][i];
    return res;
}
struct Point
{
    int x,y;
};
vector<Point>g[N];
int main()
{
    LL ans=0;
    scanf("%d%d",&n,&m);
    for(int i=1; i<=n; ++i)
        scanf("%s",s[i]+1);
    for(int i=1; i<=n; ++i)
    {
        for(int j=1,k=m; j<=m; ++j,--k)
        {
            if(s[i][j]=='z')l[i][j]=l[i][j-1]+1;
            if(s[i][k]=='z')r[i][k]=r[i][k+1]+1;
        }
    }
    for(int j=1; j<=m; ++j)
    {
        for(int i=1; i<=n; ++i)
        {
            if(s[i][j]=='.')continue;
            x[i][j]=x[i+1][j-1]+1;
        }
    }
    for(int i=1; i<=n; ++i)
        for(int j=1; j<=m; ++j)
            if(s[i][j]=='z')
                g[j+r[i][j]-1].push_back(Point {i,j});
    for(int j=m; j>=1; --j)
    {
        for(int i=0; i<g[j].size(); ++i)
        {
            int t=g[j][i].x+g[j][i].y;
            add(t,g[j][i].y);
        }
        for(int i=1; i<=n; ++i)
        {
            if(s[i][j]=='.')continue;
            int p=min(l[i][j],x[i][j]);
            ans+=sum(i+j,j)-sum(i+j,j-p);
        }
    }
    printf("%I64d\n",ans);
    return 0;
}
View Code

 

posted @ 2016-02-24 20:41  shuguangzw  阅读(310)  评论(0编辑  收藏  举报