题解 (by;zjvarphi)
现特判,如果存在相邻的点相等,那么它可以来回走,所以直接输出 -1。
那么现在直接暴力搜索,可以发现最多只会走 (log) 步。
但是这样状态数还是太多,记忆化一下即可。
Code
#include<bits/stdc++.h>
#define ri signed
#define pd(i) ++i
#define bq(i) --i
#define func(x) std::function<x>
namespace IO{
char buf[1<<21],*p1=buf,*p2=buf;
#define gc() p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?(-1):*p1++
#define debug1(x) std::cerr << #x"=" << x << ' '
#define debug2(x) std::cerr << #x"=" << x << std::endl
#define Debug(x) assert(x)
struct nanfeng_stream{
template<typename T>inline nanfeng_stream &operator>>(T &x) {
bool f=false;x=0;char ch=gc();
while(!isdigit(ch)) f|=ch=='-',ch=gc();
while(isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48),ch=gc();
return x=f?-x:x,*this;
}
}cin;
}
using IO::cin;
namespace nanfeng{
#define ch(x,y) (x-1)*m+(y)
#define FI FILE *IN
#define FO FILE *OUT
template<typename T>inline T cmax(T x,T y) {return x>y?x:y;}
template<typename T>inline T cmin(T x,T y) {return x>y?y:x;}
static const int N=4e4+7;
struct edge{int v,nxt;}e[N<<2];
int first[N],w[N],dp[N][330],t=1,n,m,al,ans;
int dx[]={0,1,0,-1},dy[]={1,0,-1,0};
bool fg;
auto add=[](int u,int v) {e[t]={v,first[u]},first[u]=t++;};
func(int(int,int)) dfs=[](int x,int nw) {
if (nw<=300&&dp[x][nw]) return dp[x][nw];
int cur=0;
for (ri i(first[x]),v;i;i=e[i].nxt)
if (1ll*nw*w[x]==1ll*w[v=e[i].v]) cur=cmax(cur,dfs(v,nw));
else if (!nw&&!(w[e[i].v]%w[x])) cur=cmax(cur,dfs(v,w[e[i].v]/w[x]));
if (nw<=300) dp[x][nw]=cur+1;
return cur+1;
};
inline int main() {
FI=freopen("matrix.in","r",stdin);
FO=freopen("matrix.out","w",stdout);
cin >> n >> m;
for (ri i(1);i<=n;pd(i))
for (ri j(1);j<=m;pd(j)) {
int cur=ch(i,j);
cin >> w[cur];
}
for (ri i(1);i<=n;pd(i))
for (ri j(1);j<=m;pd(j)) {
int cur=ch(i,j);
for (ri k(0);k<4;pd(k)) {
int ti=i+dx[k],tj=j+dy[k],nw=ch(ti,tj);
if (ti<1||ti>n||tj<1||tj>m) continue;
add(cur,nw);
}
}
al=n*m;
for (ri i(1);i<=al;pd(i))
for (ri j(first[i]);j;j=e[j].nxt) if (w[i]==w[e[j].v]) {fg=true;break;}
if (fg) return printf("-1"),0;
for (ri i(1);i<=al;pd(i)) ans=cmax(ans,dfs(i,0));
printf("%d
",ans);
return 0;
}
}
int main() {return nanfeng::main();}