atcode062D(预处理&优先队列)

题目链接:http://abc062.contest.atcoder.jp/tasks/arc074_b

 

题意:从3*n个元素中删除n个元素,使得剩余元素中前n个元素的和减后n个元素的和最大;

 

思路:用b[i]存储前i个元素中选 n 个元素和能达到的最大值,c[i+1]存储后i个元素中选择 n 个元素能达到的最小值;

然后再遍历一次,取 max (b[i]-c[i+1]) 即为答案;

 

代码:

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <queue>
 4 #define ll long long
 5 using namespace std;
 6 
 7 const int MAXN = 3e5+10;
 8 const ll inf = 0x3f3f3f3f3f3f3f3f;
 9 ll a[MAXN], b[MAXN], c[MAXN];
10 
11 int main(void){
12     int n;
13     ll cnt1=inf, cnt2=-inf, ans1=0, ans2=0, ans=-inf;
14     scanf("%d", &n);
15     for(int i=1; i<=3*n; i++){
16         scanf("%lld", &a[i]);
17     }
18     priority_queue<ll, vector<ll>, greater<ll> > q1;
19     for(int i=1; i<=2*n; i++){
20         if(i <= n){
21             q1.push(a[i]);
22             ans1 += a[i];
23             b[i] = ans1;
24             continue;
25         }
26         ll cnt = q1.top();
27         if(cnt < a[i]){
28             q1.pop();
29             q1.push(a[i]);
30             ans1 -= cnt;
31             ans1 += a[i];
32         }
33         b[i] = ans1;
34     }
35     priority_queue<ll, vector<ll>, less<ll> > q2;
36     for(int i=3*n; i>n; i--){
37         if(i > 2*n){
38             q2.push(a[i]);
39             ans2 += a[i];
40             c[i] = ans2;
41             continue;
42         }
43         ll cnt = q2.top();
44         if(cnt > a[i]){
45             q2.pop();
46             q2.push(a[i]);
47             ans2 -= cnt;
48             ans2 += a[i];
49         }
50         c[i] = ans2;
51     }
52     for(int i=n; i<=2*n; i++){
53         ans = max(ans, b[i]-c[i+1]);
54     }
55     cout << ans << endl;
56     return 0;
57 }
View Code

 

posted @ 2017-05-21 11:02  geloutingyu  阅读(261)  评论(0编辑  收藏  举报