Problem A
Chess Queen
Input: Standard Input
Output: StandardOutput
You probably know how the game ofchess is played and how chess queen operates. Two chess queens are in attackingposition 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 areshown 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 attackingposition in that.
Input
Input file can contain up to 5000lines of inputs. Each line contains two non-negative integers which denote thevalue 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 produceone line of output. This line contains an integer which denotes in how manyways two queens can be in attacking position in an (MxN) board, wherethe values of M and N came from the input. All output values willfit in 64-bit signed integer.
SampleInput Output for Sample Input
2 2 100 223 2300 1000 0 0 | 12 10907100 11514134000 |
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
public class Main
{
private static final boolean DEBUG = false;
private BufferedReader cin;
private PrintWriter cout;
private StreamTokenizer tokenizer;
private long m, n;
public void init()
{
try {
if (DEBUG) {
cin = new BufferedReader(new InputStreamReader(
new FileInputStream("d:\\OJ\\uva_in.txt")));
} else {
cin = new BufferedReader(new InputStreamReader(System.in));
}
cout = new PrintWriter(new OutputStreamWriter(System.out));
tokenizer = new StreamTokenizer(cin);
} catch (Exception e) {
e.printStackTrace();
}
}
public String next()
{
try {
tokenizer.nextToken();
if (tokenizer.ttype == StreamTokenizer.TT_EOF) return null;
else if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) return String.valueOf((int)tokenizer.nval);
else return tokenizer.sval;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public boolean input()
{
m = Long.parseLong(next());
n = Long.parseLong(next());
if (m == 0 && n == 0) return false;
if (m < n) {
long tmp = m;
m = n;
n = tmp;
}
return true;
}
public void solve()
{
long ans;
ans = m * (m - 1) * n + n * (n - 1) * m +
(n * (n - 1) * (2 * n - 1) / 6 - (n - 1) * n / 2) * 4 + 2 * n * (n - 1) * (m - n + 1);
cout.println(ans);
cout.flush();
}
public static void main(String[] args)
{
Main solver = new Main();
solver.init();
while (solver.input()) {
solver.solve();
}
}
}