1 条题解

  • 0
    @ 2026-1-11 15:23:43

    #include <bits/stdc++.h>
    using std::cin;
    using std::cout;
    
    typedef std::pair <int, int> pr;
    typedef std::map <int, int> map;
    const int N = 200054, M = N * 2, INF = 0x3f3f3f3f;
    
    int n, E, ti;
    int a[N];
    int to[M], first[N], next[M];
    map f[N];
    
    inline int max(const int x, const int y) {return x < y ? y : x;}
    
    inline void addedge(int u, int v) {
    	to[++E] = v, next[E] = first[u], first[u] = E;
    	to[++E] = u, next[E] = first[v], first[v] = E;
    }
    
    void insert(map &A, const pr &x) {
    	map::iterator it, jt; bool ret;
    	std::tie(it, ret) = A.emplace(x);
    	if (!ret) it->second += x.second - x.first;
    	for (jt = it; it != A.begin(); )
    		if ((--jt)->second >= it->first)
    			jt->second += it->second - it->first, A.erase(it), it = jt;
    		else break;
    	for (jt = std::next(it); jt != A.end(); )
    		if (it->second >= jt->first)
    			it->second += jt->second - jt->first, jt = A.erase(jt);
    		else break;
    }
    
    void decrease(map &A, int x) {
    	int s = -x, t; map::iterator it;
    	for (it = A.begin(); it != A.end(); ++it) {
    		s += it->second - it->first;
    		if (s > 0) {
    			t = it->second, A.erase(A.begin(), ++it),
    			A.emplace_hint(A.begin(), t - s, t);
    			return;
    		}
    	}
    	A.clear();
    }
    
    inline void merge(map &A, map &B) {
    	if (A.size() < B.size()) A.swap(B);
    	for (const pr &e : B) insert(A, e);
    }
    
    void dfs(int x, int px = 0) {
    	int i, y;
    	f[x].clear();
    	if (x == ti) {f[x].emplace(max(-a[x], 0), INF); return;}
    	for (i = first[x]; i; i = next[i])
    		if ((y = to[i]) != px) dfs(y, x), merge(f[x], f[y]);
    	if (a[x] > 0) insert(f[x], pr(0, a[x]));
    	else if (a[x] < 0) decrease(f[x], -a[x]);
    }
    
    void work() {
    	int i, u, v, s = 0;
    	cin >> n >> ti, E = 0;
    	memset(first, 0, (n + 1) << 2);
    	for (i = 1; i <= n; ++i) cin >> a[i];
    	for (i = 1; i < n; ++i) cin >> u >> v, addedge(u, v);
    	dfs(1);
    	for (const pr &e : f[1]) {
    		if (s < e.first) break;
    		if (e.second >= INF) {cout << "escaped\n"; return;}
    		s += e.second - e.first;
    	}
    	cout << "trapped\n";
    }
    
    int main() {
    	int T;
    	std::ios::sync_with_stdio(false), cin.tie(NULL);
    	for (cin >> T; T; --T) work();
    	return 0;
    }
    
    • 1

    信息

    ID
    5719
    时间
    1000ms
    内存
    128MiB
    难度
    10
    标签
    递交数
    1
    已通过
    1
    上传者