動態規劃-面積最大的全1子矩陣

來源:互聯網
上載者:User
題目描述:

在一個M * N的矩陣中,所有的元素只有0和1,從這個矩陣中找出一個面積最大的全1子矩陣,所謂最大是指元素1的個數最多。

輸入:

輸入可能包含多個測試範例。
對於每個測試案例,輸入的第一行是兩個整數m、n(1<=m、n<=1000):代表將要輸入的矩陣的大小。
矩陣共有m行,每行有n個整數,分別是0或1,相鄰兩數之間嚴格用一個空格隔開。

輸出:

對應每個測試案例,輸出矩陣中面積最大的全1子矩陣的元素個數。

範例輸入:
2 20 00 04 40 0 0 00 1 1 00 1 1 00 0 0 0
範例輸出:
04

#include <stdio.h>#include <string.h>#include <iostream>using namespace std;int mat[1010][1010];int h[1010]; //當前的高度int l[1010]; //儲存符合當前高度的,左起始位置int r[1010]; //右起始位置int main(){int n, m;freopen("input.txt", "r", stdin);while (scanf("%d%d", &n, &m) == 2){for (int i = 1; i <= n; i++){for (int j = 1; j <= m; j++){scanf("%d", &mat[i][j]);}}memset(h, 0, sizeof(h));int ans = 0;for (int i = 1; i <= n; i++){for (int j = 1; j <= m; j++){if (mat[i][j] == 1){h[j]++;}else{h[j] = 0;}}h[0] = h[m + 1] = -1;//l[j] : 符合高度h[j]的矩陣的左起始位置for (int j = 1; j <= m; j++){int k = j; // k儲存 左起始位置while (h[j] <= h[k - 1]){k = l[k - 1]; //依次和前一個高度比較,如果當前高度小於等於k的前一個,則 k繼續向左。}l[j] = k;}//for (int j = 1; j <= m; j++)//{//cout << l[j] << " ";//}//cout << endl ;for (int j = m; j >= 1; j--){int k = j;while (h[j] <= h[k + 1])k = r[k + 1];r[j] = k;}//for (int j = 1; j <= m; j++)//{//cout << r[j] << " ";//}//cout << endl <<endl;for (int j = 1; j <= m; j++){if (ans < h[j] * (r[j] - l[j] + 1)){ans = h[j] * (r[j] - l[j] + 1);}}}printf("%d\n", ans);}return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.