2019ICPC(银川) - Largest Common Submatrix(单调栈)
題目鏈接:點(diǎn)擊查看
題目大意:給出兩個(gè)n*m的矩陣,問(wèn)最大的公共子矩陣的面積是多少
題目分析:一開(kāi)始看到這個(gè)題目是想到了一個(gè)n^4的算法。。就是暴力枚舉,肯定是不行的了,最后的時(shí)候還是隊(duì)友把思路一步步轉(zhuǎn)正,最終把這個(gè)題出了,首先我們肯定不能枚舉所有的子矩陣,所以我們必須換個(gè)思路
因?yàn)檫@個(gè)矩陣中所有的數(shù)都是1~n*m的全排列,這一點(diǎn)讓我比較在意,可以利用到的信息就是在第一個(gè)矩陣中隨便找一個(gè)數(shù)都可以用O(1)時(shí)間在第二個(gè)矩陣中查找其相應(yīng)的位置,有了這一點(diǎn)之后我們發(fā)現(xiàn)就可以對(duì)于每一個(gè)點(diǎn)(i,j)維護(hù)該點(diǎn)可以向右擴(kuò)大的最大長(zhǎng)度,所謂擴(kuò)大也就是向右邊找最大相等的長(zhǎng)度,這樣用n*m的時(shí)間復(fù)雜度維護(hù)一個(gè)dp[i][j],再枚舉每一列,將整個(gè)矩陣逆時(shí)針旋轉(zhuǎn)90度,問(wèn)題就轉(zhuǎn)換成了以每一列為底的的一個(gè)求最大矩陣的問(wèn)題了,單調(diào)棧的模板問(wèn)題,但現(xiàn)在還有一個(gè)小問(wèn)題,就是相鄰兩行并不一定都是連續(xù)的,所以我們需要再維護(hù)一個(gè)dp2[i][j],用來(lái)維護(hù)每個(gè)點(diǎn)(i,j)向下可以擴(kuò)大的最大長(zhǎng)度,這樣我們就可以用dp2數(shù)組來(lái)確定向下的邊界了,最后套上單調(diào)棧的模板就變成模板題了
代碼:
#include<iostream> #include<cstdlib> #include<string> #include<cstring> #include<cstdio> #include<algorithm> #include<climits> #include<cmath> #include<cctype> #include<stack> #include<queue> #include<list> #include<vector> #include<set> #include<map> #include<sstream> #include<unordered_map> using namespace std;typedef long long LL;const int inf=0x3f3f3f3f;const int N=1e3+100;struct Pos {int x,y; }pos[N*N];struct Node {int h,w;Node(int H,int W){h=H;w=W;} };int dp[N][N],dp2[N][N];int maze[N][N],maze2[N][N];int main() { // freopen("input.txt","r",stdin); // ios::sync_with_stdio(false);int n,m;scanf("%d%d",&n,&m);for(int i=1;i<=n;i++)for(int j=1;j<=m;j++)scanf("%d",&maze[i][j]);for(int i=1;i<=n;i++)for(int j=1;j<=m;j++){scanf("%d",&maze2[i][j]);pos[maze2[i][j]].x=i;pos[maze2[i][j]].y=j;} for(int i=1;i<=n;i++)for(int j=m;j>=1;j--){int x1=i,y1=j;int x2=pos[maze[i][j]].x;int y2=pos[maze[i][j]].y;if(maze[x1][y1+1]==maze2[x2][y2+1])dp[x1][y1]=dp[x1][y1+1]+1;elsedp[x1][y1]=1;}for(int i=n;i>=1;i--)for(int j=1;j<=m;j++){int x1=i,y1=j;int x2=pos[maze[i][j]].x;int y2=pos[maze[i][j]].y;if(maze[x1+1][y1]==maze2[x2+1][y2])dp2[x1][y1]=dp2[x1+1][y1]+1;elsedp2[x1][y1]=1;}int ans=0;for(int i=1;i<=m;i++)//枚舉列{int mark=1;//行的下標(biāo) while(mark<=n){stack<Node>st;for(int j=mark;j<=mark+dp2[mark][i]-1;j++){int w=0;while(st.size()&&st.top().h>dp[j][i]){w+=st.top().w;ans=max(ans,w*st.top().h);st.pop();}st.push(Node(dp[j][i],w+1));}int w=0;while(st.size()){w+=st.top().w;ans=max(ans,w*st.top().h);st.pop();}mark+=dp2[mark][i];}} cout<<ans<<endl;return 0; }?
總結(jié)
以上是生活随笔為你收集整理的2019ICPC(银川) - Largest Common Submatrix(单调栈)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: POJ - 2893 M × N Puz
- 下一篇: 2019ICPC(银川) - Funct