Cod sursa(job #1913939)

Utilizator roxannemafteiuMafteiu-Scai Roxana roxannemafteiu Data 8 martie 2017 14:48:08
Problema Ubuntzei Scor 10
Compilator cpp Status done
Runda minune11 Marime 2.22 kb
#include <bits/stdc++.h>

using namespace std;

const int INF = 0X3f3f3f3f;
const int N_MAX = 2001;

struct Edge {
    int node, length;
    Edge(int n, int l) : node(n), length(l) {}
};

int n, m, k, solution = INF;
vector <int> towns;
vector <Edge> graph[N_MAX], path;
bitset <N_MAX> inPath;

void read() {
    ifstream fin("ubuntzei.in");

    fin >> n >> m >> k;

    towns.resize(k);
    for (auto &town : towns)
        fin >> town;

    while (m--) {
        int a, b, l;
        fin >> a >> b >> l;
        graph[a].emplace_back(b, l);
        graph[b].emplace_back(a, l);
    }

    fin.close();
}

void bfs() {
    vector <int> dist(n + 1, INF);
    queue <Edge> q;
    bitset <N_MAX> inQ;

    dist[1] = 0;
    q.emplace(1, 0);
    inQ.set(1);

    while (!q.empty()) {
        int node = q.front().node;
        int length = q.front().length;
        q.pop();
        inQ.reset(node);

        for (const auto &son : graph[node]) {
            int newLength = son.length + length;
            if (newLength < dist[son.node]) {
                dist[son.node] = newLength;
                if (!inQ[son.node]) {
                    q.emplace(son.node, newLength);
                    inQ.set(son.node);
                }
            }
        }
    }

    solution = dist[n];
}

inline int updateMinLength() {
    return accumulate(path.begin(), path.end(), 0,
    [](int sum, const Edge& current) { return sum + current.length; });
}

inline bool allTownInPath() {
    for (const auto &town : towns)
        if (!inPath[town])
            return false;

    return true;
}

void dfs(int node, int length) {
    path.emplace_back(node, length);
    inPath.set(node);

    if (node == n && allTownInPath())
        solution = min(solution, updateMinLength());
    else
        for (const auto &son : graph[node])
            if (!inPath[son.node])
                dfs(son.node, son.length);

    path.pop_back();
    inPath.reset(node);
}

void write() {
    ofstream fout("ubuntzei.out");

    if (k == 0)
        bfs();
    else
        dfs(1, 0);

    fout << solution;

    fout.close();
}

int main() {
    read();
    write();
    return 0;
}