Sum solution to a problem of dynamic programming HDU1003 Max and maximum field expansion

Topic links: http://acm.hdu.edu.cn/showproblem.php?pid=1003

Subject to the effect:
solving a sequence of maximum field and, starting and ending coordinates have been foremost that the largest sub-segment.

Problem-solving ideas:
the defined state \ (f [i] \) is to \ (a [i] \) at the end of the field and the maximum, there are state transition equation:

\[f[i] = \max(0, f[i-1]) + a[i]\]

At the same time a defined state \ (s [i] \) represented by \ (a [i] \) coordinate of the left end of the element is maximum field, there are:

  • \(f[i] \lt 0\) 时,\(s[i] = i\)
  • This \ (f [i] \ ge 0 \) Sometimes, \ (S [I] = S [I-1] \)

Codes are as follows:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
int T, n, a[maxn], f[maxn], anss, anst, s[maxn], ans;
int main() {
    scanf("%d", &T);
    for (int cas = 1; cas <= T; cas ++) {
        if (cas > 1) puts("");
        scanf("%d", &n);
        for (int i = 1; i <= n; i ++) scanf("%d", a+i);
        ans = f[1] = a[1];
        anss = anst = s[1] = 1;
        for (int i = 2; i <= n; i ++) {
            if (f[i-1] >= 0) {
                f[i] = f[i-1] + a[i];
                s[i] = s[i-1];
            }
            else {
                f[i] = a[i];
                s[i] = i;
            }
            if (f[i] > ans) {
                ans = f[i];
                anss = s[i];
                anst = i;
            }
        }
        printf("Case %d:\n", cas);
        printf("%d %d %d\n", ans, anss, anst);
    }
    return 0;
}

Guess you like

Origin www.cnblogs.com/quanjun/p/12189728.html