The Zong of the Zee
Time limit3sMemory limit512 MB
Given m lines of length n with at most one unknown letter per line, count the permutations that turn each line into the next one, modulo 1e9+7.
- Level
Hard8 of 10
- Topics
- String, Combinatorics, Math
- Solved
- No attempts yet
Problem
The Imperturbable Captain of the Unterzee chases the Pirate-Poet. Their rivalry was set long ago and since then knows no limits. Every time the Captain arrives at the port where the Pirate-Poet was expected to be, they find nothing but a message from the Pirate-Poet saying that she left the port a few days ago, along with another line of the never-ending masterpiece: the Zong of the Zee. Both the Captain and the Pirate-Poet know that the end of the Zong will put an ultimate end to their rivalry. Once the Captain retrieves it, they will find the Pirate-Poet and the final clash will begin. Port after port, line after line... Perhaps the answer was there all along. The Captain knows they cannot possibly last long enough to witness the end of the Zong, so the only thing they can do is outplay the Pirate-Poet. So far, every line of the poem has been an anagram of the first one. The Captain also suspects that every line is obtained the same way, by applying a fixed permutation to the previous line. That is, the character at position of a new line was at position of the previous line. The Captain wants to recover the whole poem by guessing the intended permutation. First, they want to know how many candidates they have to check. The Captain copied every line of the poem carefully: lines of Unterzian letters each. Some letters (but at most one per line) may be replaced by question marks ("?"), meaning the Captain is not sure which letter it was. Count the permutations that are consistent with the data. That is, count the permutations for which there is a way to replace every "?" with some Unterzian letter so that each line is obtained from the previous one by applying this permutation. Output the answer modulo . The Captain knows what to do with this information. Probably.
Input
The first line contains two integers and (). The -th of the following lines contains the -th line of the poem. Each line has exactly characters, each being an Unterzian letter or a question mark ("?"). Each line contains at most one question mark. Each Unterzian letter has ASCII code between 33 and 126, except "?", which has code 63.
Output
Output a single integer, the answer to the problem.