ahu-746-梯田二分+bfs

来源:互联网 发布:linux mount -a 编辑:程序博客网 时间:2024/04/28 22:29

1数据水2二分查找加速

#include <cstdio>#include <cstring>#include <cmath>#include <cstdlib>#include <queue>#include <iostream>#include <algorithm>using namespace std;int i,j,k,t,map[110][110],color[110][110],n,m,p,q,bu[4][2] = {1,0,-1,0,0,1,0,-1},am[20000],n1[2],m1[2],he;struct node{    int x,y;};int bfs(int height){  memset(color,0,sizeof(color));  int am1 = 0;  node node1,node2;  queue<node>qu;  for(i=0;i<n;i++)  for(j=0;j<2;j++)    if(map[i][m1[j]]<=height&&color[i][m1[j]]==0){      node1.x = i;      node1.y = m1[j];      color[i][m1[j]] = 1;      qu.push(node1);      am1++;    }  for(i=0;i<m;i++)  for(j=0;j<2;j++)    if(map[n1[j]][i]<=height&&color[n1[j]][i]==0){      node1.x = n1[j];      node1.y = i;      color[n1[j]][i] = 1;      qu.push(node1);      am1++;    }   while(!qu.empty())   {      node1 = qu.front();      qu.pop();      for(i=0; i<4; i++)      {        int X = node1.x+bu[i][0],Y = node1.y+bu[i][1];        if(X>=0&&X<n&&Y>=0&&Y<m&&color[X][Y]==0&&map[X][Y]<=height){            node2.x = X;            node2.y = Y;            qu.push(node2);            color[X][Y] = 1;            am1++;          }      }   }   return am1;  }void binsearch(int left,int right){    if(left == right)    {        int am1 = bfs(am[left]);        if(am1>=p && am1<=q)he =am[left];    }    else    {    int middle = (left+right)/2;    int am1 = bfs(am[middle]);    if(am1>=p && am1<=q){        he =am[middle];        binsearch(left,middle);    }    else if(am1<p)binsearch(middle+1,right);    else binsearch(left,middle);    }}int main(){  scanf("%d",&t);  while(t--)  {    scanf("%d%d%d%d",&n,&m,&p,&q);    for(i=0; i<n; i++)    for(j=0; j<m; j++)    {       scanf("%d",&map[i][j]);       am[i*m+j] = map[i][j];    }    n1[0] = 0;n1[1] = n-1;    m1[0] = 0;m1[1] = m-1;     int l = n*m;    sort(am,am + n*m);    he = -1;    binsearch(0,l-1);    printf("%d\n",he);    }  return 0; } 
0 0