Uva 11538 - Chess Queen(计数)

ChessQueen

 

You probably know how the game of chess isplayed and how chess queen operates. Two chess queens are in attacking positionwhen they are on same row, column or diagonal of a chess board. Suppose twosuch chess queens (one black and the other white) are placed on (2x2) chessboard. They can be in attacking positions in 12 ways, these are shown in thepicture below:

 

Given an (NxM) board you willhave to decide in how many ways 2 queens can be in attacking position in that.

 

Input

 

Input file can contain up to 5000 lines ofinputs. Each line contains two non-negative integers which denote the valueof M andN (0< M, N£106)respectively.

 

Input is terminated by a line containingtwo zeroes. These two zeroes need not be processed.

 

Output

 

For each line of input produce one line ofoutput. This line contains an integer which denotes in how many ways two queenscan be in attacking position in  an (MxN) board, where thevalues of M and N came from the input. Alloutput values will fit in 64-bit signed integer.

 

SampleInput                             

2 2

100 223

2300 1000

0 0

Output for Sample Input

12

10907100

11514134000

 【题意】

   m*n的国际象棋棋盘中放置两个不同的皇后,问有多少种放置方法使得两个皇后可以相互攻击,答案在带符号64位整形范围内。

【思路】

   计数问题,相互攻击可分为3类,一类是行,一类是列,另一类是对角线,三种情况相互独立,用加法原理。在同一行相互攻击很简单有a = m*n*(n-1)种情况,同理列的情况数为b = n*m*(m-1),在对角线上有’/’和’\’两种方向的对角线,所以结果要乘2,两皇后顺序可颠倒所以再乘2。假设m>n,则共有n+m-1条对角线,长度分别是1,2,3,…n-1,n,n,…n,n-1,…,3,2,1(m-n+1个n),长为l的对角线的情况数为l*(l-1)所以对上面的(n+m-1)条对角线的情况数求和,结果d = 2*2*(sum(i*(i-1))[1,n-1]+ m*(m-1)/2*(n-m+1))

   这里sum(i*(i-1))=sum(i^2)-sum(i),然后就能用公式了

 

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef unsigned long long ull;

const int maxn = 1e6 + 500;

int main() {
	ull m, n;
	while (cin >> m >> n && m + n) {
		if (n < m) swap(n, m);
		ull ab = m*n*(n - 1) + n*m*(m - 1);
		ull d = 2 * (m - 1)*m*(2 * m - 1) / 3 - 2 * (m - 1)*m  + 2 * m*(m - 1)*(n - m + 1);
		ull ans = ab + d;
		cout << ans << endl;
	}
	return 0;
}

 

 

 

posted @ 2017-11-07 00:04  不想吃WA的咸鱼  阅读(170)  评论(0编辑  收藏  举报