树上贪心类——子树之和 / 新贡献:1031T1

本文搬运自本人高中时期CSDN博客,若图片加载不出来,可到原文查看:https://blog.csdn.net/zhangtingxiqwq/article/details/134170718

http://cplusoj.com/d/senior/p/SS231031A

可以发现从上面打下来,我们有两种对策:

  1. 直接引一条上来

  2. 下面每条分别对付

我们直接按照这种方法维护一个类似树形dp的东西就行了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include<bits/stdc++.h>
using namespace std;
#define int long long
inline int read(){int x=0,f=1;char ch=getchar(); while(ch<'0'||
ch>'9'){if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9'){
x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}return x*f;}
#define Z(x) (x)*(x)
#define pb push_back
//mt19937 rand(time(0));
//mt19937_64 rand(time(0));
//srand(time(0));
#define N 510
//#define M
//#define mo
struct node {
int y, z;
};
int n, m, i, j, k, T;
int f[N], g[N], u, v, w, flg;
int a[N], b[N], Sn, Tn;
vector<node>G[N];

void dfs1(int x, int fa) {
g[x]=1e18; f[x]=0;
if(a[x]) g[x]=0;
for(auto t : G[x]) {
int y=t.y, z=t.z;
if(y==fa) continue;
// printf("%lld -> %lld | %lld\n", x, y, z);
dfs1(y, x);
g[x]=min(g[x], g[y]+z);
f[x]+=max(0ll, f[y]-z);
}
if(b[x]) f[x]=g[x]+1;
else if(x!=1) f[x]=min(f[x], g[x]+1);
// printf("f[%lld] => %lld | %lld\n", x, f[x], g[x]);
// if(fa==1 && g[x]>=1e18) flg=1;

if(f[x]>=1e18) b[fa]=1, f[x]=0;
}

signed main()
{
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
freopen("game.in", "r", stdin);
freopen("game.out", "w", stdout);
T=read();
while(T--) {
n=read(); Sn=read(); Tn=read(); flg=0;
for(i=1; i<=n; ++i) G[i].clear(), a[i]=b[i]=0;
for(i=1; i<n; ++i) {
u=read(); v=read(); w=read()+1;
// printf("%d %d %d\n", u, v, w);
G[u].pb({v, w}); G[v].pb({u, w});
}
for(i=1; i<=Sn; ++i) k=read(), a[k]=1;
for(i=1; i<=Tn; ++i) k=read(), b[k]=1;
if(b[1]) { printf("Impossible\n"); continue; }
dfs1(1, 0);
if(b[1]) { printf("Impossible\n"); continue; }
printf("%lld\n", f[1]);
}

return 0;
}