Cod sursa(job #546387)

Utilizator DraStiKDragos Oprica DraStiK Data 4 martie 2011 21:00:52
Problema Team Scor 95
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.81 kb
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;

#define pb push_back
#define mp make_pair
#define sc second
#define fs first

#define INF 0x3f3f3f3f
#define LIM 10005
#define DIM 505
#define MAX 55

vector <pair <int,int> > g[DIM];
int bst[MAX][MAX][MAX];
int D[MAX],dst[DIM];
int cst[MAX][MAX];
bool viz[DIM];
int N,M,P;

int pozitie=LIM-1;
char buff[LIM];

struct cmp
{
    bool operator () (const int &a,const int &b)
    {
        return D[a]>D[b];
    }
}; priority_queue <int,vector <int>,cmp> q;


inline void cit (int &nr)
{
    char semn;

    for (semn='+'; !isdigit (buff[pozitie]); )
    {
        semn=buff[pozitie];
        if (++pozitie==LIM)
        {
            fread (buff,1,LIM,stdin);
            pozitie=0;
        }
    }
    for (nr=0; isdigit (buff[pozitie]); )
    {
        nr=nr*10+buff[pozitie]-'0';
        if (++pozitie==LIM)
        {
            fread (buff,1,LIM,stdin);
            pozitie=0;
        }
    }
    if (semn=='-')
        nr=-nr;
}

void read ()
{
    int i,x,y,z;

    cit (P); cit (N); cit (M);
    for (i=1; i<=M; ++i)
    {
        cit (x); cit (y); cit (z);
        g[x].pb (mp (y,z));
        g[y].pb (mp (x,z));
    }
    for (i=1; i<=N; ++i)
        cit (D[i]);
    D[0]=1;
}

inline void dijkstra (int start)
{
    vector <pair <int,int> > :: iterator it;
    int nod;

    for (nod=1; nod<=N; ++nod)
        dst[nod]=INF;
    dst[start]=0;

    for (q.push (start); !q.empty (); )
    {
        nod=q.top (); q.pop (); viz[nod]=0;
        for (it=g[nod].begin (); it!=g[nod].end (); ++it)
            if (dst[nod]+it->sc<dst[it->fs])
            {
                dst[it->fs]=dst[nod]+it->sc;
                if (!viz[it->fs])
                {
                    viz[it->fs]=1;
                    q.push (it->fs);
                }
            }
    }
}

inline void calc (int x,int y,int start)
{
    int nod;

    if (x>y)
    {
        bst[x][y][start]=0;
        return ;
    }

    for (nod=x; nod<=y; ++nod)
    {
        if (bst[x][nod-1][nod]==INF)
            calc (x,nod-1,nod);
        if (bst[nod+1][y][nod]==INF)
            calc (nod+1,y,nod);
        bst[x][y][start]=min (bst[x][y][start],bst[x][nod-1][nod]+bst[nod+1][y][nod]+cst[start][nod]);
    }
}

void solve ()
{
    int i,j,k;

    for (i=0; i<=P; ++i)
    {
        dijkstra (D[i]);
        for (j=0; j<=P; ++j)
            cst[i][j]=dst[D[j]];
    }

    for (i=0; i<=P; ++i)
        for (j=0; j<=P; ++j)
            for (k=0; k<=P; ++k)
                bst[i][j][k]=INF;
    calc (1,P,0);
    printf ("%d",bst[1][P][0]);
}

int main ()
{
    freopen ("team.in","r",stdin);
    freopen ("team.out","w",stdout);

    read ();
    solve ();

    return 0;
}