Young gardener didn’t visit his garden for a long time, and now it’s not very pleasant there:
n caterpillars have appeared on the ground.
Kirill decided to use this opportunity to have some fun and organized a competition — "caterpillar crawl-race."
At Kirill’s command all caterpillars start crawling from the ground to the top of a tree. But they get tired pretty fast. After crawling
t
i cm
i-th caterpillar needs to rest for
t
i minutes. During that time it slides down a bit. Crawling speed of a caterpillar is 1 cm/minute, sliding speed — also 1 cm/minute.
Kirill is very much interested to find out how high on the tree is the leading caterpillar at different moments in time.
First line contains one integer
n — the number of caterpillars (1 ≤
n ≤ 10
6).
Second line contains
n integers
t
i — characteristics of caterpillars (1 ≤
t
i ≤ 10
9).
In the third line there is a number
q — number of moments in time, which Kirill finds interesting (1 ≤
q ≤ 10
6).
Remaining
q lines contain one query from Kirill each. A query is described by
x
i — number of minutes since the start of the competition (1 ≤
x
i ≤ 10
6).
For every query print in a separate line one integer, that describes how high is the highest caterpillar at the given moment of time.
input | output |
---|---|
4 1 3 2 1 12 1 2 3 4 5 6 7 8 9 10 11 12 | 1 2 3 2 1 2 1 2 3 2 1 0 |
把所有山峰的顶点都求出来,用数组存储。然后上升求一遍,下降求一遍。
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e6+5;
int a[maxn+7],ans[maxn+7];
int main()
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
sort(a,a+n);
n=unique(a,a+n)-a;
int q,x;
if(a[n-1]>=maxn)
{
scanf("%d",&q);
for(int i=1;i<=q;i++)
scanf("%d",&x),printf("%d\n",x);
return 0;
}
memset(ans,0,sizeof(ans));
for(int i=0;i<n;i++)
{
int j;
for(j=a[i];j<=maxn;j+=2*a[i])
ans[j]=max(ans[j],a[i]);
ans[maxn]=max(ans[maxn],a[i]-j+maxn);
}
for(int i=1;i<=a[n-1];i++)
ans[i]=i;
for(int i=1;i<=maxn;i++)
ans[i]=max(ans[i],ans[i-1]-1);
for(int i=maxn-1;i>=1;i--)
ans[i]=max(ans[i],ans[i+1]-1);
scanf("%d",&q);
for(int i=1;i<=q;i++)
scanf("%d",&x),printf("%d\n",ans[x]);
return 0;
}