Dominoes#1104

Dominoes (Editorial)

Let us build a directed graph: the vertices are dominoes, and an edge x \to y means that the falling domino knocks down the domino . If we push the domino , then all dominoes reachable from vertex will fall.

Strongly connected components. Let us split the graph into strongly connected components. Inside one component, any vertex is reachable from any other. Therefore, if at least one domino of a component falls, all its other dominoes fall as well, and the component can be treated as a single vertex.

Component graph. Let us contract each component into one vertex and draw an edge from component to component if the original graph contains an edge from a vertex of component to a vertex of component . The resulting component graph (condensation) contains no cycles: components lying on a common cycle would form one strongly connected component.

Let us call a component a source if no edge enters it from other components.

Therefore, the answer equals the number of source components.

Finding the sources. Let us find the strongly connected components and color the vertices so that is the number of the component of vertex . Initially, we consider all components to be sources. Then we iterate over all edges i \to \mathit{to}: if \mathit{color}[i] \ne \mathit{color}[\mathit{to}], then an edge from another component enters the component , so it is not a source. It remains to count the remaining sources.

Complexity. The strongly connected components are found in O(n + m), and iterating over the edges takes O(n + m). The total complexity is O(n + m).

Example

The graphs from the examples look as follows. The dominoes that need to be pushed are highlighted in orange.

In the first example, each of the components , and consists of one vertex. The edges 1 \to 2 and 2 \to 3 connect different components, so the components and are not sources. One source remains: it is enough to push domino .

In the second example, all five components also consist of one vertex. Edges from other components enter vertices (from vertices and ), (from vertices and ) and (from vertex ). The sources are the components and , so the answer is .

Let us also consider a graph in which the strongly connected components contain several vertices (n = 7):

The graph has four strongly connected components: \{1, 2, 3\}, , and . In the component graph, edges lead from \{1, 2, 3\} and to , and from to . The sources are the components \{1, 2, 3\} and . It is enough to push any domino of the first component, for example , and domino . The answer is .

Algorithm Implementation

The input graph is stored in the adjacency list , and the reversed graph (the graph in which the directions of all edges are reversed) in the adjacency list . The array is first used to mark visited vertices during depth-first search, and then to mark source components. The array receives the vertices in the order in which their processing finishes, and is the number of the strongly connected component to which vertex belongs.

vector<vector<int> > g, gr;
vector<int> used, top, color;

The function dfs1 performs a depth-first search on the input graph and adds the vertices to the array in the order in which their processing finishes.

void dfs1(int v)
{
  used[v] = 1;
  for (int to : g[v])
    if (!used[to]) dfs1(to);
  top.push_back(v);
}

The function dfs2 performs a depth-first search on the reversed graph and colors all reachable uncolored vertices with color . These vertices form one strongly connected component.

void dfs2(int v, int c)
{
  color[v] = c;
  for (int to : gr[v])
    if (color[to] == -1) dfs2(to, c);
}

The main part of the program. Read the input data and build the input and reversed graphs.

scanf("%d %d",&n,&m);
g.resize(n+1);
gr.resize(n+1);
cnt = 0;
for(i = 0; i < m; i++)
{
  scanf("%d %d",&a,&b);
  g[a].push_back(b);
  gr[b].push_back(a);
}

Run a depth-first search on the input graph from each unvisited vertex. The order in which the processing of vertices finishes is stored in the array .

used.resize(n+1);
for(i = 1; i <= n; i++)
  if (!used[i]) dfs1(i);

Iterate over the vertices in decreasing order of their finishing times; to do this, reverse the array . Each call of dfs2 from an uncolored vertex finds the next strongly connected component and colors it with color , after which is increased by .

color.assign(n+1,-1);
reverse(top.begin(), top.end());
c = 0;
for (int v : top)
  if (color[v] == -1) dfs2(v, c++);

After coloring, the variable equals the number of strongly connected components, and the components are numbered from to c - 1. Set \mathit{used}[k] = 1 for all components : initially, each of them is considered a source. Iterate over all edges of the graph .

used.assign(c,1);
for (i = 1; i < g.size(); i++)
  for (int to : g[i])

If the vertices and lie in different components, then an edge from another component enters the component . Its dominoes will fall if domino falls, so it is not a source. Set \mathit{used}[\mathit{color}[\mathit{to}]] = 0.

    if (color[i] != color[to]) used[color[to]] = 0;

Count the number of source components, that is, the number of ones in the array . In each of them, one domino has to be pushed.

c = 0;
for(i = 0; i < used.size(); i++)
  if (used[i]) c++;

Print the answer.

printf("%d\n",c);

Java implementation

import java.util.*;

public class Main
{
  static ArrayList<Integer>[] g, gr;	
  static int used[], color[];
  static Vector<Integer> top = new Vector<Integer>();

  static void dfs1(int v)
  {
    used[v] = 1;
    for(int i = 0; i < g[v].size(); i++)
    {
      int to = g[v].get(i);
      if (used[to] == 0) dfs1(to);
    }
    top.add(v);
  }

  static void dfs2(int v, int c)
  {
    color[v] = c;
    for(int i = 0; i < gr[v].size(); i++)
    {
      int to = gr[v].get(i);
      if (color[to] == -1) dfs2(to,c);
    }
  }
  
  @SuppressWarnings("unchecked")  
  public static void main(String[] args)
  {
    Scanner con = new Scanner(System.in);
    int n = con.nextInt();
    int m = con.nextInt();
    
    g = new ArrayList[n+1];
    for(int i = 0; i <= n; i++)
      g[i] = new ArrayList<Integer>();
    gr = new ArrayList[n+1];
    for(int i = 0; i <= n; i++)
      gr[i] = new ArrayList<Integer>();
    
    for (int i = 0; i < m; i++)
    {
      int a = con.nextInt();
      int b = con.nextInt();
      g[a].add(b);
      gr[b].add(a);
    }

    used = new int[n+1];
    for(int i = 1; i <= n; i++)
      if (used[i] == 0) dfs1(i);
    
    color  = new int[n+1];
    Arrays.fill(color, -1);
    int c = 0;
    for(int i = 1; i <= n; i++)
    {
      int v = top.get(n-i);
      if (color[v] == -1) dfs2(v,c++);
    }

    used = new int[c];
    Arrays.fill(used, 1);
    for(int i = 1; i < g.length; i++)
    for(int j = 0; j < g[i].size(); j++)
    {
      int to = g[i].get(j);
      // check edge i -> j if they in the same scc.
      if (color[i] != color[to]) used[color[to]] = 0;
    }

    c = 0;
    for(int i = 0; i < used.length; i++)
      if (used[i] == 1) c++;
    
    System.out.println(c);
    con.close();
  }
}