P1269 signal amplifier

P1269 signal amplifier

Question: Given a tree structure, No. 1 is the root node, and each node can receive and transmit signals. Each edge has a cost. If the signal value is negative when it reaches a certain node, a signal amplifier can be placed at its parent node to make the signal value from its parent node equal to the signal value from the root node.
Ask if all nodes can receive the signal, the least signal amplifier is needed. Otherwise output ""

Idea: Fa Fa firstF a array save each child node tonow nowThe distance of the n o w node, and then traverse to the root node, and then go up to findnow nown o w node is the depth of the subtree, usedis disThe d i s array is stored. Return tonow nownow节点时,如果 d i s [ n o w ] + F a [ n o w ] > m dis[now]+Fa[now]>m dis[now]+Fa[now]>m , said innow nown o w parent node of nodefa faThe signal sent by the f a node cannot completely covernow nown o w subtree, illustrated infa faThe f a node must put a signal amplifier. dis [now] dis[now]d i s [ n o w ] should be changed to0 00

#include<bits/stdc++.h>
using namespace std;
const int N = 20010;
const int inf = 0x7ffffff;
int head[N], tot = 1, ans = 0;
int dis[N], Fa[N];
struct tree{
    
    
    int to, next, v;
} t[N<<1];

void add(int x, int y, int we) {
    
    //图的存储
    t[tot].to = y , t[tot].next = head[x], t[tot].v = we, head[x] = tot++;
}

void dfs(int now, int fa, int m) {
    
    //dfs遍历
    for(int i=head[now]; i != 0; i=t[i].next) {
    
    
        if(t[i].to != fa) {
    
    
            Fa[t[i].to] = t[i].v;//记录节点到其父亲的深度
            dfs(t[i].to, now, m);//往下遍历
            dis[now] = max(dis[t[i].to]+t[i].v, dis[now]);//找子树深度
        }
    }
    if(Fa[now] + dis[now] > m) ans++, dis[now] = 0;//判断是否要放信号放大器。
}
int main() {
    
    
    int n, m, x, y, f = 0;
    cin >> n;
    for(int i=1; i<=n; i++) {
    
    
        cin >> m;
        for(int j=0; j<m; j++) {
    
    
            cin >> x >> y;
            f = max(f, y);
            add(i, x, y);
        }
    }
    cin >> m;
    if(f >= m) {
    
    cout << "No solution."; return 0;}//特判,不能完全覆盖的情况
    dfs(1, 0, m);
    cout << ans;
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45363113/article/details/108569100