hdu1705 Count the grid

皮克定理是指一个计算点阵中顶点在格点上的多边形面积公式,该公式可以表示为2S=2a+b-2,其中a表示多边形内部的点数,b表示多边形边界上的点数,s表示多边形的面积。

多边形边界上的整数点怎么求呢?

当然是gcd啦~~  gcd(x1-x2, y1-y2)就是这条边上整数点的个数。但是仅仅一条边是不准确的(有一个端点没有算上),需要把所有边的gcd加上才是皮克定理中的「b」。

1.0*gcd(Math.abs(x1-x2),Math.abs(y1-y2))+gcd(Math.abs(x1-x3),Math.abs(y1-y3))+gcd(Math.abs(x2-x3),Math.abs(y2-y3));//计算边点
1.0*Math.abs((x2-x1)*(y3-y1)-(y2-y1)*(x3-x1))/2;//由三点坐标求三角形面积,用了向量叉积

 

package javahd;

//import java.text.DecimalFormat;
import java.util.Scanner;

public class hdu1705 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        //DecimalFormat df = new DecimalFormat("0.000");
        while (sc.hasNext()){
            int x1 = sc.nextInt();
            int y1 = sc.nextInt();
            int x2 = sc.nextInt();
            int y2 = sc.nextInt();
            int x3 = sc.nextInt();
            int y3 = sc.nextInt();
            if (x1==0 && x2==0 && x3==0 && y1==0 && y2==0 && y3==0){
                break;
            }
            double edgnod=1.0*gcd(Math.abs(x1-x2),Math.abs(y1-y2))+gcd(Math.abs(x1-x3),Math.abs(y1-y3))+gcd(Math.abs(x2-x3),Math.abs(y2-y3));//计算边点我也不知道这是啥原理
            double s=1.0*Math.abs((x2-x1)*(y3-y1)-(y2-y1)*(x3-x1))/2;//由三点坐标求三角形面积,用了向量叉积
            //System.out.println(df.format(s-edgnod/2+1));
            int res = (int) (s-edgnod/2+1);
            System.out.println(res);
        }
    }
    public static int gcd(int a ,int b){
        if (b>a){
            int tmp = a;
            a = b;
            b = tmp;
        }
        if (b==0){
            return a;
        }else{
            return gcd(b,a%b);
        }
    }
}

 

posted @ 2024-10-02 16:26  XiaohuangTX  阅读(0)  评论(0编辑  收藏  举报