What is the best way to sort a partially ordered l

2020-02-28 07:22发布

Probably best illustrated with a small example.
Given the relations

A < B < C
A < P < Q 

Correct outputs would be

ABCPQ or APQBC or APBCQ ... etc.

In other words, any ordering is valid in which the given relationships hold.

I am most interested in the solution that is easiest to implement, but the best O(n) in speed and time is interesting as well.

3条回答
别忘想泡老子
2楼-- · 2020-02-28 07:55

Do several sorts. First sort according to the first rule, then according to the second one and so on. Should work, unless your rules contain contradictions. sure easy enough to implement.

查看更多
贪生不怕死
3楼-- · 2020-02-28 08:15

This is called topological sorting.

The standard algorithm is to output a minimal element, then remove it and repeat until done.

查看更多
一纸荒年 Trace。
4楼-- · 2020-02-28 08:19

You could repeatedly call make_heap, pop_heap in C++ with the sequence at hand.

查看更多
登录 后发表回答