統計01矩陣中全1子矩陣的個數
一、51Nod 1291
題意:600*600的01矩陣,統計寬i高j的全1矩陣的個數。html
題解:枚舉矩陣的下邊界,對於每一個下邊界,統計全部寬極大的矩形的答案(高度能夠用差分)。$n^2$ 統計完以後,咱們已知全部高度的寬極大的答案,列一下式子發現兩次前綴和就是最後答案。c++
代碼:spa
#include<bits/stdc++.h> using namespace std; #define fi first #define se second #define mp make_pair #define pb push_back #define rep(i, a, b) for(int i=(a); i<(b); i++) #define sz(x) (int)x.size() #define de(x) cout<< #x<<" = "<<x<<endl #define dd(x) cout<< #x<<" = "<<x<<" " typedef long long ll; typedef pair<int, int> pii; typedef vector<int> vi; const int N=666; int n,m,top; int u[N], sta[N]; ll c[N][N]; char s[N]; int main() { scanf("%d%d",&n,&m); rep(i,1,n+1) { scanf("%s",s+1); rep(j,1,m+1) u[j]=(s[j]=='1')?u[j]+1:0; top=0; sta[++top]=0; rep(j,1,m+2) { while(u[sta[top]]>u[j]) { ++c[max(u[sta[top-1]], u[j])+1][j-sta[top-1]-1]; --c[u[sta[top]]+1][j-sta[top-1]-1]; --top; } while(top&&u[sta[top]]==u[j]) --top; sta[++top]=j; } } rep(i,2,n+1) rep(j,1,m+1) c[i][j]+=c[i-1][j]; rep(i,1,n+1) { for(int j=m-1;j;--j) c[i][j]+=c[i][j+1]; for(int j=m-1;j;--j) c[i][j]+=c[i][j+1]; } rep(i,1,n+1) rep(j,1,m+1) printf("%lld%c",c[i][j]," \n"[j==m]); return 0; }
二、Wannafly挑戰賽12 D
題意:1e9*1e9的01矩陣,1的個數5000個,統計全0矩陣的個數。code
題解:全部狀況 減去 包含1的。對於每一個1,統計以它爲最上左的答案。htm
代碼:get
#include<bits/stdc++.h> using namespace std; #define fi first #define se second #define mp make_pair #define pb push_back #define rep(i, a, b) for(int i=(a); i<(b); i++) #define sz(x) (int)x.size() #define de(x) cout<< #x<<" = "<<x<<endl #define dd(x) cout<< #x<<" = "<<x<<" " typedef long long ll; typedef pair<int, int> pii; typedef vector<int> vi; const int N=5050, P=1e9+7; int n,m,c,ans; pii a[N]; ll kpow(ll a, ll b) { ll res=1; while(b) { if(b&1) res=res*a%P; a=a*a%P; b>>=1; } return res; } void upd(int &a, ll b) { a+=b; if(a>=P) a-=P; } int main() { scanf("%d%d%d",&n,&m,&c); rep(i,1,c+1) { int x,y;scanf("%d%d",&x,&y); a[i]=mp(x, y); } sort(a+1, a+1+c); rep(i,1,c+1) { int l=1, r=m; for(int j=i-1;~j;--j) { if(a[j].fi!=a[j+1].fi) upd(ans, 1ll*(n-a[i].fi+1)*(a[j+1].fi-a[j].fi)%P*(r-a[i].se+1)%P*(a[i].se-l+1)%P); if(a[j].se<=a[i].se) l=max(l, a[j].se+1); if(a[j].se>=a[i].se) r=min(r, a[j].se-1); } } printf("%lld\n",(1ll*n*(n+1)%P*m%P*(m+1)%P*kpow(4, P-2)%P-ans+P)%P); return 0; }