Explanation
Simplification
First off, let's just do away with all that weird subarray stuff and look at the following simplification:
Given two arrays and , permute to minimize .
This simpler one is solvable by a greedy approach. We match the largest element in to the smallest one in , the second-largest in to the second-smallest in , and so on and so forth until we've matched all of them.
The intuition behind this is that we want to minimize the impact larger elements in will have on the sum so we match them to smaller ones in .
Actual Problem
Unfortunately, the original problem isn't as simple.
However, notice that we can precompute the number of occurrences a particular index will appear among all the summations.
With this, if we know will appear exactly times in the summation, then we can preemptively multiply by before doing the matching in our simplification.
If we use 0-indexing, each index is included in positions. This is because there's start positions for subarrays on the left and end positions on the right.
Then, we can multiply each element of by its number of occurrences to reduce this to our simpler problem!
Implementation
Time Complexity:
C++
#include <algorithm>#include <iostream>#include <vector>using std::cout;using std::endl;using std::vector;int main() {int len;
Java
import java.io.*;import java.util.*;public class Permutator {public static void main(String[] args) throws IOException {BufferedReader read = new BufferedReader(new InputStreamReader(System.in));int len = Integer.parseInt(read.readLine());int[] a = Arrays.stream(read.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
Python
len_ = int(input())a = [int(i) for i in input().split()]b = [int(i) for i in input().split()]subarr_num = [(i + 1) * (len_ - i) for i in range(len_)]actual_a = [i * j for i, j in zip(subarr_num, a)]actual_a.sort()b.sort(reverse=True)total = sum(i * j for i, j in zip(actual_a, b))print(total)
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!