BZOJ 3505 [Cqoi2014]数三角形(组合数学)

 

【题目链接】 http://www.lydsy.com/JudgeOnline/problem.php?id=3505

 

【题目大意】

  给定一个nxm的网格,请计算三点都在格点上的三角形共有多少个。
  注意三角形的三点不能共线。

 

【题解】

  我们计算三个点组合的情况,去除横竖三共线,以及斜着三点共线的情况即可。
  一个矩形斜对角上的整点数为其长宽的最大公约数+1.

 

【代码】

#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long LL;
LL c[1001000][4],ans;
int n,m;
void init(){
    c[0][0]=1;
    for(int i=1;i<=n*m;i++){
        c[i][0]=1;
        for(int j=1;j<=3;j++)c[i][j]=c[i-1][j-1]+c[i-1][j];
    }
}
void solve(){
    ans=c[n*m][3]-n*c[m][3]-m*c[n][3];
    for(int i=1;i<n;i++)for(int j=1;j<m;j++){
        LL t=__gcd(i,j)+1;
        if(t>2)ans-=(t-2)*2*(n-i)*(m-j);
    }
}
int main(){
    while(~scanf("%d%d",&n,&m)){
        ans=0;n++;m++;
        init(); solve();
        printf("%lld\n",ans);
    }return 0;
}
posted @ 2017-05-17 00:02  forever97  阅读(226)  评论(0编辑  收藏  举报