首页 > 代码库 > UVA - 12075 Counting Triangles

UVA - 12075 Counting Triangles

Description

Download as PDF

Triangles are polygons with three sides and strictly positive area. Lattice triangles are the triangles all whose vertexes have integer coordinates. In this problem you have to find the number of lattice triangles in anMxN grid. For example in a (1x 2) grid there are 18 different lattice triangles as shown in the picture below:

\epsfbox{p3295.eps}

Input 

The input file contains at most 21 sets of inputs.

Each set of input consists of two integers M andN (0 < M, N$ \le$1000 ). These two integers denote that you have to count triangles in an(MxN) grid.

Input is terminated by a case where the value of M andN are zero. This case should not be processed.

Output 

For each set of input produce one line of output. This output contains the serial of output followed by the number lattice triangles in the(MxN) grid. You can assume that number of triangles will fit in a 64-bit signed integer.

Sample Input 

1 1
1 2
0 0

Sample Output 

Case 1: 4
Case 2: 18
题意: 给你n*m的网格,问你能有几个三角形。
思路: 我们先计算任意三个点组成的可能,然后排除同一水平,同一垂直的,同一斜线的,前两个比较好计算,同一斜线的稍复杂。
同一斜线的和上一题UVA - 1393 Highways 一样也是要用容斥原理,首先我们动手计算一下,可能发现每次多的是gcd(i, j)-1,然后再去重,dp[i][j]代表从左上角[0,0]
到这个点[i,j]并以这两个点为端点枚举三点共线的个数,最后还要递推一次,得到n*m的网格三点共线的个数,当然这也要*2,感觉怪怪的,瞎搞过的
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
typedef long long ll;
using namespace std;
const int maxn = 1010;

ll dp[maxn][maxn], ans[maxn][maxn];
int n, m;

int gcd(int a, int b) {
	return b==0?a:gcd(b, a%b);
}

void init() {
	memset(dp, 0, sizeof(dp));
	memset(ans, 0, sizeof(ans));

	for (int i = 1; i < maxn; i++)
		for (int j = 1; j < maxn; j++)
			dp[i][j] = dp[i-1][j] + dp[i][j-1] - dp[i-1][j-1] + gcd(i, j) - 1;

	for (int i = 1; i < maxn; i++)
		for (int j = 1; j < maxn; j++)
			ans[i][j] = ans[i-1][j] + ans[i][j-1] - ans[i-1][j-1] + dp[i][j];
}

ll cal(int x) {
	if (x < 3)
		return 0;
	return (ll) x * (x - 1) * (x - 2) / 6;
}

int main() {
	init(); 
	int cas = 1;
	while (scanf("%d%d", &n, &m) != EOF && n + m) {
		printf("Case %d: ", cas++);
		ll sum = cal((n+1)*(m+1)) - (m+1)*cal(n+1) - (n+1)*cal(m+1) - ans[n][m] * 2;
		printf("%lld\n", sum);
	}
	return 0;
}