Gnomes#7945

Gnomes (Editorial)

Let us associate a directed graph with the problem. The vertices of the graph are the gnomes, and each statement defines an edge. If gnome s_1 is shorter than gnome s_2 (that is, s_1 < s_2), we add a directed edge s_1 \to s_2. The statement s_1 > s_2 is equivalent to s_2 < s_1 and defines the edge s_2 \to s_1. Thus, every edge is directed from a shorter gnome to a taller one.

Gnome names are strings, so first we assign each name a unique integer vertex index.

When the statements are contradictory. Suppose the graph contains a cycle v_1 \to v_2 \to \ldots \to v_k \to v_1. Then v_1 is shorter than v_2, v_2 is shorter than v_3, , v_k is shorter than v_1. By transitivity, gnome v_1 is shorter than itself, which is impossible. Therefore, at least one of the gnomes lied.

Conversely, if the graph is acyclic, it has a topological sort — an ordering of the vertices in which every edge goes from an earlier vertex to a later one. Assign the gnomes heights 1, 2, 3, \ldots in topological order. Then s_1 < s_2 holds for every edge s_1 \to s_2, that is, all statements are true simultaneously.

Thus, the answer is "impossible" if and only if the constructed graph contains a cycle.

Cycle detection. To find a cycle in a directed graph, we use depth-first search with three vertex colors:

If during the search an edge v \to to from the current vertex leads to a gray vertex , then lies on the current path from the root to . Together with the edge v \to to, this path forms a cycle. An edge to a black vertex does not create a cycle: from a black vertex it is impossible to return to , otherwise would have been visited earlier.

The graph may be disconnected, so we start a depth-first search from every vertex that has not been visited yet.

Example

The graphs corresponding to the examples from the problem statement look as follows (left — the graph of the first example, right — of the second):

The first graph contains the cycle Dori Kili Balin Dori. It means that Dori is shorter than Kili, Kili is shorter than Balin, and Balin is shorter than Dori. Then Dori is shorter than himself, so the statements are contradictory and the answer is "impossible".

The second graph is acyclic. Its topological sort is Kili, Balin, Dori. Assigning the gnomes heights in this order (Kili Balin Dori), we get that all three statements hold simultaneously. The answer is "possible".

Consider how the graph is built for the first test. Each name receives an index in the order of its first appearance in the input. The first name is Dori, which receives index . Next comes Balin — index . In the second statement, the name Balin already has an index, so a new index is assigned only to Kili — index . Thus, name\_to\_id[Dori] = 0, name\_to\_id[Balin] = 1, name\_to\_id[Kili] = 2, and the graph contains the edges 1 \to 0, 2 \to 1 and 0 \to 2.

Let us simulate the depth-first search. We call : vertex (Dori) becomes gray. Along the edge 0 \to 2 we move to the white vertex (Kili), which becomes gray. Along the edge 2 \to 1 we move to the white vertex (Balin), which also becomes gray. The edge 1 \to 0 leaves vertex and leads to the gray vertex . A cycle is found, so we set flag = 1.

Algorithm implementation

Store the directed graph as an adjacency list . The array stores the vertex colors during the depth-first search: — white, — gray, — black. The map name\_to\_id maps a gnome's name to a vertex index: the gnome named corresponds to vertex name\_to\_id[s].

vector<vector<int> > g;
vector<int> used;
unordered_map<string, int> name_to_id;

The function get_id returns the index of the vertex corresponding to the gnome named . Indices are assigned in the order in which names first appear: from to id - 1, where is the number of distinct gnomes encountered so far.

int get_id(string name)
{

If the gnome named has already been encountered, return the index assigned to it earlier.

  if (name_to_id.count(name)) return name_to_id[name];

Otherwise, assign the next index to the gnome named and increase by .

  return name_to_id[name] = id++;
}

The function dfs performs a depth-first search starting from vertex . On entering vertex , it becomes gray.

void dfs(int v)
{
  used[v] = 1;
  for (int to : g[v])
  {

Consider the edge (v, to). If it leads to a gray vertex, a cycle is found. Set flag = 1 and stop the search.

    if (used[to] == 1)
    {
      flag = 1;
      return;
    }

If vertex has not been visited yet (it is white), continue the depth-first search from it.

    if (used[to] == 0) dfs(to);
  }

After all vertices reachable from have been processed, vertex becomes black.

  used[v] = 2;
}

The main part of the program. Read the number of statements . The number of distinct gnomes does not exceed 10^4, so the graph has at most that many vertices. Allocate memory for the adjacency list and the color array; initially all vertices are white.

cin >> n;
g.resize(10001); used.resize(10001,0);

Gnome numbering starts from .

id = 0;

Process the statements. Each of them defines one directed edge of the graph.

for (i = 0; i < n; i++)
{

Read a statement of the form s_1 < s_2 or s_1 > s_2: the name , the sign and the name .

  cin >> l >> op >> r;

Find the indices and of the vertices corresponding to the gnomes and .

  u = get_id(l);
  v = get_id(r);

An edge is directed from a shorter gnome to a taller one. If l < r, add the edge u \to v, otherwise add the edge v \to u.

  if (op == "<")
    g[u].push_back(v);
  else
    g[v].push_back(u);
}

The variable becomes if a cycle is found in the graph.

flag = 0;

The graph may be disconnected, so start a depth-first search from every vertex that has not been visited yet. The vertices are numbered from to id - 1. As soon as a cycle is found, stop the search.

for (i = 0; i < id; i++)
{
  if (!used[i]) dfs(i);
  if (flag == 1) break;
}

If a cycle is found, the statements are contradictory — print "impossible", otherwise print "possible".

if (flag == 1) printf("impossible\n");
else printf("possible\n");

Java implementation

import java.util.*;

public class Main {
  static List<List<Integer>> g = new ArrayList<>();
  static int[] used;
  static Map<String, Integer> nameToId = new HashMap<>();
  static int id = 0;
  static boolean hasCycle = false;

  static int getId(String name) {
    if (!nameToId.containsKey(name))
      nameToId.put(name, id++);
    return nameToId.get(name);
  }

  static void dfs(int v) {
    used[v] = 1;
    for (int to : g.get(v)) {
      if (used[to] == 1) {
        hasCycle = true;
        return;
      }
      if (used[to] == 0) dfs(to);
    }
    used[v] = 2;
  }
    
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    used = new int[10001];

    for (int i = 0; i < 10001; i++)
       g.add(new ArrayList<>());

    for (int i = 0; i < n; i++) {
      String l = sc.next();
      String op = sc.next();
      String r = sc.next();

      int u = getId(l);
      int v = getId(r);

      if (op.equals("<"))
        g.get(u).add(v);
      else
        g.get(v).add(u);
    }

    for (int i = 0; i < id; i++) {
      if (used[i] == 0) {
        dfs(i);
        if (hasCycle) break;
      }
    }

    System.out.println(hasCycle ? "impossible" : "possible");
  }
}