Optimal Marriage On Planet X

In the classical marriage problem on Earth, you are given n men, n women, plus a compatibility rating for each pair of man and woman (higher means more compatible). You have to find the optimal pairing (i.e. a marriage), n disjoint pairs of men and women, such that the sum of the compatibility ratings for the formed pairs (marriages) is maximum. Typically, this is solved using maximum bipartite matching algorithms such as the Hungarian Method, or network flow algorithms. Unfortunately, it is not so easy on planet X, because there are 3 sexes/genders instead of 2 :-) !!! The 3 sexes are Xelox,Yakki, and Zabra. You are given n Xeloxes, n Yakkis, and n Zabras, and a set of compatibility ratings, r(x, y, z) for each triple (x, y, z) where x is a Xelox, y is a Yakki, z is a Zabra. In this problem, you have to form n disjoint triples, such that the sum of their compatibility ratings is maximal. Since the aliens on planet X do not want their compatibility ratings to be too similar, for any two different compatibility ratings r1, and r2, it is guarranteeed that 300 ∗ abs(r1 − r2) > (r1 + r2). Input There is a number of inputs. Each input begins with n (n < 21). n3 lines follow; each of the form: xyzr where x is the index of a Xelox, y is the index of a Yakki, z is the index of a Zabra, and 0 < x, y, z < n+1. r is the compatibility rating, r(x, y, z) of this triple. r fits inside an unsigned 32 bit integer. Output For each input, output the maximum sum of the compatibility ratings after forming the optimal triples (marriages) on a single line. Sample Input 2 1110 1120 1210 1229 2119 2120 2210 2220 Sample Output 18