Problem J
(2/3/4)-D Sqr/Rects/Cubes/Boxes?
Input: standard input
Output: standard output
Time Limit: 2 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 ofN 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 whereS2 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
公式:
输入N边;
正方形(k维数) s = 1^k + 2^k + 3^K + …… N^k;
矩形(k维数) m =( N*(N+1)/2)^K - s;
方法1:#include<iostream>
#include<stdio.h>
#include<math.h>
#define N 200
using namespace std;
int main(){
long long n;
//long long s2[N],s3[N],s4[N];
//long long r2[N],r3[N],r4[N];
//s2[0] = 0;
//s3[0] = 0;
//s4[0] = 0;
while(scanf("%lld",&n) != EOF)
{
long long m = (n + 1)*n/2;
long long s1 = m*m;
long long s2 = m*m*m;
long long s3 = m*m*m*m;
long long r1 = 0;
long long r2 = 0;
long long r3 = 0;
int i ;
for( i = 1 ; i <= n; i++)
{
r1 += i*i;
r2 += i*i*i;
r3 += i*i*i*i;
/*s2[i] = s2[i - 1] + i *i;
s3[i] = s3[i - 1] + i*i*i;
s4[i] = s4[i - 1] + i*i*i*i;
r2[i] = (i*(i + 1)/2)*(i*(i+1)/2) - s2[i];
r3[i] =(i*(i + 1)/2)*(i*(i+1)/2)*(i*(i + 1)/2) - s3[i];
r4[i] = (i*(i+1)/2)*((i+1)*i/2)*((i+1)*i/2)*((i+1)*i/2) - s4[i];
*/
}
printf("%lld %lld %lld %lld %lld %lld\n",r1,s1 - r1,r2,s2-r2,r3,s3-r3);
}
return 0;
}
方法2:
求总数的时候不可以不可以放在循环里面,不然会wa。
#include<iostream>
#include<stdio.h>
#include<math.h>
#include <cstring>
#define N 200
using namespace std;
int main(){
int n;
long long s2[N],s3[N],s4[N], m;
long long r2[N],r3[N],r4[N];
s2[0] = 0;
s3[0] = 0;
s4[0] = 0;
while(scanf("%d",&n) != EOF)
{
for(int i = 1 ; i <= n; i++)
{
s2[i] = s2[i - 1] + i *i;
s3[i] = s3[i - 1] + i*i*i;
s4[i] = s4[i - 1] + i*i*i*i;
}
m = n * (n + 1) / 2;
r2[n] = m * m - s2[n];
r3[n] = m * m * m - s3[n];
r4[n] = m * m * m * m - s4[n];
printf("%lld %lld %lld %lld %lld %lld\n",s2[n],r2[n],s3[n],r3[n],s4[n],r4[n]);
}
return 0;
}