Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

least count of words required to construct a target string

// C++ program to find the Least count of words required to construct a target String
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

ll ans;

void fun(ll ind, vector<ll> &cur, ll step, vector<ll> &target, vector<vector<ll>> &arr)
{
    ll c = 0;
    for (int i = 0; i < 26; i++)
    {
        if (cur[i] > target[i])
            return;
        // updating the count for all letters.
        if (cur[i] == target[i])
            c++;
    }

    // if target has been constructed update and return.
    if (c == 26)
    {
        ans = min(ans, step);
        return;
    }
    if (ind == arr.size())
        return;

    vector<ll> tmp = cur;
    bool f = false;
    for (int i = 0; i < 26; i++)
    {
        if (tmp[i] + arr[ind][i] > target[i])
        {
            tmp[i] = target[i];
        }
        else
        {
            tmp[i] += arr[ind][i];
        }

        if (tmp[i] != cur[i])
            f = true;
    }
    if (f)
    {
        fun(ind, tmp, step + 1, target, arr);
    }

    fun(ind + 1, cur, step, target, arr);
}

void solve()
{
    ll n;
    cin >> n;
    vector<vector<ll>> brr(n, vector<ll>(26));
    for (int i = 0; i < n; i++)
    {
        string s;
        cin >> s;
        for (auto y : s)
        {
            brr[i][y - 'a']++;
        }
    }
    string target;
    cin >> target;
    vector<ll> tar(26);
    for (auto x : target)
    {
        tar[x - 'a']++;
    }

    ans = LLONG_MAX;
    vector<ll> cur(26);
    fun(0, cur, 0, tar, brr);
    if (ans == LLONG_MAX)
    {
        cout << -1 << endl;
    }
    else
    {
        cout << ans << endl;
    }
}

int main()
{
    solve();
    return 0;
}
Source by www.codingninjas.com #
 
PREVIOUS NEXT
Tagged: #count #words #required #construct #target #string
ADD COMMENT
Topic
Name
2+5 =