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

India and China Origins hdu 5652 (BFS+二分)

时间:2016-08-19 20:40:30      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

 

http://acm.split.hdu.edu.cn/showproblem.php?pid=5652

 

 

题意:中国和印度中间由平原‘0‘和高山‘1‘两种地理环境。高山是无限高的,不论怎样过不去。每一年都会又多出一座高山。下面K行表示第i年maps[x][y]变为高山。问你在第几年后,两国人民不能再彼此互相联系了。若是k年后,仍能联系,输出‘-1‘。

 

分析:若是每一年都依次判断,那肯定会死的很惨的吧。最近二分写了好几道题了,可以根据二分的方法写。

 

 

技术分享
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
#include <queue>
#include <stack>
#include <math.h>

using namespace std;

#define INF 0x3f3f3f3f
const int maxn = 600;
typedef long long LL;
char str[maxn][maxn], maps[maxn][maxn];
int v[maxn][maxn];
int n, m;
int dir[4][2]= {{0,1},{1,0},{0,-1},{-1,0}};

struct node
{
    int x, y;
} s[maxn*maxn];

int BFS(int x, int y)
{
   node begins, now, next;
   begins.x = x;
   begins.y = y;

   queue<node>Q;
   Q.push(begins);

   memset(v, 0, sizeof(v));

   v[0][y] = 1;

   while(Q.size())
   {
       now = Q.front();
       Q.pop();

       if(now.x == n-1) return 1;

       for(int i=0; i<4; i++)
       {
           next = now;
           next.x += dir[i][0];
           next.y += dir[i][1];

           if(next.x>=0 && next.x<n && next.y>=0 && next.y<m && maps[next.x][next.y]==0 && !v[next.x][next.y])
           {
               v[next.x][next.y] = 1;
               Q.push(next);
           }
       }
   }
   return 0;
}

int Judge(int x)
{
    for(int i=0; i<n; i++)
        strcpy(maps[i], str[i]);

    for(int i=1; i<=x; i++)
        maps[s[i].x][s[i].y]=1;

    for(int i=0; i<m; i++)///从maps[0][i]寻找是否有通向n-1行的路
    {
        if(maps[0][i]==0)
        {
           if(BFS(0, i))
            return 1;
        }
    }
    return 0;
}

int main()
{
    int T, k;

    scanf("%d", &T);

    while(T --)
    {
        scanf("%d %d", &n, &m);

        for(int i=0; i<n; i++)
            scanf("%s", str[i]);

        scanf("%d", &k);

        for(int i=1; i<=k; i++)
            scanf("%d %d", &s[i].x, &s[i].y);

        int l = 1;
        int r = k;
        int ans = -1;

        while(l <= r)
        {
            int mid=(l+r)/2;

            if(!Judge(mid))///若第mid年不能通过,则往前寻找,判断是否还有最优解
            {
                ans = mid;
                r= mid - 1;
            }
            else
            {
                l = mid + 1;
            }
        }

        printf("%d\n", ans);
    }
    return 0;
}
View Code

 

India and China Origins hdu 5652 (BFS+二分)

标签:

原文地址:http://www.cnblogs.com/daydayupacm/p/5788865.html

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