您的位置:首页 > 其它

【bzoj3505】[Cqoi2014]数三角形

2018-01-11 22:17 197 查看

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: