10656 - Maximum Sum (II)
Time limit: 3.000 seconds
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=1597
In a given a sequence of non-negative integers you will have to find such a sub-sequence in it whose summation is maximum.
Input
The input file contains several input sets. The description of each set is given below:
Each set starts with an integer N (N<1000) that indicates how many numbers are in that set. Each of the next N lines contains a single non-negative integer. All these numbers are less than 10000.
Input is terminated by a set where N=0. This set should not be processed.
Output
For each set of input produce one line of output. This line contains one or more integers which is are taken from the input sequence and whose summation is maximum. If there is more than one such sub-sequence print the one that has minimum length. If there is more than one sub-sequence of minimum length, output the one that occurs first in the given sequence of numbers. A valid sub-sequence must have a single number in it. Two consecutive numbers in the output are separated by a single space.
Sample Input
2
3
4
0
Output for Sample Input
3 4
注意子序列可以不連續(有些題沒說連續但是範例是連續的,有些題看上去像是連續的但WA了後才知道是可以不連續的)
完整代碼:
/*0.029s*/ #include<cstdio> int main() { int n, a; bool vis; while (scanf("%d", &n), n) { vis = false; while (n--) { scanf("%d", &a); if (a) { if (vis) putchar(' '); vis = true; printf("%d", a); } } if (!vis) putchar('0'); putchar(10); } return 0; }
查看本欄目更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/