练习1978A. Alice and Books
题目如下
A. Alice and Books
time limit per test1 second
memory limit per test256 megabytes
Alice has 𝑛 books. The 1-st book contains 𝑎1 pages, the 2-nd book contains 𝑎2 pages, …, the 𝑛-th book contains 𝑎𝑛 pages. Alice does the following:
She divides all the books into two non-empty piles. Thus, each book ends up in exactly one of the two piles.
Alice reads one book with the highest number in each pile.
Alice loves reading very much. Help her find the maximum total number of pages she can read by dividing the books into two piles.
Input
Each test consists of multiple test cases. The first line contains a single integer 𝑡 (1≤𝑡≤500) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer 𝑛 (2≤𝑛≤100) — the number of books Alice has.
The second line of each test case contains 𝑛 integers 𝑎1,𝑎2,…,𝑎𝑛 (1≤𝑎𝑖≤109) — the number of pages in each book.
Output
For each test case, output a single integer — the maximum number of pages Alice can read.
题目大意
现有数组表示了从1到n的n页,每页的页数不同,现在将这n页分到两堆中,每堆中挑选出索引最大的,将他们代表的页数相加,最大能得到的页数和是多少。
题目分析
两堆中根据索引大小来判断,那么要使页数尽量大,要使得页数大的在各自堆中索引也尽量大。
点击查看代码
#include <iostream>
using namespace std;
int main(){
int t;
cin >> t;
while(t--){
int n;
cin >> n;
long long a[101];
for(int i = 0; i < n; i++){
cin >> a[i];
}
long long sum = 0;
if(n == 2){
sum = a[0] + a[1];
}else{
long long max = a[0];
for(int i = 1; i < n - 1; i++){
if(a[i] > max){
max = a[i];
}
}
sum = max + a[n - 1];
}
cout << sum << endl;
}
}

浙公网安备 33010602011771号