1008 猫咪们狂欢
分析:
会创建一个二分图
代码:
#include <bits/stdc++.h>
#define ll long long
#define INF 1e9
using namespace std;
const int N=10005;
const int M=100010;
struct edge{
ll v,c,ne;
}e[M];
int h[N],idx=1;
int d[N],cur[N];
int s,t;
void add(int ui,int vi,ll wi){
e[++idx]={vi,wi,h[ui]};
h[ui]=idx;
e[++idx]={ui,0,h[vi]};
h[vi]=idx;
}
ll bfs(){
memset(d,0,sizeof(d));
queue<int>q;
q.push(s), d[s]=1;
while(q.size()){
int u=q.front(); q.pop();
for(int i=h[u];i;i=e[i].ne){
int v=e[i].v;
if(d[v]==0&&e[i].c){
d[v]=d[u]+1;
q.push(v);
if(v==t) return true;
}
}
}
return false;
}
ll dfs(int u,ll mf){
if(u==t) return mf;
ll sum=0;
for(int i=cur[u];i;i=e[i].ne){
cur[u]=i;
int v=e[i].v;
if(d[v]==d[u]+1&&e[i].c){
ll f=dfs(v,min(mf,e[i].c));
e[i].c-=f;
e[i^1].c+=f;
sum+=f;
mf-=f;
if(mf==0) break;
}
}
if(sum==0) d[u]=0;
return sum;
}
ll dinic(){
ll flow=0;
while(bfs()){
memcpy(cur,h,sizeof(h));
flow+=dfs(s,1e9);
}
return flow;
}
void solve(){
idx=1;
for(int i=0;i<t;i++) h[i]=0;
int nn,m; cin>>nn>>m;
t=3*nn-1;
set<int>sets;
for(int i=1;i<=m;i++){
int x; scanf("%d",&x);
sets.insert(x);
}
ll ans=0;
for(int i=1;i<nn;i++){
int u,v,w; scanf("%d%d%d",&u,&v,&w);
if (sets.find(u) == sets.end()||sets.find(v) == sets.end()) continue;
ans+=w;
add(0,nn+i,w);
add(nn+i,u,INF);
add(nn+i,v,INF);
}
for(int i=1;i<nn;i++){
int u,v,w; scanf("%d%d%d",&u,&v,&w);
if (sets.find(u) == sets.end()||sets.find(v) == sets.end()) continue;
ans+=w;
add(2*nn+i-1,t,w);
add(u,2*nn+i-1,INF);
add(v,2*nn+i-1,INF);
}
cout<<(ans-dinic())<<endl;
}
int main(){
int tp; cin>>tp;
while(tp--){
solve();
}
return 0;
}