mahmoud-a
9/1/2017 - 7:41 AM

https://arena.topcoder.com/#/u/practiceCode/13574/7776/8692/1/298183

#include <bits/stdc++.h>

#define ll long long
#define sz(v) ((int) ((v).size()))
#define clr(v, d) memset(v, d, sizeof(v))
#define lp(i, n) for(int i = 0; i < (int)(n); ++i)
#define rep(i, v) for(int i = 0; i < sz(v); ++i)

using namespace std;

const int MAX = 55;
const int OO = 1e9;

int n, l;
string a[MAX], sorted[MAX];
string s;
int cache[MAX][MAX];

int isValid(int st, int en) {
    string sub = s.substr(st, en-st+1);
    string tmp = sub;
    sort(tmp.begin(), tmp.end());
    int indx = -1;

    int cost = OO, tmpCost = 0;
    lp(i, n) {
        tmpCost = 0;

        if(tmp == sorted[i]) {
            //cout << "DEBUG 2: " << sub << " " << a[i] << endl;
            indx = i;
            lp(j, sub.length())
                if(sub[j] != (a[indx])[j])
                    tmpCost++;
                //cout << "DEBUG tmpCost : " << tmpCost << endl;
            cost = min(cost, tmpCost);
        }
    }

    if(indx == -1)
        return -1;
    //cout << "COOOOOOST " << cost << endl;
    return cost;
}

int minDeco(int i, int last) {
    if(i == l) {
        if(i == last)
            return 0;
        return OO;
    }

    int &ret = cache[i][last];
    if(ret != -1)
        return ret;
    ret = OO;
    int cost;
    if((cost = isValid(last, i)) != -1) {
        ret = minDeco(i+1, i+1) + cost;
    }

    ret = min(ret, minDeco(i+1, last));

    return ret;
}
/*
int main() {
    clr(cache, -1);
    cin>>s;
    l = s.length();
    cin>>n;
    string tmp;
    lp(i, n) {
        cin>>a[i];
        tmp = a[i];
        sort(tmp.begin(), tmp.end());
        sorted[i] = tmp;
    }
    int x = minDeco(0, 0);
    cout << (x == OO ? -1 : x) << endl;
    return 0;
}

*/

class SentenceDecomposition {
public:
    int decompose(string s1, vector<string> v) {
        clr(cache, -1);
        s = s1;
        l = s.length();
        n = v.size();
        string tmp;
        lp(i, n) {
            a[i] = v[i];
            tmp = a[i];
            sort(tmp.begin(), tmp.end());
            sorted[i] = tmp;
        }
        int x = minDeco(0, 0);
        return ( x == OO ? -1 : x );
    }
};