P17642 [ICPC 2019 Yinchuan R] Largest Common Submatrix 题解
赛时没调出来。
代码进行了折叠,最好自己写哦,有助于对知识点的理解。
实则是码风不好。
欢迎提出疑问,指出错误。
思路
1.
看到最大的公共子矩阵,聪明的你肯定想到了 P1439,举一反三通过离散化识别是否相邻,以及相邻方向。
于是我们可以以其中一个矩阵为基础离散化。
code
for(int i=1; i<=n; i++)
for(int j=1; j<=m; j++) {
cin>>a;
p[a]=(i-1)*(m+1)+j;
}
for(int i=1; i<=n; i++)
for(int j=1; j<=m; j++) {
cin>>b[i][j];
b[i][j]=p[b[i][j]];
}
你可能会疑惑(也可能不疑惑),为什么要乘 \(m+1\) 而不是 \(m\)?
因为我们要通过离散化后的数值判断是否相邻,如若不加一,会导致后续步骤将每行的最后一个与下一行的第一个识别为左右相邻。
可结合下方例子理解:
3 3
1 2 3
4 5 6
7 8 9
3 4 5
6 7 8
1 2 4
后续过程会将 3 和 4 识别为左右相邻,导致错误。
2.
聪明的你又想到既然已经离散化,可以将每个点向右、向下的最长合法延伸距离求出来。
code
for(int i=n; i>0; i--)
for(int j=m; j>0; j--) {
s[i][j][0]=s[i][j][1]=1;
if(b[i][j+1]==b[i][j]+1)
s[i][j][0]+=s[i][j+1][0];
if(b[i+1][j]==b[i][j]+m+1)
s[i][j][1]+=s[i+1][j][1];
}
你可能会疑惑,为什么没有什么可疑惑的,我也不知道。
3.
接下来的思路就非常清晰了,思路有很多:
三个也是多。
我是用单调栈实现。
code
check 函数
void check() {
int len=0;
while(!st.empty()) {
node t=st.top();
st.pop();
len+=t.num;
maxn=max(maxn,t.h*len);
}
}
单调栈
for(int i=1; i<=n; i++) {
for(int j=1; j<=m; j++) {
if(s[i][j-1][0]==1)
check();
int cnt=0;
while(!st.empty()&&st.top().h>=s[i][j][1]) {
node t=st.top();
st.pop();
cnt+=t.num;
maxn=max(maxn,cnt*t.h);
}
cnt++;
st.push({s[i][j][1],cnt});
maxn=max(maxn,s[i][j][1]*cnt);
}
check();
}
cout<<maxn;
有关复杂度
时间:\(O(nm)\)。
空间:\(O(nm)\)。
code
屏幕前的 dalao 肯定不屑于看吧。
code
#include<bits/stdc++.h>
using namespace std;
const int N=1e3+3;
struct node {
int h,num;
};
int b[N][N],p[N*N],s[N][N][2],maxn;
stack<node> st;
void check() {
int len=0;
while(!st.empty()) {
node t=st.top();
st.pop();
len+=t.num;
maxn=max(maxn,t.h*len);
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n,m,a;
cin>>n>>m;
for(int i=1; i<=n; i++)
for(int j=1; j<=m; j++) {
cin>>a;
p[a]=(i-1)*(m+1)+j;
}
for(int i=1; i<=n; i++)
for(int j=1; j<=m; j++) {
cin>>b[i][j];
b[i][j]=p[b[i][j]];
}
for(int i=n; i>0; i--)
for(int j=m; j>0; j--) {
s[i][j][0]=s[i][j][1]=1;
if(b[i][j+1]==b[i][j]+1) s[i][j][0]+=s[i][j+1][0];
if(b[i+1][j]==b[i][j]+m+1) s[i][j][1]+=s[i+1][j][1];
}
for(int i=1; i<=n; i++) {
for(int j=1; j<=m; j++) {
if(s[i][j-1][0]==1)
check();
int cnt=0;
while(!st.empty()&&st.top().h>=s[i][j][1]) {
node t=st.top();
st.pop();
cnt+=t.num;
maxn=max(maxn,cnt*t.h);
}
cnt++;
st.push({s[i][j][1],cnt});
maxn=max(maxn,s[i][j][1]*cnt);
}
check();
}
cout<<maxn;
return 0;
}
结语
谢谢你,谢谢你读我的文章。

浙公网安备 33010602011771号