Cod sursa(job #1118378)

Utilizator NicuCJNicu B. NicuCJ Data 24 februarie 2014 10:35:50
Problema Ubuntzei Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.86 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

struct nod
{
    int d, c;
};
vector<nod> gr[2001];
queue<int> coada;
int k, x[17], a[17], a1, b1, c1, n, m, cost, d[16][2001], minim, xf;
bool luat[17];
ifstream f("ubuntzei.in");
ofstream g("ubuntzei.out");
void back(int t)
{
    int i;
    for(i=1; i<=k; i++)
    {
        if(luat[i])
            continue;
        luat[i]=1;
        x[t]=i;
        cost+=d[x[t-1]][a[i]];
        if(cost>minim)
        {
            cost-=d[x[t-1]][a[i]];
            luat[i]=0;
            continue;
        }
        if(t==k)
        {
            cost+=d[x[t]][n];
            if(cost<minim)
                minim=cost;
            cost-=d[x[t]][n];
            luat[i]=0;
        }
        else
        {
            back(t+1);
            cost-=d[x[t-1]][a[i]];
            luat[i]=0;
        }
    }
}



int main()
{
    int i, j;

    f>>n>>m;
    f>>k;
    minim=99999999;
    for(i=1; i<=k; i++)
    {
        f>>a[i];
    }
    for(i=1; i<=m; i++)
    {
        f>>a1>>b1>>c1;
        nod A;
        A.d=b1;
        A.c=c1;
        gr[a1].push_back(A);
        A.d=a1;
        gr[b1].push_back(A);
    }
    //facem BELLMAN FORD din 1, a1, a2...ak.
    a[0]=1;
    a[k+1]=n;
    for(i=0; i<=k; i++)
    {
        for(j=1; j<=n; j++)
        {
            d[i][j]=999999999;
        }
        d[i][a[i]]=0;
        coada.push(a[i]);
        while(!coada.empty())
        {
            xf=coada.front(); coada.pop();
            for(j=0; j<gr[xf].size(); j++)
            {
                if(d[i][xf]+gr[xf][j].c<d[i][gr[xf][j].d])
                {
                    d[i][gr[xf][j].d]=d[i][xf]+gr[xf][j].c;
                    coada.push(gr[xf][j].d);
                }
            }
        }
    }
    back(1);
    g<<minim;
}