Explanation
Let be Bessie's ith instruction and be Elsie's jth instruction. Additionally, let denote the set of unique expressions we can make by interleaving Bessie's first instructions and Elsie's first instructions. For example, in the sample:
3 12+ +02
- : (interleaving and )
- : (interleaving and )
- : (interleaving and )
- : (interleaving and )
Notation
In the below solution,
- denotes the number of elements in a set
- denotes the union of sets and (elements in either or )
- denotes the intersection of sets and (elements in both and )
- denotes an arbitrary expression in
- denotes applying that instruction to each expression in the set
So, how do we calculate ?
When either or are 0, either Bessie or Elsie's instruction set will be empty, meaning the interleaving is uniquely determined and thus for all .
Great, but what if and are both nonzero? Evidently, any interleaving of Bessie's first instructions and Elsie's first instructions must either end with instruction or instruction . We can thus rewrite the expressions that end with as (let's denote this set as ) and the ones that end with as (let's denote this set as ). We also have the following:
- As long as isn't ,
- As long as isn't ,
Take some time to convince yourself of these, especially points 1 and 2!
Not Convinced?
Use the fact that if we apply the same, non- operation to two distinct expressions, the results will still be distinct.
At this point, you may be tempted to conclude that
Don't make this mistake! Remember the Principle of Inclusion-Exclusion:
For example, if and , we overcount if we simply concatenate these two sets, so we need to subtract , which, in this case, is .
In our case, we overcount . So which expressions are in this set? This is a crucial part of the solution, so make sure to spend some time thinking about it before reading the answer below! To make this easier, you may want to first assume neither Bessie nor Elsie has the instruction, as it's not too hard to figure out whether contains the expression and reduces the number of edge cases we need to consider.
Hint
Detailed Explanation
TL;DR
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;using ll = long long;const int N = 2e3 + 1;const int MOD = 1e9 + 7;// adding and subtracing under modll ad(ll &a, ll b) { return a = (a + b) % MOD; }
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!