Search
 
SCRIPT & CODE EXAMPLE
 

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;
}
Comment

PREVIOUS NEXT
Code Example
Java :: java for loop example 
Java :: does not have a NavController set on 21312310 kotlin 
Java :: javafx check if enter pressed 
Java :: intent for youtube android stackoveroverflow 
Java :: android java onUpgrade() 
Java :: x^n+y^n=z^n 
Java :: Array first Occurence 
Java :: unmappable character java 
Java :: java skip foreach 
Java :: java destroy object 
Java :: Java take() Method 
Java :: java log4j2 load configuration 
Java :: tenth digit is odd in c 
Java :: java get current method name 
Java :: Reference in java equal operator 
Java :: get bimap by uri in android 
Java :: java program for wind-chill temperature 
Java :: clear datepicker javafx 
Java :: confirmation dialog android 
Java :: setBackgrounfTint color to relative layout from java file 
Java :: {1 2 3 4 5 } 
Java :: open google maps cycling navigation 
Java :: java non blocking notifier 
Java :: Bukkit dev paid account 
Java :: array erstellen java 
Java :: Spring Boot user registration and login REST API 
Java :: java division int by 0 
Java :: java swing place objects vertically 
Java :: system out java quick 
Java :: odd numbers in java 
ADD CONTENT
Topic
Content
Source link
Name
6+1 =