1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#include <stdio.h>

typedef unsigned long long V;

V tab[2000][2000];
int n;
V sum;
char vec[2001];

V find_min(int x)
{
    int a, b;
    int i, j;
    V m = -1;
    
    a = b = x;
    
    while(a-1 >= 0 && vec[a-1] != '.')
    {
        a--;
    }
    
    while(b+1 < n && vec[b+1] != '.')
    {
        b++;
    }
    
    for(i = a; i <= x; i++)
    {
        for(j = x; j <= b; j++)
        {
            if(tab[i][j] < m)
            {
                m = tab[i][j];
            }
        }
    }
    
    return m;
}

V calc(int lvl)
{
    V m;
    V min, x;
#ifdef OPT
    V s;
#endif
    int i;
    
    if(lvl == n)
    {
#ifdef DEBUG
        printf("# sum = %llu\n", sum);
#endif
        return sum;
    }
    
    m = -1;
    for(i = 0; i < n; i++)
    {
#ifdef OPT
        if(vec[i] == '.')
        {
            s = find_min(i);
            //printf("min: %d - %llu\n", i, s);
            if(s < m) m = s;
        }
        else
#endif
        if(vec[i] == 'O')
        {
            vec[i] = 'x';
        }
    }

    min = -1;
    for(i = 0; i < n; i++)
    {
        if(vec[i] == '.'
#ifdef OPT
        && find_min(i) == m
#endif
        )
        {
#ifndef OPT
            m = find_min(i);
#endif
            vec[i] = lvl < 9 ? '1'+lvl : 'O';
            sum += m;
#ifdef DEBUG
            printf("# [%3d:%2d] %s %llu %llu\n", lvl, i, vec, m, sum);
#endif
            x = calc(lvl+1);
            if(x < min) min = x;
            sum -= m;
            vec[i] = '.';
        }
    }

    return min;
}

int main(int argc, char **argv)
{
    int i, j;
    FILE *f;
    V min;

#ifdef DEBUG
    f = fopen(argv[1], "r");
#else
    f = stdin;
#endif

    fscanf(f, "%d", &n);
    for(i = 0; i < n; i++)
    {
        for(j = i; j < n; j++)
        {
            fscanf(f, "%llu", &tab[i][j]);
        }
        vec[i] = '.';
    }
    vec[i] = 0;

#ifdef DEBUG
    fclose(f);
#endif

    min = -1;    
    sum = 0;
    min = calc(0);

    printf("%llu\n", min);

    return 0;
}