Description
给定一个n x m的网格,请计算三点都在格点上的三角形共有多少个。下图为4x4的网格上的一个三角形。
注意三角形的三点不能共线。
Input
输入一行,包含两个空格分隔的正整数m和n。
Output
输出一个正整数,为所求三角形数量。
Sample Input
Input I:
1 1
Input II:
2 2
Sample Output
Output I:
4
Output II:
76
HINT
对于30%数据
1≤m, n≤10
对于100%数据
1≤m, n≤1000
判一下横纵坐标的gcd就ok
看代码
扫描二维码关注公众号,回复:
2754509 查看本文章
#include<stdio.h>
long long a[1001][1001];
long long z;
long long gcd(long long x,long long y)
{
if(y==0)
return a[x][y];
return a[x][y]=gcd(y,x%y);
}
long long ans,q;
int main()
{
long long n,m,i,j;
scanf("%lld%lld",&n,&m);
for(i=0;i<=n;i++)
a[i][0]=i;
for(i=0;i<=m;i++)
a[0][i]=i;
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
gcd(i,j);
q=(m+1)*(n+1);
ans=q*(q-1)*(q-2)/6;
for(i=0;i<=n;i++)
for(j=0;j<=m;j++)
{
if(i!=0||j!=0)
{
if(i==0||j==0)
ans-=(a[i][j]-1)*(n-i+1)*(m-j+1);
else
ans-=2*(a[i][j]-1)*(n-i+1)*(m-j+1);
}
}
printf("%lld",ans);
}