Блог пользователя adamWarlock

Автор adamWarlock, история, 7 лет назад, По-английски

Suppose there are n animals from 1 to n+1 kinds and you are given m pairs of animals such that they can't put in the same pair of cages as they are hostile towards each other.

Suppose n = 4 and m = 2 and m pair are {1,3},{2,4} . So possible number of cages are 7 as {1},{2},{3},{4},{1,2},{1,4},{2,3}. sets such as {1,3},{2,4},{1,2,3,4} are not possible as 1,3 are hostile and 2,4 are hostile so they can't be put together in same cage or set. So you need to tell the number of cages that are possible

Can someone help me to solve this question?

  • Проголосовать: нравится
  • -2
  • Проголосовать: не нравится

»
7 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

You can do it with inclusion-exclusion principle in O(2 ^ M * N), by storing for each mask of pairs the set of animals which you have to have with bitset so you have a good constant

»
7 лет назад, скрыть # |
 
Проголосовать: нравится +111 Проголосовать: не нравится

What kind of country is asking you these questions just to get a visa?

»
7 лет назад, скрыть # |
 
Проголосовать: нравится -21 Проголосовать: не нравится

I solved this question using Priority Queue PQ. Construct an adjacency list that stores all the kinds of animals that have their kind greater than that animal kind and have clash with that animal. E.g:- If there is a clash between animals 3 and 5, then store 5 in the list of 3 but NOT 3 in the list of 5. Then, maintain a Priority Queue and add n in it.

Now start iterating from the last index(i.e. n — 1) and if adj[i].size() == 0(i.e no enemy) then add PQ.pop (minimum element from Priority Queue) to ans , else if adj[i].size() != 0, then find the kind of enemy with the smallest number (lets say its k) that has clash with it. Now add min(k, PQ.pop()) to ans and add k to PQ. Hope this helps.