45分暴力
可以发现,根据题目给的条件,我们可以直接暴力模拟(暴力法)来求。但是,这种做法的时间复杂度在平均情况下是 的,所以可以轻松通过测试。但是,再最坏情况下,时间复杂度为 ,在 时无法通过测试,具体请看我在讨论区发的帖。
代码
#include<bits/stdc++.h>
#define N (int)(2e3+1e1)
using namespace std;
long long n,m,x,y,tp,ans;
int mv[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
long long s[2][N][N];
void update(){
for(int i=1;i<=n;++i){
for(int j=1;j<=m;++j){
long long std=s[0][i][j];
for(int k=0;k<=3;++k){
int dx=i+mv[k][0],dy=j+mv[k][1];
std=__gcd(std,s[0][dx][dy]);
}
s[1][i][j]=std;
}
}
for(int i=1;i<=n;++i){
for(int j=1;j<=m;++j) s[0][i][j]=s[1][i][j];
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin>>n>>m;
for(int i=1;i<=n;++i){
for(int j=1;j<=m;++j){
cin>>s[0][i][j];
tp=__gcd(tp,s[0][i][j]);
}
}
cin>>x>>y;
if(tp!=1){
cout<<-1<<endl;
} else {
while(s[0][x][y]!=1) update(),++ans;
cout<<ans<<endl;
}
return 0;
}100分做法
既然直接模拟无法成功,我们就可以考虑二分时间 。
范围
如何确定时间界限?可以发现,在矩阵
,其中 中,经过一次求最大公约数可以得到
容易发现,当 时,全图均变为 。
下限容易得到:。所以,二分代码应该这样写:
while(R>=L){
mid=L+((R-L)>>1);
if(check(mid)) R=mid-1;
else L=mid+1;
}检查
接着,我们要写 check 函数。由于 ,可以得到,在 天后,位于 坐标的数会变为在距离 的曼哈顿距离 的最大公约数。于是,check 函数就好写了:
bool check(int p){
long long gd=a[x][y];
for(int i=1;i<=n;++i){
for(int j=1;j<=m;++j){
if(abs(i-x)+abs(j-y)<=p){
gd=__gcd(gd,a[i][j]);
}
}
}
if(gd==1) return true;
else return false;
}特判
- 假如永远都不可能得到 ,那么全图所有数字的最大公约数不等于 。
- 若 的位置原本为 ,输出 。 特判代码:
if(a[x][y]==1){
cout<<0<<endl;
return 0;
} else if(!check(R)){
cout<<-1<<endl;
return 0;
}复杂度分析
一次 check 函数的复杂度为 ,而二分的复杂度为 ,所以总复杂度为 ,可以通过测试。
代码
#include<bits/stdc++.h>
#define N (int)(2e3+1e1)
using namespace std;
long long n,m,a[N][N],L=1,R,mid,x,y;
bool check(int p){
long long gd=a[x][y];
for(int i=1;i<=n;++i){
for(int j=1;j<=m;++j){
if(abs(i-x)+abs(j-y)<=p){
gd=__gcd(gd,a[i][j]);
}
}
}
if(gd==1) return true;
else return false;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin>>n>>m;
R=n+m-1;
for(int i=1;i<=n;++i){
for(int j=1;j<=m;++j) cin>>a[i][j];
}
cin>>x>>y;
if(a[x][y]==1){
cout<<0<<endl;
return 0;
} else if(!check(R)){
cout<<-1<<endl;
return 0;
}
while(R>=L){
mid=L+((R-L)>>1);
if(check(mid)) R=mid-1;
else L=mid+1;
}
cout<<L<<endl;
return 0;
}