UVa - 11538 - Chess Queen

先上题目

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:

 

 

 
  

Figure: in a (2x2) chessboard 2 queens can be in attacking position in 12 ways

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, N£106) 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

    图片可能看不到,可以去UVa上面找这题看一下。

  题意就是在一个n*m的棋盘里面放两只王后一黑一白,求出她们会互相攻击的摆法的数目。

     这里先分析她们的互相攻击关系有3种:同一行(a),同一列(b),对角线(c)。然后对她们进行分类计算。

  求出a=n*m*(m-1);

    b=m*n*(n-1);

    c=2*(2*n*(n-1)*(3*m-n-1))/3;

    其中c是对角线的情况。这里需要用推出公式,由Ni=1,2,3···,(n-m+1)个n,···3,2,1可得出其中一只王后在棋盘上的每一条斜线上面方法,而另一只王后则在第i种情况下有(Ni)-1种情况ΣNi*(Ni-1)。同时有两个方向的斜线要考虑,所以要乘以2。

    这里还要需要注意乘法溢出的问题,最好使用unsigned long long。由于输入输出的麻烦,以后做排列组合的问题最后用cin和cout来完成。

    还有一个问题需要注意的就是这里要假设n<=m因为c的计算公式是在这个条件下进行的。所以在计算前要判断一下两者大小,并且确定是否要交换。

上代码

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <iostream>
 4 
 5 using namespace std;
 6 
 7 int main()
 8 {
 9     unsigned long long  n,m;
10     while((cin>>n>>m),(n || m))
11     {
12         unsigned long long a,b,c,d,sum;
13         if(n>m)
14         {
15             n=n^m;
16             m=n^m;
17             n=n^m;
18         }
19         a=n*m*(m-1);
20         b=m*n*(n-1);
21         c=2*n*(n-1);
22         d=(3*m-n-1);
23         if(c%3) d/=3;
24         else c/=3;
25         c=c*d;
26         sum=a+b+c;
27         cout<<a+b+c<<endl;
28 
29     }
30     return 0;
31 }
32 
33 
34 /*
35 
36 2 2
37 100 223
38 2300 1000
39 0 0
40 
41 
42 12
43 10907100
44 11514134000
45 
46 */
View Code

 

转载于:https://www.cnblogs.com/sineatos/p/3185045.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值