An interesting game

2.7

11 votes
Algorithms, Greedy Algorithms
Problem

You are given two arrays a1,a2, ,an and b1,b2, ,bn where n is an even number. 

Alice and Bob are playing a game on these arrays. In each turn, Alice selects two unused numbers before numbers i and j such that 1i,jn and ij. Bob selects one of them and this number is denoted as x and adds bx to his score. Alice takes the remaining one, that is denoted as y, and adds ay to his scores.

Alice and Bob want to maximize their scores simultaneously. Your task is to determine the difference between their scores after the game. Totally, they have n2 turns.

In other words, your task is to find the difference between Alice's and Bob's scores after all turns if both sides move optimally

Input format

  • The first line contains one integer t (1t1000) denoting the number of test cases. 
  • The first line of each test case contains one integer n (1n300000) denoting the length of the array. It is guaranteed that n is even.
  • The second line of each test case contains n distinct integers a1,a2, ,an (1ai109) denoting the elements of array a.
  • The third line of each test case contains n distinct integers b1,b2, ,bn (1bi109) denoting the elements of the array b.

The sum of n over all test cases does not exceed 300000.

Output format

For each test case, print a single integer denoting the difference between Alice's and Bob's scores after the game if both players move optimally

Time Limit: 3
Memory Limit: 256
Source Limit:
Explanation

The moves of the first test case:

  1. Alice will choose integers 3 and 4. Bob must take 4 (it is optimally for him), hence Alice chooses 3. After the game, both of them have 8 scores.
  2. Alice will choose integers 1, 2. Bob must take 1 (it is optimally for him), hence Alice chooses 1. After the game, Alice has a score of 10 and Bob has a score of 14. Consequently, the answer is 10 - 14 = -4.

The moves of the second test case:

  1. Alice will choose integers 2, 3. Bob must take 3 (it is optimally for him), hence Alice chooses 2. After the game, Alice has 8 scores, Bob 3 scores.
  2. Alice will choose integers 5, 6. Bob must take 6 (it is optimally for him), hence Alice chooses 5. After the game, Alice has 18 scores, Bob 7 scores. 
  3. Alice will choose integers 1, 4. Bob must take 4 (it is optimally for him), hence Alice chooses 1. After the game, Alice has 25 scores, Bob 17 scores. Consequently, the answer is 25 - 18 = 7.

It can be shown that both players move as optimally as they can and there can be no better outcome. 

Editor Image

?