Count knockout brackets of minimum height in which player M wins the tournament, given a fixed win relation over N up to 16 players.
Hard8Divide and conquerDynamic programmingBit manipulationCombinatoricsNo attempts yetTime limit8sMemory limit512 MBThe national tennis association is holding a competition among professional players. The competition is a knockout tournament, and arranging the bracket is your job.
You have a detailed report on every participant. It lists the results of the recent matches between all pairs of participants, and the data shows that the outcome depends only on who the two opponents are. Whenever player i meets player j, the same side always wins.
One of your close friends is in the competition and you want him to take the gold medal, so you want to know how many brackets let him win. There are too many participants to count by hand, so write a program that counts the brackets in which your friend wins the gold medal.
To keep the trick hidden, you cannot build a contrived bracket. The height of the tournament tree has to be as small as possible.
A bracket is a binary tree with one of the N players at each leaf. Every internal node is one match between the winners of its two subtrees, and the player who wins at the root takes the gold medal. The height of the tree is the largest number of matches on a path from the root down to a leaf, and it must equal the smallest value a binary tree with N leaves can reach, which is ⌈log2N⌉. Two brackets that differ only by exchanging the two whole subtrees of some match count as one bracket.
The input has several datasets. Each dataset has the following format.
N M
R11 R12 ... R1N
R21 R22 ... R2N
...
RN1 RN2 ... RNN
N is the number of players, 2≤N≤16. M is your friend's ID, 1≤M≤N, and players are numbered from 1. Rij is the result of a match between player i and player j. If player i always wins, Rij=1, otherwise Rij=0. The matrix is consistent: for every i=j, Rij=0 if and only if Rji=1. The diagonal entries Rii are given for convenience and are always 0.
The end of the input is a line holding two zeros. That line is not a dataset and must not be processed.
For each dataset, print on one line the number of brackets in which your friend wins the first prize.