Cod sursa(job #2418848)

Utilizator AlexandruLuchianov1Alex Luchianov AlexandruLuchianov1 Data 6 mai 2019 16:37:27
Problema Team Scor 40
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.16 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream 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;
  bool operator < (Edge const &a) const{
    return cost < a.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(node != e.to && 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;
}