Masab's blog

By Masab, history, 18 hours ago, In English

I have an undirected graph and I need to reorder its vertices into a permutation that satisfies the following “prefix-neighbors” property:

Property: For every vertex v_i (with i > 0) in the permutation, if there exists any vertex v_j (with j < i) that is adjacent to v_i (i.e., (v_j, v_i) is an edge in E), then every vertex v_k with k < j must also be adjacent to v_i.

In other words, if has any neighbors among the vertices that come before it in the ordering, then those neighbors must form a contiguous block starting from the very first vertex in the ordering.

For example, consider a graph with vertices and edges: (0,1) (0,2) (1,3) (2,3)

0
 / \
1   2
 \ /
  3

One valid ordering is [1, 2, 0, 3]:

  • Vertex 1: Placed first, so no condition applies.
  • Vertex 2: Placed second; if it has any neighbor among vertices before it, then the very first vertex must be adjacent—but here it happens that 2 is not adjacent to 1, so the condition is not triggered.
  • Vertex 0: Placed third; its neighbors among are 1 and 2. The earliest (lowest-index) neighbor is 1, which is at the beginning of the ordering.
  • Vertex 3: Placed last; its neighbors among are 1 and 2 (its first neighbor is 1 at index 0), so the condition is satisfied.

My questions are:

  1. Algorithm & Complexity: Is it possible to compute such a permutation in time?
  2. Approach:What algorithm would you recommend for this problem?
  3. Uniqueness:Under what conditions is such an ordering unique, and how can I detect if multiple valid orders exist or if no valid ordering exists?

Any algorithm sketches, insights, or sample code in Python or C++ would be greatly appreciated!

Full text and comments »

  • Vote: I like it
  • +1
  • Vote: I do not like it

By Masab, history, 4 years ago, In English

Suppose, I have given N distinct pairs(x, y) of elements. Choose k pairs from these elements every time. Count the chosen ways when number of distinct value is equal to R in the chosen pairs.

Constraints: N = 100 K >= 50 k <= R <= 2K.

Example: Given, N = 6, k = 3, r = 4.

Pairs: a. (1, 2) b. (1, 3) c. (2, 4) d. (2, 5) e. (3, 4) f. (4, 5)

Now if we choose pairs (a, b, e), the distinct values are:- S = {1, 2, 3, 4} Number of Distinct values |S| = 4 and |S| == R. So, this is a valid combination.

If we choose pairs (c, d, e}, the distinct values are:- S = {2, 3, 4, 5} Number of Distinct values |S| = 4 and |S| == R. So, this is a valid combination.

But, if we choose pairs (a, b, f), the distinct values are:- S = {1, 2, 3, 4, 5} Number of Distinct values |S| = 5 and |S| > R. So, this is not a valid combination.

In this example, there is more valid and invalid combinations. I have to count the valid combination for bigger datasets. Is there any combination formula or Dynamic Programming solution for this problem. An algorithm would be very helpful.

Full text and comments »

  • Vote: I like it
  • +5
  • Vote: I do not like it