24h購物| | PChome| 登入
2012-04-04 09:45:40| 人氣1,662| 回應0 | 上一篇 | 下一篇

[UVA][DP] 10502 - Counting Rectangles

推薦 0 收藏 0 轉貼0 訂閱站台

Problem C
Counting rectangles
 

In some tests there appears the problem of finding the number of rectangles (or circles, or triangles, ...) of different sizes in a figure. We consider the problem of counting rectangles (including squares) in a rectangular board.

Given a rectangular board with n rows and m columns, with valid possitions marked with 1 and non valid possitions marked with 0,  we want to count the number of rectangles (including squares) in the board formed by squares marked with 1.

The Input

The input will consist of a series of problems, with each problem in a serie of lines. In the first and second lines the rows (n) and columns (m) of the board are indicated, in the next n lines the board in represented, with a row of the board in each line, and m 0 or 1 (without spaces) in each line. When the input of a problem finishes the next problem begins in the next line. The input finishes when 0 appears as the dimension of the board. Both dimensions of the board are less than or equal to 100.

The Output

The solution of each problem appears in a line, without separation between lines. For example, in the board

 

11

01

the rectangles are:

 

1-

--

 

-1

--

 

--

-1

 

11

--

 

-1

-1

 

Sample Input

2

11

01

4

3

110

101

111

011 

0

Sample Output

5

22 


做法 : O(N^3)


求更快解法!


#include <stdio.h>

int main() {
    int n, m, i, j, k;
    char map[101][101];
    while(scanf("%d", &n) == 1 && n) {
        scanf("%d", &m);
        for(i = 0; i < n; i++)
            scanf("%s", &map[i]);
        int ans = 0, length, width, tmp;
        for(i = 0; i < n; i++) {
            int sum[101] = {};
            for(j = i; j < n; j++) {
                for(k = 0; k < m;  k++) {
                    sum[k] += map[j][k]-'0';
                    if(k == 0 || tmp != length*width)
                        tmp = 0, length = 0;
                    tmp += sum[k];
                    length++, width = j-i+1;
                    if(tmp == length*width)
                        ans += length;
                }
            }
        }
        printf("%d\n", ans);
    }
    return 0;
}

台長: Morris
人氣(1,662) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA][D&C] 10702 - Travelling Salesman
此分類上一篇:[UVA][DP] 624 - CD

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文