Cod sursa(job #1895594)

Utilizator hantoniusStan Antoniu hantonius Data 28 februarie 2017 06:39:24
Problema Ubuntzei Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.8 kb
#include <iostream> // sterge
#include <fstream>
#include <algorithm>
#include <vector>
#include <climits>
#define maxn 2002
using namespace std;

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

vector <pair <int, int> > g[maxn];
int n, m, k, viz[maxn], dist[maxn], friends[20], aux, res;

struct muchie
{
    int x, y, c;
};
muchie v[1000];

void read()
{
    int aux, x, y;

    fin >> n >> m >> k;
    for (int i = 1; i <= k; i++) {
        fin >> aux;
        friends[i] = aux;
    }
    for (int i = 1; i <= m; i++) {
        fin >> x >> y >> aux;
        g[x].push_back(make_pair(y, aux));
        g[y].push_back(make_pair(x, aux));
    }
}

void drum(int param)
{
    int vf, ok = 1, poz, minv;
    vector <pair <int, int> >::iterator it;

    vf = friends[param];
    for (int i = 1; i <= n; i++)
        viz[i] = 0;
    viz[vf] = 1;
    for (int i = 1; i <= n; i++)
        dist[i] = INT_MAX;
    dist[vf] = 0;
    for (it = g[vf].begin(); it != g[vf].end(); it++)
        dist[it->first] = it->second;
    while (ok == 1) {
        minv = INT_MAX;
        for (int i = 1; i <= n; i++)
            if (viz[i] == 0 && dist[i] < minv) {
                minv = dist[i];
                poz = i;
            }
        if (minv == INT_MAX)
            ok = 0;
        else {
            viz[poz] = 1;
            for (it = g[poz].begin(); it != g[poz].end(); it++)
                if (dist[it->first] > dist[poz] + it->second)
                    dist[it->first] = dist[poz] + it->second;
        }
    }
    aux++;
    v[aux].x = 0;
    v[aux].y = param;
    v[aux].c = dist[1];
    aux++;
    v[aux].x = k + 1;
    v[aux].y = param;
    v[aux].c = dist[n];
    for (int i = 1; i <= k; i++) {
        if (i != param) {
            aux++;
            v[aux].x = i;
            v[aux].y = param;
            v[aux].c = dist[friends[i]];
        }
    }
}

bool cmp(muchie lhs, muchie rhs)
{
    return lhs.c < rhs.c;
}

void solve()
{
    int vec[20], nr = 0, i, a, b;

    for (i = 1; i <= k; i++)
        drum(i);
    sort(v + 1, v + k * k + 2 * k, cmp);
    for (i = 0; i <= k + 1; i++)
        vec[i] = i;
    i = 0;
    while (nr < k + 1) {
        i++;
        a = v[i].x;
        b = v[i].y;
        if (vec[a] != vec[b]) {
            nr++;
            res = res + v[i].c;
            if (vec[a] <= vec[b]) {
                for (int j = 0; j <= k + 1; j++)
                    if (vec[j] == vec[b])
                        vec[j] = vec[a];
            }
            else {
                for (int j = 0; j <= k + 1; j++)
                    if (vec[j] == vec[a])
                        vec[j] = vec[b];
            }

        }
    }
}

int main()
{
    read();
    solve();
    fout << res;
    return 0;
}