前缀和用于优化时间复杂度。
下面的例题难度依次上升。
一、最小和(一维数组)
题目描述:
输入n个数的数列,所有相邻m数的和有n-m+1个,求其中的最小值。
输入格式:
第一行,n,m
第二行,有n个正整数
输出格式:
输出最小值
输入样例:
6 3
10 4 1 5 5 2
输出样例:
10
反正我没看题解之前,就是一个嵌套循环,一个个枚举下去。OK,下面是代码:
#include<bits/stdc++.h>
using namespace std;
const int INF=0x3f3f3f;
int main()
{
int a[1000]={0}, sum[1000];
int n, m;
cin>>n>>m;
for(int i=1; i<=n; i++)
{
cin>>a[i];
sum[i]=sum[i-1]+a[i];
}
int min=INF;
for(int i=0; i<=n-m; i++)
{
min=min<(sum[i+m]-sum[i])?min:(sum[i+m]-sum[i]);
}
cout<<min<<endl;
}
二、To The Max(二维数组)
传送门:http://poj.org/problem?id=1050
题目描述:
Given a two-dimensional array of positive and negative integers, a sub-rectangle is any contiguous sub-array of size 1*1 or greater located within the whole array. The sum of a rectangle is the sum of all the elements in that rectangle. In this problem the sub-rectangle with the largest sum is referred to as the maximal sub-rectangle. As an example, the maximal sub-rectangle of the array:
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
is in the lower left corner:
9 2
-4 1
-1 8 a
nd has a sum of 15.
输入格式:
The input consists of an N * N array of integers. The input begins with a single positive integer N on a line by itself, indicating the size of the square two-dimensional array. This is followed by N^2 integers separated by whitespace (spaces and newlines). These are the N^2 integers of the array, presented in row-major order. That is, all numbers in the first row, left to right, then all numbers in the second row, left to right, etc. N may be as large as 100. The numbers in the array will be in the range [-127,127].
输出格式:
Output the sum of the maximal sub-rectangle.
输入样例:
40 -2 -7 0 9 2 -6 2 -4 1 -4 1 -1 8 0 -2
输出样例:
15
题目大意是:在已知二维数组中找到一个子二维数组使得该子数组为最大。
AC代码:
#include<iostream>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define INF 0x3f3f3f3f
int joy(int a[], int n)
{
int m=-INF, tmp=-1;
for(int i=0; i<n; i++)
{
if(tmp>0) tmp+=a[i];
else tmp=a[i];
m=tmp>m?tmp:m;
}
return m;
}
int main()
{
int n;
while(cin>>n)
{
int a[100][100];
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
cin>>a[i][j];
}
}
int ans=-INF, tmp;
int s[10000];
for(int i=0; i<n; i++)
{
memset(s, 0, sizeof(int)*n);
for(int j=i; j<n; j++)
{
for(int k=0; k<n; k++)
{
s[k]+=a[j][k];
}
tmp=joy(s, n);
ans=tmp>ans?tmp:ans;
}
}
cout<<ans<<endl;
}
return 0;
}