hdu 1026 Ignatius and the Princess I(bfs+priority_queue)

来源:互联网 发布:数据成熟度模型 编辑:程序博客网 时间:2024/05/17 14:17

第一次写这种题,参考一下网上的代码。

 1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 #include <queue> 5 int dir[][2] = {{-1,0}, {0,1}, {1,0}, {0,-1}};    //四个方向 6 int n, m; 7 const int MAXN = 105; 8 struct Node 9 {10     int x, y, time;11     friend bool operator<(Node a, Node b)            //重载12     {13         return a.time > b.time;14     }15 };16 struct cmap17 {18     char c;19     int nx, ny;20 }map[MAXN][MAXN];21 int fight[MAXN][MAXN], vis[MAXN][MAXN];              //fight用来标记有monster的HP22 int bfs()23 {24     Node now, next;25     std::priority_queue<Node> q;26     now.x = n - 1, now.y = m - 1;27     char s = map[now.x][now.y].c;28     if (s>='1' && s<= '9')29     {30         now.time = map[now.x][now.y].c - '0';31         fight[now.x][now.y] = map[now.x][now.y].c - '0';32     }33     else34         now.time = 0;35     q.push(now);36     while (!q.empty())37     {38         now = q.top();39         q.pop();40         if (now.x == 0 && now.y == 0)41             return now.time;42         for (int i = 0; i < 4; ++i)43         {44             next.x = now.x + dir[i][0];45             next.y = now.y + dir[i][1];46             if (next.x>=0 && next.x<n && next.y>=0 && next.y<m && 47                     map[next.x][next.y].c != 'X' && !vis[next.x][next.y])48             {49                 vis[next.x][next.y] = 1;50                 s = map[next.x][next.y].c;51                 if (s>='1' && s<='9')52                 {53                     next.time = now.time + s - '0' + 1;54                     fight[next.x][next.y] = s - '0';55                 }56                 else57                     next.time = now.time + 1;58                 map[next.x][next.y].nx = now.x;59                 map[next.x][next.y].ny = now.y;60                 q.push(next);61             }62         }63     }64     return -1;65 }66 int main()67 {68     while (scanf("%d %d", &n, &m) != EOF)69     {70         for (int i = 0; i < n; ++i)71             for (int j = 0; j < m; ++j)72                 std::cin >> map[i][j].c;73         memset(vis, 0, sizeof(vis));74         memset(fight, 0, sizeof(fight));75         int ans = bfs();76         if (ans != -1)77         {78             printf("It takes %d seconds to reach the target position, let me show you the way.\n", ans);79             int num = 1, x = 0, y = 0;80             while (num <= ans)81             {82                 int fx = map[x][y].nx, fy = map[x][y].ny;83                 printf("%ds:(%d,%d)->(%d,%d)\n", num++, x, y, fx, fy);84                 for (int t = 1; t <= fight[fx][fy]; ++t)85                     printf("%ds:FIGHT AT (%d,%d)\n", num++, fx, fy);86                 x = fx, y = fy;87             }88         }89         else90             printf("God please help our poor hero.\n");91         printf("FINISH\n");92     }93     system("pause");94     return 0;95 }
原创粉丝点击