Cod sursa(job #573909)

Utilizator tamas_iuliaTamas Iulia tamas_iulia Data 6 aprilie 2011 17:44:11
Problema Bibel Scor 95
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.82 kb
#include <stdio.h>
#include <string.h>
#define Nmax 17
#define INF 2147000000

int a[1<<Nmax][Nmax];
struct punct{
    int x,y;
} P[2][Nmax+1];

int val[2][Nmax+1],d[Nmax+1][Nmax+1];
int N,st;

inline int Minim(int x,int y){ return x<y ? x:y; }
 inline int D( punct o, punct p) {
        return (o.x-p.x)*(o.x-p.x)+(o.y-p.y)*(o.y-p.y);
}


inline void work(){
    int i,j,dist,sol,conf;
    memset(val[st],0,sizeof(val[st]));
    for(i=1;i<=N;++i)
        for(j=1;j<=N;++j)
        if(i!=j)
            d[i][j]=  D(P[st][i] , P[st][j] );

    for(i=0;i<N;++i){
        dist=INF;
        for(j=1;j<=val[st^1][0];++j)
            if( dist > val[st^1][j] + D(P[st][i+1],P[st^1][j]))
                dist = val[st^1][j] + D(P[st][i+1],P[st^1][j]);
        a[1<<i][i]=dist;
    }

    for( conf=1; conf<(1<<N); ++conf )
    if( conf&(conf-1) )
        for(i=0; (1<<i) <= conf;++i)
            if( conf&(1<<i) ){
                a[conf][i]=INF;

                for(j=0; (1<<j) <= conf; ++j)
                    if( (conf&(1<<j)) && j!=i && a[conf][i]>a[conf^(1<<i)][j] + d[i+1][j+1]  )
                        a[conf][i]=a[conf^(1<<i)][j] + d[i+1][j+1];
            }

    sol=INF;
    for(i=0;i<N;++i){
        val[st][i+1]=a[(1<<N)-1][i];
        if( sol > val[st][i+1]) sol=val[st][i+1];
    }
    val[st][0]=N;

    printf("%d\n",sol);
}

int main(){
    int i,tip;
    freopen("bibel.in","r",stdin);
    freopen("bibel.out","w",stdout);
    val[1][val[1][0]=1]=0;
    st=0; N=0;
    do{
        scanf("%d",&tip);
        if( !tip ) ++N,scanf("%d%d",&P[st][N].x,&P[st][N].y);
        else{
            if( tip==1 ){
                work();

                N=0;
                st ^=1;
            }
        }
    } while( tip != 2 );

    fclose(stdin); fclose(stdout);
    return 0;
}