← 返回 openai 的题目列表Count Nodes in a Distributed Tree via Async Messages
类型:online_judge
Count Nodes in a Distributed Tree (Async Messaging)
You are given a directed tree rooted at root. Each node represents an independent machine:
You cannot directly access node.children or any global graph structure.
The only way to communicate is via asynchronous messages.
A primitive API is provided:
sendAsyncMessage(nodeId, message): asynchronously send a message to the node with id nodeId.
You must implement the following callback on every node:
receiveMessage(fromNodeId, message): invoked when this node receives a message from fromNodeId.
Goal
Design a message protocol and node-side logic so that when a counting request is initiated from root, the root outputs the total number of nodes in the entire tree.
Requirements
All traversal and aggregation must be done through sendAsyncMessage/receiveMessage.
You must define the message format to distinguish requests vs responses.
Each node maintains per-request intermediate state (e.g., pending children, partial aggregates).
The root prints/returns the final answer after it has collected all subtree results.
I/O (per counting run)
Input: rootId; and all nodes have receiveMessage registered.
Output: root prints/returns an integer total node count.
Assumptions
Number of nodes N up to 1e5.
Depth can be large.
Messages may arrive concurrently.
Example topology
1 -> {2,3}, 2 -> {4,5}, 3 -> {6}
Expected output: 6
Example
Input
root=1, edges: 1->[]
Output
1