#P1620. Longest Super Beautiful Unbeatable String

    ID: 14906 Type: Default 1000ms 256MiB

Longest Super Beautiful Unbeatable String

Longest Super Beautiful Unbeatable String

Caima believes that the letters O and X are the most beautiful. A string composed solely of these two letters is called a beautiful string. Among such strings, we call a string a Super Beautiful Unbeatable String if it satisfies the following conditions:

  • Any contiguous substring consisting only of X's has length at most \(\max_{X}\).
  • Any contiguous substring consisting only of O's has length at most \(\max_{O}\).
  • The entire string contains at most \(\mathtt{count}_{O}\) occurrences of O and at most \(\mathtt{count}_{X}\) occurrences of X.

Your task is to determine the maximum possible length of a Super Beautiful Unbeatable String that can be constructed under these restrictions.

Explanation:

You are given four integers: count_O, count_X, max_O and max_X. Note that if one of the letters is missing (e.g. count_O = 0 or count_X = 0), then the string is made up entirely of the other letter but still should obey the maximal consecutive limit (max_O or max_X respectively). In such a case, the maximum possible length is simply the minimum of the available count and the allowed consecutive count.

In the general case when both letters are available, one can always interleave the two types of letters to avoid exceeding the maximum allowed consecutive letters. In particular, if all letters can be used then the answer is count_O + count_X. However, if one letter is too abundant to be separated by the other letter, then only part of that letter can be used. More precisely, the maximum number of, say, O's that can be arranged without violating the consecutive constraint is \(\min(\mathtt{count}_{O},\; \max_{O} \times (\mathtt{count}_{X}+1))\) (and similarly for X). Thus, the answer is computed as:

[ \text{answer} = \min(\mathtt{count}{O},, \max{O} \times (\mathtt{count}{X}+1)) + \min(\mathtt{count}{X},, \max_{X} \times (\mathtt{count}_{O}+1)). ]

inputFormat

The input consists of a single line containing four space-separated integers:

  1. count_O: the maximum number of letter O available.
  2. count_X: the maximum number of letter X available.
  3. max_O: the maximum allowed length for any contiguous substring of O's.
  4. max_X: the maximum allowed length for any contiguous substring of X's.

outputFormat

Output a single integer representing the maximum possible length of a Super Beautiful Unbeatable String that can be constructed under the given constraints.

sample

5 0 5 3
5