您的位置:首页 > 产品设计 > UI/UE

【HDU 6047 Maximum Sequence】 + 优先队列

2017-07-27 17:19 211 查看
Maximum Sequence

Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 21 Accepted Submission(s): 10

Problem Description

Steph is extremely obsessed with “sequence problems” that are usually seen on magazines: Given the sequence 11, 23, 30, 35, what is the next number? Steph always finds them too easy for such a genius like himself until one day Klay comes up with a problem and ask him about it.

Given two integer sequences {ai} and {bi} with the same length n, you are to find the next n numbers of {ai}: an+1…a2n. Just like always, there are some restrictions on an+1…a2n: for each number ai, you must choose a number bk from {bi}, and it must satisfy ai≤max{aj-j│bk ≤ j< i}, and any bk can’t be chosen more than once. Apparently, there are a great many possibilities, so you are required to find max{∑2nn+1ai} modulo 109+7 .

Now Steph finds it too hard to solve the problem, please help him.

Input

The input contains no more than 20 test cases.

For each test case, the first line consists of one integer n. The next line consists of n integers representing {ai}. And the third line consists of n integers representing {bi}.

1≤n≤250000, n≤a_i≤1500000, 1≤b_i≤n.

Output

For each test case, print the answer on one line: max{∑2nn+1ai} modulo 109+7。

Sample Input

4

8 11 8 5

3 1 4 2

Sample Output

27

Hint

For the first sample:

1. Choose 2 from {bi}, then a_2…a_4 are available for a_5, and you can let a_5=a_2-2=9;

2. Choose 1 from {bi}, then a_1…a_5 are available for a_6, and you can let a_6=a_2-2=9;

Source

2017 Multi-University Training Contest - Team 2

题解:预处理:a_i -= i ,易证明从最小的b开始选每次选最大的一定可以使结果最大。 证明思路:如果条件改为a_i<=max{a_j-j|b_k<=j<=n},那么b的顺序与最后的结果无关。条件改回来后,由于每次要计算一个数的最大值时都有a_(n+1)…a_(i-1)在范围中,所以每次只需让a_i - i尽可能大,那么就把大的数尽早用上,每次一定考虑尽量多的数字,这样取得的数字就尽可能的大。 所以说每次就是求区间最值,加在答案上。由于贪心的思路,每次要求的区间的下界是单调不降的,故可以用单调队列优化到O(n)的复杂度。 由于1 ≤ b_i ≤ n,对b排序可以用哈希排序(桶排序)完成。

进一步观察,可以发现这样贪心时 a_(n+1)…a_i 其实是单调不增的,所以并不需要每次求区间最值了,选第一个数时就选最大的,后面的选择顺序与最终结果无关了。

AC代码:

#include<cstdio>
#include<cmath>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAX = 3e5 + 10;
const int mod = 1e9 + 7;
typedef long long LL;
int a[MAX],b[MAX];
int main()
{
int n;
while(~scanf("%d",&n)){
priority_queue <pair <int,int> > q;
for(int i = 1; i <= n; i++){
scanf("%d",&a[i]);
pair <int,int> w;
w.first = a[i] - i;
w.second = i;
q.push(w);
}
for(int i = 1; i <= n; i++)
scanf("%d",&b[i]);
sort(b + 1,b + 1 + n);
LL ans = 0;
for(int i = 1; i <= n; i++){
int p = b[i];
while(p > q.top().second)
q.pop();
pair <LL,int> w;
w = q.top();
ans = (LL)(ans + w.first) % mod;
w.first = w.first - n - i;
w.second = n + i;
q.push(w);
}
printf("%lld\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: