Cod sursa(job #635316)

Utilizator PetcuIoanPetcu Ioan Vlad PetcuIoan Data 19 noiembrie 2011 10:15:40
Problema Portal3 Scor 0
Compilator cpp Status done
Runda .com 2011 Marime 2.37 kb
#include<stdio.h>
#include<assert.h>
#include<algorithm>
using namespace std;

struct hax
{
    int x1,y1,c,x2,y2;
};

struct point
{
    int x,y;
};

point z0,zi[3],zf[3],zn;
hax p1,p2,p3;
int t,n,m,c[3],st[4],viz[4],cool[4];
long long sol;

void read()
{
    scanf("%d%d",&n,&m);
    scanf("%d%d%d%d%d",&p1.x1,&p1.y1,&p1.x2,&p1.y2,&p1.c);
    scanf("%d%d%d%d%d",&p2.x1,&p2.y1,&p2.x2,&p2.y2,&p2.c);
    scanf("%d%d%d%d%d",&p3.x1,&p3.y1,&p3.x2,&p3.y2,&p3.c);

    c[0]=p1.c;
    c[1]=p2.c;
    c[2]=p3.c;

    z0.x=0;
    z0.y=0;

    zn.x=n;
    zn.y=m;

    zi[0].x=p1.x1;
    zi[0].y=p1.y1;

    zi[1].x=p2.x1;
    zi[1].y=p2.y1;

    zi[2].x=p3.x1;
    zi[2].y=p3.y1;

    zf[0].x=p1.x2;
    zf[0].y=p1.y2;

    zf[1].x=p2.x2;
    zf[1].y=p2.y2;

    zf[2].x=p3.x2;
    zf[2].y=p3.y2;
}

inline int mod(int x)
{
    if(x<0)
        return -x;
    return x;
}

int mh(point x1,point x2)
{
    return mod(x2.x-x1.x)+mod(x2.y-x1.y);
}

void bk(int k)
{
    if(k==st[0]+1)
    {
        int i,lim,j;
        point cp;
        long long s;
        lim=1<<st[0];
        for(i=0;i<lim;++i)
        {
            s=0;
            cp.x=0;
            cp.y=0;
            for(j=0;j<st[0];++j)
                if(i&(1<<j))
                {
                    s+=c[cool[j]];
                    s+=mh(cp,zi[cool[j]]);
                    cp.x=zf[cool[j]].x;
                    cp.y=zf[cool[j]].y;
                }
                else
                {
                    s+=c[cool[j]];
                    s+=mh(cp,zf[cool[j]]);
                    cp.x=zi[cool[j]].x;
                    cp.y=zi[cool[j]].y;
                }
            s+=mh(cp,zn);
            sol=min(sol,s);
        }
    }
    int i;
    for(i=1;i<=st[0];++i)
        if(!viz[i])
        {
            viz[i]=1;
            cool[k]=i;
            bk(k+1);
            viz[i]=0;
        }
}

void solve()
{
    assert(freopen("portal3.in","r",stdin)!=NULL);
    assert(freopen("portal3.out","w",stdout)!=NULL);
    scanf("%d",&t);
    int i,j,k;
    for(i=1;i<=t;++i)
    {
        read();
        sol=mh(z0,zn);
        for(j=1;j<8;++j)
        {
            for(k=0;k<3;++k)
                if(j&(1<<k))
                    st[++st[0]]=k;
            bk(1);
            while(st[0])
            {
                st[st[0]]=0;
                st[0]--;
            }
        }
        printf("%lld\n",sol);
    }
}

int main()
{
    solve();
    return 0;
}