[LeetCode] The Time When the Network Becomes Idle

2039. The Time When the Network Becomes Idle

There is a network of n servers, labeled from 0 to n - 1. You are given a 2D integer array edges, where edges[i] = [ui, vi] indicates there is a message channel between servers ui and vi, and they can pass any number of messages to each other directly in one second. You are also given a 0-indexed integer array patience of length n.

All servers are connected, i.e., a message can be passed from one server to any other server(s) directly or indirectly through the message channels.

The server labeled 0 is the master server. The rest are data servers. Each data server needs to send its message to the master server for processing and wait for a reply. Messages move between servers optimally, so every message takes the least amount of time to arrive at the master server. The master server will process all newly arrived messages instantly and send a reply to the originating server via the reversed path the message had gone through.

At the beginning of second 0, each data server sends its message to be processed. Starting from second 1, at the beginning of every second, each data server will check if it has received a reply to the message it sent (including any newly arrived replies) from the master server:

  • If it has not, it will resend the message periodically. The data server i will resend the message every patience[i] second(s), i.e., the data server i will resend the message if patience[i] second(s) have elapsed since the last time the message was sent from this server.

  • Otherwise, no more resending will occur from this server.
    The network becomes idle when there are no messages passing between servers or arriving at servers.

Return the earliest second starting from which the network becomes idle.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
int networkBecomesIdle(vector<vector<int>>& edges, vector<int>& patience) {
int res = 0;
vector<int> t(patience.size(), -1);
unordered_map<int, vector<int>> g;
for(auto& e : edges) {
g[e[0]].push_back(e[1]);
g[e[1]].push_back(e[0]);
}
queue<pair<int, int>> q;
q.push({0, 0});
while(!q.empty()) {
auto p = q.front();
q.pop();
if(t[p.first] != -1) continue;
t[p.first] = p.second * 2;
for(auto nxt : g[p.first]) {
if(t[nxt] == -1) q.push({nxt, p.second + 1});
}
}
for(int i = 1; i < patience.size(); i++) {
int replyTime = t[i];
int lastRetry = max(1, (((t[i] - 1) / patience[i])) * patience[i] + 1);
res = max(res, replyTime + lastRetry);
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/29/PS/LeetCode/the-time-when-the-network-becomes-idle/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.