Source Code
#include "bits/stdc++.h"
using namespace std;
typedef long long ll;
#define IN freopen("input.txt", "r", stdin)
#define OUT freopen("output.txt", "w", stdout)
typedef vector<int> vi;
typedef pair<int, int> pi;
#define F first
#define S second
#define PB push_back
#define MP make_pair
#define REP(i, a, b) for (int i = a; i <= b; i++)
void dfs(string a, string b, int si)
{
}
int main()
{
    int n, q;
    cin >> n >> q;
    map<int, int> mp, mp2;
    vector<pair<int, int>> v(n);
    for (int i = 0; i < n; i++)
    {
        cin >> v[i].second;
        mp[v[i].second]++;
    }
    for (int i = 0; i < n; i++)
        cin >> v[i].first;
    sort(v.begin(), v.end());
    mp2 = mp;
    while (q--)
    {
        mp = mp2;
        int x;
        cin >> x;
        int mx = -1, temp;
        for (int i = 0; i < n; i++)
        {
            if (mp[v[i].second] > mx)
            {
                mx = mp[v[i].second];
                temp = v[i].second;
            }
        }
        if (temp == x)
            cout << 0 << " ";
        else
        {
            int cost = 0, cost2 = 0;
            int j = 0;
            int id = 0;
            for (int i = 0; i < n; i++)
            {
                if (v[i].second == temp)
                {
                    id = i;
                    break;
                }
            }
            int w = 0;
            while (mp[x] <= mp[temp])
            {
                if (mp[x] + 2 > mp[temp] && w == 0)
                { 
                    cost2 = cost;
                    cost2 += v[id].first;
                    w = 1;
                }
                if (v[j].second != x)
                {
                    cost += v[j].first;
                    mp[v[j].second]--;
                    mp[x]++;
                }
                j++;
            }
             cout << min(cost, cost2) << ' ';
        }
    }
}
Copy
Mode Queries monther abu zaina
GNU G++17
5013 ms
2.3 MB
Wrong Answer