Cod sursa(job #63292)

Utilizator goguGogu Marian gogu Data 27 mai 2007 18:37:04
Problema Cast Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.72 kb
#include <cstdio>
#include <cstdlib>
#include <string>
#define pow(x) (1u<<(x))
#define inf 1012345678

using namespace std;

unsigned n, cost[16][16];
unsigned best[12][1<<12];
char ok[12][1<<12];

unsigned calc(unsigned p, unsigned biti)
{
    if (ok[p][biti]) return best[p][biti];
    ok[p][biti]=1;
    if (!biti) return 0;
    unsigned sol = inf, nb=0, i, j, k;
    unsigned poz[12], mask, inv, tot;
    for (i=0; i<n; i++)
        if (pow(i) & biti) nb++;
    nb--;
    tot = pow(nb);
    for (i=0; i<n; i++)     
        if ((biti & pow(i)) && cost[p][i]<sol){
           for (j=k=0; j<n; j++)
               if ((pow(j) & biti) && j!=i) poz[k++]=pow(j);
           for (j=0; j<tot; j++){
               mask=0;
               #define W(k) if (j & pow(k)) mask+=poz[k];
               W(0) W(1) W(2) W(3) W(4) W(5) W(6) W(7) W(8) W(9)
               inv = (biti & (~mask)) - pow(i);
               unsigned val = cost[p][i] + calc(p, mask);
               if (val>=sol) continue;
               if (cost[p][i]+calc(i, inv) > val) val = cost[p][i]+calc(i, inv);
               if (val < sol) sol=val;
           }
        }
    best[p][biti]=sol;
    return best[p][biti];
}

void solve()
{
     unsigned i, j;
     scanf("%u", &n);
     for (i=0; i<n; i++)
         for (j=0; j<n; j++)
             scanf("%u", cost[i]+j);
     memset(ok, 0, sizeof(ok));
     for (i=0; i<n; i++)
         for (j=0; j<n; j++)
             if (i!=j) best[i][pow(j)]=cost[i][j], ok[i][pow(j)]=1;
     printf("%d\n", calc(0, pow(n)-2));
}

int main()
{
    int tst;
    freopen("cast.in", "r", stdin);
    freopen("cast.out", "w", stdout);
    scanf("%d", &tst);
    while (tst--) solve();
    return 0;
}