Source Code
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define ld long double
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define PI 3.14159265
#define fast ios::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL)
typedef pair<ll,ll> pli;
typedef pair<int,int> pii;
typedef pair<ld,ld> pld;
ll MOD=1000000007 ;
ll MX=1000000000000000;

ll n,m;
ll a[1000100];
ll b[1000100];
ll cost[1000100];
ll l[1000100];
ll r[1000100];
ll pos[1000100];
vector<ll>adj[1000100];
vector<ll> dp[1000100];
ll sum[1000100];
int main()
{
    fast;
    //freopen("input.txt","r",stdin);
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
    }
    ll negsum=0;
    for(int i=1;i<=n;i++)
    {
        cin>>cost[i];
        sum[i]=sum[i-1]+cost[i];
        if(cost[i]<0)
            negsum+=cost[i];
    }
    for(int i=1;i<=m;i++)
    {
        cin>>b[i];
        pos[b[i]]=i;
    }
    ll st=1;
    for(int i=1;i<=n;i++)
    {
        if(st<=m&&a[i]==b[st])
        {
            l[st]=i;
            st++;
        }
    }
    st=m;
    for(int i=n;i>=1;i--)
    {
        if(st>0&&a[i]==b[st])
        {
            r[st]=i;
            st--;
        }
    }
    for(int i=1;i<=n;i++)
    {
        if(pos[a[i]]!=0)
        {
            if(i>=l[pos[a[i]]]&&i<=r[pos[a[i]]])
            {
                adj[pos[a[i]]].pb(i);
            }
        }

    }
    adj[m+1].pb(n+1);
    dp[m+1].pb(0);
    for(int i=1;i<=m;i++)
    {
        for(int j=0;j<adj[i].size();j++)
        {
            dp[i].pb(0);
        }
    }
    ll res=-MX;
    for(int i=m;i>=1;i--)
    {
        ll ma=-MX;
        ll ptr=adj[i+1].size()-1;
        for(int j=adj[i].size()-1;j>=0;j--)
        {
            while(ptr>=0&&adj[i+1][ptr]>adj[i][j])
            {
                ma=max(ma,dp[i+1][ptr]);
                ptr--;
            }
            dp[i][j]=min((ll)0,cost[adj[i][j]])+ma;
            //cout<<i<<" "<<j<<" "<<dp[i][j]<<endl;
            if(i==1)
                res=max(res,dp[i][j]);
        }
    }
    //cout<<res<<endl;
    cout<<negsum-res<<endl;




    return 0;
}
Copy
Always with Me, Always with You Mr_Programmer_98
GNU G++17
286 ms
98.4 MB
Accepted