it's guaranteed that the original 'n' nodes will never be deleted. |
This makes the problem easier.
-1 <= n,w <= pow(10,5)
- 1 <= w,wi <= pow(10,9) |
Negative weights make the problem much harder.
You should verify if weights can be negative. Also I don't understand why this specifies "w" as having two upper limits. That makes me nervous. Is the spec unclear? Am I just not understanding something?
You can't delete any of the original N nodes. And when you add a new node, it springs forth as a branch from an existing node. So there is only 1 cycle in the graph (the original one)
x can be -1? What the heck does that mean?? Aren't the original N nodes labeled 1 to N? Or are they 0 to N-1? Your description says they are "numbered 'i' from to 'n-1'" numbered from what to n-1? You should verify these details.
Okay, the point here is that it looks like the source node X is always one of the original N nodes. So if the furthest node is on a tree that sprung out of one of the original N nodes then
the path must still go through the base of the tree. For each node on the cycle, store (among other things)
unsigned furthestNodeOnTree; // ID of the furthest node on the tree
int costToFurthestOnTree; // the cost from this node to furthestNodeOnTree
Now you can find the furthest node from X like so (pseudocode):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
vector<Node> nodes;
unsigned lastNode = X;
int distance = 0; // distance from X to current node on the cycle
for (i=0; i<n-1; ++i) { // for the n-1 other nodes on the cycle;
int nextNode = (X+i) % n +1;
distance += weight(lastNode, nextNode); // weight of edge from lastNode to nextNode
// you might chose to store these in a vector or something.
if (distance > maxDist) {
bestNode = nextNode;
maxDist = distance;
}
if (distance + nodes[nextNode].costToFurthestOnTree > maxDist) {
bestNode = nextNode;
maxDist = distance+nodes[nextNode].costToFurthestNodeOnTree;
}
lastNode = nextNode;
}
// Now bestNode contains the number of the node on the cycle that is the base of the tree with the most distant node.
|
Note that bestNode doesn't actually refer to the most distant node. It refers to the node on the cycle that is the root of the tree that contains the most distant node. I did this because you'll need to update this info in this node when adding or deleting other nodes. The node that is most distant is easily accessible as nodes[bestNode].furthestNodeOnTree.
When you insert or delete a node, you just have to update the max distance/node for the node on the cycle that is the base of the tree.