题目描述:
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
提示:
无
题意解析:
题目给出一个三角形的栅栏,问里面最多可以养多少牛(即多少个整数坐标点,不包括边界)
具体实现:
首先可以想到暴力遍历范围内的点,判断其是否在给定的三角形中。
求出原点到(n,m)点的斜率 K1,(p,0)到(n,m)的斜率为 K2 ,设当前点的坐标为(X,Y)。
当前点到原点的斜率为K3 ,当前点到(p,0)点的斜率为K4。
遍历当前点:
当K3<K1 并且 K4>K2 时,点在栅栏内,总数+1;否则(X,Y)->(X+1,1)
AC代码:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,m,p;
double k1,k2;
int sum=0;
cin >> n >> m >> p;
k1=(double)m/(double)n;
k2=(double)m/(double)(n-p);
if (p>n)
{
for (int x=1;x<p;x++)
{
if (x<n)
{
for (int y=1;(double)y/(double)x<k1;y++)
{
sum++;
}
}
else if (x>n)
{
for (int y=1;(double)y/(double)(x-p)>k2;y++)
{
sum++;
}
}
else sum+=(m-1);
}
}
else if (p<n)
{
for (int x=1;x<n;x++)
{
if (x<=p)
{
for (int y=1;(double)y/(double)x<k1;y++)
{
sum++;
}
}
else
{
for (int y=1;(double)y/(double)x<k1;y++)
{
if ((double)y/(double)(x-p)>k2) sum++;
}
}
}
}
else
{
for (int x=1;x<n;x++)
{
for (int y=1;(double)y/(double)x<k1;y++)
{
sum++;
}
}
}
cout << sum << endl;
return 0;
}
总结:
暴力遍历。