题目传送:HDU - 1003
思路:最大子序列和
dp[i]= a[i] (dp[i-1]<0)
dp[i]= dp[i-1]+a[i] (dp[i-1]>=0)
AC代码:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <deque>
#include <cctype>
#define LL long long
#define INF 0x7fffffff
using namespace std;
int n;
int main() {
int T;
int cas = 1;
scanf("%d", &T);
while(T --) {
scanf("%d", &n);
int sum = 0;
int ans = -INF;
int from, to;
int qi = 1, zhong = 1;
for(int i = 1; i <= n; i ++) {
int t;
scanf("%d", &t);
sum += t;
zhong = i;
if(sum > ans) {
ans = sum; from = qi; to = zhong;
}
if(sum < 0) {
qi = i + 1; sum = 0;
}
}
printf("Case %d:\n%d %d %d\n", cas ++, ans, from, to);
if(T != 0) printf("\n");
}
return 0;
}
题目传送:POJ - 1050
思路:最大子矩阵和,原理和上面那个题一样,就是把i~j行的列上的数加到一行去,再算该行的最大子序列和即可(0<=i<=j <n)
AC代码:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <deque>
#include <cctype>
#define LL long long
#define INF 0x7fffffff
using namespace std;
int a[105][105];
int tmp[105];
int n;
int fun() {
int max = -1, sum = 0;
for(int i = 0; i < n; i ++) {
sum += tmp[i];
if(sum > max) max = sum;
if(sum < 0) sum = 0;
}
return max;
}
int main() {
while(scanf("%d", &n) != EOF) {
for(int i = 0; i < n; i ++) {
for(int j = 0; j < n; j ++) {
scanf("%d", &a[i][j]);
}
}
int ans = -1;
for(int i = 0; i < n; i ++) {
memset(tmp, 0, sizeof(tmp));
for(int j = i; j < n; j ++) {
for(int k = 0; k < n; k ++) {
tmp[k] += a[j][k];
}
int t = fun();
if(ans < t) ans = t;
}
}
cout << ans << endl;
}
return 0;
}