Source Code
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define F first
#define S second
const ll add = 1e6+10;
int n , m , b[1000010];
ll ans = 0 , sum = 0 , dp[1000010];
pair<int,ll>arr[1000010];
int nxt[1000010] , ma[1000010] , nxt_me[1000010] , ma2[1000010] , ma3[1000010];
bool test[1000010];
ll rec(int ind,  int j)
{
    if (ind == 0)return -1e9;
    if (j == m)
        return dp[ind] = max(arr[ind].S , rec(nxt[ind] , j));
    return dp[ind] = max(rec(nxt[ind] , j) , rec(nxt_me[ind] , j+1) + arr[ind].S);
}
void tra(int ind , int j)
{
    if (ind == 0)return;
    if (j == m)
    {
        if(arr[ind].S == dp[ind])
        {
            test[ind] = true;
            return;
        }
        else
            tra(nxt[ind] , j);
    }
    if (dp[ind] == dp[nxt[ind]])
        tra(nxt[ind] , j);
    else
    {
        test[ind] = true;
        tra(nxt_me[ind] , j+1);
    }

}
int main ()
{
    cin >> n >> m;
    for (int i = 1 ; i <= n ; i++)
        cin >> arr[i].F;
    for (int i = 1 ; i <= n ; i++)
        cin >> arr[i].S;
    for (int i = 1 ; i <= m ; i++)
        cin >> b[i] , ma2[b[i]] = i;
    for(int i = n ; i > 0 ; i--)
    {
        nxt[i] = ma[arr[i].F] , ma[arr[i].F] = i;
        int ind = ma2[arr[i].F];
        if (ind)
            nxt_me[i] = ma[b[ind+1]];
    }
    rec(ma[b[1]] , 1);
    tra(ma[b[1]] , 1);
    for (int i = 1 ; i <= n ; i++)
        if (!test[i] && arr[i].S < 0)sum += arr[i].S;
    cout << sum << '\n';

return 0;
}
Copy
Always with Me, Always with You MD0
GNU G++17
435 ms
43.1 MB
Accepted