lc.2039. 网络空闲的时刻 DFS

class Solution {
public:
    int networkBecomesIdle(vector<vector<int>>& edges, vector<int>& patience) {
        int n = patience.size();//获取图的节点数
        vector<int> cost(n, 0);//建立保存路径长度的数组
        vector<vector<int>> son(n);//存储节点间的路径
        for(auto e : edges) {//遍历图找出所有路径
            int a = e[0], b = e[1];
            son[a].push_back(b);
            son[b].push_back(a);
        }
        queue<int> q;//建立队列以便于找出所有路径长度
        int time = 0;//深度优先搜索
        for(auto a : son[0]) q.push(a);//将a点的所有直接路径加入队列
        while(!q.empty()) {//遍历所有路径
            int tmpn = q.size();
            time++;
            while(tmpn--) {//遍历队列并加入下一路径
                auto now = q.front(); q.pop();
                if(cost[now] != 0) continue;
                else {
                    cost[now] = time;
                    for(auto next : son[now]) {
                        if(cost[next] == 0 && next != 0) q.push(next);
                    }
                }
            }
        }
        for(int i = 1; i < n; i++) {
            cost[i] *= 2;
            if(patience[i] < cost[i]) {
                if(cost[i] % patience[i] == 0) cost[i] = 2 * cost[i] - patience[i];
                else cost[i] = 2 * cost[i] - (cost[i] % patience[i]);
            }
        }
        return *max_element(cost.begin(), cost.end()) + 1;
    }
};

https://leetcode-cn.com/problems/the-time-when-the-network-becomes-idle/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值