Topic links
Test instructions: Give the chessboard of M row N, when the two queens can attack each other when they are on the same row or on the same diagonal, ask how many kinds of attacks are common.
Analysis: The first can be discussed by the principle of addition: ① two queens in the same row; ② two queens in the same column; ③ two queens on the same diagonal (/or \);
Secondly, the multiplication principle is used to discuss:
① the same row (a), select a row to place one of the Queens, M*n, and then select one of the other n-1 positions in the chosen line to place the other queen; a total of m*n* (n-1);
② the same column (B), the case is n*m* (m-1);
③ on the same diagonal (D), first discuss/direction diagonal:
For the convenience of assuming m>=n, the diagonal length from left to right is:
,... ..., n-1,n,n,... ..., n,n,n-1,... ... 3,2,1
The middle of which N has (m-n+1) A;
Then total: (1*0 + 2*1 + ... + (n-1) * (n-2)) * 2 + (m-n+1) *n* (n-1) case;
where ∑[1,n-1] (i* (i-1)) =∑[1,n-1] (i*i-i) =∑[1,n-1] (i*i)-∑[1,n-1] (i);
∑[1,n-1] (I*i) = N (n-1) * (2n-1)/6; ∑ (1,n-1) (i) = N (n-1)/2;
The original can be simplified to n (n-1) * (2n-4)/3 + (m-n+1) *n* (n-1);
In addition to the diagonal condition, the same as above, then d = * (n (n-1) * (2n-4)/3 + (m-n+1) *n* (n-1));
The answer is a+b+d;
The code is as follows
1#include <iostream>2#include <cstdio>3#include <cstdlib>4 using namespacestd;5 6typedef unsignedLong LongULL;7 8 intMain ()9 {Ten ULL m, N; One while(Cin >> M >>N) A { - if(!m &&!n) Break; - if(m<N) Swap (m, n); theULL A = m*n* (n1), B = n*m* (M-1); -ULL D =2* (n1)*(2*n-4)/3+ (m-n+1) *n* (n1)); -cout << a+b+d <<Endl; - } + return 0; -}
View Code
"Basic Counting Method---addition principle and multiplication principle" UVa 11538-chess Queen