Problem:
Score : 100 points

Problem Statement

There are N flowers arranged in a row.
For each i (1 \leq i \leq N), the height and the beauty of the i-th flower from the left is h_i and a_i, respectively.
Here, h_1, h_2, \ldots, h_N are all distinct.

Taro is pulling out some flowers so that the following condition is met:

The heights of the remaining flowers are monotonically increasing from left to right.

Find the maximum possible sum of the beauties of the remaining flowers.

Constraints

All values in input are integers.

1 \leq N \leq 2 × 10^5

1 \leq h_i \leq N

h_1, h_2, \ldots, h_N are all distinct.

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 \ldots h_N
a_1 a_2 \ldots a_N

Output

Print the maximum possible sum of the beauties of the remaining flowers.

Sample Input 1

4
3 1 4 2
10 20 30 40

Sample Output 1

60

We should keep the second and fourth flowers from the left.
Then, the heights would be 1, 2 from left to right, which is monotonically increasing, and the sum of the beauties would be 20 + 40 = 60.

Sample Input 2

1
1
10

Sample Output 2

10

The condition is met already at the beginning.

Sample Input 3

5
1 2 3 4 5
1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 3

5000000000

The answer may not fit into a 32-bit integer type.

Sample Input 4

9
4 2 5 8 3 6 1 7 9
6 8 8 4 6 3 5 7 5

Sample Output 4

31

We should keep the second, third, sixth, eighth and ninth flowers from the left.

Solution in C++14 (GCC 5.4.1) (judge verdict: Time Limit Exceeded)

#include<iostream>
#include<vector>
#define ll long long
#define inf 1e9
using namespace std;
int n;
int h[200005];
int tr[1000000];
ll v[200005];
vector<int>ed[200005];
ll dp[200005];
void init(int i,int l,int r){
	 if(l==r){tr[i]=l;return;}
	 int m=l+(r-l)/2;
	 init(2*i+1,l,m);
	 init(2*i+2,m+1,r);
	 if(h[tr[2*i+1]]<h[tr[2*i+2]])tr[i]=tr[2*i+1];
	 else tr[i]=tr[2*i+2];
}
int qry(int i,int l,int r,int l1,int r1,int nn){
	if(l>r1||r<l1)return inf;
	if(l>=l1&&r<=r1&&h[tr[i]]>nn)return tr[i];
	if(l==r)return inf;
	int m=l+(r-l)/2;
	int lft=qry(2*i+1,l,m,l1,r1,nn);
	int rit=qry(2*i+2,m+1,r,l1,r1,nn);
	if(rit==inf)return lft;
	else if(lft==inf)return rit;
	if(min(h[lft],h[rit])<=nn)return inf;
	else if(h[lft]<=nn)return rit;
	else if(h[rit]<=nn)return lft;
	return (h[lft]<h[rit])?lft:rit;
}
ll rec(int i){
	ll x=0;
	for(int j:ed[i]){
		x=max(x,rec(j));
	}
	return dp[i]=v[i]+x;
}
int main()
{
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>h[i];
	}
	for(int i=0;i<n;i++)cin>>v[i];
	init(0,0,n-1);
	for(int i=0;i<n;i++){
		int q=qry(0,0,n-1,i+1,n-1,h[i]);
		while(q!=inf){
			ed[i].push_back(q);
			q=qry(0,0,n-1,i+1,q-1,h[i]);
		}
	}
	ll ans=0;
	for(int i=0;i<n;i++){if(dp[i]==0)rec(i);ans=max(ans,dp[i]);}
	cout<<ans;
}