Problem Description
Let N be a positive integer.
There is a numerical sequence of length 3N, a=(a1,a2,…,a3N). Snuke is constructing a new sequence of length 2N, a', by removing exactly N elements from a without changing the order of the remaining elements. Here, the score of a' is defined as follows: (the sum of the elements in the first half of a')−(the sum of the elements in the second half of a').
Find the maximum possible score of a'.
Constraints
- 1≤N≤105
- ai is an integer.
- 1≤ai≤109
Partial Score
- In the test set worth 300 points, N≤1000.
Input
Input is given from Standard Input in the following format:
N
a1 a2 … a3NOutput
Print the maximum possible score of a'.
Example
Sample Input 1
2
3 1 4 1 5 9Sample Output 1
1
When a2 and a6 are removed, a' will be (3,4,1,5), which has a score of (3+4)−(1+5)=1.Sample Input 2
1
1 2 3Sample Output 2
-1
For example, when a1 are removed, a' will be (2,3), which has a score of 2−3=−1.Sample Input 3
3
8 2 2 7 4 6 5 3 8Sample Output 3
5
For example, when a2, a3 and a9 are removed, a' will be (8,7,4,6,5,3), which has a score of (8+7+4)−(6+5+3)=5.
题意: 给一个长度为 3n 的序列,删除 n 个数,使得新序列前 n 个数的和减去后 n 个数的和的差值最大,输出这个差值
思路:
删除 n 个数后,剩下的 2n 个数顺序不变,由于这 2n 个数的分界点一定是在 n~2n 这 n 个数之间,因此可以对前 n 个数、后 n 个数分别求和,使用一个优先队列来维护最大和,再用一个优先队列来维护最小和
Source Program
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<bitset>
#define EPS 1e-9
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define LL long long
const int MOD = 1E9+7;
const int N = 1000000+5;
const int dx[] = {-1,1,0,0,-1,-1,1,1};
const int dy[] = {0,0,-1,1,-1,1,-1,1};
using namespace std;
LL a[N];
LL before[N],last[N];
int main() {
int n;
scanf("%d",&n);
LL maxSum=0,minSum=0;
priority_queue<LL> minSumQ;
priority_queue<LL, vector<LL>, greater<LL> > maxSumQ;
for(int i=1;i<=3*n;i++){
scanf("%d",&a[i]);
if(i<=n){
maxSum+=a[i];
maxSumQ.push(a[i]);
}
else if(i>2*n){
minSum+=a[i];
minSumQ.push(a[i]);
}
}
before[n]=maxSum;
for(int i=n+1;i<=2*n;i++) {
LL temp=maxSumQ.top();
if(temp<a[i]){
maxSum+=a[i]-temp;
maxSumQ.pop();
maxSumQ.push(a[i]);
}
before[i]=maxSum;
}
last[2*n]=minSum;
for(int i=2*n-1;i>=n;i--){
LL temp=minSumQ.top();
if(temp>a[i+1]){
minSum+=a[i+1]-temp;
minSumQ.pop();
minSumQ.push(a[i+1]);
}
last[i]=minSum;
}
LL res=before[n]-last[n];
for(int i=n+1;i<=2*n;i++)
res=max(res,before[i]-last[i]);
printf("%lld\n",res);
return 0;
}