题解 : 这个题目我们可以把边的权值从大到小排序 ,为什么这样排序呢,因为在排序的时候我们可以按照从大到小依次将边加入到最小生成树中去,加入进去后我们可以发现一个,当两个点连载一起时候加入的那条边就是要删去的边 因为这是这两个点之间最小的一条边。 还需要注意在合并的时候我们必须保证根节点是要被破坏的点这样就可以了 具体实现看代码了
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <vector>
#define ll long long
using namespace std;
const int maxn = 3e5 + 10;
const ll INF = 1e15 + 7;
int n,m;
struct edge {
int from,to;
ll cost;
};
vector <edge> edges;
int cnt = 0;
ll ans = 0;
bool vis[maxn] = {0};
int p[maxn] = {0};
int find (int x) {
if (x == p[x]) return x;
return p[x] = find (p[x]);
}
bool issame (int v,int u) {
return find (v) == find (u);
}
void u (int x,int y) {
if (issame(x, y))return;
p[y] = x;
}
bool cmp (const edge a,const edge b) {
return a.cost > b.cost;
}
void solve () {
cnt = edges.size();
for (int i = 0;i <= n; ++ i) p[i] = i;
sort(edges.begin(), edges.end(), cmp);
for (int i = 0;i < cnt; ++ i) {
int from = edges[i].from;
int to = edges[i].to;
int uu = find (from),v = find (to);
if (vis[uu] && vis[v]) ans += edges[i].cost;
if (vis[uu]) u(uu,v);
else u (v,uu);
}
}
int main () {
ios_base :: sync_with_stdio(false);
int T;
cin >> T;
while (T --) {
cin >> n >> m;
edges.clear();
ans = 0;
memset (vis,0,sizeof (vis));
for (int i = 1;i < n; ++ i) {
int x,y;
ll c;
cin >> x >> y >> c;
edges.push_back({x,y,c});
}
for (int i = 0;i < m; ++ i) {
int x;
cin >> x;
vis[x] = 1;
}
solve();
cout << ans << endl;
}
return 0;
}