Suppose there are n candles which are aligned from left to right. The i-th candle from the left side has the height h[i] and the color c[i]. We also have an integer k, represents there are colors in range 1 to k. We have to find how many strictly increasing colorful sequences of candies are there? The increasing sequence is checked based on heights, and a sequence is said to be colorful if there are at least one candle of each color in range 1 to K are available. If the answer is too large, then return result mod 10^9 + 7.
So, if the input is like K = 3 h = [1,3,2,4] c = [1,2,2,3], then the output will be 2 because it has sequences [1,2,4] and [1,3,4].
To solve this, we will follow these steps −
- Define a function read() . This will take T, i
- s := 0
- while i > 0, do
- s := s + T[i]
- s := s mod 10^9+7
- i := i -(i AND -i)
- return s
- Define a function update() . This will take T, i, v
- while i <= 50010, do
- T[i] := T[i] + v
- T[i] := T[i] mod 10^9+7
- i := i +(i AND -i)
- return v
- From the main method, do the following −
- L := 2^k, R := 0, N := size of h
- for i in range 0 to L - 1, do
- T := an array of size 50009 and fill with 0
- t := 0
- for j in range 0 to N - 1, do
- if (i after shifting bits (c[j] - 1) times to the right) is odd, then
- t := t + update(T, h[j], read(T, h[j] - 1) + 1)
- t := t mod 10^9+7
- if (i after shifting bits (c[j] - 1) times to the right) is odd, then
- if (number of bits in i) mod 2 is same as k mod 2, then
- R := R + t
- R := R mod 10^9+7
- otherwise,
- R := (R + 10^9+7) - t
- R := R mod 10^9+7
- return R
Example
Let us see the following implementation to get better understanding −
def solve(k, h, c): def read(T, i): s = 0 while i > 0: s += T[i] s %= 1000000007 i -= (i & -i) return s def update(T, i, v): while i <= 50010: T[i] += v T[i] %= 1000000007 i += (i & -i) return v def number_of_bits(b): c = 0 while b: b &= b - 1 c += 1 return c L = 2 ** k R = 0 N = len(h) for i in range(L): T = [0 for _ in range(50010)] t = 0 for j in range(N): if (i >> (c[j] - 1)) & 1: t += update(T, h[j], read(T, h[j] - 1) + 1) t %= 1000000007 if number_of_bits(i) % 2 == k % 2: R += t R %= 1000000007 else: R += 1000000007 - t R %= 1000000007 return R k = 3 h = [1,3,2,4] c = [1,2,2,3] print(solve(k, h, c))
Input
3, [1,3,2,4], [1,2,2,3]
Output
2