[USACO12MAR]Tractor S
P1849 [USACO12MAR]Tractor S - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
转换为最短路问题,有稻草的权值为1,没有的为0,向没有稻草的点移动放在队列顶端,向有稻草的点移动放队列末端,这样队列中前面一部分和后面一部分差值最大为1
#include<bits/stdc++.h>
using namespace std;
#define lint long long
#define pb push_back
#define pf push_front
const int xx[4]={1,-1,0,0},yy[4]={0,0,-1,1};
int d[1010][1010]={0},ans[1010][1010],mp[1010][1010]={0};
deque<int> vx,vy,vstep;
int main(){
int n,x0,y0;
cin >> n >> x0 >> y0;
for(int i=1;i<=n;i++){
int xc,yc;
scanf("%d%d",&xc,&yc);
mp[xc][yc]=1;
}
memset(ans,-1,sizeof(ans));
vx.pb(x0);
vy.pb(y0);
vstep.pb(0);
d[x0][y0]=1;
int x,y,step;
while(vx.empty()==0){
x=vx.front();
y=vy.front();
ans[x][y]=vstep.front();
vx.erase(vx.begin());
vy.erase(vy.begin());
vstep.erase(vstep.begin());
if(x==0 && y==0) break;
for(int i=0;i<4;i++)
if(x+xx[i]<=x0*2+1 && y+yy[i]<=y0*2+1 && x+xx[i]>=0 && y+yy[i]>=0 && d[x+xx[i]][y+yy[i]]==0){
if(mp[x+xx[i]][y+yy[i]]==1) {
vx.pb(x+xx[i]);
vy.pb(y+yy[i]);
vstep.pb(ans[x][y]+1);
}
else {
vx.pf(x+xx[i]);
vy.pf(y+yy[i]);
vstep.pf(ans[x][y]);
}
d[x+xx[i]][y+yy[i]]=1;
}
}
cout << ans[0][0];
return 0;
}