Cod sursa(job #2190228)

Utilizator calinfloreaCalin Florea calinflorea Data 30 martie 2018 10:20:09
Problema Ubuntzei Scor 45
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.14 kb
#include <bits/stdc++.h>
#define NMax 2006
#define oo (1 << 30)

using namespace std;

ifstream fin ("ubuntzei.in");
ofstream fout ("ubuntzei.out");

struct Pereche
{
    int c, nod;

    bool operator < (const Pereche & e) const
    {
        return c > e.c;
    }
};

queue <Pereche> q;
vector <pair <int, int> > L[NMax];
int n, m, k;
int a[NMax], drum[NMax], st[NMax];
int b[NMax][NMax], costminim = oo;
bool viz[NMax];

inline void Citire()
{
    int i, x, y, z;

    fin >> n >> m;
    fin >> k;

    for(i = 1; i <= k; i++)
        fin >> a[i];

    for(i = 1; i <= m; i++)
    {
        fin >> x >> y >> z;
        L[x].push_back({y, z});
        L[y].push_back({x, z});
    }
}

inline void Initializare()
{
    int i;

    for(i = 1; i <= n; i++)
        drum[i] = oo;
}

inline void Dijkstra()
{
    int i, j, nod, cost, K;

    for(K = 1; K <= n; K++)
    {
        Initializare();
        q.push({0, K});
        drum[K] = 0;

        while(!q.empty())
        {
            i = q.front().nod;
            q.pop();

            for(j = 0; j < L[i].size(); j++)
            {
                nod = L[i][j].first;
                cost = L[i][j].second;

                if(drum[nod] > drum[i] + cost)
                {
                    drum[nod] = drum[i] + cost;
                    q.push({drum[nod], nod});
                }
            }
        }

        for(i = 1; i <= n; i++)
            b[K][i] = drum[i];
    }
}

inline void Rezolva()
{
    int i, S = b[1][st[1]];

    for(i = 1; i < k; i++)
        S += b[st[i]][st[i + 1]];
    S += b[st[k]][n];

    costminim = min(S, costminim);
}

void Back(int top)
{
    if(top == k + 1)
        Rezolva();
    else
        for(int i = 1; i <= k; i++)
            if(!viz[a[i]])
            {
                st[top] = a[i];
                viz[a[i]] = 1;
                Back(top + 1);
                viz[a[i]] = 0;
            }
}

int main()
{
    Citire();
    Dijkstra();
    Back(1);
    if(k != 0)
        fout << costminim << "\n";
    else
        fout << b[1][n] << "\n";
    return 0;
}