10177 - (2/3/4)-D Sqr/Rects/Cubes/Boxes?
Time limit: 3.000 seconds
You can see a (4x4) grid below. Can you tell me how many squares and rectangles are hidden there? You can assume that squares are not rectangles. Perhaps one can count it by hand but can you count it for a (100x100) grid or a (10000x10000) grid. Can you do it for higher dimensions? That is can you count how many cubes or boxes of different size are there in a (10x10x10) sized cube or how many hyper-cubes or hyper-boxes of different size are there in a four-dimensional (5x5x5x5) sized hypercube. Remember that your program needs to be very efficient. You can assume that squares are not rectangles, cubes are not boxes and hyper-cubes are not hyper-boxes.
![]() | ![]() |
Fig: A 4x4 Grid | Fig: A 4x4x4 Cube |
Input
The input contains one integer N (0<=N<=100) in each line, which is the length of one side of the grid or cube or hypercube. As for the example above the value of N is 4. There may be as many as 100 lines of input.
Output
For each line of input, output six integers S2, R2, S3, R3, S4, R4 in a single line where S2 means no of squares of different size in ( NxN) two-dimensional grid, R2 means no of rectangles of different size in (NxN) two-dimensional grid. S3, R3, S4, R4 means similar cases in higher dimensions as described before.
Sample Input:
12
3
Sample Output:
1 0 1 0 1 05 4 9 18 17 64
14 22 36 180 98 1198
思路:
以二维为例,正方形的个数怎么算?
1×1的肯定有n×n个,2×2的就有(n-1)*(n-1)个。。。。。。。n×n的只有1个,就是平方和公式。
同理三维就是立方和公式,四维就是4次幂和。
然后我们要求出包含正方形的矩形的个数,减去正方形个数就能求出非正方形矩形的个数了,怎么求?
我们可以这样思考:每条边任意取两条线,这两条线一定能组成一个矩形(当然也可能是正方形,正方形也是矩形)。
所以矩形的个数就是就是C(n+1,2) * C(n+1,2),也就是(n+1)* n / 2 的平方,那么3维也就是3次方,四维就是4次方。
先放上未优化的代码:
/*0.015s*/
#include<cstdio>
#include<cstring>
#include<cmath>
int main(void)
{
long long n, s[3], q[3];
while (~scanf("%lld", &n))
{
memset(s, 0, sizeof(s));
memset(q, 0, sizeof(q));
long long k = n * (n + 1) >> 1;
for (int i = 1; i <= n; i++)
for (int j = 0; j < 3; j++)
s[j] += pow(i, j + 2);
for (int i = 0; i < 3; i++)
q[i] = pow(k, i + 2) - s[i];
for (int i = 0; i < 2; i++)
printf("%lld %lld ", s[i], q[i]);
printf("%lld %lld\n", s[2], q[2]);
}
return 0;
}
优化代码:
/*0.013s*/
#include <cstdio>
int main(void)
{
long long N;
long long s2, r2, s3, r3, s4, r4;
while (~scanf("%lld", &N))
{
s2 = N * (N + 1) * ((N << 1) + 1) / 6;
r2 = N * N * (N + 1) * (N + 1) >> 2;
s3 = r2;
r3 = r2 * N * (N + 1) >> 1;
s4 = (6 * N * N * N * N * N + 15 * N * N * N * N + 10 * N * N * N - N) / 30;
r4 = r3 * N * (N + 1) >> 1;
printf("%lld %lld %lld %lld %lld %lld\n", s2, r2 - s2, s3, r3 - s3, s4, r4 - s4);
}
return 0;
}