ZOJ 3955 Saddle Point (树状数组)

来源:互联网 发布:app软件开发流程 编辑:程序博客网 时间:2024/06/05 13:40

H. Saddle Point

Chiaki has an n × m matrix A. Rows are numbered from 1 to n from top to bottom and columns are numbered from 1 to m from left to right. The element in the i-th row and the j-th column is Ai, j.

Let M({i1, i2, …, is}, {j1, j2, …, jt}) be the matrix that results from deleting row i1, i2, …, is and column j1, j2, …, jt of A and f({i1, i2, …, is}, {j1, j2, …, jt}) be the number of saddle points in matrix M({i1, i2, …, is}, {j1, j2, …, jt}).

Chiaki would like to find all the value of f({i1, i2, …, is}, {j1, j2, …, jt}). As the output may be very large ((2n1)(2m1) matrix in total), she is only interested in the value

1i1<<isn1j1<<jtm0s<n0t<mf({i1,i2,,is},{j1,j2,,jt})mod(109+7).

Note that a saddle point of a matrix is an element which is both the only largest element in its column and the only smallest element in its row.

解题思路

此题求原矩阵 A 删除若干行及若干列后产生的一个新的矩阵 Sub_A ,其中有多少个元素 Sub_Ai,j 。其中 Sub_Ai,j 需要满足其是矩阵 Sub_A 同一行唯一的最小元素及同一列唯一的最大元素。矩阵 A 共有 (2n1)(2m1) 种子矩阵。

此题需单独考虑矩阵 A 中每一个 Ai,j 对答案 ans 的贡献。Ai,j 对答案的贡献次数为 2revCi,j+revRi,j ,其中 revCi,j 表示矩阵 A 中同一列小于 Ai,j 的数的个数,revRi,j 表示矩阵 A 中同一行大于 Ai,j 的数的个数。

代码

#include<bits/stdc++.h>using namespace std;const int mod = 1e9 + 7;const int MAXN = 1000000 + 10;int n, m, A[1010][1010];int revR[1010][1010],   revC[1010][1010];long long pow2[2010] = {1ll};int bit[MAXN];int lowbit(int x){  return x & -x;  }void add(int x, int w){    for(int i=x;i<MAXN;i+=lowbit(i))        bit[i]+=w;}int get(int x){    int res = 0;    for(int i=x;i;i-=lowbit(i))        res += bit[i];    return res;}void init(){    for(int i=1;i<=2000;i++)    {        pow2[i] = pow2[i-1] * 2;        if(pow2[i] > mod)   pow2[i] %= mod;    }    for(int i=1;i<=n;i++)    {        for(int j=1;j<=m;j++)            add(A[i][j], 1);        for(int j=1;j<=m;j++)            revR[i][j] = get(MAXN-1) - get(A[i][j]);        for(int j=1;j<=m;j++)            add(A[i][j], -1);    }    for(int j=1;j<=m;j++)    {        for(int i=1;i<=n;i++)            add(A[i][j], 1);        for(int i=1;i<=n;i++)            revC[i][j] = get(A[i][j]-1);        for(int i=1;i<=n;i++)            add(A[i][j], -1);    }}int main(){    int T;    scanf("%d",&T);    while(T--)    {        scanf("%d %d",&n,&m);        for(int i=1;i<=n;i++)        for(int j=1;j<=m;j++)            scanf("%d", &A[i][j]);        init();        long long ans = 0;        for(int i=1;i<=n;i++)        for(int j=1;j<=m;j++)        {            ans += pow2[revC[i][j] + revR[i][j]];            if(ans > mod)   ans %= mod;        }        printf("%lld\n", ans);    }}
0 0
原创粉丝点击