Gym 102263 Problem - Bashar and Hamada
题目类型:思维
题意
给定一个长度为 n 的数组,然后每次从中取一个长为 k 的子序列且子序列中任意两个不同元素的差的绝对值的总和要最大,其中 k 从 2~n。
分析
k = 2 时一定是取数组中的最小值和最大值即 Min、Max
s2 = Max - Min
k = 3 时取 Min、x、Max
s3 = Max - x + Max - Min + x - Min = 2 * s2
k = 4 时取Min、x、y、Max
s4 = Max - y + Max - x + Max - Min + y - x + y - Min + x - Min
整理一下
s4 = s2 + s3 + |y - x|
想要使 s4 最大则需要 x 为剩下元素中最小的,y 为剩下元素中最大的。
所以之后的就是一次剩下元素中最小的,一次取剩下元素中最大的,重复进行。
具体细节可参考代码:
代码
import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
static final int MAX_N = 300010;
static final int INF = 0x3f3f3f3f;
static final int mod = 1000000007;
public static void main(String[] args) throws IOException {
initReader(System.in);
solve();
printWriter.flush();
}
/****************************************************************************************************************/
static int[] a = new int[MAX_N];
public static void solve() throws IOException {
int n = nextInt();
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
Arrays.sort(a, 0, n);
Deque<Integer> dq = new LinkedList<Integer>();
for (int i = 0; i < n; i++) {
dq.addLast(a[i]);
}
long minSum = 0, maxSum = 0;
minSum += dq.pollFirst();
maxSum += dq.pollLast();
long ans = maxSum - minSum;
long cnt1 = 0, cnt2 = 0;
printWriter.print(ans + " ");
// if time is even operate the min value,else operate the max value
int time = 0;
while (!dq.isEmpty()) {
if ((time & 1) == 0) {
ans += maxSum - minSum + (cnt1 - cnt2) * dq.peekFirst();
minSum += dq.pollFirst();
cnt1++;
} else {
ans += cnt1 * dq.peekLast() - minSum + maxSum - cnt2 * dq.peekLast();
maxSum += dq.pollLast();
cnt2++;
}
printWriter.print(ans + " ");
time++;
}
printWriter.println();
}
/****************************************************************************************************************/
static BufferedReader reader;
static StringTokenizer tokenizer;
static PrintWriter printWriter;
static void initReader(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
}
static boolean hasNext(){
try {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
} catch (Exception e) {
return false;
}
return true;
}
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
static String nextLine() {
try {
return reader.readLine();
} catch (Exception e) {
return null;
}
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
static char nextChar() throws IOException {
return next().charAt(0);
}
}