Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <queue>
- #include <iostream>
- #include <vector>
- #include <cstring>
- #include <iostream>
- #include <set>
- #include <cstring>
- //#include <bits/stdc++.h>
- using namespace std;
- typedef long long ll;
- const int maxn = 1e5 + 10;
- const ll INF = 3e16 + 10;
- int n, m, k;
- vector<pair<int, int> > graph[maxn];
- int cities[maxn];
- bool to_build[maxn];
- struct node {
- int idx;
- ll cost;
- node () {}
- node(int _idx, ll _cost) {
- idx = _idx;
- cost = _cost;
- }
- bool operator < (const node &tmp) const {
- return cost > tmp.cost;
- }
- };
- pair<int, ll> find_nearest_city() {
- vector<ll> dist(n, INF);
- vector<bool> visited(n, false);
- dist[0] = 0;
- priority_queue<node> pq;
- pq.push(node(0, 0));
- while(!pq.empty()) {
- node c = pq.top();
- pq.pop();
- if(visited[c.idx]) continue;
- visited[c.idx] = true;
- for(int i = 0; i < (int) graph[c.idx].size(); i++) {
- int neighbour = graph[c.idx][i].first;
- ll weight = graph[c.idx][i].second;
- if(!visited[neighbour] and c.cost + weight < dist[neighbour]) {
- dist[neighbour] = c.cost + weight;
- pq.push(node(neighbour, dist[neighbour]));
- }
- }
- }
- ll shortest_distance = INF;
- int nearest_city = -1;
- for(int i = 0; i < k; i++) {
- if(shortest_distance > dist[cities[i]]) {
- shortest_distance = dist[cities[i]];
- nearest_city = cities[i];
- }
- }
- return make_pair(nearest_city, shortest_distance);
- }
- ll dijkstra(int S) {
- vector<ll> dist(n, INF);
- dist[S] = 0;
- priority_queue<node> pq;
- pq.push(node(S, 0));
- set<int> st;
- ll result = 0;
- while(!pq.empty() and (int) st.size() < k) {
- node c = pq.top();
- pq.pop();
- if(c.cost > dist[c.idx]) continue;
- if(to_build[c.idx]) {
- result += c.cost;
- c.cost = 0;
- to_build[c.idx] = false;
- st.insert(c.idx);
- }
- dist[c.idx] = c.cost;
- for(int i = 0; i < (int) graph[c.idx].size(); i++) {
- int neighbour = graph[c.idx][i].first;
- ll weight = graph[c.idx][i].second;
- pq.push(node(neighbour, c.cost + weight));
- }
- }
- return result;
- }
- int main() {
- ios_base::sync_with_stdio(false);
- memset(to_build, false, sizeof to_build);
- cin >> n >> m;
- for(int i = 0; i < m; i++) {
- int a, b, c;
- cin >> a >> b >> c;
- graph[a].push_back(make_pair(b, c));
- graph[b].push_back(make_pair(a, c));
- }
- cin >> k;
- for(int i = 0; i < k; i++) {
- cin >> cities[i];
- to_build[cities[i]] = true;
- }
- pair<int, ll> nearest_city = find_nearest_city();
- ll result = dijkstra(nearest_city.first);
- cout << nearest_city.second + result << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement