【HDU - 1559】最大子矩陣 (二維字首和裸題)
阿新 • • 發佈:2018-12-08
題幹:
給你一個m×n的整數矩陣,在上面找一個x×y的子矩陣,使子矩陣中所有元素的和最大。
Input
輸入資料的第一行為一個正整數T,表示有T組測試資料。每一組測試資料的第一行為四個正整數m,n,x,y(0<m,n<1000 AND 0<x<=m AND 0<y<=n),表示給定的矩形有m行n列。接下來這個矩陣,有m行,每行有n個不大於1000的正整數。
Output
對於每組資料,輸出一個整數,表示子矩陣的最大和。
Sample Input
1 4 5 2 2 3 361 649 676 588 992 762 156 993 169 662 34 638 89 543 525 165 254 809 280
Sample Output
2474
解題報告:
預處理一個字首和然後O1查詢就行了。(四個月前寫的題今天在學最小環問題的時候忽然發現了,emmm拿出來寫一個部落格吧)
AC程式碼:
#include<bits/stdc++.h> #define ll long long using namespace std; const int MAX = 1e3 + 5; const int INF = 0x3f3f3f3f; ll a[MAX][MAX]; int main() { int t; int m,n,x,y; ll maxx; cin>>t; while(t--) { maxx = -INF; scanf("%d%d%d%d",&m,&n,&x,&y); for(int i = 1; i<=m; i++) { for(int j = 1; j<=n; j++) { scanf("%lld",&a[i][j]); } } for(int i = 1; i<=m; i++) { for(int j = 1; j<=n; j++) { a[i][j] = a[i][j] + a[i-1][j] + a[i][j-1] - a[i-1][j-1]; } } //從i,j開始 到 i+x-1,j+y-1 for(int i = 1; i<=m-x+1; i++) { for(int j = 1; j<=n-y+1; j++) { maxx = max(maxx,a[i+x-1][j+y-1]-a[i+x-1][j-1]-a[i-1][j+y-1]+a[i-1][j-1]); } } printf("%lld\n",maxx); } return 0 ; }