24h購物| | PChome| 登入
2012-06-05 06:43:36| 人氣737| 回應0 | 上一篇 | 下一篇

[ACM-ICPC][DP] 4867 - Maximum Square

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

Given an N x M matrix of all 1s and 0s, find the largest submatrix which is a square containing all 1s.

Input 

There will be several test cases in the input. Each test case will begin with two integers, N and M (1$ le$N, M$ le$1, 000) indicating the number of rows and columns of the matrix. The next N lines will each contain M space-separated integers, guaranteed to be either 0 or 1. The input will end with a line with two 0s.

Output 

For each test case, print a single integer, indicating the width (and height) of the largest square of all 1s, or 0 if there are no 1s. Print no extra spaces, and do not print any blank lines between answers.

Sample Input 

4 5 
0 1 0 1 1 
1 1 1 1 1 
0 1 1 1 0 
1 1 1 1 1 
3 4 
1 1 1 1 
1 1 1 1 
1 1 1 1 
6 6 
0 0 0 0 0 0 
0 0 0 0 0 0 
0 0 0 0 0 0 
0 0 0 0 0 0 
0 0 0 0 0 0 
0 0 0 0 0 0 
0 0

Sample Output 

3 
3 
0

求最大矩形, DP 方法找到左, 左上, 上 方的最大矩形, 三者的最小值+1 

#include <stdio.h>
#include <string.h>
#define min(x, y) ((x) < (y) ? (x) : (y))
inline int ReadInt(int *x) {
    static char c, neg;
    while((c = getchar()) < '-')    {if(c == EOF) return EOF;}
    neg = (c == '-') ? -1 : 1;
    *x = (neg == 1) ? c-'0' : 0;
    while((c = getchar()) >= '0')
        *x = (*x << 3) + (*x << 1) + c-'0';
    *x *= neg;
    return 1;
}
int main() {
    int n, m;
    int i, j, A[1001], B[1001];
    while(scanf("%d %d", &n, &m) == 2) {
        memset(A, 0, sizeof(A));
        memset(B, 0, sizeof(B));
        if(n == 0 && m == 0)
            break;
        int *ta = A, *tb = B, *tc;
        int ans = 0, x, t;
        for(i = 1; i <= n; i++) {
            for(j = 1; j <= m; j++) {
                ReadInt(&x);
                if(x) {
                    ta[j] = ta[j-1];
                    ta[j] = min(ta[j], tb[j-1]);
                    ta[j] = min(ta[j], tb[j]);
                    ta[j]++;
                    if(ta[j] > ans)
                        ans = ta[j];
                } else
                    ta[j] = 0;
            }
            tc = ta, ta = tb, tb = tc;
        }
        printf("%d\n", ans);
    }
    return 0;
}

台長: Morris
人氣(737) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[ACM-ICPC][Greedy解] 5864 - Register Allocation
此分類上一篇:[UVA][樹形 DP] 10243 - Fire! Fire!! Fire!!!

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