Description
给定一个nxm的网格,请计算三点都在格点上的三角形共有多少个。下图为4x4的网格上的一个三角形。
注意三角形的三点不能共线。
Input
输入一行,包含两个空格分隔的正整数m和n。
Output
输出一个正整数,为所求三角形数量。
Sample Input
2 2
Sample Output
76
题解
我们可以发现从网格中选取三角形,实际上就是从
(n+1)∗(m+1)
(
n
+
1
)
∗
(
m
+
1
)
个点中选取3个点,然后再减去多余的就可以了。
怎么减去多于的呢,我们首先考虑每一列,存在三点共线的情况有
C[n][3]
C
[
n
]
[
3
]
种,一共m列.然后考虑每一行,存在三点共线的情况一共是
C[m][3]
C
[
m
]
[
3
]
种,一共n行,最后考虑对角线的情况,对于对角线的情况我们只需要计算出坐标
(i,j)
(
i
,
j
)
的gcd就可以/
代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#define ll long long
using namespace std;
const int MAXN=1e3;
ll c[1000004][5],n,m,sum,ans;
ll gcd(int a,int b)
{
return b==0 ? a : gcd(b,a%b);
}
void Init()
{
c[0][0]=1;
for(int i=1;i<=sum;i++)
{
c[i][0]=1;
for(int j=1;j<=3;j++)
{
c[i][j]=c[i-1][j]+c[i-1][j-1];
}
}
}
int main()
{
scanf("%lld%lld",&n,&m);
n++,m++;
sum=n*m;
Init();
ans=c[sum][3];
ans-=c[n][3]*m+c[m][3]*n;
for(int i=1;i<n;i++)
{
for(int j=1;j<m;j++)
{
ll now=gcd(i,j);
if(now==1) continue ;
now++;
ans-=(now-2)*(n-i)*(m-j)*2;
}
}
printf("%lld",ans);
return 0;
}