Fish (Codeforces 16E)
Tags: DP, bitmasks

n fish, numbered from 1 to n, live in a lake. Every day right one pair of fish meet, and the probability of each other pair meeting is the same. If two fish with indexes i and j meet, the first will eat up the second with the probability aij, and the second will eat up the first with the probability aji = 1 - aij. The described process goes on until there are at least two fish in the lake. For each fish find out the probability that it will survive to be the last in the lake.

Input: The first line contains integer n (1 ≤ n ≤ 18) — the amount of fish in the lake. Then there follow n lines with n real numbers each — matrix a. aij (0 ≤ aij ≤ 1) — the probability that fish with index i eats up fish with index j. It's guaranteed that the main diagonal contains zeros only, and for other elements the following is true: aij = 1 - aji. All real numbers are given with not more than 6 characters after the decimal point.

Output: Output n space-separated real numbers accurate to not less than 6 decimal places. Number with index i should be equal to the probability that fish with index i will survive to be the last in the lake.


Sample Inputs:
2
0 0.5
0.5 0

5
0 1 1 1 1
0 0 0.5 0.5 0.5
0 0.5 0 0.5 0.5
0 0.5 0.5 0 0.5
0 0.5 0.5 0.5 0

Sample Outputs:
0.500000 0.500000

1.000000 0.000000 0.000000 0.000000 0.000000

Solution (Python):
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n = int(input())
a = [list(map(float, input().split())) for _ in range(n)]
pow2 = [1]
for _ in range(n):
    pow2.append(2 * pow2[-1])
m = pow2[n]
dp = [0] * m
dp[-1] = 1
for i in range(m - 1, 0, -1):
    x = []
    for j in range(n):
        if i & pow2[j]:
            x.append(j)
    u = len(x) * (len(x) - 1) // 2
    if not u or not dp[i]:
        continue
    dpi = dp[i]
    for j in x:
        aj = a[j]
        for k in x:
            if j == k:
                continue
            l = i ^ pow2[k]
            dp[l] += dpi * aj[k] / u
ans = [dp[i] for i in pow2[:-1]]
sys.stdout.write(' '.join(map(str, ans)))

Solution (Python):
import sys
from array import array

def input():
    return sys.stdin.buffer.readline().decode('utf-8')
n = int(input())
prob = [tuple(map(float, input().split())) for _ in range(n)]
full_bit = (1 << n) - 1
dp = [0.0] * full_bit + [1.0]
for bit in range(full_bit, 0, -1):
    popcount = len([1 for i in range(n) if 1 << i & bit])
    if popcount == 1 or dp[bit] == 0.0:
        continue
    div = 1 / (popcount * (popcount - 1) >> 1)
    for i in range(n):
        if 1 << i & bit == 0:
            continue
        for j in range(i + 1, n):
            if 1 << j & bit == 0:
                continue
            dp[bit - (1 << j)] += dp[bit] * prob[i][j] * div
            dp[bit - (1 << i)] += dp[bit] * prob[j][i] * div
print(*(dp[1 << i] for i in range(n)))

Solution (Python):
import os, sys, math
from io import BytesIO, IOBase

def main():
    n = int(input())
    prob = []
    for i in range(n):
        prob.append(arrin(float))
    FishBitmaskIterative(n, prob)
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = 'x' in file.mode or 'r' not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b'\n') + (not b)
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            (self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode('ascii'))
        self.read = lambda : self.buffer.read().decode('ascii')
        self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
arrin = lambda x: list(map(x, input().split()))

def maximumSumOneDeletionAtmost(self, nums):
    pos = False
    for i in nums:
        if i > 0:
            pos = True
    if not pos:
        return max(nums)
    dp = {}
    mx = -1000000000
    dp[0, 0] = nums[0]
    dp[0, 1] = 0
    for i in range(1, len(nums)):
        dp[i, 0] = max(nums[i], nums[i] + dp[i - 1, 0])
        dp[i, 1] = max(nums[i] + dp[i - 1, 1], dp[i - 1, 0])
        mx = max(mx, dp[i, 1], dp[i, 0])
    return max(mx, dp[0, 0], dp[0, 1])

def onesComplement(n):
    number_of_bits = int(math.floor(math.log(n) / math.log(2))) + 1
    return (1 << number_of_bits) - 1 ^ n

def FishBitmaskIterative(n, prob):
    dp = [0 for _ in range(1 << n)]
    dp[0] = 1
    for mask in range(1 << n):
        alive_in_the_stage_before = n - bin(mask).count('1') + 1
        choosing_two = alive_in_the_stage_before * (alive_in_the_stage_before - 1) / 2
        for alive in range(n):
            if not mask & 1 << alive:
                for dead in range(n):
                    if mask & 1 << dead:
                        dp[mask] += dp[mask ^ 1 << dead] * prob[alive][dead] / choosing_two
    ma = 1 << n
    ans = []
    for i in range(n):
        ans.append(dp[ma - 1 - (1 << i)])
    print(*ans)
if __name__ == '__main__':
    main()