This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define f first
#define s second
#define pb push_back
#define ep emplace
#define eb emplace_back
#define lb lower_bound
#define ub upper_bound
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define uniquev(v) sort(all(v)), (v).resize(unique(all(v)) - (v).begin())
#define mem(f,x) memset(f , x , sizeof(f))
#define sz(x) (int)(x).size()
#define __lcm(a, b) (1ll * ((a) / __gcd((a), (b))) * (b))
#define mxx *max_element
#define mnn *min_element
#define cntbit(x) __builtin_popcountll(x)
#define len(x) (int)(x.length())
const int N = 2e5 + 10;
int p[N], sz[N];
int get(int a) {
return p[a] ? get(p[a]) : a;
}
bool unite(int a, int b) {
a = get(a), b = get(b);
if (a == b)
return 0;
if (sz[a] < sz[b])
swap(a, b);
sz[a] += sz[b];
p[b] = a;
return 1;
}
vector < pair <int, int>> ed[N];
int sp[N][20], timer = 1, in[N], ou[N];
ll dep[N];
void dfs(int u, int v) {
sp[u][0] = v;
for (int i = 1; i < 20; i++)
sp[u][i] = sp[sp[u][i - 1]][i - 1];
in[u] = timer;
for (auto x : ed[u]) {
if (x.f == v)
continue;
dep[x.f] = dep[u] + x.s;
dfs(x.f, u);
}
ou[u] = timer++;
}
bool anc(int a, int b) {
return in[a] <= in[b] && ou[a] >= ou[b];
}
int lca(int a, int b) {
if (anc(a, b))
return a;
if (anc(b, a))
return b;
for (int i = 19; i >= 0; i--) {
if (anc(sp[a][i], b) == 0)
a = sp[a][i];
}
return sp[a][0];
}
ll solve() {
int n, k, m;
cin >> n >> k >> m;
vector <int> lst;
for (int i = 0; i < k; i++) {
int a;
cin >> a;
lst.pb(a);
}
vector < vector <int>> save;
for (int i = 0; i < m; i++) {
int a, b, c;
cin >> a >> b >> c;
save.pb({c, a, b});
}
sort(all(lst), [&](int a, int b) {return in[a] < in[b];});
sort(all(save));
for (auto x : save) {
if (unite(x[1], x[2])) {
ed[x[2]].pb({x[1], x[0]});
ed[x[1]].pb({x[2], x[0]});
}
}
dfs(1, 1);
for (int i = 0; i < k - 1; i++) {
lst.pb(lca(lst[i], lst[i + 1]));
}
uniquev(lst);
sort(all(lst), [&](int a, int b) {return in[a] < in[b];});
stack <int> st;
ll ans = 0;
for (auto x : lst) {
if (st.empty()) {
st.push(x);
continue;
}
while (anc(st.top(), x) == 0) {
st.pop();
}
ans += (dep[x] - dep[st.top()]);
st.push(x);
}
return ans;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t = 1;
//cin >> t;
while (t--) {
//solve();
cout << solve() << '\n';
}
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |