Pagini recente » Cod sursa (job #2858594) | Cod sursa (job #2559042) | Cod sursa (job #2407873) | Cod sursa (job #956102) | Cod sursa (job #2633982)
#include <bits/stdc++.h>
#define maxn 55
#define maxv 505
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;
}
};
InParser fin("team.in");
std::ofstream fout("team.out");
int x[maxn];
int dist[maxv][maxv];
int dest[maxn];
int dp[maxn][maxn][maxn];
void computeMinDist(int n){
int i, j, k;
for (k=1; k<=n; k++){
for (i=1; i<=n; i++){
if (i == k) continue;
for (j=1; j<=n ; j++){
if (j == k or j == i) continue;
if (dist[i][k] == -1 or dist[k][j] == -1) continue;
if (dist[i][j] == -1) dist[i][j] = 1e9;
dist[i][j] = std::min (dist[i][j], dist[i][k] + dist[k][j]);
}
}
}
}
int main()
{
int n, V, E, src, dst, cost, i, j, k, u;
fin >> n >> V >> E;
for (i=1; i<=V; i++)
for (j=1; j<=V; j++)
dist[i][j] = -1;
for (i=1; i<=V; i++)
dist[i][i] = 0;
for (i=0; i<E; i++) {
fin >> src >> dst >> cost;
dist[src][dst] = cost;
dist[dst][src] = cost;
}
/*
for (i=1; i<=V; i++, fout << '\n')
for (j=1; j<=V; j++)
fout << dist[i][j] << ' ';
*/
for (i=1; i<=n; i++)
fin >> dest[i];
computeMinDist(V);
for (i=1; i<=n; i++)
dp[i][i][i] = 0;
for (int l=0; l<=n; l++)
for (i=1; i<=n-l; i++){
j = i + l;
for (k=1; k<=n; k++){
if (k == i and k == j)
continue;
dp[i][j][k] = 1e9;
for (u=i; u<=j; u++){
//std::cout << dp[i][u-1][u] << ' ' << dp[u+1][j][i] << ' ' << dist[dest[u]][dest[k]] << dp[i][u-1][u] + dp[u+1][j][i] + dist[dest[u]][dest[k]] << '\n';
//std::cout << std::min (dp[i][j][k], dp[i][u-1][u] + dp[u+1][j][u] + dist[dest[u]][dest[k]]) << '\n';
dp[i][j][k] = std::min (dp[i][j][k], dp[i][u-1][u] + dp[u+1][j][u] + dist[dest[u]][dest[k]]);
}
}
}
int ans = 1e9;
for (i=1; i<=n; i++)
ans = std::min (ans, dp[1][n][i] + dist[1][dest[i]]);
fout << ans;
return 0;
}