TZOJ 5103: Electric Fence

5103: Electric Fence 

描述

In this problem, "lattice points" in the plane are points with integer coordinates.

In order to contain his cows, Farmer John constructs a triangular electric fence by stringing a "hot" wire from the origin (0,0) to a lattice point [n,m] (0<=n<32,000, 0<m<32,000), then to a lattice point on the positive x axis [p,0] (0<p<32,000), and then back to the origin (0,0).

A cow can be placed at each lattice point within the fence without touching the fence (very thin cows). Cows can not be placed on lattice points that the fence touches. How many cows can a given fence hold?

输入

The single input line contains three space-separated integers that denote n, m, and p.

输出

A single line with a single integer that represents the number of cows the specified fence can hold.

样例输入  7 5 10

样例输出  20

题目大意:由(0,0)(0,p)(n,m)三个顶点构成的三角形,问这个三角形里有多少个不在边界上的格点,n,m,p都是输入给出的。

思路:第一时间还是不会写,一遇到图形类型的题目很难想到怎么用代码去表达,只有暴力的方法,但是还是觉得很繁琐,查资料得到一个有趣的皮克定理,专门来求解这一类以格点为顶点的多边形的内部点数量,具体就是s为多边形面积,a为多边形内部的整数点,b为多边形边上的整数点,公式:s=a+b/2-1.由于只是三角形,并且一条边是在x轴上的,因此面积s是最容易求解出来的,问题的求解就转化为如何求出三角形边上的格点数量,但我第一时间还是想到的暴力,枚举点到点的x轴坐标,然后一个一个带入看y坐标是否是整数,但是也是很复杂,如果遇到数据范围较大的时候还会超时,再次查资料发现用gcd求公约数的方法也能得到整数点数量,gcd(abs(x1-x2),abs(y1-y2))。我用(0,0)和(2,2)带入得到2,但是实际上是三个点,我就打算gcd然后+1的,但是最后结果就错了,之后把+1删了后才对了,后面发现我算三条边每次都+1的话就是把三个顶点重复算了,导致最后整数点多了2个才导致的错误,后面是代码。

#include<bits/stdc++.h>
using namespace std;
//s=a+b/2-1,a为多边形内部顶点个数,b为多边形边上整点数。 
double gcd(int x,int y)
{
    if(y==0)return x;
    if(x<y)return gcd(y,x);
    else return gcd(y,x%y);
}
int main()
{
    int j,i;
    double n,m,p,a,b;
    scanf("%lf %lf %lf",&n,&m,&p);
    double s=p*m/2;
    b=gcd((int)n,(int)m)+p+gcd(abs((int)(n-p)),(int)m);
    //printf("%lf %lf\n",s,b);
    a=s+1-b/2;
    printf("%.0lf",a);

代码引用的格式不知道为什么一直不对,就直接复制到文本里去了,我写的时候想到三角形面积可能会出现小数部分,就用的double,但是求gcd又要int类型,所以写的比较麻烦,但是写完看后附代码的时候他们直接int就完事了,也不知道为什么。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值