Pagini recente » Cod sursa (job #2420405) | Cod sursa (job #2223496) | Cod sursa (job #33709) | Cod sursa (job #48502) | Cod sursa (job #1154105)
#include <cstring>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
const int oo = 0x3f3f3f3f;
const int NIL = -1;
const int MAX_V = 500;
const int MAX_N = 50;
int N, V, G[MAX_V][MAX_V], Source, Answer;
int Destinations[MAX_N], Cost[MAX_N + 1][MAX_N + 1];
void Dijkstra(const int source, int distances[MAX_V]) {
bool used[MAX_V];
memset(used, 0, sizeof(used));
for (int x = 0; x < V; ++x)
distances[x] = oo;
distances[source] = 0;
int x = source;
do {
for (int y = 0; y < V; ++y)
if (!used[y])
distances[y] = min(distances[y], distances[x] + G[x][y]);
used[x] = true;
x = NIL;
for (int y = 0; y < V; ++y)
if (!used[y] && (x == NIL || distances[y] < distances[x]))
x = y;
} while (x != NIL);
}
void BuildCost() {
vector<int> vertices;
vertices.push_back(Source);
for (int x = 0; x < N; ++x)
vertices.push_back(Destinations[x]);
sort(vertices.begin(), vertices.end());
vertices.erase(unique(vertices.begin(), vertices.end()), vertices.end());
int newV = int(vertices.size()), newIndex[MAX_V];
memset(newIndex, -1, sizeof(newIndex));
for (int i = 0; i < newV; ++i)
newIndex[vertices[i]] = i;
for (int x = 0; x < N; ++x)
Destinations[x] = newIndex[Destinations[x]];
for (int i = 0; i < newV; ++i) {
int distances[MAX_V];
Dijkstra(vertices[i], distances);
for (int j = 0; j < newV; ++j)
Cost[i][j] = distances[vertices[j]];
}
V = newV;
}
void Solve() {
BuildCost();
int dp[MAX_N + 1][MAX_N][MAX_N];
memset(dp, oo, sizeof(dp));
for (int length = 1; length <= N; ++length) {
for (int x = 0; x < V; ++x) {
for (int first = 0, last = length - 1; last < N; ++first, ++last) {
for (int split = first; split <= last; ++split) {
int current = Cost[x][Destinations[split]];
if (split > first)
current += dp[Destinations[split]][first][split - 1];
if (split < last)
current += dp[Destinations[split]][split + 1][last];
dp[x][first][last] = min(dp[x][first][last], current);
}
}
}
}
Answer = dp[Source][0][N - 1];
}
void Read() {
ifstream in("team.in");
int E;
in >> N >> V >> E;
memset(G, oo, sizeof(G));
for (int x = 0; x < V; ++x)
G[x][x] = 0;
for (; E > 0; --E) {
int x, y, c;
in >> x >> y >> c;
--x;
--y;
G[x][y] = G[y][x] = c;
}
for (int x = 0; x < N; ++x) {
in >> Destinations[x];
--Destinations[x];
}
Source = 0;
in.close();
}
void Print() {
ofstream out("team.out");
out << Answer << "\n";
out.close();
}
int main() {
Read();
Solve();
Print();
return 0;
}