Cheapest Assignment

medium bitmask dp 1000 ms · 256 MB

Cheapest Assignment

There are n workers and n jobs. Worker i can do job j at a cost of c_{i,j}.

Every worker must get exactly one job, and every job must be given to exactly one worker. Find the minimum possible total cost of such an assignment.

Input

The first line contains an integer n (1 ≤ n ≤ 20).

Each of the next n lines contains n integers. The j-th integer of the i-th line is c_{i,j} (0 ≤ c_{i,j} ≤ 10^9), the cost of worker i doing job j.

Output

Print one integer: the minimum total cost.

Notes

In the first example, the best assignment gives job 2 to worker 1, job 1 to worker 2 and job 3 to worker 3, for a total of 2 + 3 + 4 = 9. Giving worker 1 their cheapest job (job 1, cost 1) looks tempting, but then the cheapest way to finish costs 13 more, for a total of 14.

In the second example there is only one worker and one job.

The answer may not fit in a 32-bit integer.

Example 1

Input

3
1 2 7
3 9 8
6 5 4

Output

9

Example 2

Input

1
7

Output

7

Hints · reveal one at a time if you're stuck

Hint 1

With n = 20 there are far too many ways to pick a permutation, and greedy choices fail. Think about the workers in a fixed order: once some workers have been served, what information about the jobs taken so far do you actually need for the rest?

Hint 2

Only the set of jobs already taken matters, not which worker took which job, and the size of that set tells you which worker is next. So the state can be a subset of jobs, and you can grow a subset by giving the next worker one more free job.

Hint 3

Compute the cheapest cost for every subset of jobs in increasing order of subset value, since each step adds a bit. This is about n times 2^n work, which is fast. Remember the total can exceed 32 bits.

report an issue Prefer your own editor? sooks prep 44 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.