Cod sursa(job #1120915)

Utilizator 2dorTudor Ciurca 2dor Data 25 februarie 2014 10:46:21
Problema Ubuntzei Scor 15
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.31 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

const int MAXN = 2005;
vector<pair<int, int> > G[MAXN];
int N, M, K;
int Solution, AllCitiesVisited;
short k[MAXN];//which cities we have to get through in order to reach the final destination
//we designate a power of 2 to each of these cities; this will allow us to use a bitmask
short pow2[20];//the powers of 2; we need this to encrypt which cities
// have been visited in a certain state
struct triplu {
    short node;
    short bitmask;
    int cost;
};

struct cmp {
    bool operator()(triplu A, triplu B) const {
        return A.cost > B.cost;
    }
};

priority_queue<triplu, vector<triplu>, cmp> PQ;

void Read() {
    fin >> N >> M;
    fin >> K;
    int x, y, z;
    for (int i = 1; i <= K; ++i) {
        fin >> x;
        k[x] = i;
    }
    for (int i = 0; i < M; ++i) {
        fin >> x >> y >> z;
        G[x].push_back(make_pair(y, z));
        G[y].push_back(make_pair(x, z));
    }
}

void CalculatePowersOfTwo() {
    for (int i = 1; i < 16; ++i)
        pow2[i] = (1 << (i - 1));
}

void Go() {
    triplu aux;
    aux.node = 1;
    aux.bitmask = 0;
    aux.cost = 0;
    PQ.push(aux);
    do {
        triplu state = PQ.top();
        PQ.pop();
        //fout << state.node << ' ' << state.bitmask << ' ' << state.cost << '\n';
        if ( (state.node == N) && (state.bitmask == ((1 << K) - 1)) ) {
            Solution = state.cost;
            break;
        }
        vector<pair<int, int> >::iterator it;
        for (it = G[state.node].begin(); it != G[state.node].end(); ++it) {
            if ( k[it->first] && !( state.bitmask & ( 1 << (k[it->first] - 1) ) ) )
                aux.bitmask = state.bitmask + pow2[k[it->first]];
            else
                aux.bitmask = state.bitmask;
            aux.node = it->first;
            aux.cost = state.cost + it->second;
            PQ.push(aux);

        }
    }while (!PQ.empty());
}

int main() {
    Read();
    cerr <<"Data Read.\n";
    CalculatePowersOfTwo();
    cerr << "Powers of two calculated.\n";
    Go();
    cerr << "Solution found.\n";
    fout << Solution << '\n';
    fin.close();
    fout.close();
    return 0;
}