Arson#4369

Arson (Editorial)

To solve the problem, it is necessary to run a breadth-first search from multiple sources. To do this, place all ignition points into a queue and then start the algorithm.

Example

The graph shown in the example has the following structure:

Algorithm implementation

Declare the arrays.

vector<int> dist;
vector<vector<int> > g;
queue<int> q;

The bfs function performs a breadth-first search. All sources for this search are preloaded into the queue .

void bfs(void)
{
  while (!q.empty())
  {
    int v = q.front(); q.pop();
    for (int to : g[v])
      if (dist[to] == -1)
      {
        q.push(to);
        dist[to] = dist[v] + 1;
      }
  }
}

The main part of the program. Read the input data. Build the graph.

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

The array stores the time after which vertex i will catch fire. Initially, all values of are set to .

dist = vector<int>(n+1,-1);

Read the numbers of the vertices that serve as ignition points. For each such vertex set dist[id] = 0 and add it to the queue.

scanf("%d",&k);
for(i = 0; i < k; i++)
{
  scanf("%d",&id);
  dist[id] = 0;
  q.push(id);
}

Run the breadth-first search.

bfs();

Let's find the vertex that will catch fire last. The variable stores the time after which it will ignite.

mx = -1;
for(i = 1; i <= n; i++)
  if (dist[i] > mx)
  {
    mx = dist[i];
    id = i;
  }

First, print the value of dist[id] — the time when the last vertex will catch fire. Then, print the number of the vertex .

printf("%d\n",dist[id]);
printf("%d\n",id);

Java implementation

import java.util.*;

public class Main
{
  static ArrayList<Integer>[] g;
  static Queue<Integer> q = new LinkedList<Integer>();  
  static int dist[];
  static int n, m;
   
  static void bfs()
  {
    while(!q.isEmpty())
    {
      int v = q.poll();
      for(int i = 0; i < g[v].size(); i++)
      {
        int to = g[v].get(i);
        if (dist[to] == -1)
        {
          q.add(to);
          dist[to] = dist[v] + 1;
        }
      }
    }
  }
  
  @SuppressWarnings("unchecked")  
  public static void main(String[] args)
  {
    Scanner con = new Scanner(System.in);
    n = con.nextInt(); m = con.nextInt();
    
    g = new ArrayList[n+1];
    for(int i = 0; i <= n; i++)
      g[i] = new ArrayList<Integer>();
    
    dist = new int[n+1];
 
    for (int i = 0; i < m; i++)
    {
      int u = con.nextInt();
      int v = con.nextInt();
      g[u].add(v);
      g[v].add(u);
    }

    Arrays.fill(dist,-1);    
    int k = con.nextInt();
    for (int i = 0; i < k; i++)
    {
      int id = con.nextInt();
      dist[id] = 0;
      q.add(id);
    }
    
    bfs();

    int max = -1, id = -1;
    for(int i = 1; i <= n; i++)
      if (dist[i] > max)
      {
        max = dist[i];
        id = i;
      }

    System.out.println(dist[id]);
    System.out.println(id);
    con.close();
  }
}