练习codeforces1557A. Ezzat and Two Subsequences
题目如下
A. Ezzat and Two Subsequences
time limit per test1 second
memory limit per test256 megabytes
Ezzat has an array of 𝑛 integers (maybe negative). He wants to split it into two non-empty subsequences 𝑎 and 𝑏, such that every element from the array belongs to exactly one subsequence, and the value of 𝑓(𝑎)+𝑓(𝑏) is the maximum possible value, where 𝑓(𝑥) is the average of the subsequence 𝑥.
A sequence 𝑥 is a subsequence of a sequence 𝑦 if 𝑥 can be obtained from 𝑦 by deletion of several (possibly, zero or all) elements.
The average of a subsequence is the sum of the numbers of this subsequence divided by the size of the subsequence.
For example, the average of [1,5,6] is (1+5+6)/3=12/3=4, so 𝑓([1,5,6])=4.
Input
The first line contains a single integer 𝑡 (1≤𝑡≤103)— the number of test cases. Each test case consists of two lines.
The first line contains a single integer 𝑛 (2≤𝑛≤105).
The second line contains 𝑛 integers 𝑎1,𝑎2,…,𝑎𝑛 (−109≤𝑎𝑖≤109).
It is guaranteed that the sum of 𝑛 over all test cases does not exceed 3⋅105.
Output
For each test case, print a single value — the maximum value that Ezzat can achieve.
Your answer is considered correct if its absolute or relative error does not exceed 10−6.
Formally, let your answer be 𝑎, and the jury's answer be 𝑏. Your answer is accepted if and only if |𝑎−𝑏|max(1,|𝑏|)≤10−6.
题目大意
将已有数组分为两组,分别求两组数的平均值,最后将两组平均值相加,求最大的平均值之和;
题目思路
本题要求求平均值之和,因为数组中允许有负数存在,所以我们分组的策略是,将最大的数分离出来,保证了最大数的完整,再求剩下数的平均值
完整代码如下
点击查看代码
#include <stdio.h>
#include <stdlib.h>
int compare(const void* a, const void* b){
return (*(long long*)b - *(long long*)a);
}
int main(){
int t;
scanf("%d",&t);
while(t--){
int n;
scanf("%d",&n);
long long num[200005];
long long total = 0;
for(int i = 0; i < n; i++){
scanf("%lld", &num[i]);
total += num[i];
}
qsort(num, n, sizeof(long long), compare);
long long max = num[0];
total -= max; // 剩下部分求平均
double result = max + (double)total / (n - 1);
printf("%.9lf\n", result);
}
return 0;
}
注意输出要求格式

浙公网安备 33010602011771号