1. 程式人生 > >poj 2318

poj 2318

題意:給出矩形的左上和右下的座標,在矩形中有n個木棒,木棒之間不會相交,然後給出木棒上下端點的橫座標,接著有m個玩具,給出玩具的座標。輸出木棒圍成的區域中有玩具的個數。

思路:由於資料範圍大,所以對有序的木棒二分,叉積判斷點在木棒的哪端。

#include<iostream>
#include<cstdio>
using namespace std;
const int maxn = 5010;
struct point {
    double x , y;    
};
double Xmult(point a , point b , point c) {
    return (b.x-a.x)*(c.y-a.y) - (b.y-a.y)*(c.x-a.x);
}
point P[maxn] , Pu[maxn] , Pd[maxn];
int  sum[maxn];
int n , m , k;
void Bin(point X) {
    int l , r , ans;
    double tmp;
    l = 0; r = n+1;
    while(l <= r) {
        int mid = (l+r)/2;
        tmp = Xmult(X , Pu[mid] , Pd[mid]);
        if(tmp < 0) {
            ans = mid;
            //printf("ans = %d\n",ans);
            r = mid-1;    
        } else l = mid+1;
    }
    //printf("id = %d\n",ans);
    sum[ans-1] ++;
}
int main() {
    double x1 , y1 , x2 , y2;
    int i , j;
    while(~scanf("%d",&n)) {
        if(!n) break;
        scanf("%d%lf%lf%lf%lf",&m,&x1,&y1,&x2,&y2);
        for(i = 1 ; i <= n ; i ++) {
            scanf("%lf%lf",&Pu[i].x,&Pd[i].x);
            Pu[i].y = y1;
            Pd[i].y = y2;
        }
        Pu[0].x = x1;Pu[0].y=y1;
        Pd[0].x = x1;Pd[0].y=y2;
        Pu[n+1].x = x2;Pu[n+1].y=y1;
        Pd[n+1].x = x2;Pd[n+1].y=y2;
        for(i = 0 ; i < m ; i ++) scanf("%lf%lf",&P[i].x,&P[i].y);
        k  = 0;
        memset(sum , 0 , sizeof(sum));
        for(i = 0 ; i < m ; i ++) Bin(P[i]);
        for(i = 0 ; i <= n ; i ++) printf("%d: %d\n",i,sum[i]);
        printf("\n");
    }    
}