Chess Queen
题目大意:给定一个n × m的棋盘,问有多少种方法放置黑、白两皇后使其相互攻击
同一行/列:nm * (n + m - 2)
不妨令m > n
对角线:不难发现对角线长度为1,2,3...n-1,n,n,n,.....,n,(m - n + 1)个n,n - 1,....,3,2,1
对角线方案 = 2 * Σ(i = 1 to n - 1)i(i - 1) + (m - n + 1) * n * (n - 1)
Σ(i = 1 to n - 1)i(i - 1) = Σ(i = 1 to n - 1)i^2 - Σ(i = 1 to n - 1)i = (n - 1) * n * (2n - 1) / 6 - n (n - 1)/2
(Σ(i = 1 to n)i^2 = n * (n + 1) * (2 * n + 1) / 6)
带入有对角线方案 = 2n * (n - 1) * (3 * m - n - 1)
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cstdlib> 5 #include <algorithm> 6 #include <queue> 7 #include <vector> 8 #define min(a, b) ((a) < (b) ? (a) : (b)) 9 #define max(a, b) ((a) > (b) ? (a) : (b)) 10 #define abs(a) ((a) < 0 ? (-1 * (a)) : (a)) 11 inline void swap(long long &a, long long &b) 12 { 13 long long tmp = a;a = b;b = tmp; 14 } 15 inline void read(long long &x) 16 { 17 x = 0;char ch = getchar(), c = ch; 18 while(ch < '0' || ch > '9') c = ch, ch = getchar(); 19 while(ch <= '9' && ch >= '0') x = x * 10 + ch - '0', ch = getchar(); 20 if(c == '-') x = -x; 21 } 22 23 const long long INF = 0x3f3f3f3f; 24 long long n,m; 25 int main() 26 { 27 while(scanf("%lld %lld", &n, &m) != EOF && n * n + m * m) 28 { 29 if(n > m) swap(n, m); 30 printf("%lld ", n * m * (n - 1) + n * m * (m - 1) + 2 * n * (n - 1) * (3 * m - n - 1) / 3); 31 } 32 return 0; 33 }