果园里的树

题目:

 

原理:如果点在三角形内部,则三个小三角形的面积之和等于大三角形的面积

 

重点是~

 

 

 

//果园里的树 
#include<iostream>
#include<cmath>
#define EPS 1e-9
using namespace std;

double area2(double x0, double y0, double x1, double y1, double x2, double y2)
{
    double s = x0 * y1 + x1 * y2 + x2 * y0 - x0 * y2 - x1 * y0 - x2 * y1;
    if(s < 0)
        s = -1 * s;
    return s;
}

int main()
{
    double x0, y0, x1, y1, x2, y2;
    cin >> x0 >> y0 >> x1 >> y1 >> x2 >> y2;
    double min_x, min_y, max_x, max_y;
    
    //计算包含三角形的最小矩形    
    min_x = x0 < x1 ? x0 : x1;
    min_x = min_x < x2 ? min_x : x2;
    min_x = floor(min_x);       //下限 
    min_y = y0 < y1 ? y0 : y1;
    min_y = min_y < y2 ? min_y : y2;
    min_y = floor(min_y);
    
    max_x = x0 > x1 ? x0 : x1;
    max_x = max_x > x2 ? max_x : x2;
    max_x = ceil(max_x);       //上限 
    max_y = y0 > y1 ? y0 : y1;
    max_y = max_y > y2 ? max_y : y2;
    max_y = ceil(max_y);
    
    //对矩形内的点依次做判断 
    double s = area2(x0, y0, x1, y1, x2, y2);    
    int c1 = 0, c2 = 0;
    
    for(int i = min_x; i <= max_x; i++)
    {
        for(int j = min_y; j <= max_y; j++)
        {
            double s1 = area2(i, j, x0, y0, x1, y1); 
            double s2 = area2(i, j, x0, y0, x2, y2); 
            double s3 = area2(i, j, x1, y1, x2, y2);
            
            if(s1 + s2 + s3 - s <= EPS)        //分布在三角形内部的坐标点 
                c1++;            
            if((s1 <= EPS) || (s2 <= EPS) || (s3 <= EPS))        //分布在三角形边界的坐标点
                c2++;
        }
    }
    
    cout << c1 << endl;
    cout << c2 << endl;
    
    return 0;
}

 

posted @ 2016-03-18 22:34  Nagihiko  阅读(250)  评论(0编辑  收藏  举报