【待完善】UVA-11538:Chess Queen

UVA-11538:Chess Queen

来源:UVA

标签:数论

参考资料:

相似题目:

题目

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 (2 × 2) chess board. They can be in attacking positions in 12 ways, these are shown in the picture below:
这里写图片描述
Given an (N × M) board you will have to decide in how many ways 2 queens can be in attacking position in that.

输入

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.

输出

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 (M × N) board, where the values of M and N came from the input. All output values will fit in 64-bit signed integer.

输入样例

2 2
100 223
2300 1000
0 0

输出样例

12
10907100
11514134000

题目大意

解题思路

总方案数=所有行的方案数+所有列的方案数+所有对角线的方案数。在同一行上有n(n-1)种(即A(n,2)),共m行,故所有行的方案数为mn(n-1)。所有列的方案数类似。在m*n的棋盘中,对角线的长度依次是1,2,3,…,m-1,m,m,m,m(共n-m+1个m),m-1,m-2,…,2,1,这样就与行列一样了。由于对角线有2种方向,所以结果要乘2。

参考代码(AC)

#include<stdio.h>
int main(){
    long long m,n;//m:row, n:col
    while(scanf("%lld%lld",&m,&n) && m){
        unsigned long long ans=0;
        if(m>n){
            unsigned long long t=m;
            m=n;
            n=t;
        }
        ans+=m*n*(n-1);//row 
        ans+=n*m*(m-1);//col 
        ans+=2*m*(m-1)*(3*n-m-1)/3;//diagonal
        printf("%lld\n",ans);
    }
    return 0;
}

参考代码(WA)

#include<stdio.h>
int main(){
    int m,n;//m:row, n:col
    while(scanf("%d%d",&m,&n) && m){
        unsigned long long ans=0;
        if(m>n){
            int t=m;
            m=n;
            n=t;
        }
        ans+=m*n*(n-1);//row 
        ans+=n*m*(m-1);//col 
        ans+=2*m*(m-1)*(3*n-m-1)/3;//diagonal
        printf("%lld\n",ans);
    }
    return 0;
} 

猜你喜欢

转载自blog.csdn.net/wingrez/article/details/81488135