Cod sursa(job #1747177)

Utilizator depevladVlad Dumitru-Popescu depevlad Data 24 august 2016 16:30:51
Problema Poligon Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.74 kb
#include <fstream>
#include <algorithm>
 
using namespace std;
 
const int kMaxN = 805;
const double kEps = 1e-6;

int Compare(double a, double b) {
  if(a - b > kEps) return 1;
  if(b - a > kEps) return -1;
  return 0;
}

struct Point {
  double x;
  double y;
  Point() {}
  Point(double _x, double _y) { x = _x; y = _y; }
};

struct Segment {
  Point a;
  Point b;
  Segment() {}
  Segment(Point _a, Point _b) { a = _a; b = _b; }
  Point Middle() const { return Point((a.x + b.x) / 2, (a.y + b.y) / 2); }
  inline bool operator <(Segment const& other) const { return Compare(Middle().y, other.Middle().y) == -1; }
};

int N, Q;
Point P[kMaxN];
vector<int> xCoords;
vector<vector<pair<Point, Point>>> Strips;

bool SegmentSorter(pair<Point, Point> const& a, pair<Point, Point> const &b) {  
  return Compare(a.first.y + a.second.y, b.first.y + b.second.y) < 0;
}

int CrossProduct(Point a, Point b, Point c) {
  double termFi = (b.x - a.x) * (c.y - a.y);
  double termSe = (b.y - a.y) * (c.x - a.x);
  return (Compare(termFi, termSe) == -1 ? -1 : Compare(termFi, termSe) == 0 ? 0 : 1);
}

int main() {
  ifstream fin("poligon.in");
  ofstream fout("poligon.out");
  
  fin >> N >> Q;
  for(int i = 1; i <= N; i++) {
    fin >> P[i].x >> P[i].y;
    xCoords.push_back(P[i].x);
  }
  P[N + 1] = P[1];
  
  sort(xCoords.begin(), xCoords.end());
  xCoords.erase(unique(xCoords.begin(), xCoords.end()), xCoords.end());
  
  for(int i = 0; i < xCoords.size() - 1; i++) {
    Strips.push_back(vector<pair<Point, Point>>());
    for(int j = 1; j <= N; j++) {
      bool toSwap = 0;
      if(P[j].x > P[j + 1].x) swap(P[j], P[j + 1]), toSwap = 1;
      if(P[j].x <= xCoords[i] && P[j + 1].x > xCoords[i]) {
        int64_t a = P[j].y - P[j + 1].y;
        int64_t b = P[j + 1].x - P[j].x;
        int64_t c = - (a * P[j].x + b * P[j].y);
        Strips.back().emplace_back(Point(xCoords[i], -(1.0 * a * xCoords[i] + c) / b), 
                                   Point(xCoords[i + 1], -(1.0 * a * xCoords[i + 1] + c) / b));
      }
      if(toSwap) swap(P[j], P[j + 1]);
    }
    sort(Strips.back().begin(), Strips.back().end(), SegmentSorter);
  }
  
  int solCnt = 0;
  while(Q--) {
    int x, y;
    fin >> x >> y;
    
    int sId = upper_bound(xCoords.begin(), xCoords.end(), x) - xCoords.begin() - 1;
    if(0 <= sId && sId <= Strips.size()) {
      int L = 0, R = Strips[sId].size() - 1;
      while(L <= R) {
        int M = (L + R) >> 1;
        int Sgn = CrossProduct(Strips[sId][M].first, Strips[sId][M].second, Point(x, y));
        if(!Sgn) { L = 1; break; }
        else if(Sgn < 0) R = M - 1;
        else L = M + 1;
      }
      solCnt += (L & 1);
    }
  }
  
  fout << solCnt << "\n";
  return 0;
}