栗酱的连通图
栗酱的连通图
https://ac.nowcoder.com/acm/problem/14678
思路
其实就是输入一个长度为n的数组,数组中元素值均为偶数,按照题中的规定,计算任意两个元素之间的值(两个元素之和再除以2)。那么可以找出数组中最大的元素(通过排序可实现,或者定义一个变量max
,循环遍历一遍数组也可以找出),然后将数组中其他元素都跟这个max
进行求和再除以2,把结果统计到一变量中即可。
代码实现
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// t组数据
int t = sc.nextInt();
for(int i = 0; i < t; i++){
// 数组长度
int n = sc.nextInt();
int[] arr = new int[n];
// 输入数组元素值
for(int j = 0; j < n; j++) {
arr[j] = sc.nextInt();
}
// 对数组排序,找最大的
Arrays.sort(arr);
int sum = 0;
for(int x = 0; x < n - 1; x++) {
sum += (arr[x] + arr[n-1]) / 2;
}
System.out.println(sum);
}
}
}