Archives
Trending
Support
Login
clear text
XML
Django
JavaScript
MATLAB
C
C++
C#
Python
SQL
Shell
Bash
Markdown
YAML
JSON
HTML
CSS
PHP
Java
Ruby
Go
Rust
Swift
Kotlin
Arduino
TypeScript
Perl
Autohotkey
Lua
SQF
R
Scala
Haskell
Groovy
Dart
Clojure
VB.NET
Objective-C
PowerShell
Bash
CoffeeScript
Verilog
#include
#include
#include
#include
#include
#include
#include
//#include
using namespace std; typedef long long ll; const int maxn = 1e5 + 10; const ll INF = 3e16 + 10; int n, m, k; vector
> 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
find_nearest_city() { vector
dist(n, INF); vector
visited(n, false); dist[0] = 0; priority_queue
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
dist(n, INF); dist[S] = 0; priority_queue
pq; pq.push(node(S, 0)); set
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
nearest_city = find_nearest_city(); ll result = dijkstra(nearest_city.first); cout << nearest_city.second + result << endl; return 0; }
Mark as private (unlisted)
for 30 minutes
for 6 hours
for 1 day
for 1 week
for 1 month
for 1 year
everlasting (like CCCP)