PAT 1등급 1007 맥심썸 서브스퀸스 썸(25점) 분할/DP
6988 단어 PAT 등급
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;
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
1093 Count PAT's (25점) DP 포함 방법The string APPAPT contains two PAT’s as substrings. The first one is formed by the 2nd, the 4th, and the 6th characters,...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.