Untitled

 avatar
unknown
c_cpp
a year ago
1.9 kB
5
Indexable
#include<iostream>
#include <bits/stdc++.h>

#define ll long long
#define ld long double
#define IO ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
using namespace std;
const int N = 2e5 + 6;


string get_min_s(string s) {
    string ans = "";
    set<int> st;
    int n = s.size();

    deque<int> q[26];

    for (int i = 0; i < n; i++) {
        q[s[i] - 'a'].push_back(i);
        st.insert(s[i] - 'a');
    }

    int last = -1;
    while (!st.empty()) {
        auto it = st.begin();
        while (it != st.end()) {
            int c = *it;
            while (q[c].front() <= last)q[c].pop_front();

            bool flag = true;

            for (int i = 0; i < 26; i++) {
                if (st.count(i) == 0)continue;
                if (q[i].back() < q[c].front()) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                ans += (char) (c + 'a');
                st.erase(it);
                last = q[c].front();
                break;
            }
            it++;
        }
    }
    return ans;
}

int a[N];
ll dp[N][30];
int vis[N][30], tc;
string s, pat;

ll solve(int i, int j) {
    if (j == pat.size())return 0;
    if (i == s.size())return -1e18;
    ll &ans = dp[i][j];
    if (vis[i][j] == tc)return ans;
    vis[i][j] = tc;
    ans = solve(i + 1, j);
    if (s[i] == pat[j]) {
        ans = max(ans, solve(i + 1, j + 1) + a[i]);
    }
    return ans;
}

void doWork() {
    int n;
    cin >> n >> s;
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    pat = get_min_s(s);
    tc++;
    cout<<pat<<"\n";
    cout << solve(0, 0) << "\n";
}

int main() {
    IO
    int t = 1;

    cin >> t;
    for (int i = 1; i <= t; i++) {
        //  cout << "Case #" << i << ": ";
        doWork();
    }
}
Editor is loading...
Leave a Comment