PAT 1등급 1007 맥심썸 서브스퀸스 썸(25점) 분할/DP

6988 단어 PAT 등급
1007 Maximum Subsequence Sum (25점)
Time limit: 200 ms
Memory limit: 64 MB
Source limit: 16 KB
Given a sequence of K K K integers {   N 1 ,   N 2 ,   . . . ,   N K   }\left\{\N_1,\N_2,\...,\N_K\\right\} { N1​, N2​, ..., NK​ }. A continuous subsequence is defined to be {   N i ,   N i + 1 ,   . . . ,   N j   }\left\{\N_i,\N_{i+1},\...,\N_j\\right\} { Ni​, Ni+1​, ..., Nj​ } where 1 ≤ i ≤ j ≤ K 1≤i≤j≤K 1≤i≤j≤K. The Maximum Subsequence is the continuous subsequence which has the largest sum of its elements. For example, given sequence { -2, 11, -4, 13, -5, -2 }, its maximum subsequence is { 11, -4, 13 } with the largest sum being 20.
Now you are supposed to find the largest sum, together with the first and the last numbers of the maximum subsequence.
Input
Each input file contains one test case. Each case occupies two lines. The first line contains a positive integer K   ( ≤ 10000 ) K\(≤10000) K (≤10000). The second line contains K K K numbers, separated by a space.
Output
For each test case, output in one line the largest sum, together with the first and the last numbers of the maximum subsequence. The numbers must be separated by one space, but there must be no extra space at the end of a line. In case that the maximum subsequence is not unique, output the one with the smallest indices i i i and j j j (as shown by the sample case). If all the K K K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence.
Example
input
10-10 1 2 3 4 -5 -23 3 7 -21
output
10 1 4
제목:
최대 하위 시퀀스의 합을 구하려면 N N 개의 수로 구성된 시퀀스를 입력합니다.
아이디어:
두 가지 알고리즘: 분할 알고리즘, 동적 기획.
분치 알고리즘은 서열을 둘로 나누어 왼쪽의 가장 큰 서열과 오른쪽의 가장 큰 서열의 합을 구한 다음에 두 개의 서열을 뛰어넘는 가장 큰 서열의 합을 구한다.최종적으로 삼자 중 가장 큰 합을 취하다.
동적 기획 방법은 수조를 한 번 훑어보고sum를 마이너스로 하는 서열을 버리는 것이다.
참조 코드:
#include 
const int MAXN = 10000;
int a[MAXN], n;
int main() {
    int ret = -1, sum = 0, pre = 0, n;
    scanf("%d", &n);
    int lo = 0, hi = n - 1;
    for (int i = 0; i < n; ++i) {
        scanf("%d", a + i);
        sum += a[i];
        if (ret < sum) {
            ret = sum;
            lo = pre;
            hi = i;
        }
        else if (sum < 0) {
            sum = 0;
            pre = i + 1;
        }
    }
    if (ret < 0) ret = 0;
    printf("%d %d %d
"
, ret, a[lo], a[hi]); return 0; }

좋은 웹페이지 즐겨찾기