Problem A
Chess Queen
Input: Standard Input
Output: Standard Output
You probably know how the game of chess is played and how chess queen operates. Two chess queens are in attacking position when they are on same row, column or diagonal of a chess board. Suppose two such chess queens (one black and the other white) are placed on (2x2) chess board. They can be in attacking positions in 12 ways, these are shown in the picture below:
![](http://acm.bnu.edu.cn/bnuoj/external/115/p11538.jpg)
Given an (NxM) board you will have to decide in how many ways 2 queens can be in attacking position in that.
Input
Input file can contain up to 5000 lines of inputs. Each line contains two non-negative integers which denote the value of M and N (0< M, N106) respectively.
Input is terminated by a line containing two zeroes. These two zeroes need not be processed.
Output
For each line of input produce one line of output. This line contains an integer which denotes in how many ways two queens can be in attacking position in an (MxN) board, where the values of M and N came from the input. All output values will fit in 64-bit signed integer.
Sample Input Output for Sample Input
2 2 100 223 2300 1000 0 0 |
12 10907100 11514134000 |
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 // File Name: UVA11538.cpp 2 // Author: sheng 3 // Created Time: 2013年05月14日 星期二 13时24分11秒 4 5 #include <stdio.h> 6 #include <math.h> 7 typedef long long LL; 8 9 int main() 10 { 11 LL n, m; 12 LL ans, temps; 13 while (scanf ("%lld%lld", &n, &m) == 2 && (n || m)) 14 { 15 if (n > m) //保证n是最小的 16 { 17 n ^= m; 18 m ^= n; 19 n ^= m; 20 } 21 ans = n * (n-1) * m + m * (m-1) * n; //统计同行同列的情况 22 temps = 0; 23 for (LL i = 2; i < n; i ++) //对角线最多有n个格子,线统计2->n-1个格子的情况 24 { 25 temps += i * (i-1); 26 } 27 temps *= 4; 28 for (LL i = 0; i < 2 * (m - n + 1); i ++) //这里统计斜边n个格子的情况,最多有(m-n+1)条n个格子的斜边,由于有正有反,所以要乘以一个2; 29 { 30 temps += n * (n-1); 31 } 32 ans += temps; //统计结果 33 printf ("%lld\n", ans); 34 } 35 return 0; 36 }
一个大牛的代码://我不知道ta的公式是怎么来的,求解释
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 //11538 Chess Queen Accepted C++ 0.024 2013-04-22 08:15:00 2 #include <iostream> 3 #include <algorithm> 4 #include <cstdio> 5 using namespace std; 6 7 int main() 8 { 9 unsigned long long n, m; 10 while(cin >> n >> m) { 11 if(!m&&!n) break; 12 if(n>m) swap(n, m); 13 long long res = n*m*(m+n-2)+2*n*(n-1)*(3*m-n-1)/3 ; 14 cout << res << endl; 15 } 16 return 0; 17 }