Cod sursa(job #597281)

Utilizator mihaipopa12Popa Mihai mihaipopa12 Data 21 iunie 2011 17:04:08
Problema Poligon Scor 70
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.71 kb
#include<stdio.h>
#include<algorithm>
#include<vector>

#define maxN 805
#define i64 long long

using namespace std;

FILE*f=fopen("poligon.in","r");
FILE*g=fopen("poligon.out","w");

int n,q,i,j,D[maxN],dx,Nr[maxN],p,m,u;
int bnd,x,y,nrpct,lowerpoints,aa,bb;
double ym1,ym2; i64 cc,d; double u1,u2;
pair<int,int>S[maxN][maxN];

struct pct{
	int x;
	int y;
}A[maxN],B[maxN],z;

struct cmp{
	inline bool operator () ( const pct &a, const pct &b ) {
		if ( a.x != b.x )
			return a.x < b.x;
		return a.y < b.y;
	}
};

inline void citire () {
	
	fscanf(f,"%d %d",&n,&q);
	for ( i = 1 ; i <= n ; ++i ){
		fscanf(f,"%d %d",&A[i].x,&A[i].y);
		B[i] = A[i];
	}
}

inline double fct ( pair<int,int> a, int d1, int d2 ){
	if ( A[a.first].y == A[a.second].y ){
		return A[a.first].y;
	}
	aa = A[a.second].y - A[a.first].y; bb = A[a.first].x - A[a.second].x; cc = 1LL*A[a.second].x * A[a.first].y - 1LL*A[a.first].x * A[a.second].y;
	u1 = (double)( -cc - 1LL*aa*d1 ) / bb;
	u2 = (double)( -cc - 1LL*aa*d2 ) / bb;
	double rez = (u1 + u2)/2;
	return rez;
}

struct cmp2{
	inline bool operator () ( const pair<int,int> &a, const pair<int,int> &b ) {
		ym1 = fct(a,D[i],D[i+1]);
		ym2 = fct(b,D[i],D[i+1]);
		return ym1 < ym2;
	}
};

inline void first () {
	
	sort( B+1, B+n+1, cmp() ); B[0].x = -(1<<29);
	
	for ( i = 1 ; i <= n ; ++i ){
		if ( B[i].x != B[i-1].x ){
			D[++dx] = B[i].x;
		}
	}
	
	A[n+1] = A[1];
	for ( i = 1 ; i < dx ; ++i ){
		for ( j = 1 ; j <= n ; ++j ){
			if ( A[j].x == A[j+1].x ) continue;
			if ( A[j].x < A[j+1].x && A[j].x <= D[i] && A[j+1].x >= D[i+1] ){
				++Nr[i];
				S[i][Nr[i]].first = j; S[i][Nr[i]].second = j+1;
				continue;
			}
			if ( A[j].x > A[j+1].x && A[j].x >= D[i+1] && A[j+1].x <= D[i] ){
				++Nr[i];
				S[i][Nr[i]].first = j+1; S[i][Nr[i]].second = j;
			}
		}
		sort( S[i]+1,S[i]+Nr[i]+1,cmp2() );
	}
}

inline int cb1 ( int X ){
	
	int pas = 1 << 10,i;
	
	for ( i = 0 ; pas ; pas >>= 1 ){
		if ( i + pas <= dx && D[i+pas] <= X )
			i += pas;
	}
	return i;
}

inline i64 det( pct a, pct b , pct c ){
	i64 Det = 1LL*(a.x - c.x) * (b.y - c.y) + 1LL*(a.y - c.y) * (c.x - b.x);
	return Det;
}

inline int cb2 () {
	
	p = 0; u = Nr[bnd];
	
	while ( p <= u ){
		m = (p + u) >> 1; d = det(A[S[bnd][m].first],z,A[S[bnd][m].second]);
		if ( d <= 0 )
			p = m + 1;
		else
			u = m - 1;
	}
	return u;
}

inline void solve () {
	
	while ( q-- ){
		
		fscanf(f,"%d %d",&x,&y); z.x = x; z.y = y;
		
		if ( x < D[1] || x > D[dx] ){
			continue;
		}
		bnd = cb1(x);
		lowerpoints = cb2();
		
		if ( lowerpoints && ((lowerpoints & 1) || ( !det(A[S[bnd][lowerpoints].first],z,A[S[bnd][lowerpoints].second]) )) )
			++nrpct;
		
	}
	
	fprintf(g,"%d\n",nrpct);
}

int main () {
	
	citire();
	first();
	solve();
	
	fclose(f);
	fclose(g);
	
	return 0;
}