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/