Pagini recente » Cod sursa (job #3274050) | Cod sursa (job #2936126) | Cod sursa (job #2517072) | Cod sursa (job #2971658) | Cod sursa (job #1121101)
#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;
short keys;
};
struct cmp {
bool operator()(triplu A, triplu B) const {
if (A.cost == B.cost)
return A.keys < B.keys;
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;
aux.keys = 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 (BM[*it] == state.bitmask) {
//
// }
if ( k[it->first] && !( state.bitmask & ( 1 << (k[it->first] - 1) ) ) ) {
aux.bitmask = state.bitmask + pow2[k[it->first]];
aux.keys = state.keys + 1;
}else {
aux.bitmask = state.bitmask;
aux.keys = state.keys;
}
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;
}