A n * m grid as follow:
Count the number of triangles, three of whose vertice must be grid-points.
Note that the three vertice of the triangle must not be in a line(the right picture is not a triangle).
Input
The input consists of several cases. Each case consists of two positive integersn andm (1 ≤n, m ≤ 1000).
Output
For each case, output the total number of triangle.
Sample Input
1 1 2 2
Sample Output
4 76
hint
hint for 2nd case: C(9, 3) - 8 = 76
Zoj 3647 Gao the Grid 在一个 n*m 个方格中(顶点有( n+1 ) *(m+1) 个),求所有三角形数,即三点不共线的所有情况。 令所有点的个数为 t, 用 c[t,3] 来枚举所有情况,用总数扣去所有三点共线数就是所求的三角形数。那么在求三点共线的情况时,水平和垂直的情况读者自己考虑。对于倾斜的情况,先枚举两端的端点,如图,在一个 6*10 的方格中选 4*4 的两个端点,其中可构成三点花线的另一点的个数为最大公约数 gcd(4,4) -1. 如图中的三个点,然后用乘于剩下的倍数( 6-4+1 ) * ( 10-4+1 ),再乘于 2 (倾斜时有右上,右下两种情况) . 然后依次枚举所有的矩形,求出所有三点共线的情况。于是所有情况减三点共线情况就是答案了。我开始的错误思想:也是枚举矩形,但是没有固定矩形对角线上的俩点,设对角线上有n点,用C[n][3]求的,这样会多出好多情况,重复,所以一直wa。。。orz,又来在搜了结题报告,就差在那里了,杯具。。
参考此处:http://blog.csdn.net/woshi250hua/article/details/8033408
我的代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#define ll long long
using namespace std;
ll gcd(ll a,ll b)
{
return b?gcd(b,a%b):a;
}
ll C3(ll n) {
if(n<3)
return 0;
ll ret;
ret=n*(n-1)*(n-2)/6;
return ret;
}
int main() {
ll n, m;
while(scanf("%lld%lld", &n, &m)!=EOF)
{
ll ans ;ll num=2;
ans=C3((n+1)*(m+1));
ans=ans-(n+1)*C3(m+1)-(m+1)*C3(n+1);
for(ll b=2;b<=m;b++)
for(ll a=2;a<=n;a++)
{
ans = ans - (n-a+1)*(m-b+1)*(gcd(a,b)-1)*2;
}
printf("%lld\n",ans);
}
return 0;
}
另外附上一个求组合c[n][r]的模板:
long long C(int n,int r) { if(n<r)return 0;//这个一定要 if(n-r<r)r=n-r; int i,j; long long ret=1; for(i=0,j=1;i<r;i++) { ret*=(n-i); for(;j<=r&&ret%j==0;j++) ret/=j; } return ret; }