Cod sursa(job #2046514)

Utilizator TherevengerkingSurani Adrian Therevengerking Data 23 octombrie 2017 21:02:29
Problema Ubuntzei Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.16 kb
#include <bits/stdc++.h>

using namespace std;
#define pii pair<int, int>
#define pb push_back
#define x first
#define y second
ifstream fin("ubuntzei.in");
ofstream fout("ubuntzei.out");
const int Nmax = 2005;
int n, m, k, rez;
int dp[65600][20], cst[Nmax][Nmax], c[20];
vector<pii>v[Nmax];
struct ee
{
    int nod, cost;
    bool operator < (const ee &other) const{
        return cost > other.cost;
    }
};
priority_queue<ee>pq;
void parc(int cost, int nod, int tata)
{
    for(auto i : v[nod])
        if(cst[tata][i.x] > cst[tata][nod] + i.y)
        {
            cst[tata][i.x] = cst[tata][nod] + i.y;
            pq.push({i.x, cst[tata][i.x]});
        }
}
int main()
{
    fin >> n >> m >> k;
    for(int i = 0; i < k; ++i)
        fin >> c[i];
    for(int i = 1; i <= n; ++i)
        for(int j = 1; j <= n; ++j)
            cst[i][j] = 1 << 30;
    for(int i  = 1, a, b , d; i <= m; ++i)
    {
        fin >> a >> b >> d;
        v[a].pb({b, d});
        v[b].pb({a, d});
    }
    cst[1][1] = 0;
    pq.push({1, 0});
    while(!pq.empty())
    {
        int a = pq.top().cost;
        int b = pq.top().nod;
        pq.pop();
        parc(a, b, 1);
    }
    for(int i = 0; i < k; ++i)
    {
        cst[c[i]][c[i]] = 0;
        pq.push({c[i], 0});
        while(!pq.empty())
        {
            int a = pq.top().cost;
            int b = pq.top().nod;
            pq.pop();
            parc(a, b, c[i]);
        }
    }
    for(int i = 0; i < 1 << k; ++i)
        for(int j = 0; j < k; ++j)
            dp[i][j] = 1 << 30;
    for(int i = 0; i < k; ++i)
    {
        dp[1 << i][i] = cst[1][c[i]];
        //cout <<  cst[1][c[i]] << " ";
    }
    for(int i = 1; i < 1 << k; ++i)
        for(int j = 0; j < k; ++j)
        {
            int ii = i & ~(1 << j);
            if(i == ii)continue;
            for(int jj = 0; jj < k; ++jj)
                dp[i][j] = min(dp[i][j], dp[ii][jj] + cst[c[jj]][c[j]]);
        }
    rez = 1 << 30;
    for(int i = 0; i < k; ++i)
        rez = min(rez, dp[(1 << k) - 1][i] + cst[c[i]][n]);
    if(k == 0)
        fout << cst[1][n];
    else fout << rez;
    return 0;
}