基准时间限制:2 秒 空间限制:131072 KB 分值: 40 难度:4级算法题
一个M*N的矩阵,找到此矩阵的一个子矩阵,并且这个子矩阵的元素的和是最大的,输出这个最大的值。
例如:3*3的矩阵:
-1 3 -1
2 -1 3
-3 1 2
和最大的子矩阵是:
3 -1
-1 3
1 2
Input
第1行:M和N,中间用空格隔开(2 <= M,N <= 500)。 第2 - N + 1行:矩阵中的元素,每行M个数,中间用空格隔开。(-10^9 <= M[i] <= 10^9)
Output
输出和的最大值。如果所有数都是负数,就输出0。
Input示例
3 3
-1 3 -1
2 -1 3
-3 1 2
Output示例
7
//前缀和,轻松解决n*n
1 # include <cstdio> 2 # include <cstring> 3 # include <cstdlib> 4 # include <iostream> 5 # include <vector> 6 # include <queue> 7 # include <stack> 8 # include <map> 9 # include <bitset> 10 # include <sstream> 11 # include <set> 12 # include <cmath> 13 # include <algorithm> 14 # pragma comment(linker,"/STACK:102400000,102400000") 15 using namespace std; 16 # define LL long long 17 # define pr pair 18 # define mkp make_pair 19 # define lowbit(x) ((x)&(-x)) 20 # define PI acos(-1.0) 21 # define INF 0x3f3f3f3f3f3f3f3f 22 # define eps 1e-8 23 # define MOD 1000000007 24 25 inline int scan() { 26 int x=0,f=1; char ch=getchar(); 27 while(ch<‘0‘||ch>‘9‘){if(ch==‘-‘) f=-1; ch=getchar();} 28 while(ch>=‘0‘&&ch<=‘9‘){x=x*10+ch-‘0‘; ch=getchar();} 29 return x*f; 30 } 31 inline void Out(int a) { 32 if(a<0) {putchar(‘-‘); a=-a;} 33 if(a>=10) Out(a/10); 34 putchar(a%10+‘0‘); 35 } 36 # define N 505 37 /**************************/ 38 LL sum[N][N]; 39 40 int main() 41 { 42 int n ,m; 43 scanf("%d%d",&m,&n); 44 for (int i=1;i<=n;i++) 45 { 46 for (int j=1;j<=m;j++) 47 { 48 int x = scan(); 49 sum[i][j]=sum[i][j-1]+x; 50 } 51 } 52 LL ans=0; 53 for (int i=1;i<=m;i++) 54 for (int j=i;j<=m;j++) 55 { 56 LL tp=0; 57 for (int k=1;k<=n;k++) 58 { 59 tp = max(sum[k][j]-sum[k][i-1]+tp,0LL); 60 ans = max(tp,ans); 61 } 62 } 63 printf("%lld\n",ans); 64 return 0; 65 }
时间: 2024-12-17 07:43:33