hdu1264Counting Squares

也是离散化的题目,和之前的画墙如出一辙,据说可以用线段树+离散化。。。以后要试一下

#include <iostream>
using namespace std;
const int size = 1100;
int x[2*size], y[2*size];
int ax[size], bx[size], ay[size], by[size];
bool map1[2*size][2*size];
bool cmp(int a, int b)
{
     return a < b;
}
int n;
int BinaryS(int ans, int st, int ed, int *x)
{
    int left = st, right = ed;
    while (left <= right){
          int mid = (left+right)/2;
          if (x[mid] == ans){ return mid;}
          if (x[mid] < ans){
             left = mid+1;          
          }     
          if (x[mid] > ans){
             right = mid-1;          
          }
    }
}
int main()
{
    //freopen("IN.txt", "r", stdin);
    //freopen("OUT.txt", "w", stdout);
    int w, h;
    int nc = 0;
    bool flag = false;
    while (!flag){
          int nx, ny;
          nx = ny = 0;
          int ii1 = 0;
          while (scanf("%d%d%d%d", &ax[ii1], &ay[ii1], &bx[ii1], &by[ii1])){
                if (ax[ii1] == -1 && ay[ii1] == -1 && bx[ii1]==-1 && by[ii1] == -1 && ax[ii1] == -1)break;
                if (ax[ii1] == -2 && ay[ii1] == -2 && bx[ii1]==-2 && by[ii1] == -2 && ax[ii1] == -2){flag = true;break;}
                if (ax[ii1] > bx[ii1])swap(ax[ii1], bx[ii1]);
                if (ay[ii1] > by[ii1])swap(ay[ii1], by[ii1]);
                x[nx ++] = ax[ii1], y[ny ++] = ay[ii1];
                x[nx ++] = bx[ii1], y[ny ++] = by[ii1];
                ii1 ++;
          }
          int xx = 0, yy = 0;
          for (int i = 1; i < nx; i ++){//如果存在相同的点
              if (x[i] != x[i-1]){
                 xx ++;
                 x[xx] = x[i];        
              }
          }
          for (int i = 1; i < ny; i ++){
              if (y[i] != y[i-1]){
                 yy ++;
                 y[yy] = y[i];        
              }   
          }
          sort(x, x+xx+1, cmp);
          sort(y, y+yy+1, cmp);
          memset(map1, false, sizeof(map1));
          for (int i = 0; i < ii1; i ++){
              int sx = BinaryS(ax[i], 0, xx, x);
              int sy = BinaryS(ay[i], 0, yy, y);
              int ex = BinaryS(bx[i], 0, xx, x);
              int ey = BinaryS(by[i], 0, yy, y);
              //离散化
              for (int ii = sx; ii < ex; ii ++){
                  for (int j = sy; j < ey; j ++){
                      map1[ii][j] = true;
                  }   
              }
          }
          int sum = 0;
          for (int i = 0; i < xx; i ++){
              for (int j = 0; j < yy; j ++){
                  if (map1[i][j]){
                     sum += (x[i+1]-x[i])*(y[j+1]-y[j]);
                  }
              }   
          }
          printf("%d\n",sum);
    }
    return 0;
}

你可能感兴趣的:(hdu1264Counting Squares)