UVALive 3295 Counting Triangles
题意:给出一个a*b的网格,在网格上取不共线的三点构成三角形,求三角形总数。
分析:就是一一道简单的组合数计算题目,设总结点数为n,则取三个节点的个数为C(n,3),
然后减去横向、竖向、斜向的三点共线的个数即可,斜线三点共线等价于所枚举的矩形的长宽成倍数关系,即gcd不为1
1 #include <iostream> 2 #include <algorithm> 3 #include <cstring> 4 #include <cstdio> 5 #include <vector> 6 #include <cstdlib> 7 #include <iomanip> 8 #include <cmath> 9 #include <ctime> 10 #include <map> 11 #include <set> 12 #include <queue> 13 using namespace std; 14 #define lowbit(x) (x&(-x)) 15 #define max(x,y) (x>y?x:y) 16 #define min(x,y) (x<y?x:y) 17 #define MAX 100000000000000000 18 #define MOD 1000000007 19 #define pi acos(-1.0) 20 #define ei exp(1) 21 #define PI 3.141592653589793238462 22 #define INF 0x3f3f3f3f3f 23 #define mem(a) (memset(a,0,sizeof(a))) 24 typedef long long ll; 25 ll gcd(ll a,ll b){ 26 return b?gcd(b,a%b):a; 27 } 28 bool cmp(int x,int y) 29 { 30 return x>y; 31 } 32 const int N=10005; 33 const int mod=1e9+7; 34 int main(){ 35 ll a, b; 36 int cas = 1; 37 while(scanf("%lld%lld", &a, &b)!=EOF && (a||b)){ 38 ll n = (a+1)*(b+1); 39 ll sum1 = n*(n-1)*(n-2)/6; //C(n,3) 40 ll sum2 = (b+1)*(a+1)*a*(a-1)/6 + (a+1)*(b+1)*b*(b-1)/6; //横向或竖向三点共线的个数 41 ll sum3 = 0; //斜线上三点共线的个数的一半 42 int i, j; 43 for(i=2; i<=a; i++) 44 for(j=2; j<=b; j++) 45 sum3 += (gcd(i,j)-1) * (a-i+1) * (b-j+1); 46 ll ans = sum1 - 2*sum3 - sum2; 47 printf("Case %d: %lld\n", cas++, ans); 48 } 49 return 0; 50 }