Cod sursa(job #2561726)

Utilizator dnprxDan Pracsiu dnprx Data 29 februarie 2020 09:37:30
Problema Ubuntzei Scor 25
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.06 kb
#include <bits/stdc++.h>
#define oo 1e9 + 1
using namespace std;

vector< pair<int, int> > L[2001];
int n, k;
int a[20][20]; /// a[i][j]=drumul minim de la i la j
    /// unde i si j sunt cele k noduri + nodurile 1 si n
int C[20]; /// aici memorez cele k noduri
int d[2001];
int dp[18][(1 << 16) + 2];
int SOL;
int viz[20], st[20], W;

priority_queue< pair<int, int> > Q;

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

void Citire()
{
    int m, i, x, y, cost;
    fin >> n >> m;
    fin >> k;
    SOL = oo;
    for (i = 1; i <= k; i++)
    {
        fin >> C[i];
        W = W ^ i;
    }
    for (i = 1; i <= m; i++)
    {
        fin >> x >> y >> cost;
        L[x].push_back({y, cost});
        L[y].push_back({x, cost});
    }
    fin.close();
}

void Dijkstra(int s)
{
    int i, nod;
    Q.push({0, s});
    for(i = 1; i <= n; i++)
        d[i] = oo;
    d[s] = 0;
    while(!Q.empty())
    {
        nod = Q.top().second;
        Q.pop();
        for(auto w : L[nod])
            if(d[w.first] > d[nod] + w.second)
        {
            d[w.first] = d[nod] + w.second;
            Q.push({-d[w.first], w.first});
        }
    }
}

void ConstrMat()
{
    int i, j;
    for (i = 1; i <= k; i++)
    {
        Dijkstra(C[i]);
        for (j = 1; j <= k; j++)
            a[i][j] = d[C[j]];
        /// nodul 1 are linia 0
        a[0][i] = a[i][0] = d[1];
        /// nodul n are linia k+1
        a[k+1][i] = a[i][k+1] = d[n];
    }
}

void Calcul()
{
    int i, cost = 0;
    st[k] = W;
    for (i = 1; i <= k; i++)
        cost += a[st[i - 1]][st[i]];
    cost += a[st[k]][k + 1];
    SOL = min(SOL, cost);
}

void Back(int top)
{
    if (top == k) Calcul();
    else for (int i = 1; i <= k; i++)
        if (viz[i] == 0)
        {
            st[top] = i;
            W ^= i;
            viz[i] = 1;
            Back(top + 1);
            viz[i] = 0;
            W ^= i;
        }
}

int main()
{
    Citire();
    ConstrMat();
    Back(1);
    fout << SOL << "\n";
    return 0;
}