Linear network#10455

Linear network (Editorial)

The computers are numbered from to . Since n \le 10^9, store the status of working and failed computers in a map map<int, int> m. The value of m[i] = 0 if the computer with number is working, and m[i] = 1 if it is broken. Initially, for all 1 \le i \le n, set m[i] = 0

For convenience, we introduce two dummy broken computers with numbers and n + 1. Set m[0] = m[n + 1] = 1.

The number of groups of computers in the network will be maintained in the variable . Initially, there is one group in the network, so set cnt = 1.

Now let's consider the process of handling queries. In particular, let's examine the failure of the computer with number (query type t = 1):

For processing a query of type t = 2, it is sufficient to print the current value of the variable .

Example

Algorithm implementation

Declare a data structure map.

map<int, int> m;

Read the number of computers and the number of queries .

scanf("%d %d", &n, &q);

Initialize the dummy computers with numbers and n + 1.

m[0] = 1;
m[n + 1] = 1;

Maintain the number of groups of computers in the network in the variable . Initially, all computers are operational, so cnt = 1.

cnt = 1;

Sequentially process queries.

while (q--)
{
  scanf("%d", &t);
  if (t == 1)
  {

Query t = 1. The computer with number fails. If computer is already broken, no action is required.

    scanf("%d", &l);
    if (m[l] == 0)
    {

Otherwise, set the state of computer as broken.

      m[l] = 1;

Depending on the state of the neighboring computers of (either working or broken), recompute the number of groups:

      k = m[l - 1] + m[l + 1];
      if (k == 2) cnt--;
      else if (k == 0) cnt++;
    }
  }
  else

For query t = 2, print the current number of groups of computers in the network.

    printf("%d\n", cnt);
}