【bzoj3505】[Cqoi2014]数三角形

3505: [Cqoi2014]数三角形

Time Limit: 10 Sec   Memory Limit: 128 MB
Submit: 1881   Solved: 1147
[ Submit][ Status][ Discuss]

Description

给定一个nxm的网格,请计算三点都在格点上的三角形共有多少个。下图为4x4的网格上的一个三角形。

注意三角形的三点不能共线。

Input

输入一行,包含两个空格分隔的正整数m和n。

Output


输出一个正整数,为所求三角形数量。

Sample Input


2 2

Sample Output

76


数据范围
1<=m,n<=1000

HINT

Source

[ Submit][ Status][ Discuss]



数学题

首先答案肯定是等于在网格中随便选取三点的方案数扣去三点共线的方案数

前者明显等于C((n + 1)(m + 1),3),那么现在问题就是如何计算三点共线的方案数

这一部分的直线包括横的竖的和斜的

横的竖的好算,重要的是斜的直线

我们枚举必定要选取的两个点(a,b)、(c,d),第三个点在以它们两个形成的线段上取

那么第三个点的个数显然为gcd(|b - d|,|a - c|) - 1

但是这样的复杂度是O(n ^ 4)的,我们考虑把其中一个点固定为原点,枚举另外一个点,再通过平移得到其他与它斜率相同的点,于是这样就可以做完了


代码:

#include<cstdio>
#include<vector>
#include<queue>
#include<ctime>
#include<algorithm>
#include<cstdlib>
#include<stack>
#include<cstring>
#include<cmath>
using namespace std;

typedef long long LL;

const int INF = 2147483647;
const int maxn = 1010;

LL n,m,ans;

inline LL getint()
{
	LL ret = 0,f = 1;
	char c = getchar();
	while (c < '0' || c > '9')
	{
		if (c == '-') f = -1;
		c = getchar();
	}
	while (c >= '0' && c <= '9')
		ret = ret * 10 + c - '0',c = getchar();
	return ret * f;
}

inline LL gcd(LL a,LL b)
{
	return !b ? a : gcd(b,a % b);
}

inline LL C(LL n,LL m)
{
	LL ret = 1;
	for (int i = 1; i <= m; i++) ret = ret * (n - i + 1) / i;
	return ret;
}

int main()
{
	m = getint(); n = getint(); 
	ans = C((n + 1) * (m + 1),3) - (n + 1 >= 3 ? C(n + 1,3) * (m + 1) : 0) - (m + 1 >= 3 ? C(m + 1,3) * (n + 1) : 0);
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= m; j++)
		{
			LL t = gcd(i,j) - 1;
			ans -= t * (n - i + 1) * (m - j + 1) * 2;
		}
	printf("%lld",ans);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值