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

BFS 2015百度之星初赛2 HDOJ 5254 棋盘占领

时间:2015-06-01 18:47:02      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:

 

题目传送门

  1 /*
  2     BFS:先把1的入队,每个1和它相邻的组合后看看能不能使0变1,若有则添加入队,change函数返回改变了多少个0
  3     注意:结果还要加上原来占领的
  4 */
  5 #include <cstdio>
  6 #include <algorithm>
  7 #include <cstring>
  8 #include <cmath>
  9 #include <vector>
 10 #include <queue>
 11 #include <set>
 12 using namespace std;
 13 
 14 const int MAXN = 5e2 + 10;
 15 const int INF = 0x3f3f3f3f;
 16 int a[MAXN][MAXN];
 17 int dx[4] = {-1, -1, 1, 1};
 18 int dy[4] = {-1, 1, -1, 1};
 19 int n, m;
 20 queue<pair<int, int> > Q;
 21 
 22 int change(int x, int y)
 23 {
 24 
 25     int cnt = 0;
 26     for (int i=0; i<4; ++i)
 27     {
 28         int tx = x + dx[i];    int ty = y + dy[i];
 29         if (tx < 1 || tx > n)    continue;
 30         if (ty < 1 || ty > m)    continue;
 31         if (a[tx][ty] == 1)
 32         {
 33              if (i == 0 || i == 2)
 34              {
 35                 if (a[tx][ty+1] == 0)    {a[tx][ty+1] = 1;    ++cnt;    Q.push (make_pair (tx, ty+1));}
 36                 if (a[x][y-1] == 0)    {a[x][y-1] = 1;    ++cnt;    Q.push (make_pair (x, y-1));}
 37              }
 38              else if (i == 1 || i == 3)
 39              {
 40                 if (a[tx][ty-1] == 0)    {a[tx][ty-1] = 1;    ++cnt;    Q.push (make_pair (tx, ty-1));}
 41                 if (a[x][y+1] == 0)    {a[x][y+1] = 1;    ++cnt;    Q.push (make_pair (x, y+1));}
 42              }
 43         }
 44     }
 45 
 46     return cnt;
 47 }
 48 
 49 int BFS(void)
 50 {
 51     int ans = 0;
 52     while (!Q.empty ())
 53     {
 54         int x = Q.front ().first;    int y = Q.front ().second;    Q.pop ();
 55         ans += change (x, y);
 56     }
 57 
 58     return ans;
 59 }
 60 
 61 int main(void)        //2015百度之星初赛2 HDOJ 5254 棋盘占领
 62 {
 63     int t, cas = 0;    scanf ("%d", &t);
 64     while (t--)
 65     {
 66         while (!Q.empty ())    Q.pop ();
 67         scanf ("%d%d", &n, &m);
 68         memset (a, 0, sizeof (a));
 69 
 70         int g;    scanf ("%d", &g);
 71         int cnt = 0;
 72         while (g--)
 73         {
 74             int x, y;    scanf ("%d%d", &x, &y);
 75             if (a[x][y] == 0)
 76             {
 77                 cnt++;    a[x][y] = 1;    Q.push (make_pair (x, y));
 78             }
 79         }
 80 
 81         printf ("Case #%d:\n", ++cas);
 82         printf ("%d\n", BFS () + cnt);
 83     }
 84 
 85     return 0;
 86 }
 87 
 88 
 89 
 90 
 91 /*
 92 4
 93 2 2
 94 2
 95 1 1
 96 2 2
 97 3 3
 98 3
 99 1 1
100 2 3
101 3 2
102 2 4
103 5
104 1 1
105 1 1
106 1 2
107 1 3
108 1 4
109 2 4
110 2
111 1 1
112 2 4
113 */

 

BFS 2015百度之星初赛2 HDOJ 5254 棋盘占领

标签:

原文地址:http://www.cnblogs.com/Running-Time/p/4544521.html

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