[GXOI/GZOI2019]與或和

嘟嘟嘟


在GX大佬cyh的提議下,我就開了這道題。


看到位運算,就想到每一位單獨考慮。
那麼對於\(AND\)操做,咱們只要找全是1的子矩陣個數。
對於\(OR\)操做,用子矩陣總數-全0子矩陣個數便可。
這樣就有一個\(O(n ^ 4 logN)\)\(N\)是值域)的作法了,能夠拿到50分。
而後我就沒想出來。


如今的瓶頸在於找全1的子矩陣。
觀察發現,對於同一列的點,若是從下往上掃,以這個點爲左上角的全1子矩陣的寬必定是單調不增的,因而對於每一列,咱們維護一個單調棧,同時維護棧內元素的和便可。
複雜度\(O(n ^ 2logN)\)ios

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<queue>
#include<vector>
#include<ctime>
#include<assert.h>
using namespace std;
#define enter puts("")
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define In inline
#define forE(i, x, y) for(int i = head[x], y; (y = e[i].to) && ~i; i = e[i].nxt)
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;
const db eps = 1e-8;
const int maxn = 1e3 + 5;
const ll mod = 1e9 + 7;
In ll read()
{
    ll ans = 0;
    char ch = getchar(), las = ' ';
    while(!isdigit(ch)) las = ch, ch = getchar();
    while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
    if(las == '-') ans = -ans;
    return ans;
}
In void write(ll x)
{
    if(x < 0) putchar('-'), x = -x;
    if(x >= 10) write(x / 10);
    putchar(x % 10 + '0');
}
In void MYFILE()
{
#ifndef mrclr
    freopen("ha.in", "r", stdin);
    freopen("ha.out", "w", stdout);
#endif
}

int n, a[maxn][maxn];

In ll inc(ll a, ll b) {return a + b < mod ? a + b : a + b - mod;}

#define pr pair<int, int>
#define mp make_pair
#define fir first
#define sec second
pr st[maxn];
int b[maxn][maxn], rMax[maxn][maxn], top = 0;
In ll solve(int x, bool flg)
{
    for(int i = 1; i <= n; ++i)
        for(int j = 1; j <= n; ++j) b[i][j] = ((a[i][j] >> x) & 1) ^ flg;
    for(int i = 1; i <= n; ++i)
        for(int j = n; j; --j) rMax[i][j] = b[i][j] ? max(1, rMax[i][j + 1] + 1) : 0;
    ll ret = 0, tot = 0;
    for(int j = 1; j <= n; ++j)
    {
        tot = top = 0;
        for(int i = n; i; --i)
        {
            int tp = 1;
            while(top && st[top].fir >= rMax[i][j]) 
            {
                tot = inc(tot, mod - st[top].sec * st[top].fir % mod);
                tp += st[top].sec, --top;   
            }
            if(rMax[i][j])
            {
                tot = inc(tot, tp * rMax[i][j] % mod);
                st[++top] = mp(rMax[i][j], tp);
                ret = inc(ret, tot);
            }
        }
    }
    return ret;
}

int main()
{
//  MYFILE();
    n = read();
    for(int i = 1; i <= n; ++i)
        for(int j = 1; j <= n; ++j) a[i][j] = read();
    ll tot = 0;
    for(int i = 1; i <= n; ++i)
        for(int j = 1; j <= n; ++j) tot = inc(tot, i * j);
    ll ans1 = 0, ans2 = 0, tp = 1;
    for(int x = 0; x < 31; ++x, tp = (tp << 1) % mod)
    {
        ans1 = inc(ans1, solve(x, 0) * tp % mod);
        ans2 = inc(ans2, inc(tot, mod - solve(x, 1)) * tp % mod);
    }
    write(ans1), space, write(ans2), enter;
    return 0;
}
相關文章
相關標籤/搜索