Cod sursa(job #2975185)

Utilizator AlexandruBenescuAlexandru Benescu AlexandruBenescu Data 5 februarie 2023 18:47:10
Problema Ubuntzei Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.92 kb
#include <bits/stdc++.h>
#define INF 1000000001
#define L 2005
#define S 20
using namespace std;
ifstream fin("ubuntzei.in");
ofstream fout("ubuntzei.out");

int n, m, k;
vector <pair <int, int>> G[L];
vector <int> nodes;
int dist[L], cost[S][S], v[S];
bool vis[S];

void init_vis(){
  for (int i = 0; i < S; i++)
    vis[i] = false;
}

void dijkstra(int src){
  priority_queue <pair <int, int>> pq;
  int i, node, cost;
  for (i = 1; i <= n; i++)
    dist[i] = INF;
  dist[src] = 0;
  pq.push({-dist[src], src});
  while (!pq.empty()){
    cost = -pq.top().first;
    node = pq.top().second;
    pq.pop();
    if (cost == dist[node])
      for (auto it : G[node])
        if (cost + it.second < dist[it.first]){
          dist[it.first] = cost + it.second;
          pq.push({-dist[it.first], it.first});
        }
  }
  for (i = 1; i <= n; i++)
    if (dist[i] == INF)
      dist[i] = 0;
}

int ham(){
	vector <vector <int>> dp((1 << n), vector <int>(n, INF));
	dp[1][0] = 0;
	for (int mask = 1; mask < (int)dp.size(); mask++){
		if ((mask & 1) == 0)
      continue;
		for (int i = 0; i < n; i++){
			if ((mask & (1 << i)) == 0)
        continue;
			for (int j = 0; j < n; j++){
				if ((mask & (1 << j)) != 0)
          continue;
				dp[mask | (1 << j)][j] = min(dp[mask | (1 << j)][j], dp[mask][i] + cost[i][j]);
			}
		}
	}
	return dp[(1 << n) - 1][n - 1];
}

int main(){
  fin >> n >> m >> k;
  nodes.push_back(1);
  for (int i = 0; i < k; i++){
    int x;
    fin >> x;
    nodes.push_back(x);
  }
  nodes.push_back(n);
  for (int i = 0; i < m; i++){
    int a, b, c;
    fin >> a >> b >> c;
    G[a].push_back({b, c});
    G[b].push_back({a, c});
  }
  for (int i = 0; i < (int)nodes.size(); i++){
    dijkstra(nodes[i]);
    for (int j = 0; j < (int)nodes.size(); j++)
      cost[i][j] = dist[nodes[j]];
  }
  n = nodes.size();
  fout << ham() << "\n";
  return 0;
}