码迷,mamicode.com
首页 > 其他好文 > 详细

LA 7155. ACM-ICPC World Finals 2015 F. Keyboarding

时间:2018-01-01 00:24:23      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:strlen   --   string   clu   ret   div   pre   print   oar   

BFS 正解就是乱搞系列

#include <cstdio>
#include <cstring>

char G[50][50];
bool mk[50][50][10001];
struct QueueNode {
  int x, y, cur, dist;
  QueueNode (int x = 0, int y = 0, int cur = 0, int dist = 0):
    x(x), y(y), cur(cur), dist(dist) {}
} Q[50 * 50 * 10001], *hd, *tl;
char txt[10002];

void Qpush(int x, int y, int cur, int dist) {
  *tl++ = QueueNode(x, y, cur, dist);
  mk[x][y][cur] = true;
}

int main() {
  int r, c;
  scanf("%d%d", &r, &c);
  for (int i = 0; i < r; i++)
    for (int j = 0; j < c; j++)
      scanf(" %c", *(G + i) + j);
  
  scanf("%s", txt);
  strcat(txt, "*");
  int n = strlen(txt);
  
  Q[0] = QueueNode();
  for (hd = Q, tl = Q + 1; hd != tl; hd++) {
    if (G[hd->x][hd->y] == txt[hd->cur]) {
      if (hd->cur + 1 == n) {
        printf("%d\n", hd->dist + 1);
        break;
      }
      else
        Qpush(hd->x, hd->y, hd->cur + 1, hd->dist + 1);
    } else {
      int nx, ny;
      
      for (nx = hd->x - 1; nx >= 0 && G[hd->x][hd->y] == G[nx][hd->y]; nx--);
      if (nx >= 0 && !mk[nx][hd->y][hd->cur])
        Qpush(nx, hd->y, hd->cur, hd->dist + 1);
      
      for (nx = hd->x + 1; nx < r && G[hd->x][hd->y] == G[nx][hd->y]; nx++);
      if (nx < r && !mk[nx][hd->y][hd->cur])
        Qpush(nx, hd->y, hd->cur, hd->dist + 1);
      
      for (ny = hd->y - 1; ny >= 0 && G[hd->x][hd->y] == G[hd->x][ny]; ny--);
      if (ny >= 0 && !mk[hd->x][ny][hd->cur])
        Qpush(hd->x, ny, hd->cur, hd->dist + 1);
      
      for (ny = hd->y + 1; ny < c && G[hd->x][hd->y] == G[hd->x][ny]; ny++);
      if (ny < c && !mk[hd->x][ny][hd->cur])
        Qpush(hd->x, ny, hd->cur, hd->dist + 1);
    }
  }
  return 0;
}

LA 7155. ACM-ICPC World Finals 2015 F. Keyboarding

标签:strlen   --   string   clu   ret   div   pre   print   oar   

原文地址:https://www.cnblogs.com/P6174/p/8159296.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!