版本比较
4.26
正文
增加 22 行删除 22 行
46 行未改动4748495051515253545556565758596061616263646565 行未改动1311321331341351351361371381397 行未改动1471481491501511511521531531541551551561571581591591601611621631641651651661671681691691701711721731741751761761771781791806 行未改动18718818919019119119219319419542 行未改动2382392402412422422432442452462472472482492502512512522532542559 行未改动2652662672682692692702712722732742752762772772782792802817 行未改动2892902912922932932942952952962972982993003013023033043053053063073083092 行未改动3123133143153163163173183193203213223233243253263263273283293302 行未改动46 行未改动{ queue<node> q; q.push({sx,sy,0}); vis[sx][sy][0] = 0;
while(!q.empty()) { node cur = q.front(); q.pop(); int x = cur.x, y = cur.y, st = cur.st;
for(int i = 0;i < 4;i ++) { int nx = x + dx[i], ny = y + dy[i]; if(越界) continue;
if(当前格子是陷阱) { if(st > 0 && 未访问) // 无敌状态才能走陷阱 {65 行未改动 while(q.size()) { int t = q.front(); q.pop();
// 遍历当前城市的所有邻居 for(int i = 0;i < v[t].size();i ++) { int to = v[t][i];7 行未改动int main(){ ios::sync_with_stdio(0); cin.tie(0),cout.tie(0);
memset(vis,-1,sizeof(vis)); // 初始化所有距离为-1(未访问)
cin >> n >> m >> k >> s; // n:城市数, m:道路数, k:货物种类数, s:需要收集的种类数
// 读入每个城市生产的货物种类 for(int i = 1;i <= n;i ++) cin >> a[i];
// 读入道路信息,建图 for(int i = 1;i <= m;i ++) { int x,y; cin >> x >> y;
v[x].push_back(y); v[y].push_back(x); }
// 对每种货物分别跑多源BFS // 因为 k ≤ 100,所以可以跑 k 次 BFS,总复杂度 O(k(n+m)) for(int i = 1;i <= k;i ++) { bfs(i); }
// 对每个城市,计算最小费用 // 需要收集 s 种不同的货物,每种选最近的生产城市,自然取距离最小的 s 种 for(int i = 1;i <= n;i ++) {6 行未改动 sum += vis[i][j]; } cout << sum << " "; }
return 0;}```## 易错42 行未改动int bfs(int x,int y,int op){ vis[x][y][op] = 1; q.push({x,y,op,0});
while(q.size()) { node t = q.front(); q.pop();
// 到达目标点,返回步数 if(t.x == tx && t.y == ty) return t.step;
// 尝试向前走1、2、3步 for(int i = 1;i <= 3;i ++) { int dx = t.x + i * d[t.op][0];9 行未改动 continue; vis[dx][dy][t.op] = 1; q.push({dx,dy,t.op,t.step + 1}); }
// 左转(逆时针) int op_left = (t.op + 3) % 4; if(vis[t.x][t.y][op_left] == 0) { vis[t.x][t.y][op_left] = 1; q.push({t.x,t.y,op_left,t.step + 1}); }
// 右转(顺时针) int op_right = (t.op + 1) % 4; if(vis[t.x][t.y][op_right] == 0) {7 行未改动int main(){ ios::sync_with_stdio(0); cin.tie(0),cout.tie(0);
cin >> n >> m;
// 读入障碍物,由于机器人是1.6米的球,占据4个格子(中心在格点上) // 所以每个障碍物格子会影响周围的四个格点 // 格化点 for(int i = 1;i <= n;i ++) { for(int j = 1;j <= m;j ++) { int x; cin >> x;
if(x == 1) { a[i][j] = 1; // 左上角格点 a[i][j - 1] = 1; // 右上角格点2 行未改动 // 原题中网格是格子,机器人中心在格点上,所以障碍物格子会让周围四个格点不可走 } } }
// 读入起点、终点和初始方向 cin >> sx >> sy >> tx >> ty; char c; cin >> c; int op; if(c == 'E') op = 1; // 东 else if(c == 'S') op = 2; // 南 else if(c == 'W') op = 3; // 西 else op = 0; // 北
cout << bfs(sx,sy,op); return 0;}```2 行未改动