Cod sursa(job #701104)

Utilizator andrei.finaruFinaru Andrei Emanuel andrei.finaru Data 1 martie 2012 13:38:27
Problema Ubuntzei Scor 20
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.91 kb
#include <fstream>
#include <cstring>
#include <queue>
#include <climits>

using namespace std;

ifstream f("ubuntzei.in");
ofstream g("ubuntzei.out");

struct node
{
    int nr,c;
    node *next;
} *v[2012],*p;
int n,m,k,d[16][16],pr[16],a,b,cq,cul[2012],cost[2012],smin;
char prez[16];
queue <int> q;

void dijkstra(int s)
{
    int w;
    memset(cul,0,sizeof(cul));
    memset(cost,0,sizeof(cost));
    q.push(s);
    while(!q.empty())
    {
        w=q.front();
        q.pop();
        cul[w]=2;
        p=v[w];
        while(p)
        {
            if(!cul[p->nr] || (cul[p->nr]==2&&cost[p->nr]>cost[w]+p->c) )
            {
                cul[p->nr]=1;
                q.push(p->nr);
                cost[p->nr]=cost[w]+p->c;
            }
            else if(cost[p->nr]>cost[w]+p->c) cost[p->nr]=cost[w]+p->c;
            p=p->next;
        }
    }
}

void back(int u, int sc)
{
    int i;
    if(u==k+1)
    {
        smin=(smin<sc)?smin:sc;
        return;
    }
    for(i=1;i<=k;++i)
    {
        pr[u]=i;
        if(!prez[i])
        {
            prez[i]=1;
            sc+=d[pr[u-1]][i];
            if(sc<=smin) back(u+1,sc);
            prez[i]=0;
        }
    }
}

int main()
{
    int i,j;
    f>>n>>m>>k;
    for(i=1;i<=k;++i) f>>pr[i];
    for(i=1;i<=m;++i)
    {
        f>>a>>b>>cq;
        p=new node;
        p->nr=b;
        p->c=cq;
        p->next=v[a];
        v[a]=p;
        p=new node;
        p->nr=a;
        p->c=cq;
        p->next=v[b];
        v[b]=p;
    }
    smin=INT_MAX;
    if(!k) dijkstra(1), g<<cost[n]<<'\n';
    else
    {
        for(i=1;i<=k;++i)
        {
            dijkstra(pr[i]);
            for(j=1;j<i;++j) d[i][j]=d[j][i]=cost[pr[j]];
            d[0][i]=cost[1];
            d[i][n]=cost[n];
        }
        back(1,0);
        g<<smin<<'\n';
    }
    f.close(); g.close();
    return 0;
}