这题挺考思维的。。。以出口为根,将树看成不同层,每次都是从下向上运输货物。。。。
#include <iostream> #include <queue> #include <stack> #include <map> #include <set> #include <bitset> #include <cstdio> #include <algorithm> #include <cstring> #include <climits> #include <cstdlib> #include <math.h> #include <time.h> #define maxn 100005 #define maxm 200005 #define eps 1e-7 #define mod 1000000007 #define INF 0x3f3f3f3f #define PI (acos(-1.0)) #define lowbit(x) (x&(-x)) #define mp make_pair #define ls o<<1 #define rs o<<1 | 1 #define lson o<<1, L, mid #define rson o<<1 | 1, mid+1, R #define pii pair<int, int> #pragma comment(linker, "/STACK:16777216") typedef long long LL; typedef unsigned long long ULL; //typedef int LL; using namespace std; LL qpow(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base;base=base*base;b/=2;}return res;} LL powmod(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base%mod;base=base*base%mod;b/=2;}return res;} //head struct Edge { int v; Edge *next; }*H[maxn], E[maxm], *edges; LL dis[maxn]; int a[maxn]; int dist, n, s; void init() { edges = E; memset(H, 0, sizeof H); } void addedges(int u, int v) { edges->v = v; edges->next = H[u]; H[u] = edges++; } void dfs(int u, int fa, int dep) { if(a[u]) dist = max(dist, dep); dis[dep] += a[u]; for(Edge *e = H[u]; e; e = e->next) if(e->v != fa) dfs(e->v, u, dep+1); } void work(int _) { int u, v; scanf("%d%d", &n, &s); for(int i = 1; i < n; i++) { scanf("%d%d", &u, &v); addedges(u, v); addedges(v, u); } for(int i = 1; i <= n; i++) scanf("%d", &a[i]); dist = 0; LL ans = 0; for(Edge *e = H[s]; e; e = e->next) { int v = e->v; dist = 0; dfs(v, s, 0); LL t1 = 0, t2 = 0; for(int i = 0; i <= dist; i++) { t1 += dis[i]; if(dis[i] == 0 && t1 + t2 <= i) t2++; dis[i] = 0; } ans = max(ans, t1 + t2); } printf("Case #%d: %lld\n", _, ans); } int main() { int _; scanf("%d", &_); for(int i = 1; i <= _; i++) { init(); work(i); } return 0; }