Pagini recente » Cod sursa (job #1998612) | Cod sursa (job #1326645) | Cod sursa (job #2544892) | Cod sursa (job #1048048) | Cod sursa (job #2418851)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
class InParser {
private:
FILE *fin;
char *buff;
int sp;
char read_ch() {
++sp;
if (sp == 4096) {
sp = 0;
fread(buff, 1, 4096, fin);
}
return buff[sp];
}
public:
InParser(const char* nume) {
fin = fopen(nume, "r");
buff = new char[4096]();
sp = 4095;
}
InParser& operator >> (int &n) {
char c;
while (!isdigit(c = read_ch()) && c != '-');
int sgn = 1;
if (c == '-') {
n = 0;
sgn = -1;
} else {
n = c - '0';
}
while (isdigit(c = read_ch())) {
n = 10 * n + c - '0';
}
n *= sgn;
return *this;
}
InParser& operator >> (long long &n) {
char c;
n = 0;
while (!isdigit(c = read_ch()) && c != '-');
long long sgn = 1;
if (c == '-') {
n = 0;
sgn = -1;
} else {
n = c - '0';
}
while (isdigit(c = read_ch())) {
n = 10 * n + c - '0';
}
n *= sgn;
return *this;
}
} in ("team.in");
ofstream out ("team.out");
#define ll long long
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
#define MAX(a, b) (((a) < (b)) ? (b) : (a))
int const nmax = 500;
int const pmax = 50;
int const inf = 1000000000;
struct Edge{
int to;
int cost;
};
vector<Edge> g[5 + nmax];
int dp[5 + pmax][5 + pmax][5 + pmax];
int dist[5 + pmax][5 + nmax];
int spec[5 + pmax];
int seen[5 + nmax];
int n;
void bfs(int node, int p){
queue<int> q;
q.push(node);
dist[p][node] = 0;
for(int i = 1;i <= n;i++)
seen[i] = 0;
while(0 < q.size()){
int newnode = q.front();
q.pop();
seen[newnode] = 0;
for(int h = 0;h < g[newnode].size(); h++){
Edge e = g[newnode][h];
if(dist[p][newnode] + e.cost < dist[p][e.to]){
dist[p][e.to] = dist[p][newnode] + e.cost;
if(seen[e.to] == 0){
q.push(e.to);
seen[e.to] = 1;
}
}
}
}
}
int main()
{
int p;
in >> p >> n;
int m;
in >> m;
for(int i = 0;i <= p; i++)
for(int j = 1;j <= n;j++)
dist[i][j] = inf;
for(int i = 0;i <= p;i++)
for(int j = 1;j <= p; j++)
for(int h = j;h <= p; h++)
dp[i][j][h] = inf;
for(int i = 1;i <= m; i++){
int x, y, cost;
in >> x >> y >> cost;
g[x].push_back({y, cost});
g[y].push_back({x, cost});
}
spec[0] = 1;
bfs(1, 0);
for(int i = 1;i <= p;i++) {
in >> spec[i];
bfs(spec[i], i);
}
for(int i = 0;i <= p;i++)
for(int j = 1;j <= p;j++)
dp[i][j][j] = dist[j][spec[i]];
for(int h = 1; h <= p - 1; h++){
for(int j = 1;j <= p - h; j++){
for(int start = 0; start <= p; start++){
dp[start][j][j + h] = inf;
for(int i = j; i <= j + h; i++){
dp[start][j][j + h] = MIN(dp[start][j][j + h], dist[start][spec[i]] + dp[i][j][i - 1] + dp[i][i + 1][j + h] );
}
}
}
}
out << dp[0][1][p] << '\n';
return 0;
}