您的位置:首页 > 其它

hdu1510 White Rectangles(组合计数问题)

2015-05-22 16:09 337 查看

[align=left]Problem Description[/align]
You are given a chessboard made up of N squares by N squares with equal size. Some of the squares are colored black, and the others are colored white. Please write a program to calculate the number of rectangles which are completely
made up of white squares.

 

[align=left]Input[/align]
There are multiple test cases. Each test case begins with an integer N (1 <= N <= 100), the board size. The following N lines, each with N characters, have only two valid character values:

# - (sharp) representing a black square;

. - (point) representing a white square.

Process to the end of file.

 

[align=left]Output[/align]
For each test case in the input, your program must output the number of white rectangles, as shown in the sample output.

 

[align=left]Sample Input[/align]

2
.#
..
4
..#.
##.#
.#..
.#.#

 

[align=left]Sample Output[/align]

5
15题意:给出一个n行n列的矩阵,矩阵中仅包含.和#两种字符,问由字符.组成的矩形个数有多少个?思路:以一行为列,其个数为由1个.,2个.,,, n-1个.组成的矩形之和 两行时,从第一列开始遍历至列尾,统计计数,表示到包含第二行,第k列的.时,矩形宽度为1的矩形个数,然后相加 从第二列开始遍历到列尾,表示到包含第二行,第k列,矩形宽度为2的矩形个数 依此类推代码如下
import java.io.FileInputStream;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Scanner;

public class Main implements Runnable
{
private static final boolean DEBUG = false;
private Scanner cin;
private PrintWriter cout;
private static final int N = 101;
private static final int[][] m = new int

;
private static final int[][] dp = new int

;

private int n;

private void init()
{
try {
if (DEBUG) {
cin = new Scanner(new InputStreamReader(new FileInputStream("f:\\OJ\\uva_in.txt")));
} else {
cin = new Scanner(new InputStreamReader(System.in));
}

cout = new PrintWriter(new OutputStreamWriter(System.out));
} catch (Exception e) {
e.printStackTrace();
}
}

private boolean input()
{
if (!cin.hasNextInt()) return false;

n = cin.nextInt();

for (int i = 1; i <= n; i++) {
String tmp = cin.next();
for (int j = 1, size = tmp.length(); j <= size; j++) {
if (tmp.charAt(j - 1) == '.') m[i][j] = 1;
else m[i][j] = 0;
}
}
return true;
}

private void solve()
{
for (int i = 2; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (m[i][j] != 0) m[i][j] += m[i - 1][j];
}
}

int ans = 0;

for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
int tmp = Integer.MAX_VALUE;
for (int k = j; k <= n && m[i][k] != 0; k++) {
tmp = Math.min(tmp, m[i][k]);
ans += tmp;
}
}
}

cout.println(ans);
cout.flush();
}

@Override
public void run()
{
init();

while (input())
{
solve();
}
}

public static void main(String[] args)
{
// TODO code application logic here
new Thread(new Main()).start();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: