Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Let <code>N = cardsNumber</code>, <code>M = required[0] * required[1] * ... * required[maxColor]</code>. Then, actually, your problem could be easily solved in O(N * M) time. In your very case, that is <code>12 * 2 * 3 * 4 = 288</code> operations. :)</p> <p>One of possible ways to do this is to use a recurrence relation. Consider a function <code>logColours f(n, required)</code>. Let <code>n</code> be the current number of already considered cards; <code>required</code> is a vector from your example. Function returns the answer in a vector <code>logColours</code>. You are interested in <code>f(12, {2,3,4})</code>. Brief recurrent calculation inside a function <code>f</code> could be written like this:</p> <pre><code>std::vector&lt;int&gt; f(int n, std::vector&lt;int&gt; require) { if (cache[n].count(require)) { // we have already calculated function with same arguments, do not recalculate it again return cache[n][require]; } std::vector&lt;int&gt; logColours(maxColor, 0); // maxColor = 3 in your example for (int putColor=0; putColor&lt;maxColor; ++putColor) { if (/* there is still at least one card with color 'putColor'*/) { // put a card of color 'putColor' on place 'n' if (require[putColor] == 1) { // means we've reached needed amount of cards of color 'putColor' ++logColours[putColor]; } else { --require[putColor]; std::vector&lt;int&gt; logColoursRec = f(n+1, require); ++require[putColor]; // merge child array into your own. for (int i=0; i&lt;maxColor; ++i) logColours[i] += logColoursRec[i]; } } } // store logColours in a cache corresponding to this function arguments cache[n][required] = std::move(logColours); return cache[n][required]; } </code></pre> <p>Cache could be implemented as an <code>std::unordered_map&lt;int, std::unordered_map&lt;std::vector&lt;int&gt;, std::vector&lt;int&gt;&gt;&gt;</code>.</p> <p>Once you understand the main idea, you'll be able to implement it in even more efficient code.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload