using
System;
using
System.Collections.Generic;
using
System.Linq;
public
class
Gfg
{
public
static
void
MaxSum(
int
side, List<List<
int
>> matrix)
{
string
s =
""
;
for
(
int
i = 0; i < side; i++)
{
s += i.ToString();
}
List<
string
> cases =
new
List<
string
>();
do
{
cases.Add(s);
}
while
(NextPermutation(
ref
s));
List<
int
> sum =
new
List<
int
>();
foreach
(
var
c
in
cases)
{
List<
int
> p =
new
List<
int
>();
int
tot = 0;
for
(
int
i = 0; i < side; i++)
{
p.Add(matrix[i][
int
.Parse(c[i].ToString())]);
}
p.Sort();
for
(
int
i = side - 1; i >= 0; i--)
{
tot += p[i];
}
sum.Add(tot);
}
Console.WriteLine(sum.Max());
}
private
static
bool
NextPermutation(
ref
string
s)
{
char
[] a = s.ToCharArray();
int
n = a.Length;
int
i = n - 2;
while
(i >= 0 && a[i] >= a[i + 1]) i--;
if
(i < 0)
return
false
;
int
j = n - 1;
while
(a[j] <= a[i]) j--;
char
temp = a[i];
a[i] = a[j];
a[j] = temp;
Array.Reverse(a, i + 1, n - i - 1);
s =
new
string
(a);
return
true
;
}
public
static
void
Main()
{
int
side = 4;
List<List<
int
>> matrix =
new
List<List<
int
>> {
new
List<
int
> { 3, 4, 4, 4 },
new
List<
int
> { 1, 3, 4, 4 },
new
List<
int
> { 3, 2, 3, 4 },
new
List<
int
> { 4, 4, 4, 4 }
};
MaxSum(side, matrix);
side = 3;
matrix =
new
List<List<
int
>> {
new
List<
int
> { 1, 2, 3 },
new
List<
int
> { 6, 5, 4 },
new
List<
int
> { 7, 9, 8 }
};
MaxSum(side, matrix);
}
}