Ehsan_sShuvo's blog

By Ehsan_sShuvo, history, 6 years ago, In English

I'm getting TLE again & again for this problem . here is my solution . Please help me how would i optimize my approach ?

  • Vote: I like it
  • 0
  • Vote: I do not like it

»
6 years ago, # |
  Vote: I like it +5 Vote: I do not like it

This is a tricky problem. You won't get Accepted with a priority_queue. Actually, you won't get Accepted with a normal BFS either, because edge weights aren't all equal, you have edges with weight 0 and edges with weight 1. This means that many nodes will be pushed to the queue and processed multiple times, resulting in TLE.

In order for BFS to work fast, nodes should be pushed to the queue in non-descending distance. To achieve this, there are two ways that I know of:

1) Everytime you add a node to the queue, perform a flood-fill to all nodes connected to current node through edges with cost 0 and push them to the queue as well.

2) Use two queues, namely q1 and q2. When you get to a node using a 0-cost edge, push the new node to q1. When you get to a node using an edge with cost 1, push the new node to q2. As long as q1 is not empty, pop from q1, otherwise pop from q2. This way, you will process nodes in order of non-descending distance.

Both approaches get Accepted.

»
6 years ago, # |
  Vote: I like it 0 Vote: I do not like it

2nd method suggested by tenshi_kanade is actually 0-1 BFS. You can find a really nice tutorial about this technique here.