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
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
题目大意
给出数组 a 的前 n 项,来求 n+1~2n 的和,后 n 项中 ai 求值的原则是在数组 b 中选取一个数 bk ,然后在数组 a 中选取 aj−j(bk<=j<i) 的最大值最大值作为 ai 项的值。
解题思路
贪心的思想,在求后 n 项和时尽量使当前所求的值最大,那么也就是在数组 a 中选取的范围最大,即在数组 b 中选取的值最小,所以这里需要对数组 b 进行排序;在选取的范围内需要得到 aj-j 的最大值,那么我们可以使用优先队列来存储 aj-j 的值(用数组在更新区间最大值的过程中会超时);然后每次取出队列中的最大值,判断其 index 是否在选取的 bk 之后范围内,若是,则为当前的 ai 值。
代码实现
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
#define maxn 250007
const int mod=1e9+7;
struct node
{
int value;
int index;
friend bool operator< (node n1, node n2)
{
return n1.value < n2.value;
}
}a;
int b[maxn];
int main()
{
int n,t;
while(~scanf("%d",&n))
{
priority_queue<node>qu;
for(int i=1; i<=n; i++)
{
scanf("%d",&t);
a.value=t-i;
a.index=i;
qu.push(a);
}
for(int i=1; i<=n; i++)
scanf("%d",&b[i]);
sort(b+1,b+n+1);
int ans=0;
node now,ne;
for(int i=1; i<=n; i++)
{
now=qu.top();
while(now.index<b[i])
{
qu.pop();
now=qu.top();
}
ans=(ans+now.value)%mod;
ne.index=n+i,ne.value=now.value-(n+i);
qu.push(ne);
}
printf("%d\n",ans);
}
return 0;
}